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 createBuildVecShuffle(const SDLoc &DL, SDNode *N,
404                                   ArrayRef<int> VectorMask, SDValue VecIn1,
405                                   SDValue VecIn2, unsigned LeftIdx);
406     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
407 
408     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
409 
410     /// Walk up chain skipping non-aliasing memory nodes,
411     /// looking for aliasing nodes and adding them to the Aliases vector.
412     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
413                           SmallVectorImpl<SDValue> &Aliases);
414 
415     /// Return true if there is any possibility that the two addresses overlap.
416     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
417 
418     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
419     /// chain (aliasing node.)
420     SDValue FindBetterChain(SDNode *N, SDValue Chain);
421 
422     /// Try to replace a store and any possibly adjacent stores on
423     /// consecutive chains with better chains. Return true only if St is
424     /// replaced.
425     ///
426     /// Notice that other chains may still be replaced even if the function
427     /// returns false.
428     bool findBetterNeighborChains(StoreSDNode *St);
429 
430     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
431     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
432 
433     /// Holds a pointer to an LSBaseSDNode as well as information on where it
434     /// is located in a sequence of memory operations connected by a chain.
435     struct MemOpLink {
436       MemOpLink(LSBaseSDNode *N, int64_t Offset)
437           : MemNode(N), OffsetFromBase(Offset) {}
438       // Ptr to the mem node.
439       LSBaseSDNode *MemNode;
440       // Offset from the base ptr.
441       int64_t OffsetFromBase;
442     };
443 
444     /// This is a helper function for visitMUL to check the profitability
445     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
446     /// MulNode is the original multiply, AddNode is (add x, c1),
447     /// and ConstNode is c2.
448     bool isMulAddWithConstProfitable(SDNode *MulNode,
449                                      SDValue &AddNode,
450                                      SDValue &ConstNode);
451 
452 
453     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
454     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
455     /// the type of the loaded value to be extended.  LoadedVT returns the type
456     /// of the original loaded value.  NarrowLoad returns whether the load would
457     /// need to be narrowed in order to match.
458     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
459                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
460                           bool &NarrowLoad);
461 
462     /// Helper function for MergeConsecutiveStores which merges the
463     /// component store chains.
464     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
465                                 unsigned NumStores);
466 
467     /// This is a helper function for MergeConsecutiveStores. When the source
468     /// elements of the consecutive stores are all constants or all extracted
469     /// vector elements, try to merge them into one larger store.
470     /// \return True 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.
477     /// Stores that may be merged are placed in StoreNodes.
478     void getStoreMergeCandidates(StoreSDNode *St,
479                                  SmallVectorImpl<MemOpLink> &StoreNodes);
480 
481     /// Helper function for MergeConsecutiveStores. Checks if
482     /// Candidate stores have indirect dependency through their
483     /// operands. \return True if safe to merge
484     bool checkMergeStoreCandidatesForDependencies(
485         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
486 
487     /// Merge consecutive store operations into a wide store.
488     /// This optimization uses wide integers or vectors when possible.
489     /// \return number of stores that were merged into a merged store (the
490     /// affected nodes are stored as a prefix in \p StoreNodes).
491     bool MergeConsecutiveStores(StoreSDNode *N);
492 
493     /// \brief Try to transform a truncation where C is a constant:
494     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
495     ///
496     /// \p N needs to be a truncation and its first operand an AND. Other
497     /// requirements are checked by the function (e.g. that trunc is
498     /// single-use) and if missed an empty SDValue is returned.
499     SDValue distributeTruncateThroughAnd(SDNode *N);
500 
501   public:
502     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
503         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
504           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) {
505       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
506 
507       MaximumLegalStoreInBits = 0;
508       for (MVT VT : MVT::all_valuetypes())
509         if (EVT(VT).isSimple() && VT != MVT::Other &&
510             TLI.isTypeLegal(EVT(VT)) &&
511             VT.getSizeInBits() >= MaximumLegalStoreInBits)
512           MaximumLegalStoreInBits = VT.getSizeInBits();
513     }
514 
515     /// Runs the dag combiner on all nodes in the work list
516     void Run(CombineLevel AtLevel);
517 
518     SelectionDAG &getDAG() const { return DAG; }
519 
520     /// Returns a type large enough to hold any valid shift amount - before type
521     /// legalization these can be huge.
522     EVT getShiftAmountTy(EVT LHSTy) {
523       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
524       if (LHSTy.isVector())
525         return LHSTy;
526       auto &DL = DAG.getDataLayout();
527       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
528                         : TLI.getPointerTy(DL);
529     }
530 
531     /// This method returns true if we are running before type legalization or
532     /// if the specified VT is legal.
533     bool isTypeLegal(const EVT &VT) {
534       if (!LegalTypes) return true;
535       return TLI.isTypeLegal(VT);
536     }
537 
538     /// Convenience wrapper around TargetLowering::getSetCCResultType
539     EVT getSetCCResultType(EVT VT) const {
540       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
541     }
542   };
543 }
544 
545 
546 namespace {
547 /// This class is a DAGUpdateListener that removes any deleted
548 /// nodes from the worklist.
549 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
550   DAGCombiner &DC;
551 public:
552   explicit WorklistRemover(DAGCombiner &dc)
553     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
554 
555   void NodeDeleted(SDNode *N, SDNode *E) override {
556     DC.removeFromWorklist(N);
557   }
558 };
559 }
560 
561 //===----------------------------------------------------------------------===//
562 //  TargetLowering::DAGCombinerInfo implementation
563 //===----------------------------------------------------------------------===//
564 
565 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
566   ((DAGCombiner*)DC)->AddToWorklist(N);
567 }
568 
569 SDValue TargetLowering::DAGCombinerInfo::
570 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
571   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
572 }
573 
574 SDValue TargetLowering::DAGCombinerInfo::
575 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
576   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
577 }
578 
579 
580 SDValue TargetLowering::DAGCombinerInfo::
581 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
582   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
583 }
584 
585 void TargetLowering::DAGCombinerInfo::
586 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
587   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
588 }
589 
590 //===----------------------------------------------------------------------===//
591 // Helper Functions
592 //===----------------------------------------------------------------------===//
593 
594 void DAGCombiner::deleteAndRecombine(SDNode *N) {
595   removeFromWorklist(N);
596 
597   // If the operands of this node are only used by the node, they will now be
598   // dead. Make sure to re-visit them and recursively delete dead nodes.
599   for (const SDValue &Op : N->ops())
600     // For an operand generating multiple values, one of the values may
601     // become dead allowing further simplification (e.g. split index
602     // arithmetic from an indexed load).
603     if (Op->hasOneUse() || Op->getNumValues() > 1)
604       AddToWorklist(Op.getNode());
605 
606   DAG.DeleteNode(N);
607 }
608 
609 /// Return 1 if we can compute the negated form of the specified expression for
610 /// the same cost as the expression itself, or 2 if we can compute the negated
611 /// form more cheaply than the expression itself.
612 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
613                                const TargetLowering &TLI,
614                                const TargetOptions *Options,
615                                unsigned Depth = 0) {
616   // fneg is removable even if it has multiple uses.
617   if (Op.getOpcode() == ISD::FNEG) return 2;
618 
619   // Don't allow anything with multiple uses.
620   if (!Op.hasOneUse()) return 0;
621 
622   // Don't recurse exponentially.
623   if (Depth > 6) return 0;
624 
625   switch (Op.getOpcode()) {
626   default: return false;
627   case ISD::ConstantFP: {
628     if (!LegalOperations)
629       return 1;
630 
631     // Don't invert constant FP values after legalization unless the target says
632     // the negated constant is legal.
633     EVT VT = Op.getValueType();
634     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
635       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
636   }
637   case ISD::FADD:
638     // FIXME: determine better conditions for this xform.
639     if (!Options->UnsafeFPMath) return 0;
640 
641     // After operation legalization, it might not be legal to create new FSUBs.
642     if (LegalOperations &&
643         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
644       return 0;
645 
646     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
647     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
648                                     Options, Depth + 1))
649       return V;
650     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
651     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
652                               Depth + 1);
653   case ISD::FSUB:
654     // We can't turn -(A-B) into B-A when we honor signed zeros.
655     if (!Options->NoSignedZerosFPMath &&
656         !Op.getNode()->getFlags().hasNoSignedZeros())
657       return 0;
658 
659     // fold (fneg (fsub A, B)) -> (fsub B, A)
660     return 1;
661 
662   case ISD::FMUL:
663   case ISD::FDIV:
664     if (Options->HonorSignDependentRoundingFPMath()) return 0;
665 
666     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
667     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
668                                     Options, Depth + 1))
669       return V;
670 
671     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
672                               Depth + 1);
673 
674   case ISD::FP_EXTEND:
675   case ISD::FP_ROUND:
676   case ISD::FSIN:
677     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
678                               Depth + 1);
679   }
680 }
681 
682 /// If isNegatibleForFree returns true, return the newly negated expression.
683 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
684                                     bool LegalOperations, unsigned Depth = 0) {
685   const TargetOptions &Options = DAG.getTarget().Options;
686   // fneg is removable even if it has multiple uses.
687   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
688 
689   // Don't allow anything with multiple uses.
690   assert(Op.hasOneUse() && "Unknown reuse!");
691 
692   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
693 
694   const SDNodeFlags Flags = Op.getNode()->getFlags();
695 
696   switch (Op.getOpcode()) {
697   default: llvm_unreachable("Unknown code");
698   case ISD::ConstantFP: {
699     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
700     V.changeSign();
701     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
702   }
703   case ISD::FADD:
704     // FIXME: determine better conditions for this xform.
705     assert(Options.UnsafeFPMath);
706 
707     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
708     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
709                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
710       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
711                          GetNegatedExpression(Op.getOperand(0), DAG,
712                                               LegalOperations, Depth+1),
713                          Op.getOperand(1), Flags);
714     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
715     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
716                        GetNegatedExpression(Op.getOperand(1), DAG,
717                                             LegalOperations, Depth+1),
718                        Op.getOperand(0), Flags);
719   case ISD::FSUB:
720     // fold (fneg (fsub 0, B)) -> B
721     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
722       if (N0CFP->isZero())
723         return Op.getOperand(1);
724 
725     // fold (fneg (fsub A, B)) -> (fsub B, A)
726     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
727                        Op.getOperand(1), Op.getOperand(0), Flags);
728 
729   case ISD::FMUL:
730   case ISD::FDIV:
731     assert(!Options.HonorSignDependentRoundingFPMath());
732 
733     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
734     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
735                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
736       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
737                          GetNegatedExpression(Op.getOperand(0), DAG,
738                                               LegalOperations, Depth+1),
739                          Op.getOperand(1), Flags);
740 
741     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
742     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
743                        Op.getOperand(0),
744                        GetNegatedExpression(Op.getOperand(1), DAG,
745                                             LegalOperations, Depth+1), Flags);
746 
747   case ISD::FP_EXTEND:
748   case ISD::FSIN:
749     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
750                        GetNegatedExpression(Op.getOperand(0), DAG,
751                                             LegalOperations, Depth+1));
752   case ISD::FP_ROUND:
753       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
754                          GetNegatedExpression(Op.getOperand(0), DAG,
755                                               LegalOperations, Depth+1),
756                          Op.getOperand(1));
757   }
758 }
759 
760 // APInts must be the same size for most operations, this helper
761 // function zero extends the shorter of the pair so that they match.
762 // We provide an Offset so that we can create bitwidths that won't overflow.
763 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
764   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
765   LHS = LHS.zextOrSelf(Bits);
766   RHS = RHS.zextOrSelf(Bits);
767 }
768 
769 // Return true if this node is a setcc, or is a select_cc
770 // that selects between the target values used for true and false, making it
771 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
772 // the appropriate nodes based on the type of node we are checking. This
773 // simplifies life a bit for the callers.
774 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
775                                     SDValue &CC) const {
776   if (N.getOpcode() == ISD::SETCC) {
777     LHS = N.getOperand(0);
778     RHS = N.getOperand(1);
779     CC  = N.getOperand(2);
780     return true;
781   }
782 
783   if (N.getOpcode() != ISD::SELECT_CC ||
784       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
785       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
786     return false;
787 
788   if (TLI.getBooleanContents(N.getValueType()) ==
789       TargetLowering::UndefinedBooleanContent)
790     return false;
791 
792   LHS = N.getOperand(0);
793   RHS = N.getOperand(1);
794   CC  = N.getOperand(4);
795   return true;
796 }
797 
798 /// Return true if this is a SetCC-equivalent operation with only one use.
799 /// If this is true, it allows the users to invert the operation for free when
800 /// it is profitable to do so.
801 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
802   SDValue N0, N1, N2;
803   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
804     return true;
805   return false;
806 }
807 
808 // \brief Returns the SDNode if it is a constant float BuildVector
809 // or constant float.
810 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
811   if (isa<ConstantFPSDNode>(N))
812     return N.getNode();
813   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
814     return N.getNode();
815   return nullptr;
816 }
817 
818 // Determines if it is a constant integer or a build vector of constant
819 // integers (and undefs).
820 // Do not permit build vector implicit truncation.
821 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
822   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
823     return !(Const->isOpaque() && NoOpaques);
824   if (N.getOpcode() != ISD::BUILD_VECTOR)
825     return false;
826   unsigned BitWidth = N.getScalarValueSizeInBits();
827   for (const SDValue &Op : N->op_values()) {
828     if (Op.isUndef())
829       continue;
830     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
831     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
832         (Const->isOpaque() && NoOpaques))
833       return false;
834   }
835   return true;
836 }
837 
838 // Determines if it is a constant null integer or a splatted vector of a
839 // constant null integer (with no undefs).
840 // Build vector implicit truncation is not an issue for null values.
841 static bool isNullConstantOrNullSplatConstant(SDValue N) {
842   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
843     return Splat->isNullValue();
844   return false;
845 }
846 
847 // Determines if it is a constant integer of one or a splatted vector of a
848 // constant integer of one (with no undefs).
849 // Do not permit build vector implicit truncation.
850 static bool isOneConstantOrOneSplatConstant(SDValue N) {
851   unsigned BitWidth = N.getScalarValueSizeInBits();
852   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
853     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
854   return false;
855 }
856 
857 // Determines if it is a constant integer of all ones or a splatted vector of a
858 // constant integer of all ones (with no undefs).
859 // Do not permit build vector implicit truncation.
860 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
861   unsigned BitWidth = N.getScalarValueSizeInBits();
862   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
863     return Splat->isAllOnesValue() &&
864            Splat->getAPIntValue().getBitWidth() == BitWidth;
865   return false;
866 }
867 
868 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
869 // undef's.
870 static bool isAnyConstantBuildVector(const SDNode *N) {
871   return ISD::isBuildVectorOfConstantSDNodes(N) ||
872          ISD::isBuildVectorOfConstantFPSDNodes(N);
873 }
874 
875 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
876                                     SDValue N1) {
877   EVT VT = N0.getValueType();
878   if (N0.getOpcode() == Opc) {
879     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
880       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
881         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
882         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
883           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
884         return SDValue();
885       }
886       if (N0.hasOneUse()) {
887         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
888         // use
889         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
890         if (!OpNode.getNode())
891           return SDValue();
892         AddToWorklist(OpNode.getNode());
893         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
894       }
895     }
896   }
897 
898   if (N1.getOpcode() == Opc) {
899     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
900       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
901         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
902         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
903           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
904         return SDValue();
905       }
906       if (N1.hasOneUse()) {
907         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
908         // use
909         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
910         if (!OpNode.getNode())
911           return SDValue();
912         AddToWorklist(OpNode.getNode());
913         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
914       }
915     }
916   }
917 
918   return SDValue();
919 }
920 
921 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
922                                bool AddTo) {
923   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
924   ++NodesCombined;
925   DEBUG(dbgs() << "\nReplacing.1 ";
926         N->dump(&DAG);
927         dbgs() << "\nWith: ";
928         To[0].getNode()->dump(&DAG);
929         dbgs() << " and " << NumTo-1 << " other values\n");
930   for (unsigned i = 0, e = NumTo; i != e; ++i)
931     assert((!To[i].getNode() ||
932             N->getValueType(i) == To[i].getValueType()) &&
933            "Cannot combine value to value of different type!");
934 
935   WorklistRemover DeadNodes(*this);
936   DAG.ReplaceAllUsesWith(N, To);
937   if (AddTo) {
938     // Push the new nodes and any users onto the worklist
939     for (unsigned i = 0, e = NumTo; i != e; ++i) {
940       if (To[i].getNode()) {
941         AddToWorklist(To[i].getNode());
942         AddUsersToWorklist(To[i].getNode());
943       }
944     }
945   }
946 
947   // Finally, if the node is now dead, remove it from the graph.  The node
948   // may not be dead if the replacement process recursively simplified to
949   // something else needing this node.
950   if (N->use_empty())
951     deleteAndRecombine(N);
952   return SDValue(N, 0);
953 }
954 
955 void DAGCombiner::
956 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
957   // Replace all uses.  If any nodes become isomorphic to other nodes and
958   // are deleted, make sure to remove them from our worklist.
959   WorklistRemover DeadNodes(*this);
960   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
961 
962   // Push the new node and any (possibly new) users onto the worklist.
963   AddToWorklist(TLO.New.getNode());
964   AddUsersToWorklist(TLO.New.getNode());
965 
966   // Finally, if the node is now dead, remove it from the graph.  The node
967   // may not be dead if the replacement process recursively simplified to
968   // something else needing this node.
969   if (TLO.Old.getNode()->use_empty())
970     deleteAndRecombine(TLO.Old.getNode());
971 }
972 
973 /// Check the specified integer node value to see if it can be simplified or if
974 /// things it uses can be simplified by bit propagation. If so, return true.
975 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
976   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
977   KnownBits Known;
978   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
979     return false;
980 
981   // Revisit the node.
982   AddToWorklist(Op.getNode());
983 
984   // Replace the old value with the new one.
985   ++NodesCombined;
986   DEBUG(dbgs() << "\nReplacing.2 ";
987         TLO.Old.getNode()->dump(&DAG);
988         dbgs() << "\nWith: ";
989         TLO.New.getNode()->dump(&DAG);
990         dbgs() << '\n');
991 
992   CommitTargetLoweringOpt(TLO);
993   return true;
994 }
995 
996 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
997   SDLoc DL(Load);
998   EVT VT = Load->getValueType(0);
999   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1000 
1001   DEBUG(dbgs() << "\nReplacing.9 ";
1002         Load->dump(&DAG);
1003         dbgs() << "\nWith: ";
1004         Trunc.getNode()->dump(&DAG);
1005         dbgs() << '\n');
1006   WorklistRemover DeadNodes(*this);
1007   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1008   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1009   deleteAndRecombine(Load);
1010   AddToWorklist(Trunc.getNode());
1011 }
1012 
1013 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1014   Replace = false;
1015   SDLoc DL(Op);
1016   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1017     LoadSDNode *LD = cast<LoadSDNode>(Op);
1018     EVT MemVT = LD->getMemoryVT();
1019     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1020       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1021                                                        : ISD::EXTLOAD)
1022       : LD->getExtensionType();
1023     Replace = true;
1024     return DAG.getExtLoad(ExtType, DL, PVT,
1025                           LD->getChain(), LD->getBasePtr(),
1026                           MemVT, LD->getMemOperand());
1027   }
1028 
1029   unsigned Opc = Op.getOpcode();
1030   switch (Opc) {
1031   default: break;
1032   case ISD::AssertSext:
1033     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1034       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1035     break;
1036   case ISD::AssertZext:
1037     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1038       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1039     break;
1040   case ISD::Constant: {
1041     unsigned ExtOpc =
1042       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1043     return DAG.getNode(ExtOpc, DL, PVT, Op);
1044   }
1045   }
1046 
1047   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1048     return SDValue();
1049   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1050 }
1051 
1052 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1053   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1054     return SDValue();
1055   EVT OldVT = Op.getValueType();
1056   SDLoc DL(Op);
1057   bool Replace = false;
1058   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1059   if (!NewOp.getNode())
1060     return SDValue();
1061   AddToWorklist(NewOp.getNode());
1062 
1063   if (Replace)
1064     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1065   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1066                      DAG.getValueType(OldVT));
1067 }
1068 
1069 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1070   EVT OldVT = Op.getValueType();
1071   SDLoc DL(Op);
1072   bool Replace = false;
1073   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1074   if (!NewOp.getNode())
1075     return SDValue();
1076   AddToWorklist(NewOp.getNode());
1077 
1078   if (Replace)
1079     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1080   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1081 }
1082 
1083 /// Promote the specified integer binary operation if the target indicates it is
1084 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1085 /// i32 since i16 instructions are longer.
1086 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1087   if (!LegalOperations)
1088     return SDValue();
1089 
1090   EVT VT = Op.getValueType();
1091   if (VT.isVector() || !VT.isInteger())
1092     return SDValue();
1093 
1094   // If operation type is 'undesirable', e.g. i16 on x86, consider
1095   // promoting it.
1096   unsigned Opc = Op.getOpcode();
1097   if (TLI.isTypeDesirableForOp(Opc, VT))
1098     return SDValue();
1099 
1100   EVT PVT = VT;
1101   // Consult target whether it is a good idea to promote this operation and
1102   // what's the right type to promote it to.
1103   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1104     assert(PVT != VT && "Don't know what type to promote to!");
1105 
1106     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1107 
1108     bool Replace0 = false;
1109     SDValue N0 = Op.getOperand(0);
1110     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1111 
1112     bool Replace1 = false;
1113     SDValue N1 = Op.getOperand(1);
1114     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1115     SDLoc DL(Op);
1116 
1117     SDValue RV =
1118         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1119 
1120     // New replace instances of N0 and N1
1121     if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1122         NN0.getOpcode() != ISD::DELETED_NODE) {
1123       AddToWorklist(NN0.getNode());
1124       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1125     }
1126 
1127     if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1128         NN1.getOpcode() != ISD::DELETED_NODE) {
1129       AddToWorklist(NN1.getNode());
1130       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1131     }
1132 
1133     // Deal with Op being deleted.
1134     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1135       return RV;
1136   }
1137   return SDValue();
1138 }
1139 
1140 /// Promote the specified integer shift operation if the target indicates it is
1141 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1142 /// i32 since i16 instructions are longer.
1143 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1144   if (!LegalOperations)
1145     return SDValue();
1146 
1147   EVT VT = Op.getValueType();
1148   if (VT.isVector() || !VT.isInteger())
1149     return SDValue();
1150 
1151   // If operation type is 'undesirable', e.g. i16 on x86, consider
1152   // promoting it.
1153   unsigned Opc = Op.getOpcode();
1154   if (TLI.isTypeDesirableForOp(Opc, VT))
1155     return SDValue();
1156 
1157   EVT PVT = VT;
1158   // Consult target whether it is a good idea to promote this operation and
1159   // what's the right type to promote it to.
1160   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1161     assert(PVT != VT && "Don't know what type to promote to!");
1162 
1163     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1164 
1165     bool Replace = false;
1166     SDValue N0 = Op.getOperand(0);
1167     SDValue N1 = Op.getOperand(1);
1168     if (Opc == ISD::SRA)
1169       N0 = SExtPromoteOperand(N0, PVT);
1170     else if (Opc == ISD::SRL)
1171       N0 = ZExtPromoteOperand(N0, PVT);
1172     else
1173       N0 = PromoteOperand(N0, PVT, Replace);
1174 
1175     if (!N0.getNode())
1176       return SDValue();
1177 
1178     SDLoc DL(Op);
1179     SDValue RV =
1180         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1181 
1182     AddToWorklist(N0.getNode());
1183     if (Replace)
1184       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1185 
1186     // Deal with Op being deleted.
1187     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1188       return RV;
1189   }
1190   return SDValue();
1191 }
1192 
1193 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1194   if (!LegalOperations)
1195     return SDValue();
1196 
1197   EVT VT = Op.getValueType();
1198   if (VT.isVector() || !VT.isInteger())
1199     return SDValue();
1200 
1201   // If operation type is 'undesirable', e.g. i16 on x86, consider
1202   // promoting it.
1203   unsigned Opc = Op.getOpcode();
1204   if (TLI.isTypeDesirableForOp(Opc, VT))
1205     return SDValue();
1206 
1207   EVT PVT = VT;
1208   // Consult target whether it is a good idea to promote this operation and
1209   // what's the right type to promote it to.
1210   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1211     assert(PVT != VT && "Don't know what type to promote to!");
1212     // fold (aext (aext x)) -> (aext x)
1213     // fold (aext (zext x)) -> (zext x)
1214     // fold (aext (sext x)) -> (sext x)
1215     DEBUG(dbgs() << "\nPromoting ";
1216           Op.getNode()->dump(&DAG));
1217     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1218   }
1219   return SDValue();
1220 }
1221 
1222 bool DAGCombiner::PromoteLoad(SDValue Op) {
1223   if (!LegalOperations)
1224     return false;
1225 
1226   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1227     return false;
1228 
1229   EVT VT = Op.getValueType();
1230   if (VT.isVector() || !VT.isInteger())
1231     return false;
1232 
1233   // If operation type is 'undesirable', e.g. i16 on x86, consider
1234   // promoting it.
1235   unsigned Opc = Op.getOpcode();
1236   if (TLI.isTypeDesirableForOp(Opc, VT))
1237     return false;
1238 
1239   EVT PVT = VT;
1240   // Consult target whether it is a good idea to promote this operation and
1241   // what's the right type to promote it to.
1242   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1243     assert(PVT != VT && "Don't know what type to promote to!");
1244 
1245     SDLoc DL(Op);
1246     SDNode *N = Op.getNode();
1247     LoadSDNode *LD = cast<LoadSDNode>(N);
1248     EVT MemVT = LD->getMemoryVT();
1249     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1250       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1251                                                        : ISD::EXTLOAD)
1252       : LD->getExtensionType();
1253     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1254                                    LD->getChain(), LD->getBasePtr(),
1255                                    MemVT, LD->getMemOperand());
1256     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1257 
1258     DEBUG(dbgs() << "\nPromoting ";
1259           N->dump(&DAG);
1260           dbgs() << "\nTo: ";
1261           Result.getNode()->dump(&DAG);
1262           dbgs() << '\n');
1263     WorklistRemover DeadNodes(*this);
1264     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1265     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1266     deleteAndRecombine(N);
1267     AddToWorklist(Result.getNode());
1268     return true;
1269   }
1270   return false;
1271 }
1272 
1273 /// \brief Recursively delete a node which has no uses and any operands for
1274 /// which it is the only use.
1275 ///
1276 /// Note that this both deletes the nodes and removes them from the worklist.
1277 /// It also adds any nodes who have had a user deleted to the worklist as they
1278 /// may now have only one use and subject to other combines.
1279 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1280   if (!N->use_empty())
1281     return false;
1282 
1283   SmallSetVector<SDNode *, 16> Nodes;
1284   Nodes.insert(N);
1285   do {
1286     N = Nodes.pop_back_val();
1287     if (!N)
1288       continue;
1289 
1290     if (N->use_empty()) {
1291       for (const SDValue &ChildN : N->op_values())
1292         Nodes.insert(ChildN.getNode());
1293 
1294       removeFromWorklist(N);
1295       DAG.DeleteNode(N);
1296     } else {
1297       AddToWorklist(N);
1298     }
1299   } while (!Nodes.empty());
1300   return true;
1301 }
1302 
1303 //===----------------------------------------------------------------------===//
1304 //  Main DAG Combiner implementation
1305 //===----------------------------------------------------------------------===//
1306 
1307 void DAGCombiner::Run(CombineLevel AtLevel) {
1308   // set the instance variables, so that the various visit routines may use it.
1309   Level = AtLevel;
1310   LegalOperations = Level >= AfterLegalizeVectorOps;
1311   LegalTypes = Level >= AfterLegalizeTypes;
1312 
1313   // Add all the dag nodes to the worklist.
1314   for (SDNode &Node : DAG.allnodes())
1315     AddToWorklist(&Node);
1316 
1317   // Create a dummy node (which is not added to allnodes), that adds a reference
1318   // to the root node, preventing it from being deleted, and tracking any
1319   // changes of the root.
1320   HandleSDNode Dummy(DAG.getRoot());
1321 
1322   // While the worklist isn't empty, find a node and try to combine it.
1323   while (!WorklistMap.empty()) {
1324     SDNode *N;
1325     // The Worklist holds the SDNodes in order, but it may contain null entries.
1326     do {
1327       N = Worklist.pop_back_val();
1328     } while (!N);
1329 
1330     bool GoodWorklistEntry = WorklistMap.erase(N);
1331     (void)GoodWorklistEntry;
1332     assert(GoodWorklistEntry &&
1333            "Found a worklist entry without a corresponding map entry!");
1334 
1335     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1336     // N is deleted from the DAG, since they too may now be dead or may have a
1337     // reduced number of uses, allowing other xforms.
1338     if (recursivelyDeleteUnusedNodes(N))
1339       continue;
1340 
1341     WorklistRemover DeadNodes(*this);
1342 
1343     // If this combine is running after legalizing the DAG, re-legalize any
1344     // nodes pulled off the worklist.
1345     if (Level == AfterLegalizeDAG) {
1346       SmallSetVector<SDNode *, 16> UpdatedNodes;
1347       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1348 
1349       for (SDNode *LN : UpdatedNodes) {
1350         AddToWorklist(LN);
1351         AddUsersToWorklist(LN);
1352       }
1353       if (!NIsValid)
1354         continue;
1355     }
1356 
1357     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1358 
1359     // Add any operands of the new node which have not yet been combined to the
1360     // worklist as well. Because the worklist uniques things already, this
1361     // won't repeatedly process the same operand.
1362     CombinedNodes.insert(N);
1363     for (const SDValue &ChildN : N->op_values())
1364       if (!CombinedNodes.count(ChildN.getNode()))
1365         AddToWorklist(ChildN.getNode());
1366 
1367     SDValue RV = combine(N);
1368 
1369     if (!RV.getNode())
1370       continue;
1371 
1372     ++NodesCombined;
1373 
1374     // If we get back the same node we passed in, rather than a new node or
1375     // zero, we know that the node must have defined multiple values and
1376     // CombineTo was used.  Since CombineTo takes care of the worklist
1377     // mechanics for us, we have no work to do in this case.
1378     if (RV.getNode() == N)
1379       continue;
1380 
1381     assert(N->getOpcode() != ISD::DELETED_NODE &&
1382            RV.getOpcode() != ISD::DELETED_NODE &&
1383            "Node was deleted but visit returned new node!");
1384 
1385     DEBUG(dbgs() << " ... into: ";
1386           RV.getNode()->dump(&DAG));
1387 
1388     if (N->getNumValues() == RV.getNode()->getNumValues())
1389       DAG.ReplaceAllUsesWith(N, RV.getNode());
1390     else {
1391       assert(N->getValueType(0) == RV.getValueType() &&
1392              N->getNumValues() == 1 && "Type mismatch");
1393       DAG.ReplaceAllUsesWith(N, &RV);
1394     }
1395 
1396     // Push the new node and any users onto the worklist
1397     AddToWorklist(RV.getNode());
1398     AddUsersToWorklist(RV.getNode());
1399 
1400     // Finally, if the node is now dead, remove it from the graph.  The node
1401     // may not be dead if the replacement process recursively simplified to
1402     // something else needing this node. This will also take care of adding any
1403     // operands which have lost a user to the worklist.
1404     recursivelyDeleteUnusedNodes(N);
1405   }
1406 
1407   // If the root changed (e.g. it was a dead load, update the root).
1408   DAG.setRoot(Dummy.getValue());
1409   DAG.RemoveDeadNodes();
1410 }
1411 
1412 SDValue DAGCombiner::visit(SDNode *N) {
1413   switch (N->getOpcode()) {
1414   default: break;
1415   case ISD::TokenFactor:        return visitTokenFactor(N);
1416   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1417   case ISD::ADD:                return visitADD(N);
1418   case ISD::SUB:                return visitSUB(N);
1419   case ISD::ADDC:               return visitADDC(N);
1420   case ISD::UADDO:              return visitUADDO(N);
1421   case ISD::SUBC:               return visitSUBC(N);
1422   case ISD::USUBO:              return visitUSUBO(N);
1423   case ISD::ADDE:               return visitADDE(N);
1424   case ISD::ADDCARRY:           return visitADDCARRY(N);
1425   case ISD::SUBE:               return visitSUBE(N);
1426   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1427   case ISD::MUL:                return visitMUL(N);
1428   case ISD::SDIV:               return visitSDIV(N);
1429   case ISD::UDIV:               return visitUDIV(N);
1430   case ISD::SREM:
1431   case ISD::UREM:               return visitREM(N);
1432   case ISD::MULHU:              return visitMULHU(N);
1433   case ISD::MULHS:              return visitMULHS(N);
1434   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1435   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1436   case ISD::SMULO:              return visitSMULO(N);
1437   case ISD::UMULO:              return visitUMULO(N);
1438   case ISD::SMIN:
1439   case ISD::SMAX:
1440   case ISD::UMIN:
1441   case ISD::UMAX:               return visitIMINMAX(N);
1442   case ISD::AND:                return visitAND(N);
1443   case ISD::OR:                 return visitOR(N);
1444   case ISD::XOR:                return visitXOR(N);
1445   case ISD::SHL:                return visitSHL(N);
1446   case ISD::SRA:                return visitSRA(N);
1447   case ISD::SRL:                return visitSRL(N);
1448   case ISD::ROTR:
1449   case ISD::ROTL:               return visitRotate(N);
1450   case ISD::ABS:                return visitABS(N);
1451   case ISD::BSWAP:              return visitBSWAP(N);
1452   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1453   case ISD::CTLZ:               return visitCTLZ(N);
1454   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1455   case ISD::CTTZ:               return visitCTTZ(N);
1456   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1457   case ISD::CTPOP:              return visitCTPOP(N);
1458   case ISD::SELECT:             return visitSELECT(N);
1459   case ISD::VSELECT:            return visitVSELECT(N);
1460   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1461   case ISD::SETCC:              return visitSETCC(N);
1462   case ISD::SETCCE:             return visitSETCCE(N);
1463   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1464   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1465   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1466   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1467   case ISD::AssertZext:         return visitAssertZext(N);
1468   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1469   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1470   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1471   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1472   case ISD::BITCAST:            return visitBITCAST(N);
1473   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1474   case ISD::FADD:               return visitFADD(N);
1475   case ISD::FSUB:               return visitFSUB(N);
1476   case ISD::FMUL:               return visitFMUL(N);
1477   case ISD::FMA:                return visitFMA(N);
1478   case ISD::FDIV:               return visitFDIV(N);
1479   case ISD::FREM:               return visitFREM(N);
1480   case ISD::FSQRT:              return visitFSQRT(N);
1481   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1482   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1483   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1484   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1485   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1486   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1487   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1488   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1489   case ISD::FNEG:               return visitFNEG(N);
1490   case ISD::FABS:               return visitFABS(N);
1491   case ISD::FFLOOR:             return visitFFLOOR(N);
1492   case ISD::FMINNUM:            return visitFMINNUM(N);
1493   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1494   case ISD::FCEIL:              return visitFCEIL(N);
1495   case ISD::FTRUNC:             return visitFTRUNC(N);
1496   case ISD::BRCOND:             return visitBRCOND(N);
1497   case ISD::BR_CC:              return visitBR_CC(N);
1498   case ISD::LOAD:               return visitLOAD(N);
1499   case ISD::STORE:              return visitSTORE(N);
1500   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1501   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1502   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1503   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1504   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1505   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1506   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1507   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1508   case ISD::MGATHER:            return visitMGATHER(N);
1509   case ISD::MLOAD:              return visitMLOAD(N);
1510   case ISD::MSCATTER:           return visitMSCATTER(N);
1511   case ISD::MSTORE:             return visitMSTORE(N);
1512   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1513   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1514   }
1515   return SDValue();
1516 }
1517 
1518 SDValue DAGCombiner::combine(SDNode *N) {
1519   SDValue RV = visit(N);
1520 
1521   // If nothing happened, try a target-specific DAG combine.
1522   if (!RV.getNode()) {
1523     assert(N->getOpcode() != ISD::DELETED_NODE &&
1524            "Node was deleted but visit returned NULL!");
1525 
1526     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1527         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1528 
1529       // Expose the DAG combiner to the target combiner impls.
1530       TargetLowering::DAGCombinerInfo
1531         DagCombineInfo(DAG, Level, false, this);
1532 
1533       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1534     }
1535   }
1536 
1537   // If nothing happened still, try promoting the operation.
1538   if (!RV.getNode()) {
1539     switch (N->getOpcode()) {
1540     default: break;
1541     case ISD::ADD:
1542     case ISD::SUB:
1543     case ISD::MUL:
1544     case ISD::AND:
1545     case ISD::OR:
1546     case ISD::XOR:
1547       RV = PromoteIntBinOp(SDValue(N, 0));
1548       break;
1549     case ISD::SHL:
1550     case ISD::SRA:
1551     case ISD::SRL:
1552       RV = PromoteIntShiftOp(SDValue(N, 0));
1553       break;
1554     case ISD::SIGN_EXTEND:
1555     case ISD::ZERO_EXTEND:
1556     case ISD::ANY_EXTEND:
1557       RV = PromoteExtend(SDValue(N, 0));
1558       break;
1559     case ISD::LOAD:
1560       if (PromoteLoad(SDValue(N, 0)))
1561         RV = SDValue(N, 0);
1562       break;
1563     }
1564   }
1565 
1566   // If N is a commutative binary node, try commuting it to enable more
1567   // sdisel CSE.
1568   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1569       N->getNumValues() == 1) {
1570     SDValue N0 = N->getOperand(0);
1571     SDValue N1 = N->getOperand(1);
1572 
1573     // Constant operands are canonicalized to RHS.
1574     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1575       SDValue Ops[] = {N1, N0};
1576       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1577                                             N->getFlags());
1578       if (CSENode)
1579         return SDValue(CSENode, 0);
1580     }
1581   }
1582 
1583   return RV;
1584 }
1585 
1586 /// Given a node, return its input chain if it has one, otherwise return a null
1587 /// sd operand.
1588 static SDValue getInputChainForNode(SDNode *N) {
1589   if (unsigned NumOps = N->getNumOperands()) {
1590     if (N->getOperand(0).getValueType() == MVT::Other)
1591       return N->getOperand(0);
1592     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1593       return N->getOperand(NumOps-1);
1594     for (unsigned i = 1; i < NumOps-1; ++i)
1595       if (N->getOperand(i).getValueType() == MVT::Other)
1596         return N->getOperand(i);
1597   }
1598   return SDValue();
1599 }
1600 
1601 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1602   // If N has two operands, where one has an input chain equal to the other,
1603   // the 'other' chain is redundant.
1604   if (N->getNumOperands() == 2) {
1605     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1606       return N->getOperand(0);
1607     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1608       return N->getOperand(1);
1609   }
1610 
1611   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1612   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1613   SmallPtrSet<SDNode*, 16> SeenOps;
1614   bool Changed = false;             // If we should replace this token factor.
1615 
1616   // Start out with this token factor.
1617   TFs.push_back(N);
1618 
1619   // Iterate through token factors.  The TFs grows when new token factors are
1620   // encountered.
1621   for (unsigned i = 0; i < TFs.size(); ++i) {
1622     SDNode *TF = TFs[i];
1623 
1624     // Check each of the operands.
1625     for (const SDValue &Op : TF->op_values()) {
1626 
1627       switch (Op.getOpcode()) {
1628       case ISD::EntryToken:
1629         // Entry tokens don't need to be added to the list. They are
1630         // redundant.
1631         Changed = true;
1632         break;
1633 
1634       case ISD::TokenFactor:
1635         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1636           // Queue up for processing.
1637           TFs.push_back(Op.getNode());
1638           // Clean up in case the token factor is removed.
1639           AddToWorklist(Op.getNode());
1640           Changed = true;
1641           break;
1642         }
1643         LLVM_FALLTHROUGH;
1644 
1645       default:
1646         // Only add if it isn't already in the list.
1647         if (SeenOps.insert(Op.getNode()).second)
1648           Ops.push_back(Op);
1649         else
1650           Changed = true;
1651         break;
1652       }
1653     }
1654   }
1655 
1656   // Remove Nodes that are chained to another node in the list. Do so
1657   // by walking up chains breath-first stopping when we've seen
1658   // another operand. In general we must climb to the EntryNode, but we can exit
1659   // early if we find all remaining work is associated with just one operand as
1660   // no further pruning is possible.
1661 
1662   // List of nodes to search through and original Ops from which they originate.
1663   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1664   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1665   SmallPtrSet<SDNode *, 16> SeenChains;
1666   bool DidPruneOps = false;
1667 
1668   unsigned NumLeftToConsider = 0;
1669   for (const SDValue &Op : Ops) {
1670     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1671     OpWorkCount.push_back(1);
1672   }
1673 
1674   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1675     // If this is an Op, we can remove the op from the list. Remark any
1676     // search associated with it as from the current OpNumber.
1677     if (SeenOps.count(Op) != 0) {
1678       Changed = true;
1679       DidPruneOps = true;
1680       unsigned OrigOpNumber = 0;
1681       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1682         OrigOpNumber++;
1683       assert((OrigOpNumber != Ops.size()) &&
1684              "expected to find TokenFactor Operand");
1685       // Re-mark worklist from OrigOpNumber to OpNumber
1686       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1687         if (Worklist[i].second == OrigOpNumber) {
1688           Worklist[i].second = OpNumber;
1689         }
1690       }
1691       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1692       OpWorkCount[OrigOpNumber] = 0;
1693       NumLeftToConsider--;
1694     }
1695     // Add if it's a new chain
1696     if (SeenChains.insert(Op).second) {
1697       OpWorkCount[OpNumber]++;
1698       Worklist.push_back(std::make_pair(Op, OpNumber));
1699     }
1700   };
1701 
1702   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1703     // We need at least be consider at least 2 Ops to prune.
1704     if (NumLeftToConsider <= 1)
1705       break;
1706     auto CurNode = Worklist[i].first;
1707     auto CurOpNumber = Worklist[i].second;
1708     assert((OpWorkCount[CurOpNumber] > 0) &&
1709            "Node should not appear in worklist");
1710     switch (CurNode->getOpcode()) {
1711     case ISD::EntryToken:
1712       // Hitting EntryToken is the only way for the search to terminate without
1713       // hitting
1714       // another operand's search. Prevent us from marking this operand
1715       // considered.
1716       NumLeftToConsider++;
1717       break;
1718     case ISD::TokenFactor:
1719       for (const SDValue &Op : CurNode->op_values())
1720         AddToWorklist(i, Op.getNode(), CurOpNumber);
1721       break;
1722     case ISD::CopyFromReg:
1723     case ISD::CopyToReg:
1724       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1725       break;
1726     default:
1727       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1728         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1729       break;
1730     }
1731     OpWorkCount[CurOpNumber]--;
1732     if (OpWorkCount[CurOpNumber] == 0)
1733       NumLeftToConsider--;
1734   }
1735 
1736   // If we've changed things around then replace token factor.
1737   if (Changed) {
1738     SDValue Result;
1739     if (Ops.empty()) {
1740       // The entry token is the only possible outcome.
1741       Result = DAG.getEntryNode();
1742     } else {
1743       if (DidPruneOps) {
1744         SmallVector<SDValue, 8> PrunedOps;
1745         //
1746         for (const SDValue &Op : Ops) {
1747           if (SeenChains.count(Op.getNode()) == 0)
1748             PrunedOps.push_back(Op);
1749         }
1750         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1751       } else {
1752         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1753       }
1754     }
1755     return Result;
1756   }
1757   return SDValue();
1758 }
1759 
1760 /// MERGE_VALUES can always be eliminated.
1761 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1762   WorklistRemover DeadNodes(*this);
1763   // Replacing results may cause a different MERGE_VALUES to suddenly
1764   // be CSE'd with N, and carry its uses with it. Iterate until no
1765   // uses remain, to ensure that the node can be safely deleted.
1766   // First add the users of this node to the work list so that they
1767   // can be tried again once they have new operands.
1768   AddUsersToWorklist(N);
1769   do {
1770     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1771       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1772   } while (!N->use_empty());
1773   deleteAndRecombine(N);
1774   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1775 }
1776 
1777 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1778 /// ConstantSDNode pointer else nullptr.
1779 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1780   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1781   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1782 }
1783 
1784 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1785   auto BinOpcode = BO->getOpcode();
1786   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1787           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1788           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1789           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1790           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1791           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1792           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1793           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1794           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1795          "Unexpected binary operator");
1796 
1797   // Bail out if any constants are opaque because we can't constant fold those.
1798   SDValue C1 = BO->getOperand(1);
1799   if (!isConstantOrConstantVector(C1, true) &&
1800       !isConstantFPBuildVectorOrConstantFP(C1))
1801     return SDValue();
1802 
1803   // Don't do this unless the old select is going away. We want to eliminate the
1804   // binary operator, not replace a binop with a select.
1805   // TODO: Handle ISD::SELECT_CC.
1806   SDValue Sel = BO->getOperand(0);
1807   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1808     return SDValue();
1809 
1810   SDValue CT = Sel.getOperand(1);
1811   if (!isConstantOrConstantVector(CT, true) &&
1812       !isConstantFPBuildVectorOrConstantFP(CT))
1813     return SDValue();
1814 
1815   SDValue CF = Sel.getOperand(2);
1816   if (!isConstantOrConstantVector(CF, true) &&
1817       !isConstantFPBuildVectorOrConstantFP(CF))
1818     return SDValue();
1819 
1820   // We have a select-of-constants followed by a binary operator with a
1821   // constant. Eliminate the binop by pulling the constant math into the select.
1822   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1823   EVT VT = Sel.getValueType();
1824   SDLoc DL(Sel);
1825   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1826   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1827           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1828          "Failed to constant fold a binop with constant operands");
1829 
1830   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1831   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1832           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1833          "Failed to constant fold a binop with constant operands");
1834 
1835   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1836 }
1837 
1838 SDValue DAGCombiner::visitADD(SDNode *N) {
1839   SDValue N0 = N->getOperand(0);
1840   SDValue N1 = N->getOperand(1);
1841   EVT VT = N0.getValueType();
1842   SDLoc DL(N);
1843 
1844   // fold vector ops
1845   if (VT.isVector()) {
1846     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1847       return FoldedVOp;
1848 
1849     // fold (add x, 0) -> x, vector edition
1850     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1851       return N0;
1852     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1853       return N1;
1854   }
1855 
1856   // fold (add x, undef) -> undef
1857   if (N0.isUndef())
1858     return N0;
1859 
1860   if (N1.isUndef())
1861     return N1;
1862 
1863   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1864     // canonicalize constant to RHS
1865     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1866       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1867     // fold (add c1, c2) -> c1+c2
1868     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1869                                       N1.getNode());
1870   }
1871 
1872   // fold (add x, 0) -> x
1873   if (isNullConstant(N1))
1874     return N0;
1875 
1876   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1877     // fold ((c1-A)+c2) -> (c1+c2)-A
1878     if (N0.getOpcode() == ISD::SUB &&
1879         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1880       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1881       return DAG.getNode(ISD::SUB, DL, VT,
1882                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1883                          N0.getOperand(1));
1884     }
1885 
1886     // add (sext i1 X), 1 -> zext (not i1 X)
1887     // We don't transform this pattern:
1888     //   add (zext i1 X), -1 -> sext (not i1 X)
1889     // because most (?) targets generate better code for the zext form.
1890     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1891         isOneConstantOrOneSplatConstant(N1)) {
1892       SDValue X = N0.getOperand(0);
1893       if ((!LegalOperations ||
1894            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1895             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1896           X.getScalarValueSizeInBits() == 1) {
1897         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1898         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1899       }
1900     }
1901   }
1902 
1903   if (SDValue NewSel = foldBinOpIntoSelect(N))
1904     return NewSel;
1905 
1906   // reassociate add
1907   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1908     return RADD;
1909 
1910   // fold ((0-A) + B) -> B-A
1911   if (N0.getOpcode() == ISD::SUB &&
1912       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1913     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1914 
1915   // fold (A + (0-B)) -> A-B
1916   if (N1.getOpcode() == ISD::SUB &&
1917       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1918     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1919 
1920   // fold (A+(B-A)) -> B
1921   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1922     return N1.getOperand(0);
1923 
1924   // fold ((B-A)+A) -> B
1925   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1926     return N0.getOperand(0);
1927 
1928   // fold (A+(B-(A+C))) to (B-C)
1929   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1930       N0 == N1.getOperand(1).getOperand(0))
1931     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1932                        N1.getOperand(1).getOperand(1));
1933 
1934   // fold (A+(B-(C+A))) to (B-C)
1935   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1936       N0 == N1.getOperand(1).getOperand(1))
1937     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1938                        N1.getOperand(1).getOperand(0));
1939 
1940   // fold (A+((B-A)+or-C)) to (B+or-C)
1941   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1942       N1.getOperand(0).getOpcode() == ISD::SUB &&
1943       N0 == N1.getOperand(0).getOperand(1))
1944     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1945                        N1.getOperand(1));
1946 
1947   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1948   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1949     SDValue N00 = N0.getOperand(0);
1950     SDValue N01 = N0.getOperand(1);
1951     SDValue N10 = N1.getOperand(0);
1952     SDValue N11 = N1.getOperand(1);
1953 
1954     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1955       return DAG.getNode(ISD::SUB, DL, VT,
1956                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1957                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1958   }
1959 
1960   if (SimplifyDemandedBits(SDValue(N, 0)))
1961     return SDValue(N, 0);
1962 
1963   // fold (a+b) -> (a|b) iff a and b share no bits.
1964   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1965       DAG.haveNoCommonBitsSet(N0, N1))
1966     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1967 
1968   if (SDValue Combined = visitADDLike(N0, N1, N))
1969     return Combined;
1970 
1971   if (SDValue Combined = visitADDLike(N1, N0, N))
1972     return Combined;
1973 
1974   return SDValue();
1975 }
1976 
1977 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
1978   bool Masked = false;
1979 
1980   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
1981   while (true) {
1982     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
1983       V = V.getOperand(0);
1984       continue;
1985     }
1986 
1987     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
1988       Masked = true;
1989       V = V.getOperand(0);
1990       continue;
1991     }
1992 
1993     break;
1994   }
1995 
1996   // If this is not a carry, return.
1997   if (V.getResNo() != 1)
1998     return SDValue();
1999 
2000   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2001       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2002     return SDValue();
2003 
2004   // If the result is masked, then no matter what kind of bool it is we can
2005   // return. If it isn't, then we need to make sure the bool type is either 0 or
2006   // 1 and not other values.
2007   if (Masked ||
2008       TLI.getBooleanContents(V.getValueType()) ==
2009           TargetLoweringBase::ZeroOrOneBooleanContent)
2010     return V;
2011 
2012   return SDValue();
2013 }
2014 
2015 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2016   EVT VT = N0.getValueType();
2017   SDLoc DL(LocReference);
2018 
2019   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2020   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2021       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2022     return DAG.getNode(ISD::SUB, DL, VT, N0,
2023                        DAG.getNode(ISD::SHL, DL, VT,
2024                                    N1.getOperand(0).getOperand(1),
2025                                    N1.getOperand(1)));
2026 
2027   if (N1.getOpcode() == ISD::AND) {
2028     SDValue AndOp0 = N1.getOperand(0);
2029     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2030     unsigned DestBits = VT.getScalarSizeInBits();
2031 
2032     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2033     // and similar xforms where the inner op is either ~0 or 0.
2034     if (NumSignBits == DestBits &&
2035         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2036       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2037   }
2038 
2039   // add (sext i1), X -> sub X, (zext i1)
2040   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2041       N0.getOperand(0).getValueType() == MVT::i1 &&
2042       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2043     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2044     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2045   }
2046 
2047   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2048   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2049     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2050     if (TN->getVT() == MVT::i1) {
2051       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2052                                  DAG.getConstant(1, DL, VT));
2053       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2054     }
2055   }
2056 
2057   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2058   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2059     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2060                        N0, N1.getOperand(0), N1.getOperand(2));
2061 
2062   // (add X, Carry) -> (addcarry X, 0, Carry)
2063   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2064     if (SDValue Carry = getAsCarry(TLI, N1))
2065       return DAG.getNode(ISD::ADDCARRY, DL,
2066                          DAG.getVTList(VT, Carry.getValueType()), N0,
2067                          DAG.getConstant(0, DL, VT), Carry);
2068 
2069   return SDValue();
2070 }
2071 
2072 SDValue DAGCombiner::visitADDC(SDNode *N) {
2073   SDValue N0 = N->getOperand(0);
2074   SDValue N1 = N->getOperand(1);
2075   EVT VT = N0.getValueType();
2076   SDLoc DL(N);
2077 
2078   // If the flag result is dead, turn this into an ADD.
2079   if (!N->hasAnyUseOfValue(1))
2080     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2081                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2082 
2083   // canonicalize constant to RHS.
2084   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2085   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2086   if (N0C && !N1C)
2087     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2088 
2089   // fold (addc x, 0) -> x + no carry out
2090   if (isNullConstant(N1))
2091     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2092                                         DL, MVT::Glue));
2093 
2094   // If it cannot overflow, transform into an add.
2095   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2096     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2097                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2098 
2099   return SDValue();
2100 }
2101 
2102 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2103   SDValue N0 = N->getOperand(0);
2104   SDValue N1 = N->getOperand(1);
2105   EVT VT = N0.getValueType();
2106   if (VT.isVector())
2107     return SDValue();
2108 
2109   EVT CarryVT = N->getValueType(1);
2110   SDLoc DL(N);
2111 
2112   // If the flag result is dead, turn this into an ADD.
2113   if (!N->hasAnyUseOfValue(1))
2114     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2115                      DAG.getUNDEF(CarryVT));
2116 
2117   // canonicalize constant to RHS.
2118   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2119   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2120   if (N0C && !N1C)
2121     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2122 
2123   // fold (uaddo x, 0) -> x + no carry out
2124   if (isNullConstant(N1))
2125     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2126 
2127   // If it cannot overflow, transform into an add.
2128   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2129     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2130                      DAG.getConstant(0, DL, CarryVT));
2131 
2132   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2133     return Combined;
2134 
2135   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2136     return Combined;
2137 
2138   return SDValue();
2139 }
2140 
2141 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2142   auto VT = N0.getValueType();
2143 
2144   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2145   // If Y + 1 cannot overflow.
2146   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2147     SDValue Y = N1.getOperand(0);
2148     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2149     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2150       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2151                          N1.getOperand(2));
2152   }
2153 
2154   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2155   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2156     if (SDValue Carry = getAsCarry(TLI, N1))
2157       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2158                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2159 
2160   return SDValue();
2161 }
2162 
2163 SDValue DAGCombiner::visitADDE(SDNode *N) {
2164   SDValue N0 = N->getOperand(0);
2165   SDValue N1 = N->getOperand(1);
2166   SDValue CarryIn = N->getOperand(2);
2167 
2168   // canonicalize constant to RHS
2169   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2170   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2171   if (N0C && !N1C)
2172     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2173                        N1, N0, CarryIn);
2174 
2175   // fold (adde x, y, false) -> (addc x, y)
2176   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2177     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2178 
2179   return SDValue();
2180 }
2181 
2182 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2183   SDValue N0 = N->getOperand(0);
2184   SDValue N1 = N->getOperand(1);
2185   SDValue CarryIn = N->getOperand(2);
2186   SDLoc DL(N);
2187 
2188   // canonicalize constant to RHS
2189   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2190   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2191   if (N0C && !N1C)
2192     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2193 
2194   // fold (addcarry x, y, false) -> (uaddo x, y)
2195   if (isNullConstant(CarryIn))
2196     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2197 
2198   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2199   if (isNullConstant(N0) && isNullConstant(N1)) {
2200     EVT VT = N0.getValueType();
2201     EVT CarryVT = CarryIn.getValueType();
2202     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2203     AddToWorklist(CarryExt.getNode());
2204     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2205                                     DAG.getConstant(1, DL, VT)),
2206                      DAG.getConstant(0, DL, CarryVT));
2207   }
2208 
2209   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2210     return Combined;
2211 
2212   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2213     return Combined;
2214 
2215   return SDValue();
2216 }
2217 
2218 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2219                                        SDNode *N) {
2220   // Iff the flag result is dead:
2221   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2222   if ((N0.getOpcode() == ISD::ADD ||
2223        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2224       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2225     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2226                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2227 
2228   /**
2229    * When one of the addcarry argument is itself a carry, we may be facing
2230    * a diamond carry propagation. In which case we try to transform the DAG
2231    * to ensure linear carry propagation if that is possible.
2232    *
2233    * We are trying to get:
2234    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2235    */
2236   if (auto Y = getAsCarry(TLI, N1)) {
2237     /**
2238      *            (uaddo A, B)
2239      *             /       \
2240      *          Carry      Sum
2241      *            |          \
2242      *            | (addcarry *, 0, Z)
2243      *            |       /
2244      *             \   Carry
2245      *              |   /
2246      * (addcarry X, *, *)
2247      */
2248     if (Y.getOpcode() == ISD::UADDO &&
2249         CarryIn.getResNo() == 1 &&
2250         CarryIn.getOpcode() == ISD::ADDCARRY &&
2251         isNullConstant(CarryIn.getOperand(1)) &&
2252         CarryIn.getOperand(0) == Y.getValue(0)) {
2253       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2254                               Y.getOperand(0), Y.getOperand(1),
2255                               CarryIn.getOperand(2));
2256       AddToWorklist(NewY.getNode());
2257       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2258                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2259                          NewY.getValue(1));
2260     }
2261   }
2262 
2263   return SDValue();
2264 }
2265 
2266 // Since it may not be valid to emit a fold to zero for vector initializers
2267 // check if we can before folding.
2268 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2269                              SelectionDAG &DAG, bool LegalOperations,
2270                              bool LegalTypes) {
2271   if (!VT.isVector())
2272     return DAG.getConstant(0, DL, VT);
2273   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2274     return DAG.getConstant(0, DL, VT);
2275   return SDValue();
2276 }
2277 
2278 SDValue DAGCombiner::visitSUB(SDNode *N) {
2279   SDValue N0 = N->getOperand(0);
2280   SDValue N1 = N->getOperand(1);
2281   EVT VT = N0.getValueType();
2282   SDLoc DL(N);
2283 
2284   // fold vector ops
2285   if (VT.isVector()) {
2286     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2287       return FoldedVOp;
2288 
2289     // fold (sub x, 0) -> x, vector edition
2290     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2291       return N0;
2292   }
2293 
2294   // fold (sub x, x) -> 0
2295   // FIXME: Refactor this and xor and other similar operations together.
2296   if (N0 == N1)
2297     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2298   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2299       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2300     // fold (sub c1, c2) -> c1-c2
2301     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2302                                       N1.getNode());
2303   }
2304 
2305   if (SDValue NewSel = foldBinOpIntoSelect(N))
2306     return NewSel;
2307 
2308   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2309 
2310   // fold (sub x, c) -> (add x, -c)
2311   if (N1C) {
2312     return DAG.getNode(ISD::ADD, DL, VT, N0,
2313                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2314   }
2315 
2316   if (isNullConstantOrNullSplatConstant(N0)) {
2317     unsigned BitWidth = VT.getScalarSizeInBits();
2318     // Right-shifting everything out but the sign bit followed by negation is
2319     // the same as flipping arithmetic/logical shift type without the negation:
2320     // -(X >>u 31) -> (X >>s 31)
2321     // -(X >>s 31) -> (X >>u 31)
2322     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2323       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2324       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2325         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2326         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2327           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2328       }
2329     }
2330 
2331     // 0 - X --> 0 if the sub is NUW.
2332     if (N->getFlags().hasNoUnsignedWrap())
2333       return N0;
2334 
2335     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2336       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2337       // N1 must be 0 because negating the minimum signed value is undefined.
2338       if (N->getFlags().hasNoSignedWrap())
2339         return N0;
2340 
2341       // 0 - X --> X if X is 0 or the minimum signed value.
2342       return N1;
2343     }
2344   }
2345 
2346   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2347   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2348     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2349 
2350   // fold A-(A-B) -> B
2351   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2352     return N1.getOperand(1);
2353 
2354   // fold (A+B)-A -> B
2355   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2356     return N0.getOperand(1);
2357 
2358   // fold (A+B)-B -> A
2359   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2360     return N0.getOperand(0);
2361 
2362   // fold C2-(A+C1) -> (C2-C1)-A
2363   if (N1.getOpcode() == ISD::ADD) {
2364     SDValue N11 = N1.getOperand(1);
2365     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2366         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2367       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2368       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2369     }
2370   }
2371 
2372   // fold ((A+(B+or-C))-B) -> A+or-C
2373   if (N0.getOpcode() == ISD::ADD &&
2374       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2375        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2376       N0.getOperand(1).getOperand(0) == N1)
2377     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2378                        N0.getOperand(1).getOperand(1));
2379 
2380   // fold ((A+(C+B))-B) -> A+C
2381   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2382       N0.getOperand(1).getOperand(1) == N1)
2383     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2384                        N0.getOperand(1).getOperand(0));
2385 
2386   // fold ((A-(B-C))-C) -> A-B
2387   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2388       N0.getOperand(1).getOperand(1) == N1)
2389     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2390                        N0.getOperand(1).getOperand(0));
2391 
2392   // If either operand of a sub is undef, the result is undef
2393   if (N0.isUndef())
2394     return N0;
2395   if (N1.isUndef())
2396     return N1;
2397 
2398   // If the relocation model supports it, consider symbol offsets.
2399   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2400     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2401       // fold (sub Sym, c) -> Sym-c
2402       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2403         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2404                                     GA->getOffset() -
2405                                         (uint64_t)N1C->getSExtValue());
2406       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2407       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2408         if (GA->getGlobal() == GB->getGlobal())
2409           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2410                                  DL, VT);
2411     }
2412 
2413   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2414   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2415     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2416     if (TN->getVT() == MVT::i1) {
2417       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2418                                  DAG.getConstant(1, DL, VT));
2419       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2420     }
2421   }
2422 
2423   return SDValue();
2424 }
2425 
2426 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2427   SDValue N0 = N->getOperand(0);
2428   SDValue N1 = N->getOperand(1);
2429   EVT VT = N0.getValueType();
2430   SDLoc DL(N);
2431 
2432   // If the flag result is dead, turn this into an SUB.
2433   if (!N->hasAnyUseOfValue(1))
2434     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2435                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2436 
2437   // fold (subc x, x) -> 0 + no borrow
2438   if (N0 == N1)
2439     return CombineTo(N, DAG.getConstant(0, DL, VT),
2440                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2441 
2442   // fold (subc x, 0) -> x + no borrow
2443   if (isNullConstant(N1))
2444     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2445 
2446   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2447   if (isAllOnesConstant(N0))
2448     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2449                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2450 
2451   return SDValue();
2452 }
2453 
2454 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2455   SDValue N0 = N->getOperand(0);
2456   SDValue N1 = N->getOperand(1);
2457   EVT VT = N0.getValueType();
2458   if (VT.isVector())
2459     return SDValue();
2460 
2461   EVT CarryVT = N->getValueType(1);
2462   SDLoc DL(N);
2463 
2464   // If the flag result is dead, turn this into an SUB.
2465   if (!N->hasAnyUseOfValue(1))
2466     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2467                      DAG.getUNDEF(CarryVT));
2468 
2469   // fold (usubo x, x) -> 0 + no borrow
2470   if (N0 == N1)
2471     return CombineTo(N, DAG.getConstant(0, DL, VT),
2472                      DAG.getConstant(0, DL, CarryVT));
2473 
2474   // fold (usubo x, 0) -> x + no borrow
2475   if (isNullConstant(N1))
2476     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2477 
2478   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2479   if (isAllOnesConstant(N0))
2480     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2481                      DAG.getConstant(0, DL, CarryVT));
2482 
2483   return SDValue();
2484 }
2485 
2486 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2487   SDValue N0 = N->getOperand(0);
2488   SDValue N1 = N->getOperand(1);
2489   SDValue CarryIn = N->getOperand(2);
2490 
2491   // fold (sube x, y, false) -> (subc x, y)
2492   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2493     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2494 
2495   return SDValue();
2496 }
2497 
2498 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2499   SDValue N0 = N->getOperand(0);
2500   SDValue N1 = N->getOperand(1);
2501   SDValue CarryIn = N->getOperand(2);
2502 
2503   // fold (subcarry x, y, false) -> (usubo x, y)
2504   if (isNullConstant(CarryIn))
2505     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2506 
2507   return SDValue();
2508 }
2509 
2510 SDValue DAGCombiner::visitMUL(SDNode *N) {
2511   SDValue N0 = N->getOperand(0);
2512   SDValue N1 = N->getOperand(1);
2513   EVT VT = N0.getValueType();
2514 
2515   // fold (mul x, undef) -> 0
2516   if (N0.isUndef() || N1.isUndef())
2517     return DAG.getConstant(0, SDLoc(N), VT);
2518 
2519   bool N0IsConst = false;
2520   bool N1IsConst = false;
2521   bool N1IsOpaqueConst = false;
2522   bool N0IsOpaqueConst = false;
2523   APInt ConstValue0, ConstValue1;
2524   // fold vector ops
2525   if (VT.isVector()) {
2526     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2527       return FoldedVOp;
2528 
2529     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2530     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2531   } else {
2532     N0IsConst = isa<ConstantSDNode>(N0);
2533     if (N0IsConst) {
2534       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2535       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2536     }
2537     N1IsConst = isa<ConstantSDNode>(N1);
2538     if (N1IsConst) {
2539       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2540       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2541     }
2542   }
2543 
2544   // fold (mul c1, c2) -> c1*c2
2545   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2546     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2547                                       N0.getNode(), N1.getNode());
2548 
2549   // canonicalize constant to RHS (vector doesn't have to splat)
2550   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2551      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2552     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2553   // fold (mul x, 0) -> 0
2554   if (N1IsConst && ConstValue1.isNullValue())
2555     return N1;
2556   // We require a splat of the entire scalar bit width for non-contiguous
2557   // bit patterns.
2558   bool IsFullSplat =
2559     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2560   // fold (mul x, 1) -> x
2561   if (N1IsConst && ConstValue1.isOneValue() && IsFullSplat)
2562     return N0;
2563 
2564   if (SDValue NewSel = foldBinOpIntoSelect(N))
2565     return NewSel;
2566 
2567   // fold (mul x, -1) -> 0-x
2568   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2569     SDLoc DL(N);
2570     return DAG.getNode(ISD::SUB, DL, VT,
2571                        DAG.getConstant(0, DL, VT), N0);
2572   }
2573   // fold (mul x, (1 << c)) -> x << c
2574   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2575       IsFullSplat) {
2576     SDLoc DL(N);
2577     return DAG.getNode(ISD::SHL, DL, VT, N0,
2578                        DAG.getConstant(ConstValue1.logBase2(), DL,
2579                                        getShiftAmountTy(N0.getValueType())));
2580   }
2581   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2582   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2583       IsFullSplat) {
2584     unsigned Log2Val = (-ConstValue1).logBase2();
2585     SDLoc DL(N);
2586     // FIXME: If the input is something that is easily negated (e.g. a
2587     // single-use add), we should put the negate there.
2588     return DAG.getNode(ISD::SUB, DL, VT,
2589                        DAG.getConstant(0, DL, VT),
2590                        DAG.getNode(ISD::SHL, DL, VT, N0,
2591                             DAG.getConstant(Log2Val, DL,
2592                                       getShiftAmountTy(N0.getValueType()))));
2593   }
2594 
2595   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2596   if (N0.getOpcode() == ISD::SHL &&
2597       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2598       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2599     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2600     if (isConstantOrConstantVector(C3))
2601       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2602   }
2603 
2604   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2605   // use.
2606   {
2607     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2608 
2609     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2610     if (N0.getOpcode() == ISD::SHL &&
2611         isConstantOrConstantVector(N0.getOperand(1)) &&
2612         N0.getNode()->hasOneUse()) {
2613       Sh = N0; Y = N1;
2614     } else if (N1.getOpcode() == ISD::SHL &&
2615                isConstantOrConstantVector(N1.getOperand(1)) &&
2616                N1.getNode()->hasOneUse()) {
2617       Sh = N1; Y = N0;
2618     }
2619 
2620     if (Sh.getNode()) {
2621       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2622       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2623     }
2624   }
2625 
2626   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2627   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2628       N0.getOpcode() == ISD::ADD &&
2629       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2630       isMulAddWithConstProfitable(N, N0, N1))
2631       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2632                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2633                                      N0.getOperand(0), N1),
2634                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2635                                      N0.getOperand(1), N1));
2636 
2637   // reassociate mul
2638   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2639     return RMUL;
2640 
2641   return SDValue();
2642 }
2643 
2644 /// Return true if divmod libcall is available.
2645 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2646                                      const TargetLowering &TLI) {
2647   RTLIB::Libcall LC;
2648   EVT NodeType = Node->getValueType(0);
2649   if (!NodeType.isSimple())
2650     return false;
2651   switch (NodeType.getSimpleVT().SimpleTy) {
2652   default: return false; // No libcall for vector types.
2653   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2654   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2655   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2656   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2657   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2658   }
2659 
2660   return TLI.getLibcallName(LC) != nullptr;
2661 }
2662 
2663 /// Issue divrem if both quotient and remainder are needed.
2664 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2665   if (Node->use_empty())
2666     return SDValue(); // This is a dead node, leave it alone.
2667 
2668   unsigned Opcode = Node->getOpcode();
2669   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2670   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2671 
2672   // DivMod lib calls can still work on non-legal types if using lib-calls.
2673   EVT VT = Node->getValueType(0);
2674   if (VT.isVector() || !VT.isInteger())
2675     return SDValue();
2676 
2677   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2678     return SDValue();
2679 
2680   // If DIVREM is going to get expanded into a libcall,
2681   // but there is no libcall available, then don't combine.
2682   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2683       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2684     return SDValue();
2685 
2686   // If div is legal, it's better to do the normal expansion
2687   unsigned OtherOpcode = 0;
2688   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2689     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2690     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2691       return SDValue();
2692   } else {
2693     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2694     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2695       return SDValue();
2696   }
2697 
2698   SDValue Op0 = Node->getOperand(0);
2699   SDValue Op1 = Node->getOperand(1);
2700   SDValue combined;
2701   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2702          UE = Op0.getNode()->use_end(); UI != UE;) {
2703     SDNode *User = *UI++;
2704     if (User == Node || User->use_empty())
2705       continue;
2706     // Convert the other matching node(s), too;
2707     // otherwise, the DIVREM may get target-legalized into something
2708     // target-specific that we won't be able to recognize.
2709     unsigned UserOpc = User->getOpcode();
2710     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2711         User->getOperand(0) == Op0 &&
2712         User->getOperand(1) == Op1) {
2713       if (!combined) {
2714         if (UserOpc == OtherOpcode) {
2715           SDVTList VTs = DAG.getVTList(VT, VT);
2716           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2717         } else if (UserOpc == DivRemOpc) {
2718           combined = SDValue(User, 0);
2719         } else {
2720           assert(UserOpc == Opcode);
2721           continue;
2722         }
2723       }
2724       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2725         CombineTo(User, combined);
2726       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2727         CombineTo(User, combined.getValue(1));
2728     }
2729   }
2730   return combined;
2731 }
2732 
2733 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2734   SDValue N0 = N->getOperand(0);
2735   SDValue N1 = N->getOperand(1);
2736   EVT VT = N->getValueType(0);
2737   SDLoc DL(N);
2738 
2739   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2740     return DAG.getUNDEF(VT);
2741 
2742   // undef / X -> 0
2743   // undef % X -> 0
2744   if (N0.isUndef())
2745     return DAG.getConstant(0, DL, VT);
2746 
2747   return SDValue();
2748 }
2749 
2750 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2751   SDValue N0 = N->getOperand(0);
2752   SDValue N1 = N->getOperand(1);
2753   EVT VT = N->getValueType(0);
2754 
2755   // fold vector ops
2756   if (VT.isVector())
2757     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2758       return FoldedVOp;
2759 
2760   SDLoc DL(N);
2761 
2762   // fold (sdiv c1, c2) -> c1/c2
2763   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2764   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2765   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2766     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2767   // fold (sdiv X, 1) -> X
2768   if (N1C && N1C->isOne())
2769     return N0;
2770   // fold (sdiv X, -1) -> 0-X
2771   if (N1C && N1C->isAllOnesValue())
2772     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2773 
2774   if (SDValue V = simplifyDivRem(N, DAG))
2775     return V;
2776 
2777   if (SDValue NewSel = foldBinOpIntoSelect(N))
2778     return NewSel;
2779 
2780   // If we know the sign bits of both operands are zero, strength reduce to a
2781   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2782   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2783     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2784 
2785   // fold (sdiv X, pow2) -> simple ops after legalize
2786   // FIXME: We check for the exact bit here because the generic lowering gives
2787   // better results in that case. The target-specific lowering should learn how
2788   // to handle exact sdivs efficiently.
2789   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2790       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2791                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2792     // Target-specific implementation of sdiv x, pow2.
2793     if (SDValue Res = BuildSDIVPow2(N))
2794       return Res;
2795 
2796     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2797 
2798     // Splat the sign bit into the register
2799     SDValue SGN =
2800         DAG.getNode(ISD::SRA, DL, VT, N0,
2801                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2802                                     getShiftAmountTy(N0.getValueType())));
2803     AddToWorklist(SGN.getNode());
2804 
2805     // Add (N0 < 0) ? abs2 - 1 : 0;
2806     SDValue SRL =
2807         DAG.getNode(ISD::SRL, DL, VT, SGN,
2808                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2809                                     getShiftAmountTy(SGN.getValueType())));
2810     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2811     AddToWorklist(SRL.getNode());
2812     AddToWorklist(ADD.getNode());    // Divide by pow2
2813     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2814                   DAG.getConstant(lg2, DL,
2815                                   getShiftAmountTy(ADD.getValueType())));
2816 
2817     // If we're dividing by a positive value, we're done.  Otherwise, we must
2818     // negate the result.
2819     if (N1C->getAPIntValue().isNonNegative())
2820       return SRA;
2821 
2822     AddToWorklist(SRA.getNode());
2823     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2824   }
2825 
2826   // If integer divide is expensive and we satisfy the requirements, emit an
2827   // alternate sequence.  Targets may check function attributes for size/speed
2828   // trade-offs.
2829   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2830   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2831     if (SDValue Op = BuildSDIV(N))
2832       return Op;
2833 
2834   // sdiv, srem -> sdivrem
2835   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2836   // true.  Otherwise, we break the simplification logic in visitREM().
2837   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2838     if (SDValue DivRem = useDivRem(N))
2839         return DivRem;
2840 
2841   return SDValue();
2842 }
2843 
2844 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2845   SDValue N0 = N->getOperand(0);
2846   SDValue N1 = N->getOperand(1);
2847   EVT VT = N->getValueType(0);
2848 
2849   // fold vector ops
2850   if (VT.isVector())
2851     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2852       return FoldedVOp;
2853 
2854   SDLoc DL(N);
2855 
2856   // fold (udiv c1, c2) -> c1/c2
2857   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2858   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2859   if (N0C && N1C)
2860     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2861                                                     N0C, N1C))
2862       return Folded;
2863 
2864   if (SDValue V = simplifyDivRem(N, DAG))
2865     return V;
2866 
2867   if (SDValue NewSel = foldBinOpIntoSelect(N))
2868     return NewSel;
2869 
2870   // fold (udiv x, (1 << c)) -> x >>u c
2871   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2872       DAG.isKnownToBeAPowerOfTwo(N1)) {
2873     SDValue LogBase2 = BuildLogBase2(N1, DL);
2874     AddToWorklist(LogBase2.getNode());
2875 
2876     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2877     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2878     AddToWorklist(Trunc.getNode());
2879     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2880   }
2881 
2882   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2883   if (N1.getOpcode() == ISD::SHL) {
2884     SDValue N10 = N1.getOperand(0);
2885     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2886         DAG.isKnownToBeAPowerOfTwo(N10)) {
2887       SDValue LogBase2 = BuildLogBase2(N10, DL);
2888       AddToWorklist(LogBase2.getNode());
2889 
2890       EVT ADDVT = N1.getOperand(1).getValueType();
2891       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2892       AddToWorklist(Trunc.getNode());
2893       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2894       AddToWorklist(Add.getNode());
2895       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2896     }
2897   }
2898 
2899   // fold (udiv x, c) -> alternate
2900   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2901   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2902     if (SDValue Op = BuildUDIV(N))
2903       return Op;
2904 
2905   // sdiv, srem -> sdivrem
2906   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2907   // true.  Otherwise, we break the simplification logic in visitREM().
2908   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2909     if (SDValue DivRem = useDivRem(N))
2910         return DivRem;
2911 
2912   return SDValue();
2913 }
2914 
2915 // handles ISD::SREM and ISD::UREM
2916 SDValue DAGCombiner::visitREM(SDNode *N) {
2917   unsigned Opcode = N->getOpcode();
2918   SDValue N0 = N->getOperand(0);
2919   SDValue N1 = N->getOperand(1);
2920   EVT VT = N->getValueType(0);
2921   bool isSigned = (Opcode == ISD::SREM);
2922   SDLoc DL(N);
2923 
2924   // fold (rem c1, c2) -> c1%c2
2925   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2926   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2927   if (N0C && N1C)
2928     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2929       return Folded;
2930 
2931   if (SDValue V = simplifyDivRem(N, DAG))
2932     return V;
2933 
2934   if (SDValue NewSel = foldBinOpIntoSelect(N))
2935     return NewSel;
2936 
2937   if (isSigned) {
2938     // If we know the sign bits of both operands are zero, strength reduce to a
2939     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2940     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2941       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2942   } else {
2943     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2944     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2945       // fold (urem x, pow2) -> (and x, pow2-1)
2946       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2947       AddToWorklist(Add.getNode());
2948       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2949     }
2950     if (N1.getOpcode() == ISD::SHL &&
2951         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2952       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2953       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2954       AddToWorklist(Add.getNode());
2955       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2956     }
2957   }
2958 
2959   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2960 
2961   // If X/C can be simplified by the division-by-constant logic, lower
2962   // X%C to the equivalent of X-X/C*C.
2963   // To avoid mangling nodes, this simplification requires that the combine()
2964   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2965   // against this by skipping the simplification if isIntDivCheap().  When
2966   // div is not cheap, combine will not return a DIVREM.  Regardless,
2967   // checking cheapness here makes sense since the simplification results in
2968   // fatter code.
2969   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2970     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2971     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2972     AddToWorklist(Div.getNode());
2973     SDValue OptimizedDiv = combine(Div.getNode());
2974     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2975       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2976              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2977       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2978       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2979       AddToWorklist(Mul.getNode());
2980       return Sub;
2981     }
2982   }
2983 
2984   // sdiv, srem -> sdivrem
2985   if (SDValue DivRem = useDivRem(N))
2986     return DivRem.getValue(1);
2987 
2988   return SDValue();
2989 }
2990 
2991 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2992   SDValue N0 = N->getOperand(0);
2993   SDValue N1 = N->getOperand(1);
2994   EVT VT = N->getValueType(0);
2995   SDLoc DL(N);
2996 
2997   // fold (mulhs x, 0) -> 0
2998   if (isNullConstant(N1))
2999     return N1;
3000   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3001   if (isOneConstant(N1)) {
3002     SDLoc DL(N);
3003     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3004                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3005                                        getShiftAmountTy(N0.getValueType())));
3006   }
3007   // fold (mulhs x, undef) -> 0
3008   if (N0.isUndef() || N1.isUndef())
3009     return DAG.getConstant(0, SDLoc(N), VT);
3010 
3011   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3012   // plus a shift.
3013   if (VT.isSimple() && !VT.isVector()) {
3014     MVT Simple = VT.getSimpleVT();
3015     unsigned SimpleSize = Simple.getSizeInBits();
3016     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3017     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3018       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3019       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3020       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3021       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3022             DAG.getConstant(SimpleSize, DL,
3023                             getShiftAmountTy(N1.getValueType())));
3024       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3025     }
3026   }
3027 
3028   return SDValue();
3029 }
3030 
3031 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3032   SDValue N0 = N->getOperand(0);
3033   SDValue N1 = N->getOperand(1);
3034   EVT VT = N->getValueType(0);
3035   SDLoc DL(N);
3036 
3037   // fold (mulhu x, 0) -> 0
3038   if (isNullConstant(N1))
3039     return N1;
3040   // fold (mulhu x, 1) -> 0
3041   if (isOneConstant(N1))
3042     return DAG.getConstant(0, DL, N0.getValueType());
3043   // fold (mulhu x, undef) -> 0
3044   if (N0.isUndef() || N1.isUndef())
3045     return DAG.getConstant(0, DL, VT);
3046 
3047   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3048   // plus a shift.
3049   if (VT.isSimple() && !VT.isVector()) {
3050     MVT Simple = VT.getSimpleVT();
3051     unsigned SimpleSize = Simple.getSizeInBits();
3052     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3053     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3054       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3055       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3056       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3057       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3058             DAG.getConstant(SimpleSize, DL,
3059                             getShiftAmountTy(N1.getValueType())));
3060       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3061     }
3062   }
3063 
3064   return SDValue();
3065 }
3066 
3067 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3068 /// give the opcodes for the two computations that are being performed. Return
3069 /// true if a simplification was made.
3070 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3071                                                 unsigned HiOp) {
3072   // If the high half is not needed, just compute the low half.
3073   bool HiExists = N->hasAnyUseOfValue(1);
3074   if (!HiExists &&
3075       (!LegalOperations ||
3076        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3077     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3078     return CombineTo(N, Res, Res);
3079   }
3080 
3081   // If the low half is not needed, just compute the high half.
3082   bool LoExists = N->hasAnyUseOfValue(0);
3083   if (!LoExists &&
3084       (!LegalOperations ||
3085        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3086     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3087     return CombineTo(N, Res, Res);
3088   }
3089 
3090   // If both halves are used, return as it is.
3091   if (LoExists && HiExists)
3092     return SDValue();
3093 
3094   // If the two computed results can be simplified separately, separate them.
3095   if (LoExists) {
3096     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3097     AddToWorklist(Lo.getNode());
3098     SDValue LoOpt = combine(Lo.getNode());
3099     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3100         (!LegalOperations ||
3101          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3102       return CombineTo(N, LoOpt, LoOpt);
3103   }
3104 
3105   if (HiExists) {
3106     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3107     AddToWorklist(Hi.getNode());
3108     SDValue HiOpt = combine(Hi.getNode());
3109     if (HiOpt.getNode() && HiOpt != Hi &&
3110         (!LegalOperations ||
3111          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3112       return CombineTo(N, HiOpt, HiOpt);
3113   }
3114 
3115   return SDValue();
3116 }
3117 
3118 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3119   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3120     return Res;
3121 
3122   EVT VT = N->getValueType(0);
3123   SDLoc DL(N);
3124 
3125   // If the type is twice as wide is legal, transform the mulhu to a wider
3126   // multiply plus a shift.
3127   if (VT.isSimple() && !VT.isVector()) {
3128     MVT Simple = VT.getSimpleVT();
3129     unsigned SimpleSize = Simple.getSizeInBits();
3130     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3131     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3132       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3133       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3134       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3135       // Compute the high part as N1.
3136       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3137             DAG.getConstant(SimpleSize, DL,
3138                             getShiftAmountTy(Lo.getValueType())));
3139       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3140       // Compute the low part as N0.
3141       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3142       return CombineTo(N, Lo, Hi);
3143     }
3144   }
3145 
3146   return SDValue();
3147 }
3148 
3149 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3150   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3151     return Res;
3152 
3153   EVT VT = N->getValueType(0);
3154   SDLoc DL(N);
3155 
3156   // If the type is twice as wide is legal, transform the mulhu to a wider
3157   // multiply plus a shift.
3158   if (VT.isSimple() && !VT.isVector()) {
3159     MVT Simple = VT.getSimpleVT();
3160     unsigned SimpleSize = Simple.getSizeInBits();
3161     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3162     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3163       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3164       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3165       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3166       // Compute the high part as N1.
3167       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3168             DAG.getConstant(SimpleSize, DL,
3169                             getShiftAmountTy(Lo.getValueType())));
3170       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3171       // Compute the low part as N0.
3172       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3173       return CombineTo(N, Lo, Hi);
3174     }
3175   }
3176 
3177   return SDValue();
3178 }
3179 
3180 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3181   // (smulo x, 2) -> (saddo x, x)
3182   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3183     if (C2->getAPIntValue() == 2)
3184       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3185                          N->getOperand(0), N->getOperand(0));
3186 
3187   return SDValue();
3188 }
3189 
3190 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3191   // (umulo x, 2) -> (uaddo x, x)
3192   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3193     if (C2->getAPIntValue() == 2)
3194       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3195                          N->getOperand(0), N->getOperand(0));
3196 
3197   return SDValue();
3198 }
3199 
3200 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3201   SDValue N0 = N->getOperand(0);
3202   SDValue N1 = N->getOperand(1);
3203   EVT VT = N0.getValueType();
3204 
3205   // fold vector ops
3206   if (VT.isVector())
3207     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3208       return FoldedVOp;
3209 
3210   // fold (add c1, c2) -> c1+c2
3211   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3212   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3213   if (N0C && N1C)
3214     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3215 
3216   // canonicalize constant to RHS
3217   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3218      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3219     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3220 
3221   return SDValue();
3222 }
3223 
3224 /// If this is a binary operator with two operands of the same opcode, try to
3225 /// simplify it.
3226 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3227   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3228   EVT VT = N0.getValueType();
3229   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3230 
3231   // Bail early if none of these transforms apply.
3232   if (N0.getNumOperands() == 0) return SDValue();
3233 
3234   // For each of OP in AND/OR/XOR:
3235   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3236   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3237   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3238   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3239   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3240   //
3241   // do not sink logical op inside of a vector extend, since it may combine
3242   // into a vsetcc.
3243   EVT Op0VT = N0.getOperand(0).getValueType();
3244   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3245        N0.getOpcode() == ISD::SIGN_EXTEND ||
3246        N0.getOpcode() == ISD::BSWAP ||
3247        // Avoid infinite looping with PromoteIntBinOp.
3248        (N0.getOpcode() == ISD::ANY_EXTEND &&
3249         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3250        (N0.getOpcode() == ISD::TRUNCATE &&
3251         (!TLI.isZExtFree(VT, Op0VT) ||
3252          !TLI.isTruncateFree(Op0VT, VT)) &&
3253         TLI.isTypeLegal(Op0VT))) &&
3254       !VT.isVector() &&
3255       Op0VT == N1.getOperand(0).getValueType() &&
3256       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3257     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3258                                  N0.getOperand(0).getValueType(),
3259                                  N0.getOperand(0), N1.getOperand(0));
3260     AddToWorklist(ORNode.getNode());
3261     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3262   }
3263 
3264   // For each of OP in SHL/SRL/SRA/AND...
3265   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3266   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3267   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3268   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3269        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3270       N0.getOperand(1) == N1.getOperand(1)) {
3271     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3272                                  N0.getOperand(0).getValueType(),
3273                                  N0.getOperand(0), N1.getOperand(0));
3274     AddToWorklist(ORNode.getNode());
3275     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3276                        ORNode, N0.getOperand(1));
3277   }
3278 
3279   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3280   // Only perform this optimization up until type legalization, before
3281   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3282   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3283   // we don't want to undo this promotion.
3284   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3285   // on scalars.
3286   if ((N0.getOpcode() == ISD::BITCAST ||
3287        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3288        Level <= AfterLegalizeTypes) {
3289     SDValue In0 = N0.getOperand(0);
3290     SDValue In1 = N1.getOperand(0);
3291     EVT In0Ty = In0.getValueType();
3292     EVT In1Ty = In1.getValueType();
3293     SDLoc DL(N);
3294     // If both incoming values are integers, and the original types are the
3295     // same.
3296     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3297       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3298       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3299       AddToWorklist(Op.getNode());
3300       return BC;
3301     }
3302   }
3303 
3304   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3305   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3306   // If both shuffles use the same mask, and both shuffle within a single
3307   // vector, then it is worthwhile to move the swizzle after the operation.
3308   // The type-legalizer generates this pattern when loading illegal
3309   // vector types from memory. In many cases this allows additional shuffle
3310   // optimizations.
3311   // There are other cases where moving the shuffle after the xor/and/or
3312   // is profitable even if shuffles don't perform a swizzle.
3313   // If both shuffles use the same mask, and both shuffles have the same first
3314   // or second operand, then it might still be profitable to move the shuffle
3315   // after the xor/and/or operation.
3316   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3317     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3318     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3319 
3320     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3321            "Inputs to shuffles are not the same type");
3322 
3323     // Check that both shuffles use the same mask. The masks are known to be of
3324     // the same length because the result vector type is the same.
3325     // Check also that shuffles have only one use to avoid introducing extra
3326     // instructions.
3327     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3328         SVN0->getMask().equals(SVN1->getMask())) {
3329       SDValue ShOp = N0->getOperand(1);
3330 
3331       // Don't try to fold this node if it requires introducing a
3332       // build vector of all zeros that might be illegal at this stage.
3333       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3334         if (!LegalTypes)
3335           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3336         else
3337           ShOp = SDValue();
3338       }
3339 
3340       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3341       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3342       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3343       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3344         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3345                                       N0->getOperand(0), N1->getOperand(0));
3346         AddToWorklist(NewNode.getNode());
3347         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3348                                     SVN0->getMask());
3349       }
3350 
3351       // Don't try to fold this node if it requires introducing a
3352       // build vector of all zeros that might be illegal at this stage.
3353       ShOp = N0->getOperand(0);
3354       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3355         if (!LegalTypes)
3356           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3357         else
3358           ShOp = SDValue();
3359       }
3360 
3361       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3362       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3363       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3364       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3365         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3366                                       N0->getOperand(1), N1->getOperand(1));
3367         AddToWorklist(NewNode.getNode());
3368         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3369                                     SVN0->getMask());
3370       }
3371     }
3372   }
3373 
3374   return SDValue();
3375 }
3376 
3377 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3378 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3379                                        const SDLoc &DL) {
3380   SDValue LL, LR, RL, RR, N0CC, N1CC;
3381   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3382       !isSetCCEquivalent(N1, RL, RR, N1CC))
3383     return SDValue();
3384 
3385   assert(N0.getValueType() == N1.getValueType() &&
3386          "Unexpected operand types for bitwise logic op");
3387   assert(LL.getValueType() == LR.getValueType() &&
3388          RL.getValueType() == RR.getValueType() &&
3389          "Unexpected operand types for setcc");
3390 
3391   // If we're here post-legalization or the logic op type is not i1, the logic
3392   // op type must match a setcc result type. Also, all folds require new
3393   // operations on the left and right operands, so those types must match.
3394   EVT VT = N0.getValueType();
3395   EVT OpVT = LL.getValueType();
3396   if (LegalOperations || VT != MVT::i1)
3397     if (VT != getSetCCResultType(OpVT))
3398       return SDValue();
3399   if (OpVT != RL.getValueType())
3400     return SDValue();
3401 
3402   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3403   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3404   bool IsInteger = OpVT.isInteger();
3405   if (LR == RR && CC0 == CC1 && IsInteger) {
3406     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3407     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3408 
3409     // All bits clear?
3410     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3411     // All sign bits clear?
3412     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3413     // Any bits set?
3414     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3415     // Any sign bits set?
3416     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3417 
3418     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3419     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3420     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3421     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3422     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3423       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3424       AddToWorklist(Or.getNode());
3425       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3426     }
3427 
3428     // All bits set?
3429     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3430     // All sign bits set?
3431     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3432     // Any bits clear?
3433     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3434     // Any sign bits clear?
3435     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3436 
3437     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3438     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3439     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3440     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3441     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3442       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3443       AddToWorklist(And.getNode());
3444       return DAG.getSetCC(DL, VT, And, LR, CC1);
3445     }
3446   }
3447 
3448   // TODO: What is the 'or' equivalent of this fold?
3449   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3450   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3451       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3452        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3453     SDValue One = DAG.getConstant(1, DL, OpVT);
3454     SDValue Two = DAG.getConstant(2, DL, OpVT);
3455     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3456     AddToWorklist(Add.getNode());
3457     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3458   }
3459 
3460   // Try more general transforms if the predicates match and the only user of
3461   // the compares is the 'and' or 'or'.
3462   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3463       N0.hasOneUse() && N1.hasOneUse()) {
3464     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3465     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3466     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3467       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3468       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3469       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3470       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3471       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3472     }
3473   }
3474 
3475   // Canonicalize equivalent operands to LL == RL.
3476   if (LL == RR && LR == RL) {
3477     CC1 = ISD::getSetCCSwappedOperands(CC1);
3478     std::swap(RL, RR);
3479   }
3480 
3481   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3482   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3483   if (LL == RL && LR == RR) {
3484     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3485                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3486     if (NewCC != ISD::SETCC_INVALID &&
3487         (!LegalOperations ||
3488          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3489           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3490       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3491   }
3492 
3493   return SDValue();
3494 }
3495 
3496 /// This contains all DAGCombine rules which reduce two values combined by
3497 /// an And operation to a single value. This makes them reusable in the context
3498 /// of visitSELECT(). Rules involving constants are not included as
3499 /// visitSELECT() already handles those cases.
3500 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3501   EVT VT = N1.getValueType();
3502   SDLoc DL(N);
3503 
3504   // fold (and x, undef) -> 0
3505   if (N0.isUndef() || N1.isUndef())
3506     return DAG.getConstant(0, DL, VT);
3507 
3508   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3509     return V;
3510 
3511   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3512       VT.getSizeInBits() <= 64) {
3513     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3514       APInt ADDC = ADDI->getAPIntValue();
3515       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3516         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3517         // immediate for an add, but it is legal if its top c2 bits are set,
3518         // transform the ADD so the immediate doesn't need to be materialized
3519         // in a register.
3520         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3521           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3522                                              SRLI->getZExtValue());
3523           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3524             ADDC |= Mask;
3525             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3526               SDLoc DL0(N0);
3527               SDValue NewAdd =
3528                 DAG.getNode(ISD::ADD, DL0, VT,
3529                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3530               CombineTo(N0.getNode(), NewAdd);
3531               // Return N so it doesn't get rechecked!
3532               return SDValue(N, 0);
3533             }
3534           }
3535         }
3536       }
3537     }
3538   }
3539 
3540   // Reduce bit extract of low half of an integer to the narrower type.
3541   // (and (srl i64:x, K), KMask) ->
3542   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3543   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3544     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3545       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3546         unsigned Size = VT.getSizeInBits();
3547         const APInt &AndMask = CAnd->getAPIntValue();
3548         unsigned ShiftBits = CShift->getZExtValue();
3549 
3550         // Bail out, this node will probably disappear anyway.
3551         if (ShiftBits == 0)
3552           return SDValue();
3553 
3554         unsigned MaskBits = AndMask.countTrailingOnes();
3555         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3556 
3557         if (AndMask.isMask() &&
3558             // Required bits must not span the two halves of the integer and
3559             // must fit in the half size type.
3560             (ShiftBits + MaskBits <= Size / 2) &&
3561             TLI.isNarrowingProfitable(VT, HalfVT) &&
3562             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3563             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3564             TLI.isTruncateFree(VT, HalfVT) &&
3565             TLI.isZExtFree(HalfVT, VT)) {
3566           // The isNarrowingProfitable is to avoid regressions on PPC and
3567           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3568           // on downstream users of this. Those patterns could probably be
3569           // extended to handle extensions mixed in.
3570 
3571           SDValue SL(N0);
3572           assert(MaskBits <= Size);
3573 
3574           // Extracting the highest bit of the low half.
3575           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3576           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3577                                       N0.getOperand(0));
3578 
3579           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3580           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3581           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3582           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3583           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3584         }
3585       }
3586     }
3587   }
3588 
3589   return SDValue();
3590 }
3591 
3592 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3593                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3594                                    bool &NarrowLoad) {
3595   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3596 
3597   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3598     return false;
3599 
3600   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3601   LoadedVT = LoadN->getMemoryVT();
3602 
3603   if (ExtVT == LoadedVT &&
3604       (!LegalOperations ||
3605        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3606     // ZEXTLOAD will match without needing to change the size of the value being
3607     // loaded.
3608     NarrowLoad = false;
3609     return true;
3610   }
3611 
3612   // Do not change the width of a volatile load.
3613   if (LoadN->isVolatile())
3614     return false;
3615 
3616   // Do not generate loads of non-round integer types since these can
3617   // be expensive (and would be wrong if the type is not byte sized).
3618   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3619     return false;
3620 
3621   if (LegalOperations &&
3622       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3623     return false;
3624 
3625   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3626     return false;
3627 
3628   NarrowLoad = true;
3629   return true;
3630 }
3631 
3632 SDValue DAGCombiner::visitAND(SDNode *N) {
3633   SDValue N0 = N->getOperand(0);
3634   SDValue N1 = N->getOperand(1);
3635   EVT VT = N1.getValueType();
3636 
3637   // x & x --> x
3638   if (N0 == N1)
3639     return N0;
3640 
3641   // fold vector ops
3642   if (VT.isVector()) {
3643     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3644       return FoldedVOp;
3645 
3646     // fold (and x, 0) -> 0, vector edition
3647     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3648       // do not return N0, because undef node may exist in N0
3649       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3650                              SDLoc(N), N0.getValueType());
3651     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3652       // do not return N1, because undef node may exist in N1
3653       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3654                              SDLoc(N), N1.getValueType());
3655 
3656     // fold (and x, -1) -> x, vector edition
3657     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3658       return N1;
3659     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3660       return N0;
3661   }
3662 
3663   // fold (and c1, c2) -> c1&c2
3664   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3665   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3666   if (N0C && N1C && !N1C->isOpaque())
3667     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3668   // canonicalize constant to RHS
3669   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3670      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3671     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3672   // fold (and x, -1) -> x
3673   if (isAllOnesConstant(N1))
3674     return N0;
3675   // if (and x, c) is known to be zero, return 0
3676   unsigned BitWidth = VT.getScalarSizeInBits();
3677   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3678                                    APInt::getAllOnesValue(BitWidth)))
3679     return DAG.getConstant(0, SDLoc(N), VT);
3680 
3681   if (SDValue NewSel = foldBinOpIntoSelect(N))
3682     return NewSel;
3683 
3684   // reassociate and
3685   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3686     return RAND;
3687   // fold (and (or x, C), D) -> D if (C & D) == D
3688   if (N1C && N0.getOpcode() == ISD::OR)
3689     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3690       if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3691         return N1;
3692   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3693   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3694     SDValue N0Op0 = N0.getOperand(0);
3695     APInt Mask = ~N1C->getAPIntValue();
3696     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3697     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3698       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3699                                  N0.getValueType(), N0Op0);
3700 
3701       // Replace uses of the AND with uses of the Zero extend node.
3702       CombineTo(N, Zext);
3703 
3704       // We actually want to replace all uses of the any_extend with the
3705       // zero_extend, to avoid duplicating things.  This will later cause this
3706       // AND to be folded.
3707       CombineTo(N0.getNode(), Zext);
3708       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3709     }
3710   }
3711   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3712   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3713   // already be zero by virtue of the width of the base type of the load.
3714   //
3715   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3716   // more cases.
3717   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3718        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3719        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3720        N0.getOperand(0).getResNo() == 0) ||
3721       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3722     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3723                                          N0 : N0.getOperand(0) );
3724 
3725     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3726     // This can be a pure constant or a vector splat, in which case we treat the
3727     // vector as a scalar and use the splat value.
3728     APInt Constant = APInt::getNullValue(1);
3729     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3730       Constant = C->getAPIntValue();
3731     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3732       APInt SplatValue, SplatUndef;
3733       unsigned SplatBitSize;
3734       bool HasAnyUndefs;
3735       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3736                                              SplatBitSize, HasAnyUndefs);
3737       if (IsSplat) {
3738         // Undef bits can contribute to a possible optimisation if set, so
3739         // set them.
3740         SplatValue |= SplatUndef;
3741 
3742         // The splat value may be something like "0x00FFFFFF", which means 0 for
3743         // the first vector value and FF for the rest, repeating. We need a mask
3744         // that will apply equally to all members of the vector, so AND all the
3745         // lanes of the constant together.
3746         EVT VT = Vector->getValueType(0);
3747         unsigned BitWidth = VT.getScalarSizeInBits();
3748 
3749         // If the splat value has been compressed to a bitlength lower
3750         // than the size of the vector lane, we need to re-expand it to
3751         // the lane size.
3752         if (BitWidth > SplatBitSize)
3753           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3754                SplatBitSize < BitWidth;
3755                SplatBitSize = SplatBitSize * 2)
3756             SplatValue |= SplatValue.shl(SplatBitSize);
3757 
3758         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3759         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3760         if (SplatBitSize % BitWidth == 0) {
3761           Constant = APInt::getAllOnesValue(BitWidth);
3762           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3763             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3764         }
3765       }
3766     }
3767 
3768     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3769     // actually legal and isn't going to get expanded, else this is a false
3770     // optimisation.
3771     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3772                                                     Load->getValueType(0),
3773                                                     Load->getMemoryVT());
3774 
3775     // Resize the constant to the same size as the original memory access before
3776     // extension. If it is still the AllOnesValue then this AND is completely
3777     // unneeded.
3778     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3779 
3780     bool B;
3781     switch (Load->getExtensionType()) {
3782     default: B = false; break;
3783     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3784     case ISD::ZEXTLOAD:
3785     case ISD::NON_EXTLOAD: B = true; break;
3786     }
3787 
3788     if (B && Constant.isAllOnesValue()) {
3789       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3790       // preserve semantics once we get rid of the AND.
3791       SDValue NewLoad(Load, 0);
3792 
3793       // Fold the AND away. NewLoad may get replaced immediately.
3794       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3795 
3796       if (Load->getExtensionType() == ISD::EXTLOAD) {
3797         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3798                               Load->getValueType(0), SDLoc(Load),
3799                               Load->getChain(), Load->getBasePtr(),
3800                               Load->getOffset(), Load->getMemoryVT(),
3801                               Load->getMemOperand());
3802         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3803         if (Load->getNumValues() == 3) {
3804           // PRE/POST_INC loads have 3 values.
3805           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3806                            NewLoad.getValue(2) };
3807           CombineTo(Load, To, 3, true);
3808         } else {
3809           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3810         }
3811       }
3812 
3813       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3814     }
3815   }
3816 
3817   // fold (and (load x), 255) -> (zextload x, i8)
3818   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3819   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3820   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3821                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3822                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3823     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3824     LoadSDNode *LN0 = HasAnyExt
3825       ? cast<LoadSDNode>(N0.getOperand(0))
3826       : cast<LoadSDNode>(N0);
3827     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3828         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3829       auto NarrowLoad = false;
3830       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3831       EVT ExtVT, LoadedVT;
3832       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3833                            NarrowLoad)) {
3834         if (!NarrowLoad) {
3835           SDValue NewLoad =
3836             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3837                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3838                            LN0->getMemOperand());
3839           AddToWorklist(N);
3840           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3841           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3842         } else {
3843           EVT PtrType = LN0->getOperand(1).getValueType();
3844 
3845           unsigned Alignment = LN0->getAlignment();
3846           SDValue NewPtr = LN0->getBasePtr();
3847 
3848           // For big endian targets, we need to add an offset to the pointer
3849           // to load the correct bytes.  For little endian systems, we merely
3850           // need to read fewer bytes from the same pointer.
3851           if (DAG.getDataLayout().isBigEndian()) {
3852             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3853             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3854             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3855             SDLoc DL(LN0);
3856             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3857                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3858             Alignment = MinAlign(Alignment, PtrOff);
3859           }
3860 
3861           AddToWorklist(NewPtr.getNode());
3862 
3863           SDValue Load = DAG.getExtLoad(
3864               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3865               LN0->getPointerInfo(), ExtVT, Alignment,
3866               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3867           AddToWorklist(N);
3868           CombineTo(LN0, Load, Load.getValue(1));
3869           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3870         }
3871       }
3872     }
3873   }
3874 
3875   if (SDValue Combined = visitANDLike(N0, N1, N))
3876     return Combined;
3877 
3878   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3879   if (N0.getOpcode() == N1.getOpcode())
3880     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3881       return Tmp;
3882 
3883   // Masking the negated extension of a boolean is just the zero-extended
3884   // boolean:
3885   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3886   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3887   //
3888   // Note: the SimplifyDemandedBits fold below can make an information-losing
3889   // transform, and then we have no way to find this better fold.
3890   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3891     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3892     SDValue SubRHS = N0.getOperand(1);
3893     if (SubLHS && SubLHS->isNullValue()) {
3894       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3895           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3896         return SubRHS;
3897       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3898           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3899         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3900     }
3901   }
3902 
3903   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3904   // fold (and (sra)) -> (and (srl)) when possible.
3905   if (SimplifyDemandedBits(SDValue(N, 0)))
3906     return SDValue(N, 0);
3907 
3908   // fold (zext_inreg (extload x)) -> (zextload x)
3909   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3910     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3911     EVT MemVT = LN0->getMemoryVT();
3912     // If we zero all the possible extended bits, then we can turn this into
3913     // a zextload if we are running before legalize or the operation is legal.
3914     unsigned BitWidth = N1.getScalarValueSizeInBits();
3915     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3916                            BitWidth - MemVT.getScalarSizeInBits())) &&
3917         ((!LegalOperations && !LN0->isVolatile()) ||
3918          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3919       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3920                                        LN0->getChain(), LN0->getBasePtr(),
3921                                        MemVT, LN0->getMemOperand());
3922       AddToWorklist(N);
3923       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3924       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3925     }
3926   }
3927   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3928   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3929       N0.hasOneUse()) {
3930     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3931     EVT MemVT = LN0->getMemoryVT();
3932     // If we zero all the possible extended bits, then we can turn this into
3933     // a zextload if we are running before legalize or the operation is legal.
3934     unsigned BitWidth = N1.getScalarValueSizeInBits();
3935     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3936                            BitWidth - MemVT.getScalarSizeInBits())) &&
3937         ((!LegalOperations && !LN0->isVolatile()) ||
3938          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3939       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3940                                        LN0->getChain(), LN0->getBasePtr(),
3941                                        MemVT, LN0->getMemOperand());
3942       AddToWorklist(N);
3943       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3944       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3945     }
3946   }
3947   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3948   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3949     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3950                                            N0.getOperand(1), false))
3951       return BSwap;
3952   }
3953 
3954   return SDValue();
3955 }
3956 
3957 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3958 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3959                                         bool DemandHighBits) {
3960   if (!LegalOperations)
3961     return SDValue();
3962 
3963   EVT VT = N->getValueType(0);
3964   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3965     return SDValue();
3966   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3967     return SDValue();
3968 
3969   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3970   bool LookPassAnd0 = false;
3971   bool LookPassAnd1 = false;
3972   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3973       std::swap(N0, N1);
3974   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3975       std::swap(N0, N1);
3976   if (N0.getOpcode() == ISD::AND) {
3977     if (!N0.getNode()->hasOneUse())
3978       return SDValue();
3979     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3980     if (!N01C || N01C->getZExtValue() != 0xFF00)
3981       return SDValue();
3982     N0 = N0.getOperand(0);
3983     LookPassAnd0 = true;
3984   }
3985 
3986   if (N1.getOpcode() == ISD::AND) {
3987     if (!N1.getNode()->hasOneUse())
3988       return SDValue();
3989     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3990     if (!N11C || N11C->getZExtValue() != 0xFF)
3991       return SDValue();
3992     N1 = N1.getOperand(0);
3993     LookPassAnd1 = true;
3994   }
3995 
3996   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3997     std::swap(N0, N1);
3998   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3999     return SDValue();
4000   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4001     return SDValue();
4002 
4003   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4004   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4005   if (!N01C || !N11C)
4006     return SDValue();
4007   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4008     return SDValue();
4009 
4010   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4011   SDValue N00 = N0->getOperand(0);
4012   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4013     if (!N00.getNode()->hasOneUse())
4014       return SDValue();
4015     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4016     if (!N001C || N001C->getZExtValue() != 0xFF)
4017       return SDValue();
4018     N00 = N00.getOperand(0);
4019     LookPassAnd0 = true;
4020   }
4021 
4022   SDValue N10 = N1->getOperand(0);
4023   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4024     if (!N10.getNode()->hasOneUse())
4025       return SDValue();
4026     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4027     if (!N101C || N101C->getZExtValue() != 0xFF00)
4028       return SDValue();
4029     N10 = N10.getOperand(0);
4030     LookPassAnd1 = true;
4031   }
4032 
4033   if (N00 != N10)
4034     return SDValue();
4035 
4036   // Make sure everything beyond the low halfword gets set to zero since the SRL
4037   // 16 will clear the top bits.
4038   unsigned OpSizeInBits = VT.getSizeInBits();
4039   if (DemandHighBits && OpSizeInBits > 16) {
4040     // If the left-shift isn't masked out then the only way this is a bswap is
4041     // if all bits beyond the low 8 are 0. In that case the entire pattern
4042     // reduces to a left shift anyway: leave it for other parts of the combiner.
4043     if (!LookPassAnd0)
4044       return SDValue();
4045 
4046     // However, if the right shift isn't masked out then it might be because
4047     // it's not needed. See if we can spot that too.
4048     if (!LookPassAnd1 &&
4049         !DAG.MaskedValueIsZero(
4050             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4051       return SDValue();
4052   }
4053 
4054   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4055   if (OpSizeInBits > 16) {
4056     SDLoc DL(N);
4057     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4058                       DAG.getConstant(OpSizeInBits - 16, DL,
4059                                       getShiftAmountTy(VT)));
4060   }
4061   return Res;
4062 }
4063 
4064 /// Return true if the specified node is an element that makes up a 32-bit
4065 /// packed halfword byteswap.
4066 /// ((x & 0x000000ff) << 8) |
4067 /// ((x & 0x0000ff00) >> 8) |
4068 /// ((x & 0x00ff0000) << 8) |
4069 /// ((x & 0xff000000) >> 8)
4070 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4071   if (!N.getNode()->hasOneUse())
4072     return false;
4073 
4074   unsigned Opc = N.getOpcode();
4075   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4076     return false;
4077 
4078   SDValue N0 = N.getOperand(0);
4079   unsigned Opc0 = N0.getOpcode();
4080   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4081     return false;
4082 
4083   ConstantSDNode *N1C = nullptr;
4084   // SHL or SRL: look upstream for AND mask operand
4085   if (Opc == ISD::AND)
4086     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4087   else if (Opc0 == ISD::AND)
4088     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4089   if (!N1C)
4090     return false;
4091 
4092   unsigned MaskByteOffset;
4093   switch (N1C->getZExtValue()) {
4094   default:
4095     return false;
4096   case 0xFF:       MaskByteOffset = 0; break;
4097   case 0xFF00:     MaskByteOffset = 1; break;
4098   case 0xFF0000:   MaskByteOffset = 2; break;
4099   case 0xFF000000: MaskByteOffset = 3; break;
4100   }
4101 
4102   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4103   if (Opc == ISD::AND) {
4104     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4105       // (x >> 8) & 0xff
4106       // (x >> 8) & 0xff0000
4107       if (Opc0 != ISD::SRL)
4108         return false;
4109       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4110       if (!C || C->getZExtValue() != 8)
4111         return false;
4112     } else {
4113       // (x << 8) & 0xff00
4114       // (x << 8) & 0xff000000
4115       if (Opc0 != ISD::SHL)
4116         return false;
4117       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4118       if (!C || C->getZExtValue() != 8)
4119         return false;
4120     }
4121   } else if (Opc == ISD::SHL) {
4122     // (x & 0xff) << 8
4123     // (x & 0xff0000) << 8
4124     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4125       return false;
4126     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4127     if (!C || C->getZExtValue() != 8)
4128       return false;
4129   } else { // Opc == ISD::SRL
4130     // (x & 0xff00) >> 8
4131     // (x & 0xff000000) >> 8
4132     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4133       return false;
4134     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4135     if (!C || C->getZExtValue() != 8)
4136       return false;
4137   }
4138 
4139   if (Parts[MaskByteOffset])
4140     return false;
4141 
4142   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4143   return true;
4144 }
4145 
4146 /// Match a 32-bit packed halfword bswap. That is
4147 /// ((x & 0x000000ff) << 8) |
4148 /// ((x & 0x0000ff00) >> 8) |
4149 /// ((x & 0x00ff0000) << 8) |
4150 /// ((x & 0xff000000) >> 8)
4151 /// => (rotl (bswap x), 16)
4152 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4153   if (!LegalOperations)
4154     return SDValue();
4155 
4156   EVT VT = N->getValueType(0);
4157   if (VT != MVT::i32)
4158     return SDValue();
4159   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4160     return SDValue();
4161 
4162   // Look for either
4163   // (or (or (and), (and)), (or (and), (and)))
4164   // (or (or (or (and), (and)), (and)), (and))
4165   if (N0.getOpcode() != ISD::OR)
4166     return SDValue();
4167   SDValue N00 = N0.getOperand(0);
4168   SDValue N01 = N0.getOperand(1);
4169   SDNode *Parts[4] = {};
4170 
4171   if (N1.getOpcode() == ISD::OR &&
4172       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4173     // (or (or (and), (and)), (or (and), (and)))
4174     if (!isBSwapHWordElement(N00, Parts))
4175       return SDValue();
4176 
4177     if (!isBSwapHWordElement(N01, Parts))
4178       return SDValue();
4179     SDValue N10 = N1.getOperand(0);
4180     if (!isBSwapHWordElement(N10, Parts))
4181       return SDValue();
4182     SDValue N11 = N1.getOperand(1);
4183     if (!isBSwapHWordElement(N11, Parts))
4184       return SDValue();
4185   } else {
4186     // (or (or (or (and), (and)), (and)), (and))
4187     if (!isBSwapHWordElement(N1, Parts))
4188       return SDValue();
4189     if (!isBSwapHWordElement(N01, Parts))
4190       return SDValue();
4191     if (N00.getOpcode() != ISD::OR)
4192       return SDValue();
4193     SDValue N000 = N00.getOperand(0);
4194     if (!isBSwapHWordElement(N000, Parts))
4195       return SDValue();
4196     SDValue N001 = N00.getOperand(1);
4197     if (!isBSwapHWordElement(N001, Parts))
4198       return SDValue();
4199   }
4200 
4201   // Make sure the parts are all coming from the same node.
4202   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4203     return SDValue();
4204 
4205   SDLoc DL(N);
4206   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4207                               SDValue(Parts[0], 0));
4208 
4209   // Result of the bswap should be rotated by 16. If it's not legal, then
4210   // do  (x << 16) | (x >> 16).
4211   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4212   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4213     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4214   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4215     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4216   return DAG.getNode(ISD::OR, DL, VT,
4217                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4218                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4219 }
4220 
4221 /// This contains all DAGCombine rules which reduce two values combined by
4222 /// an Or operation to a single value \see visitANDLike().
4223 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4224   EVT VT = N1.getValueType();
4225   SDLoc DL(N);
4226 
4227   // fold (or x, undef) -> -1
4228   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4229     return DAG.getAllOnesConstant(DL, VT);
4230 
4231   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4232     return V;
4233 
4234   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4235   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4236       // Don't increase # computations.
4237       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4238     // We can only do this xform if we know that bits from X that are set in C2
4239     // but not in C1 are already zero.  Likewise for Y.
4240     if (const ConstantSDNode *N0O1C =
4241         getAsNonOpaqueConstant(N0.getOperand(1))) {
4242       if (const ConstantSDNode *N1O1C =
4243           getAsNonOpaqueConstant(N1.getOperand(1))) {
4244         // We can only do this xform if we know that bits from X that are set in
4245         // C2 but not in C1 are already zero.  Likewise for Y.
4246         const APInt &LHSMask = N0O1C->getAPIntValue();
4247         const APInt &RHSMask = N1O1C->getAPIntValue();
4248 
4249         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4250             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4251           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4252                                   N0.getOperand(0), N1.getOperand(0));
4253           return DAG.getNode(ISD::AND, DL, VT, X,
4254                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4255         }
4256       }
4257     }
4258   }
4259 
4260   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4261   if (N0.getOpcode() == ISD::AND &&
4262       N1.getOpcode() == ISD::AND &&
4263       N0.getOperand(0) == N1.getOperand(0) &&
4264       // Don't increase # computations.
4265       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4266     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4267                             N0.getOperand(1), N1.getOperand(1));
4268     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4269   }
4270 
4271   return SDValue();
4272 }
4273 
4274 SDValue DAGCombiner::visitOR(SDNode *N) {
4275   SDValue N0 = N->getOperand(0);
4276   SDValue N1 = N->getOperand(1);
4277   EVT VT = N1.getValueType();
4278 
4279   // x | x --> x
4280   if (N0 == N1)
4281     return N0;
4282 
4283   // fold vector ops
4284   if (VT.isVector()) {
4285     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4286       return FoldedVOp;
4287 
4288     // fold (or x, 0) -> x, vector edition
4289     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4290       return N1;
4291     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4292       return N0;
4293 
4294     // fold (or x, -1) -> -1, vector edition
4295     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4296       // do not return N0, because undef node may exist in N0
4297       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4298     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4299       // do not return N1, because undef node may exist in N1
4300       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4301 
4302     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4303     // Do this only if the resulting shuffle is legal.
4304     if (isa<ShuffleVectorSDNode>(N0) &&
4305         isa<ShuffleVectorSDNode>(N1) &&
4306         // Avoid folding a node with illegal type.
4307         TLI.isTypeLegal(VT)) {
4308       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4309       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4310       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4311       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4312       // Ensure both shuffles have a zero input.
4313       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4314         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4315         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4316         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4317         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4318         bool CanFold = true;
4319         int NumElts = VT.getVectorNumElements();
4320         SmallVector<int, 4> Mask(NumElts);
4321 
4322         for (int i = 0; i != NumElts; ++i) {
4323           int M0 = SV0->getMaskElt(i);
4324           int M1 = SV1->getMaskElt(i);
4325 
4326           // Determine if either index is pointing to a zero vector.
4327           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4328           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4329 
4330           // If one element is zero and the otherside is undef, keep undef.
4331           // This also handles the case that both are undef.
4332           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4333             Mask[i] = -1;
4334             continue;
4335           }
4336 
4337           // Make sure only one of the elements is zero.
4338           if (M0Zero == M1Zero) {
4339             CanFold = false;
4340             break;
4341           }
4342 
4343           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4344 
4345           // We have a zero and non-zero element. If the non-zero came from
4346           // SV0 make the index a LHS index. If it came from SV1, make it
4347           // a RHS index. We need to mod by NumElts because we don't care
4348           // which operand it came from in the original shuffles.
4349           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4350         }
4351 
4352         if (CanFold) {
4353           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4354           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4355 
4356           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4357           if (!LegalMask) {
4358             std::swap(NewLHS, NewRHS);
4359             ShuffleVectorSDNode::commuteMask(Mask);
4360             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4361           }
4362 
4363           if (LegalMask)
4364             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4365         }
4366       }
4367     }
4368   }
4369 
4370   // fold (or c1, c2) -> c1|c2
4371   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4372   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4373   if (N0C && N1C && !N1C->isOpaque())
4374     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4375   // canonicalize constant to RHS
4376   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4377      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4378     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4379   // fold (or x, 0) -> x
4380   if (isNullConstant(N1))
4381     return N0;
4382   // fold (or x, -1) -> -1
4383   if (isAllOnesConstant(N1))
4384     return N1;
4385 
4386   if (SDValue NewSel = foldBinOpIntoSelect(N))
4387     return NewSel;
4388 
4389   // fold (or x, c) -> c iff (x & ~c) == 0
4390   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4391     return N1;
4392 
4393   if (SDValue Combined = visitORLike(N0, N1, N))
4394     return Combined;
4395 
4396   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4397   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4398     return BSwap;
4399   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4400     return BSwap;
4401 
4402   // reassociate or
4403   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4404     return ROR;
4405 
4406   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4407   // iff (c1 & c2) != 0.
4408   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4409     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4410       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4411         if (SDValue COR =
4412                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4413           return DAG.getNode(
4414               ISD::AND, SDLoc(N), VT,
4415               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4416         return SDValue();
4417       }
4418     }
4419   }
4420 
4421   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4422   if (N0.getOpcode() == N1.getOpcode())
4423     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4424       return Tmp;
4425 
4426   // See if this is some rotate idiom.
4427   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4428     return SDValue(Rot, 0);
4429 
4430   if (SDValue Load = MatchLoadCombine(N))
4431     return Load;
4432 
4433   // Simplify the operands using demanded-bits information.
4434   if (SimplifyDemandedBits(SDValue(N, 0)))
4435     return SDValue(N, 0);
4436 
4437   return SDValue();
4438 }
4439 
4440 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4441 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4442   if (Op.getOpcode() == ISD::AND) {
4443     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4444       Mask = Op.getOperand(1);
4445       Op = Op.getOperand(0);
4446     } else {
4447       return false;
4448     }
4449   }
4450 
4451   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4452     Shift = Op;
4453     return true;
4454   }
4455 
4456   return false;
4457 }
4458 
4459 // Return true if we can prove that, whenever Neg and Pos are both in the
4460 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4461 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4462 //
4463 //     (or (shift1 X, Neg), (shift2 X, Pos))
4464 //
4465 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4466 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4467 // to consider shift amounts with defined behavior.
4468 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4469   // If EltSize is a power of 2 then:
4470   //
4471   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4472   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4473   //
4474   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4475   // for the stronger condition:
4476   //
4477   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4478   //
4479   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4480   // we can just replace Neg with Neg' for the rest of the function.
4481   //
4482   // In other cases we check for the even stronger condition:
4483   //
4484   //     Neg == EltSize - Pos                                    [B]
4485   //
4486   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4487   // behavior if Pos == 0 (and consequently Neg == EltSize).
4488   //
4489   // We could actually use [A] whenever EltSize is a power of 2, but the
4490   // only extra cases that it would match are those uninteresting ones
4491   // where Neg and Pos are never in range at the same time.  E.g. for
4492   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4493   // as well as (sub 32, Pos), but:
4494   //
4495   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4496   //
4497   // always invokes undefined behavior for 32-bit X.
4498   //
4499   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4500   unsigned MaskLoBits = 0;
4501   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4502     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4503       if (NegC->getAPIntValue() == EltSize - 1) {
4504         Neg = Neg.getOperand(0);
4505         MaskLoBits = Log2_64(EltSize);
4506       }
4507     }
4508   }
4509 
4510   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4511   if (Neg.getOpcode() != ISD::SUB)
4512     return false;
4513   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4514   if (!NegC)
4515     return false;
4516   SDValue NegOp1 = Neg.getOperand(1);
4517 
4518   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4519   // Pos'.  The truncation is redundant for the purpose of the equality.
4520   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4521     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4522       if (PosC->getAPIntValue() == EltSize - 1)
4523         Pos = Pos.getOperand(0);
4524 
4525   // The condition we need is now:
4526   //
4527   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4528   //
4529   // If NegOp1 == Pos then we need:
4530   //
4531   //              EltSize & Mask == NegC & Mask
4532   //
4533   // (because "x & Mask" is a truncation and distributes through subtraction).
4534   APInt Width;
4535   if (Pos == NegOp1)
4536     Width = NegC->getAPIntValue();
4537 
4538   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4539   // Then the condition we want to prove becomes:
4540   //
4541   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4542   //
4543   // which, again because "x & Mask" is a truncation, becomes:
4544   //
4545   //                NegC & Mask == (EltSize - PosC) & Mask
4546   //             EltSize & Mask == (NegC + PosC) & Mask
4547   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4548     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4549       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4550     else
4551       return false;
4552   } else
4553     return false;
4554 
4555   // Now we just need to check that EltSize & Mask == Width & Mask.
4556   if (MaskLoBits)
4557     // EltSize & Mask is 0 since Mask is EltSize - 1.
4558     return Width.getLoBits(MaskLoBits) == 0;
4559   return Width == EltSize;
4560 }
4561 
4562 // A subroutine of MatchRotate used once we have found an OR of two opposite
4563 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4564 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4565 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4566 // Neg with outer conversions stripped away.
4567 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4568                                        SDValue Neg, SDValue InnerPos,
4569                                        SDValue InnerNeg, unsigned PosOpcode,
4570                                        unsigned NegOpcode, const SDLoc &DL) {
4571   // fold (or (shl x, (*ext y)),
4572   //          (srl x, (*ext (sub 32, y)))) ->
4573   //   (rotl x, y) or (rotr x, (sub 32, y))
4574   //
4575   // fold (or (shl x, (*ext (sub 32, y))),
4576   //          (srl x, (*ext y))) ->
4577   //   (rotr x, y) or (rotl x, (sub 32, y))
4578   EVT VT = Shifted.getValueType();
4579   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4580     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4581     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4582                        HasPos ? Pos : Neg).getNode();
4583   }
4584 
4585   return nullptr;
4586 }
4587 
4588 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4589 // idioms for rotate, and if the target supports rotation instructions, generate
4590 // a rot[lr].
4591 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4592   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4593   EVT VT = LHS.getValueType();
4594   if (!TLI.isTypeLegal(VT)) return nullptr;
4595 
4596   // The target must have at least one rotate flavor.
4597   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4598   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4599   if (!HasROTL && !HasROTR) return nullptr;
4600 
4601   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4602   SDValue LHSShift;   // The shift.
4603   SDValue LHSMask;    // AND value if any.
4604   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4605     return nullptr; // Not part of a rotate.
4606 
4607   SDValue RHSShift;   // The shift.
4608   SDValue RHSMask;    // AND value if any.
4609   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4610     return nullptr; // Not part of a rotate.
4611 
4612   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4613     return nullptr;   // Not shifting the same value.
4614 
4615   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4616     return nullptr;   // Shifts must disagree.
4617 
4618   // Canonicalize shl to left side in a shl/srl pair.
4619   if (RHSShift.getOpcode() == ISD::SHL) {
4620     std::swap(LHS, RHS);
4621     std::swap(LHSShift, RHSShift);
4622     std::swap(LHSMask, RHSMask);
4623   }
4624 
4625   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4626   SDValue LHSShiftArg = LHSShift.getOperand(0);
4627   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4628   SDValue RHSShiftArg = RHSShift.getOperand(0);
4629   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4630 
4631   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4632   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4633   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4634     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4635     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4636     if ((LShVal + RShVal) != EltSizeInBits)
4637       return nullptr;
4638 
4639     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4640                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4641 
4642     // If there is an AND of either shifted operand, apply it to the result.
4643     if (LHSMask.getNode() || RHSMask.getNode()) {
4644       SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4645 
4646       if (LHSMask.getNode()) {
4647         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4648         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4649                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4650                                        DAG.getConstant(RHSBits, DL, VT)));
4651       }
4652       if (RHSMask.getNode()) {
4653         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4654         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4655                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4656                                        DAG.getConstant(LHSBits, DL, VT)));
4657       }
4658 
4659       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4660     }
4661 
4662     return Rot.getNode();
4663   }
4664 
4665   // If there is a mask here, and we have a variable shift, we can't be sure
4666   // that we're masking out the right stuff.
4667   if (LHSMask.getNode() || RHSMask.getNode())
4668     return nullptr;
4669 
4670   // If the shift amount is sign/zext/any-extended just peel it off.
4671   SDValue LExtOp0 = LHSShiftAmt;
4672   SDValue RExtOp0 = RHSShiftAmt;
4673   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4674        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4675        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4676        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4677       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4678        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4679        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4680        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4681     LExtOp0 = LHSShiftAmt.getOperand(0);
4682     RExtOp0 = RHSShiftAmt.getOperand(0);
4683   }
4684 
4685   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4686                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4687   if (TryL)
4688     return TryL;
4689 
4690   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4691                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4692   if (TryR)
4693     return TryR;
4694 
4695   return nullptr;
4696 }
4697 
4698 namespace {
4699 /// Represents known origin of an individual byte in load combine pattern. The
4700 /// value of the byte is either constant zero or comes from memory.
4701 struct ByteProvider {
4702   // For constant zero providers Load is set to nullptr. For memory providers
4703   // Load represents the node which loads the byte from memory.
4704   // ByteOffset is the offset of the byte in the value produced by the load.
4705   LoadSDNode *Load;
4706   unsigned ByteOffset;
4707 
4708   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4709 
4710   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4711     return ByteProvider(Load, ByteOffset);
4712   }
4713   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4714 
4715   bool isConstantZero() const { return !Load; }
4716   bool isMemory() const { return Load; }
4717 
4718   bool operator==(const ByteProvider &Other) const {
4719     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4720   }
4721 
4722 private:
4723   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4724       : Load(Load), ByteOffset(ByteOffset) {}
4725 };
4726 
4727 /// Recursively traverses the expression calculating the origin of the requested
4728 /// byte of the given value. Returns None if the provider can't be calculated.
4729 ///
4730 /// For all the values except the root of the expression verifies that the value
4731 /// has exactly one use and if it's not true return None. This way if the origin
4732 /// of the byte is returned it's guaranteed that the values which contribute to
4733 /// the byte are not used outside of this expression.
4734 ///
4735 /// Because the parts of the expression are not allowed to have more than one
4736 /// use this function iterates over trees, not DAGs. So it never visits the same
4737 /// node more than once.
4738 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4739                                                    unsigned Depth,
4740                                                    bool Root = false) {
4741   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4742   if (Depth == 10)
4743     return None;
4744 
4745   if (!Root && !Op.hasOneUse())
4746     return None;
4747 
4748   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4749   unsigned BitWidth = Op.getValueSizeInBits();
4750   if (BitWidth % 8 != 0)
4751     return None;
4752   unsigned ByteWidth = BitWidth / 8;
4753   assert(Index < ByteWidth && "invalid index requested");
4754   (void) ByteWidth;
4755 
4756   switch (Op.getOpcode()) {
4757   case ISD::OR: {
4758     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4759     if (!LHS)
4760       return None;
4761     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4762     if (!RHS)
4763       return None;
4764 
4765     if (LHS->isConstantZero())
4766       return RHS;
4767     if (RHS->isConstantZero())
4768       return LHS;
4769     return None;
4770   }
4771   case ISD::SHL: {
4772     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4773     if (!ShiftOp)
4774       return None;
4775 
4776     uint64_t BitShift = ShiftOp->getZExtValue();
4777     if (BitShift % 8 != 0)
4778       return None;
4779     uint64_t ByteShift = BitShift / 8;
4780 
4781     return Index < ByteShift
4782                ? ByteProvider::getConstantZero()
4783                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4784                                        Depth + 1);
4785   }
4786   case ISD::ANY_EXTEND:
4787   case ISD::SIGN_EXTEND:
4788   case ISD::ZERO_EXTEND: {
4789     SDValue NarrowOp = Op->getOperand(0);
4790     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4791     if (NarrowBitWidth % 8 != 0)
4792       return None;
4793     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4794 
4795     if (Index >= NarrowByteWidth)
4796       return Op.getOpcode() == ISD::ZERO_EXTEND
4797                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4798                  : None;
4799     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4800   }
4801   case ISD::BSWAP:
4802     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4803                                  Depth + 1);
4804   case ISD::LOAD: {
4805     auto L = cast<LoadSDNode>(Op.getNode());
4806     if (L->isVolatile() || L->isIndexed())
4807       return None;
4808 
4809     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4810     if (NarrowBitWidth % 8 != 0)
4811       return None;
4812     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4813 
4814     if (Index >= NarrowByteWidth)
4815       return L->getExtensionType() == ISD::ZEXTLOAD
4816                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4817                  : None;
4818     return ByteProvider::getMemory(L, Index);
4819   }
4820   }
4821 
4822   return None;
4823 }
4824 } // namespace
4825 
4826 /// Match a pattern where a wide type scalar value is loaded by several narrow
4827 /// loads and combined by shifts and ors. Fold it into a single load or a load
4828 /// and a BSWAP if the targets supports it.
4829 ///
4830 /// Assuming little endian target:
4831 ///  i8 *a = ...
4832 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4833 /// =>
4834 ///  i32 val = *((i32)a)
4835 ///
4836 ///  i8 *a = ...
4837 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4838 /// =>
4839 ///  i32 val = BSWAP(*((i32)a))
4840 ///
4841 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4842 /// interact well with the worklist mechanism. When a part of the pattern is
4843 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4844 /// but the root node of the pattern which triggers the load combine is not
4845 /// necessarily a direct user of the changed node. For example, once the address
4846 /// of t28 load is reassociated load combine won't be triggered:
4847 ///             t25: i32 = add t4, Constant:i32<2>
4848 ///           t26: i64 = sign_extend t25
4849 ///        t27: i64 = add t2, t26
4850 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4851 ///     t29: i32 = zero_extend t28
4852 ///   t32: i32 = shl t29, Constant:i8<8>
4853 /// t33: i32 = or t23, t32
4854 /// As a possible fix visitLoad can check if the load can be a part of a load
4855 /// combine pattern and add corresponding OR roots to the worklist.
4856 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4857   assert(N->getOpcode() == ISD::OR &&
4858          "Can only match load combining against OR nodes");
4859 
4860   // Handles simple types only
4861   EVT VT = N->getValueType(0);
4862   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4863     return SDValue();
4864   unsigned ByteWidth = VT.getSizeInBits() / 8;
4865 
4866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4867   // Before legalize we can introduce too wide illegal loads which will be later
4868   // split into legal sized loads. This enables us to combine i64 load by i8
4869   // patterns to a couple of i32 loads on 32 bit targets.
4870   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4871     return SDValue();
4872 
4873   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4874     unsigned BW, unsigned i) { return i; };
4875   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4876     unsigned BW, unsigned i) { return BW - i - 1; };
4877 
4878   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4879   auto MemoryByteOffset = [&] (ByteProvider P) {
4880     assert(P.isMemory() && "Must be a memory byte provider");
4881     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4882     assert(LoadBitWidth % 8 == 0 &&
4883            "can only analyze providers for individual bytes not bit");
4884     unsigned LoadByteWidth = LoadBitWidth / 8;
4885     return IsBigEndianTarget
4886             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4887             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4888   };
4889 
4890   Optional<BaseIndexOffset> Base;
4891   SDValue Chain;
4892 
4893   SmallSet<LoadSDNode *, 8> Loads;
4894   Optional<ByteProvider> FirstByteProvider;
4895   int64_t FirstOffset = INT64_MAX;
4896 
4897   // Check if all the bytes of the OR we are looking at are loaded from the same
4898   // base address. Collect bytes offsets from Base address in ByteOffsets.
4899   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4900   for (unsigned i = 0; i < ByteWidth; i++) {
4901     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4902     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4903       return SDValue();
4904 
4905     LoadSDNode *L = P->Load;
4906     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4907            "Must be enforced by calculateByteProvider");
4908     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4909 
4910     // All loads must share the same chain
4911     SDValue LChain = L->getChain();
4912     if (!Chain)
4913       Chain = LChain;
4914     else if (Chain != LChain)
4915       return SDValue();
4916 
4917     // Loads must share the same base address
4918     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4919     int64_t ByteOffsetFromBase = 0;
4920     if (!Base)
4921       Base = Ptr;
4922     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
4923       return SDValue();
4924 
4925     // Calculate the offset of the current byte from the base address
4926     ByteOffsetFromBase += MemoryByteOffset(*P);
4927     ByteOffsets[i] = ByteOffsetFromBase;
4928 
4929     // Remember the first byte load
4930     if (ByteOffsetFromBase < FirstOffset) {
4931       FirstByteProvider = P;
4932       FirstOffset = ByteOffsetFromBase;
4933     }
4934 
4935     Loads.insert(L);
4936   }
4937   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4938          "memory, so there must be at least one load which produces the value");
4939   assert(Base && "Base address of the accessed memory location must be set");
4940   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4941 
4942   // Check if the bytes of the OR we are looking at match with either big or
4943   // little endian value load
4944   bool BigEndian = true, LittleEndian = true;
4945   for (unsigned i = 0; i < ByteWidth; i++) {
4946     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4947     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4948     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4949     if (!BigEndian && !LittleEndian)
4950       return SDValue();
4951   }
4952   assert((BigEndian != LittleEndian) && "should be either or");
4953   assert(FirstByteProvider && "must be set");
4954 
4955   // Ensure that the first byte is loaded from zero offset of the first load.
4956   // So the combined value can be loaded from the first load address.
4957   if (MemoryByteOffset(*FirstByteProvider) != 0)
4958     return SDValue();
4959   LoadSDNode *FirstLoad = FirstByteProvider->Load;
4960 
4961   // The node we are looking at matches with the pattern, check if we can
4962   // replace it with a single load and bswap if needed.
4963 
4964   // If the load needs byte swap check if the target supports it
4965   bool NeedsBswap = IsBigEndianTarget != BigEndian;
4966 
4967   // Before legalize we can introduce illegal bswaps which will be later
4968   // converted to an explicit bswap sequence. This way we end up with a single
4969   // load and byte shuffling instead of several loads and byte shuffling.
4970   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4971     return SDValue();
4972 
4973   // Check that a load of the wide type is both allowed and fast on the target
4974   bool Fast = false;
4975   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4976                                         VT, FirstLoad->getAddressSpace(),
4977                                         FirstLoad->getAlignment(), &Fast);
4978   if (!Allowed || !Fast)
4979     return SDValue();
4980 
4981   SDValue NewLoad =
4982       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4983                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4984 
4985   // Transfer chain users from old loads to the new load.
4986   for (LoadSDNode *L : Loads)
4987     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4988 
4989   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4990 }
4991 
4992 SDValue DAGCombiner::visitXOR(SDNode *N) {
4993   SDValue N0 = N->getOperand(0);
4994   SDValue N1 = N->getOperand(1);
4995   EVT VT = N0.getValueType();
4996 
4997   // fold vector ops
4998   if (VT.isVector()) {
4999     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5000       return FoldedVOp;
5001 
5002     // fold (xor x, 0) -> x, vector edition
5003     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5004       return N1;
5005     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5006       return N0;
5007   }
5008 
5009   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5010   if (N0.isUndef() && N1.isUndef())
5011     return DAG.getConstant(0, SDLoc(N), VT);
5012   // fold (xor x, undef) -> undef
5013   if (N0.isUndef())
5014     return N0;
5015   if (N1.isUndef())
5016     return N1;
5017   // fold (xor c1, c2) -> c1^c2
5018   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5019   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5020   if (N0C && N1C)
5021     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5022   // canonicalize constant to RHS
5023   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5024      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5025     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5026   // fold (xor x, 0) -> x
5027   if (isNullConstant(N1))
5028     return N0;
5029 
5030   if (SDValue NewSel = foldBinOpIntoSelect(N))
5031     return NewSel;
5032 
5033   // reassociate xor
5034   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5035     return RXOR;
5036 
5037   // fold !(x cc y) -> (x !cc y)
5038   SDValue LHS, RHS, CC;
5039   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5040     bool isInt = LHS.getValueType().isInteger();
5041     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5042                                                isInt);
5043 
5044     if (!LegalOperations ||
5045         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5046       switch (N0.getOpcode()) {
5047       default:
5048         llvm_unreachable("Unhandled SetCC Equivalent!");
5049       case ISD::SETCC:
5050         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5051       case ISD::SELECT_CC:
5052         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5053                                N0.getOperand(3), NotCC);
5054       }
5055     }
5056   }
5057 
5058   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5059   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5060       N0.getNode()->hasOneUse() &&
5061       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5062     SDValue V = N0.getOperand(0);
5063     SDLoc DL(N0);
5064     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5065                     DAG.getConstant(1, DL, V.getValueType()));
5066     AddToWorklist(V.getNode());
5067     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5068   }
5069 
5070   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5071   if (isOneConstant(N1) && VT == MVT::i1 &&
5072       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5073     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5074     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5075       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5076       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5077       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5078       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5079       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5080     }
5081   }
5082   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5083   if (isAllOnesConstant(N1) &&
5084       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5085     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5086     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5087       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5088       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5089       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5090       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5091       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5092     }
5093   }
5094   // fold (xor (and x, y), y) -> (and (not x), y)
5095   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5096       N0->getOperand(1) == N1) {
5097     SDValue X = N0->getOperand(0);
5098     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5099     AddToWorklist(NotX.getNode());
5100     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5101   }
5102   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5103   if (N1C && N0.getOpcode() == ISD::XOR) {
5104     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5105       SDLoc DL(N);
5106       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5107                          DAG.getConstant(N1C->getAPIntValue() ^
5108                                          N00C->getAPIntValue(), DL, VT));
5109     }
5110     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5111       SDLoc DL(N);
5112       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5113                          DAG.getConstant(N1C->getAPIntValue() ^
5114                                          N01C->getAPIntValue(), DL, VT));
5115     }
5116   }
5117 
5118   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5119   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5120   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5121       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5122       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5123     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5124       if (C->getAPIntValue() == (OpSizeInBits - 1))
5125         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5126   }
5127 
5128   // fold (xor x, x) -> 0
5129   if (N0 == N1)
5130     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5131 
5132   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5133   // Here is a concrete example of this equivalence:
5134   // i16   x ==  14
5135   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5136   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5137   //
5138   // =>
5139   //
5140   // i16     ~1      == 0b1111111111111110
5141   // i16 rol(~1, 14) == 0b1011111111111111
5142   //
5143   // Some additional tips to help conceptualize this transform:
5144   // - Try to see the operation as placing a single zero in a value of all ones.
5145   // - There exists no value for x which would allow the result to contain zero.
5146   // - Values of x larger than the bitwidth are undefined and do not require a
5147   //   consistent result.
5148   // - Pushing the zero left requires shifting one bits in from the right.
5149   // A rotate left of ~1 is a nice way of achieving the desired result.
5150   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5151       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5152     SDLoc DL(N);
5153     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5154                        N0.getOperand(1));
5155   }
5156 
5157   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5158   if (N0.getOpcode() == N1.getOpcode())
5159     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5160       return Tmp;
5161 
5162   // Simplify the expression using non-local knowledge.
5163   if (SimplifyDemandedBits(SDValue(N, 0)))
5164     return SDValue(N, 0);
5165 
5166   return SDValue();
5167 }
5168 
5169 /// Handle transforms common to the three shifts, when the shift amount is a
5170 /// constant.
5171 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5172   SDNode *LHS = N->getOperand(0).getNode();
5173   if (!LHS->hasOneUse()) return SDValue();
5174 
5175   // We want to pull some binops through shifts, so that we have (and (shift))
5176   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5177   // thing happens with address calculations, so it's important to canonicalize
5178   // it.
5179   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5180 
5181   switch (LHS->getOpcode()) {
5182   default: return SDValue();
5183   case ISD::OR:
5184   case ISD::XOR:
5185     HighBitSet = false; // We can only transform sra if the high bit is clear.
5186     break;
5187   case ISD::AND:
5188     HighBitSet = true;  // We can only transform sra if the high bit is set.
5189     break;
5190   case ISD::ADD:
5191     if (N->getOpcode() != ISD::SHL)
5192       return SDValue(); // only shl(add) not sr[al](add).
5193     HighBitSet = false; // We can only transform sra if the high bit is clear.
5194     break;
5195   }
5196 
5197   // We require the RHS of the binop to be a constant and not opaque as well.
5198   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5199   if (!BinOpCst) return SDValue();
5200 
5201   // FIXME: disable this unless the input to the binop is a shift by a constant
5202   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5203   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5204   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5205                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5206                  BinOpLHSVal->getOpcode() == ISD::SRL;
5207   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5208                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5209 
5210   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5211       !isCopyOrSelect)
5212     return SDValue();
5213 
5214   if (isCopyOrSelect && N->hasOneUse())
5215     return SDValue();
5216 
5217   EVT VT = N->getValueType(0);
5218 
5219   // If this is a signed shift right, and the high bit is modified by the
5220   // logical operation, do not perform the transformation. The highBitSet
5221   // boolean indicates the value of the high bit of the constant which would
5222   // cause it to be modified for this operation.
5223   if (N->getOpcode() == ISD::SRA) {
5224     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5225     if (BinOpRHSSignSet != HighBitSet)
5226       return SDValue();
5227   }
5228 
5229   if (!TLI.isDesirableToCommuteWithShift(LHS))
5230     return SDValue();
5231 
5232   // Fold the constants, shifting the binop RHS by the shift amount.
5233   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5234                                N->getValueType(0),
5235                                LHS->getOperand(1), N->getOperand(1));
5236   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5237 
5238   // Create the new shift.
5239   SDValue NewShift = DAG.getNode(N->getOpcode(),
5240                                  SDLoc(LHS->getOperand(0)),
5241                                  VT, LHS->getOperand(0), N->getOperand(1));
5242 
5243   // Create the new binop.
5244   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5245 }
5246 
5247 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5248   assert(N->getOpcode() == ISD::TRUNCATE);
5249   assert(N->getOperand(0).getOpcode() == ISD::AND);
5250 
5251   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5252   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5253     SDValue N01 = N->getOperand(0).getOperand(1);
5254     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5255       SDLoc DL(N);
5256       EVT TruncVT = N->getValueType(0);
5257       SDValue N00 = N->getOperand(0).getOperand(0);
5258       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5259       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5260       AddToWorklist(Trunc00.getNode());
5261       AddToWorklist(Trunc01.getNode());
5262       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5263     }
5264   }
5265 
5266   return SDValue();
5267 }
5268 
5269 SDValue DAGCombiner::visitRotate(SDNode *N) {
5270   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5271   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5272       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5273     if (SDValue NewOp1 =
5274             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5275       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5276                          N->getOperand(0), NewOp1);
5277   }
5278   return SDValue();
5279 }
5280 
5281 SDValue DAGCombiner::visitSHL(SDNode *N) {
5282   SDValue N0 = N->getOperand(0);
5283   SDValue N1 = N->getOperand(1);
5284   EVT VT = N0.getValueType();
5285   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5286 
5287   // fold vector ops
5288   if (VT.isVector()) {
5289     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5290       return FoldedVOp;
5291 
5292     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5293     // If setcc produces all-one true value then:
5294     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5295     if (N1CV && N1CV->isConstant()) {
5296       if (N0.getOpcode() == ISD::AND) {
5297         SDValue N00 = N0->getOperand(0);
5298         SDValue N01 = N0->getOperand(1);
5299         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5300 
5301         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5302             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5303                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5304           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5305                                                      N01CV, N1CV))
5306             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5307         }
5308       }
5309     }
5310   }
5311 
5312   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5313 
5314   // fold (shl c1, c2) -> c1<<c2
5315   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5316   if (N0C && N1C && !N1C->isOpaque())
5317     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5318   // fold (shl 0, x) -> 0
5319   if (isNullConstantOrNullSplatConstant(N0))
5320     return N0;
5321   // fold (shl x, c >= size(x)) -> undef
5322   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5323     return DAG.getUNDEF(VT);
5324   // fold (shl x, 0) -> x
5325   if (N1C && N1C->isNullValue())
5326     return N0;
5327   // fold (shl undef, x) -> 0
5328   if (N0.isUndef())
5329     return DAG.getConstant(0, SDLoc(N), VT);
5330 
5331   if (SDValue NewSel = foldBinOpIntoSelect(N))
5332     return NewSel;
5333 
5334   // if (shl x, c) is known to be zero, return 0
5335   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5336                             APInt::getAllOnesValue(OpSizeInBits)))
5337     return DAG.getConstant(0, SDLoc(N), VT);
5338   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5339   if (N1.getOpcode() == ISD::TRUNCATE &&
5340       N1.getOperand(0).getOpcode() == ISD::AND) {
5341     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5342       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5343   }
5344 
5345   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5346     return SDValue(N, 0);
5347 
5348   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5349   if (N1C && N0.getOpcode() == ISD::SHL) {
5350     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5351       SDLoc DL(N);
5352       APInt c1 = N0C1->getAPIntValue();
5353       APInt c2 = N1C->getAPIntValue();
5354       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5355 
5356       APInt Sum = c1 + c2;
5357       if (Sum.uge(OpSizeInBits))
5358         return DAG.getConstant(0, DL, VT);
5359 
5360       return DAG.getNode(
5361           ISD::SHL, DL, VT, N0.getOperand(0),
5362           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5363     }
5364   }
5365 
5366   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5367   // For this to be valid, the second form must not preserve any of the bits
5368   // that are shifted out by the inner shift in the first form.  This means
5369   // the outer shift size must be >= the number of bits added by the ext.
5370   // As a corollary, we don't care what kind of ext it is.
5371   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5372               N0.getOpcode() == ISD::ANY_EXTEND ||
5373               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5374       N0.getOperand(0).getOpcode() == ISD::SHL) {
5375     SDValue N0Op0 = N0.getOperand(0);
5376     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5377       APInt c1 = N0Op0C1->getAPIntValue();
5378       APInt c2 = N1C->getAPIntValue();
5379       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5380 
5381       EVT InnerShiftVT = N0Op0.getValueType();
5382       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5383       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5384         SDLoc DL(N0);
5385         APInt Sum = c1 + c2;
5386         if (Sum.uge(OpSizeInBits))
5387           return DAG.getConstant(0, DL, VT);
5388 
5389         return DAG.getNode(
5390             ISD::SHL, DL, VT,
5391             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5392             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5393       }
5394     }
5395   }
5396 
5397   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5398   // Only fold this if the inner zext has no other uses to avoid increasing
5399   // the total number of instructions.
5400   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5401       N0.getOperand(0).getOpcode() == ISD::SRL) {
5402     SDValue N0Op0 = N0.getOperand(0);
5403     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5404       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5405         uint64_t c1 = N0Op0C1->getZExtValue();
5406         uint64_t c2 = N1C->getZExtValue();
5407         if (c1 == c2) {
5408           SDValue NewOp0 = N0.getOperand(0);
5409           EVT CountVT = NewOp0.getOperand(1).getValueType();
5410           SDLoc DL(N);
5411           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5412                                        NewOp0,
5413                                        DAG.getConstant(c2, DL, CountVT));
5414           AddToWorklist(NewSHL.getNode());
5415           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5416         }
5417       }
5418     }
5419   }
5420 
5421   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5422   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5423   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5424       N0->getFlags().hasExact()) {
5425     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5426       uint64_t C1 = N0C1->getZExtValue();
5427       uint64_t C2 = N1C->getZExtValue();
5428       SDLoc DL(N);
5429       if (C1 <= C2)
5430         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5431                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5432       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5433                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5434     }
5435   }
5436 
5437   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5438   //                               (and (srl x, (sub c1, c2), MASK)
5439   // Only fold this if the inner shift has no other uses -- if it does, folding
5440   // this will increase the total number of instructions.
5441   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5442     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5443       uint64_t c1 = N0C1->getZExtValue();
5444       if (c1 < OpSizeInBits) {
5445         uint64_t c2 = N1C->getZExtValue();
5446         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5447         SDValue Shift;
5448         if (c2 > c1) {
5449           Mask <<= c2 - c1;
5450           SDLoc DL(N);
5451           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5452                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5453         } else {
5454           Mask.lshrInPlace(c1 - c2);
5455           SDLoc DL(N);
5456           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5457                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5458         }
5459         SDLoc DL(N0);
5460         return DAG.getNode(ISD::AND, DL, VT, Shift,
5461                            DAG.getConstant(Mask, DL, VT));
5462       }
5463     }
5464   }
5465 
5466   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5467   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5468       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5469     SDLoc DL(N);
5470     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5471     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5472     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5473   }
5474 
5475   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5476   // Variant of version done on multiply, except mul by a power of 2 is turned
5477   // into a shift.
5478   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5479       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5480       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5481     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5482     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5483     AddToWorklist(Shl0.getNode());
5484     AddToWorklist(Shl1.getNode());
5485     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5486   }
5487 
5488   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5489   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5490       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5491       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5492     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5493     if (isConstantOrConstantVector(Shl))
5494       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5495   }
5496 
5497   if (N1C && !N1C->isOpaque())
5498     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5499       return NewSHL;
5500 
5501   return SDValue();
5502 }
5503 
5504 SDValue DAGCombiner::visitSRA(SDNode *N) {
5505   SDValue N0 = N->getOperand(0);
5506   SDValue N1 = N->getOperand(1);
5507   EVT VT = N0.getValueType();
5508   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5509 
5510   // Arithmetic shifting an all-sign-bit value is a no-op.
5511   // fold (sra 0, x) -> 0
5512   // fold (sra -1, x) -> -1
5513   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5514     return N0;
5515 
5516   // fold vector ops
5517   if (VT.isVector())
5518     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5519       return FoldedVOp;
5520 
5521   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5522 
5523   // fold (sra c1, c2) -> (sra c1, c2)
5524   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5525   if (N0C && N1C && !N1C->isOpaque())
5526     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5527   // fold (sra x, c >= size(x)) -> undef
5528   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5529     return DAG.getUNDEF(VT);
5530   // fold (sra x, 0) -> x
5531   if (N1C && N1C->isNullValue())
5532     return N0;
5533 
5534   if (SDValue NewSel = foldBinOpIntoSelect(N))
5535     return NewSel;
5536 
5537   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5538   // sext_inreg.
5539   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5540     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5541     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5542     if (VT.isVector())
5543       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5544                                ExtVT, VT.getVectorNumElements());
5545     if ((!LegalOperations ||
5546          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5547       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5548                          N0.getOperand(0), DAG.getValueType(ExtVT));
5549   }
5550 
5551   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5552   if (N1C && N0.getOpcode() == ISD::SRA) {
5553     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5554       SDLoc DL(N);
5555       APInt c1 = N0C1->getAPIntValue();
5556       APInt c2 = N1C->getAPIntValue();
5557       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5558 
5559       APInt Sum = c1 + c2;
5560       if (Sum.uge(OpSizeInBits))
5561         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5562 
5563       return DAG.getNode(
5564           ISD::SRA, DL, VT, N0.getOperand(0),
5565           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5566     }
5567   }
5568 
5569   // fold (sra (shl X, m), (sub result_size, n))
5570   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5571   // result_size - n != m.
5572   // If truncate is free for the target sext(shl) is likely to result in better
5573   // code.
5574   if (N0.getOpcode() == ISD::SHL && N1C) {
5575     // Get the two constanst of the shifts, CN0 = m, CN = n.
5576     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5577     if (N01C) {
5578       LLVMContext &Ctx = *DAG.getContext();
5579       // Determine what the truncate's result bitsize and type would be.
5580       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5581 
5582       if (VT.isVector())
5583         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5584 
5585       // Determine the residual right-shift amount.
5586       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5587 
5588       // If the shift is not a no-op (in which case this should be just a sign
5589       // extend already), the truncated to type is legal, sign_extend is legal
5590       // on that type, and the truncate to that type is both legal and free,
5591       // perform the transform.
5592       if ((ShiftAmt > 0) &&
5593           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5594           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5595           TLI.isTruncateFree(VT, TruncVT)) {
5596 
5597         SDLoc DL(N);
5598         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5599             getShiftAmountTy(N0.getOperand(0).getValueType()));
5600         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5601                                     N0.getOperand(0), Amt);
5602         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5603                                     Shift);
5604         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5605                            N->getValueType(0), Trunc);
5606       }
5607     }
5608   }
5609 
5610   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5611   if (N1.getOpcode() == ISD::TRUNCATE &&
5612       N1.getOperand(0).getOpcode() == ISD::AND) {
5613     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5614       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5615   }
5616 
5617   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5618   //      if c1 is equal to the number of bits the trunc removes
5619   if (N0.getOpcode() == ISD::TRUNCATE &&
5620       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5621        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5622       N0.getOperand(0).hasOneUse() &&
5623       N0.getOperand(0).getOperand(1).hasOneUse() &&
5624       N1C) {
5625     SDValue N0Op0 = N0.getOperand(0);
5626     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5627       unsigned LargeShiftVal = LargeShift->getZExtValue();
5628       EVT LargeVT = N0Op0.getValueType();
5629 
5630       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5631         SDLoc DL(N);
5632         SDValue Amt =
5633           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5634                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5635         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5636                                   N0Op0.getOperand(0), Amt);
5637         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5638       }
5639     }
5640   }
5641 
5642   // Simplify, based on bits shifted out of the LHS.
5643   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5644     return SDValue(N, 0);
5645 
5646 
5647   // If the sign bit is known to be zero, switch this to a SRL.
5648   if (DAG.SignBitIsZero(N0))
5649     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5650 
5651   if (N1C && !N1C->isOpaque())
5652     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5653       return NewSRA;
5654 
5655   return SDValue();
5656 }
5657 
5658 SDValue DAGCombiner::visitSRL(SDNode *N) {
5659   SDValue N0 = N->getOperand(0);
5660   SDValue N1 = N->getOperand(1);
5661   EVT VT = N0.getValueType();
5662   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5663 
5664   // fold vector ops
5665   if (VT.isVector())
5666     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5667       return FoldedVOp;
5668 
5669   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5670 
5671   // fold (srl c1, c2) -> c1 >>u c2
5672   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5673   if (N0C && N1C && !N1C->isOpaque())
5674     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5675   // fold (srl 0, x) -> 0
5676   if (isNullConstantOrNullSplatConstant(N0))
5677     return N0;
5678   // fold (srl x, c >= size(x)) -> undef
5679   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5680     return DAG.getUNDEF(VT);
5681   // fold (srl x, 0) -> x
5682   if (N1C && N1C->isNullValue())
5683     return N0;
5684 
5685   if (SDValue NewSel = foldBinOpIntoSelect(N))
5686     return NewSel;
5687 
5688   // if (srl x, c) is known to be zero, return 0
5689   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5690                                    APInt::getAllOnesValue(OpSizeInBits)))
5691     return DAG.getConstant(0, SDLoc(N), VT);
5692 
5693   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5694   if (N1C && N0.getOpcode() == ISD::SRL) {
5695     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5696       SDLoc DL(N);
5697       APInt c1 = N0C1->getAPIntValue();
5698       APInt c2 = N1C->getAPIntValue();
5699       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5700 
5701       APInt Sum = c1 + c2;
5702       if (Sum.uge(OpSizeInBits))
5703         return DAG.getConstant(0, DL, VT);
5704 
5705       return DAG.getNode(
5706           ISD::SRL, DL, VT, N0.getOperand(0),
5707           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5708     }
5709   }
5710 
5711   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5712   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5713       N0.getOperand(0).getOpcode() == ISD::SRL) {
5714     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5715       uint64_t c1 = N001C->getZExtValue();
5716       uint64_t c2 = N1C->getZExtValue();
5717       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5718       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5719       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5720       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5721       if (c1 + OpSizeInBits == InnerShiftSize) {
5722         SDLoc DL(N0);
5723         if (c1 + c2 >= InnerShiftSize)
5724           return DAG.getConstant(0, DL, VT);
5725         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5726                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5727                                        N0.getOperand(0).getOperand(0),
5728                                        DAG.getConstant(c1 + c2, DL,
5729                                                        ShiftCountVT)));
5730       }
5731     }
5732   }
5733 
5734   // fold (srl (shl x, c), c) -> (and x, cst2)
5735   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5736       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5737     SDLoc DL(N);
5738     SDValue Mask =
5739         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5740     AddToWorklist(Mask.getNode());
5741     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5742   }
5743 
5744   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5745   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5746     // Shifting in all undef bits?
5747     EVT SmallVT = N0.getOperand(0).getValueType();
5748     unsigned BitSize = SmallVT.getScalarSizeInBits();
5749     if (N1C->getZExtValue() >= BitSize)
5750       return DAG.getUNDEF(VT);
5751 
5752     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5753       uint64_t ShiftAmt = N1C->getZExtValue();
5754       SDLoc DL0(N0);
5755       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5756                                        N0.getOperand(0),
5757                           DAG.getConstant(ShiftAmt, DL0,
5758                                           getShiftAmountTy(SmallVT)));
5759       AddToWorklist(SmallShift.getNode());
5760       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5761       SDLoc DL(N);
5762       return DAG.getNode(ISD::AND, DL, VT,
5763                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5764                          DAG.getConstant(Mask, DL, VT));
5765     }
5766   }
5767 
5768   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5769   // bit, which is unmodified by sra.
5770   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5771     if (N0.getOpcode() == ISD::SRA)
5772       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5773   }
5774 
5775   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5776   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5777       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5778     KnownBits Known;
5779     DAG.computeKnownBits(N0.getOperand(0), Known);
5780 
5781     // If any of the input bits are KnownOne, then the input couldn't be all
5782     // zeros, thus the result of the srl will always be zero.
5783     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5784 
5785     // If all of the bits input the to ctlz node are known to be zero, then
5786     // the result of the ctlz is "32" and the result of the shift is one.
5787     APInt UnknownBits = ~Known.Zero;
5788     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5789 
5790     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5791     if (UnknownBits.isPowerOf2()) {
5792       // Okay, we know that only that the single bit specified by UnknownBits
5793       // could be set on input to the CTLZ node. If this bit is set, the SRL
5794       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5795       // to an SRL/XOR pair, which is likely to simplify more.
5796       unsigned ShAmt = UnknownBits.countTrailingZeros();
5797       SDValue Op = N0.getOperand(0);
5798 
5799       if (ShAmt) {
5800         SDLoc DL(N0);
5801         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5802                   DAG.getConstant(ShAmt, DL,
5803                                   getShiftAmountTy(Op.getValueType())));
5804         AddToWorklist(Op.getNode());
5805       }
5806 
5807       SDLoc DL(N);
5808       return DAG.getNode(ISD::XOR, DL, VT,
5809                          Op, DAG.getConstant(1, DL, VT));
5810     }
5811   }
5812 
5813   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5814   if (N1.getOpcode() == ISD::TRUNCATE &&
5815       N1.getOperand(0).getOpcode() == ISD::AND) {
5816     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5817       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5818   }
5819 
5820   // fold operands of srl based on knowledge that the low bits are not
5821   // demanded.
5822   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5823     return SDValue(N, 0);
5824 
5825   if (N1C && !N1C->isOpaque())
5826     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5827       return NewSRL;
5828 
5829   // Attempt to convert a srl of a load into a narrower zero-extending load.
5830   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5831     return NarrowLoad;
5832 
5833   // Here is a common situation. We want to optimize:
5834   //
5835   //   %a = ...
5836   //   %b = and i32 %a, 2
5837   //   %c = srl i32 %b, 1
5838   //   brcond i32 %c ...
5839   //
5840   // into
5841   //
5842   //   %a = ...
5843   //   %b = and %a, 2
5844   //   %c = setcc eq %b, 0
5845   //   brcond %c ...
5846   //
5847   // However when after the source operand of SRL is optimized into AND, the SRL
5848   // itself may not be optimized further. Look for it and add the BRCOND into
5849   // the worklist.
5850   if (N->hasOneUse()) {
5851     SDNode *Use = *N->use_begin();
5852     if (Use->getOpcode() == ISD::BRCOND)
5853       AddToWorklist(Use);
5854     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5855       // Also look pass the truncate.
5856       Use = *Use->use_begin();
5857       if (Use->getOpcode() == ISD::BRCOND)
5858         AddToWorklist(Use);
5859     }
5860   }
5861 
5862   return SDValue();
5863 }
5864 
5865 SDValue DAGCombiner::visitABS(SDNode *N) {
5866   SDValue N0 = N->getOperand(0);
5867   EVT VT = N->getValueType(0);
5868 
5869   // fold (abs c1) -> c2
5870   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5871     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5872   // fold (abs (abs x)) -> (abs x)
5873   if (N0.getOpcode() == ISD::ABS)
5874     return N0;
5875   // fold (abs x) -> x iff not-negative
5876   if (DAG.SignBitIsZero(N0))
5877     return N0;
5878   return SDValue();
5879 }
5880 
5881 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5882   SDValue N0 = N->getOperand(0);
5883   EVT VT = N->getValueType(0);
5884 
5885   // fold (bswap c1) -> c2
5886   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5887     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5888   // fold (bswap (bswap x)) -> x
5889   if (N0.getOpcode() == ISD::BSWAP)
5890     return N0->getOperand(0);
5891   return SDValue();
5892 }
5893 
5894 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5895   SDValue N0 = N->getOperand(0);
5896   EVT VT = N->getValueType(0);
5897 
5898   // fold (bitreverse c1) -> c2
5899   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5900     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5901   // fold (bitreverse (bitreverse x)) -> x
5902   if (N0.getOpcode() == ISD::BITREVERSE)
5903     return N0.getOperand(0);
5904   return SDValue();
5905 }
5906 
5907 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5908   SDValue N0 = N->getOperand(0);
5909   EVT VT = N->getValueType(0);
5910 
5911   // fold (ctlz c1) -> c2
5912   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5913     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5914   return SDValue();
5915 }
5916 
5917 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5918   SDValue N0 = N->getOperand(0);
5919   EVT VT = N->getValueType(0);
5920 
5921   // fold (ctlz_zero_undef c1) -> c2
5922   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5923     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5924   return SDValue();
5925 }
5926 
5927 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5928   SDValue N0 = N->getOperand(0);
5929   EVT VT = N->getValueType(0);
5930 
5931   // fold (cttz c1) -> c2
5932   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5933     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5934   return SDValue();
5935 }
5936 
5937 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5938   SDValue N0 = N->getOperand(0);
5939   EVT VT = N->getValueType(0);
5940 
5941   // fold (cttz_zero_undef c1) -> c2
5942   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5943     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5944   return SDValue();
5945 }
5946 
5947 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5948   SDValue N0 = N->getOperand(0);
5949   EVT VT = N->getValueType(0);
5950 
5951   // fold (ctpop c1) -> c2
5952   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5953     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5954   return SDValue();
5955 }
5956 
5957 
5958 /// \brief Generate Min/Max node
5959 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5960                                    SDValue RHS, SDValue True, SDValue False,
5961                                    ISD::CondCode CC, const TargetLowering &TLI,
5962                                    SelectionDAG &DAG) {
5963   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5964     return SDValue();
5965 
5966   switch (CC) {
5967   case ISD::SETOLT:
5968   case ISD::SETOLE:
5969   case ISD::SETLT:
5970   case ISD::SETLE:
5971   case ISD::SETULT:
5972   case ISD::SETULE: {
5973     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5974     if (TLI.isOperationLegal(Opcode, VT))
5975       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5976     return SDValue();
5977   }
5978   case ISD::SETOGT:
5979   case ISD::SETOGE:
5980   case ISD::SETGT:
5981   case ISD::SETGE:
5982   case ISD::SETUGT:
5983   case ISD::SETUGE: {
5984     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5985     if (TLI.isOperationLegal(Opcode, VT))
5986       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5987     return SDValue();
5988   }
5989   default:
5990     return SDValue();
5991   }
5992 }
5993 
5994 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5995   SDValue Cond = N->getOperand(0);
5996   SDValue N1 = N->getOperand(1);
5997   SDValue N2 = N->getOperand(2);
5998   EVT VT = N->getValueType(0);
5999   EVT CondVT = Cond.getValueType();
6000   SDLoc DL(N);
6001 
6002   if (!VT.isInteger())
6003     return SDValue();
6004 
6005   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6006   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6007   if (!C1 || !C2)
6008     return SDValue();
6009 
6010   // Only do this before legalization to avoid conflicting with target-specific
6011   // transforms in the other direction (create a select from a zext/sext). There
6012   // is also a target-independent combine here in DAGCombiner in the other
6013   // direction for (select Cond, -1, 0) when the condition is not i1.
6014   if (CondVT == MVT::i1 && !LegalOperations) {
6015     if (C1->isNullValue() && C2->isOne()) {
6016       // select Cond, 0, 1 --> zext (!Cond)
6017       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6018       if (VT != MVT::i1)
6019         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6020       return NotCond;
6021     }
6022     if (C1->isNullValue() && C2->isAllOnesValue()) {
6023       // select Cond, 0, -1 --> sext (!Cond)
6024       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6025       if (VT != MVT::i1)
6026         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6027       return NotCond;
6028     }
6029     if (C1->isOne() && C2->isNullValue()) {
6030       // select Cond, 1, 0 --> zext (Cond)
6031       if (VT != MVT::i1)
6032         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6033       return Cond;
6034     }
6035     if (C1->isAllOnesValue() && C2->isNullValue()) {
6036       // select Cond, -1, 0 --> sext (Cond)
6037       if (VT != MVT::i1)
6038         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6039       return Cond;
6040     }
6041 
6042     // For any constants that differ by 1, we can transform the select into an
6043     // extend and add. Use a target hook because some targets may prefer to
6044     // transform in the other direction.
6045     if (TLI.convertSelectOfConstantsToMath()) {
6046       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6047         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6048         if (VT != MVT::i1)
6049           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6050         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6051       }
6052       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6053         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6054         if (VT != MVT::i1)
6055           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6056         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6057       }
6058     }
6059 
6060     return SDValue();
6061   }
6062 
6063   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6064   // We can't do this reliably if integer based booleans have different contents
6065   // to floating point based booleans. This is because we can't tell whether we
6066   // have an integer-based boolean or a floating-point-based boolean unless we
6067   // can find the SETCC that produced it and inspect its operands. This is
6068   // fairly easy if C is the SETCC node, but it can potentially be
6069   // undiscoverable (or not reasonably discoverable). For example, it could be
6070   // in another basic block or it could require searching a complicated
6071   // expression.
6072   if (CondVT.isInteger() &&
6073       TLI.getBooleanContents(false, true) ==
6074           TargetLowering::ZeroOrOneBooleanContent &&
6075       TLI.getBooleanContents(false, false) ==
6076           TargetLowering::ZeroOrOneBooleanContent &&
6077       C1->isNullValue() && C2->isOne()) {
6078     SDValue NotCond =
6079         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6080     if (VT.bitsEq(CondVT))
6081       return NotCond;
6082     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6083   }
6084 
6085   return SDValue();
6086 }
6087 
6088 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6089   SDValue N0 = N->getOperand(0);
6090   SDValue N1 = N->getOperand(1);
6091   SDValue N2 = N->getOperand(2);
6092   EVT VT = N->getValueType(0);
6093   EVT VT0 = N0.getValueType();
6094 
6095   // fold (select C, X, X) -> X
6096   if (N1 == N2)
6097     return N1;
6098   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6099     // fold (select true, X, Y) -> X
6100     // fold (select false, X, Y) -> Y
6101     return !N0C->isNullValue() ? N1 : N2;
6102   }
6103   // fold (select X, X, Y) -> (or X, Y)
6104   // fold (select X, 1, Y) -> (or C, Y)
6105   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6106     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6107 
6108   if (SDValue V = foldSelectOfConstants(N))
6109     return V;
6110 
6111   // fold (select C, 0, X) -> (and (not C), X)
6112   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6113     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6114     AddToWorklist(NOTNode.getNode());
6115     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6116   }
6117   // fold (select C, X, 1) -> (or (not C), X)
6118   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6119     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6120     AddToWorklist(NOTNode.getNode());
6121     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6122   }
6123   // fold (select X, Y, X) -> (and X, Y)
6124   // fold (select X, Y, 0) -> (and X, Y)
6125   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6126     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6127 
6128   // If we can fold this based on the true/false value, do so.
6129   if (SimplifySelectOps(N, N1, N2))
6130     return SDValue(N, 0);  // Don't revisit N.
6131 
6132   if (VT0 == MVT::i1) {
6133     // The code in this block deals with the following 2 equivalences:
6134     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6135     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6136     // The target can specify its preferred form with the
6137     // shouldNormalizeToSelectSequence() callback. However we always transform
6138     // to the right anyway if we find the inner select exists in the DAG anyway
6139     // and we always transform to the left side if we know that we can further
6140     // optimize the combination of the conditions.
6141     bool normalizeToSequence
6142       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6143     // select (and Cond0, Cond1), X, Y
6144     //   -> select Cond0, (select Cond1, X, Y), Y
6145     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6146       SDValue Cond0 = N0->getOperand(0);
6147       SDValue Cond1 = N0->getOperand(1);
6148       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6149                                         N1.getValueType(), Cond1, N1, N2);
6150       if (normalizeToSequence || !InnerSelect.use_empty())
6151         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6152                            InnerSelect, N2);
6153     }
6154     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6155     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6156       SDValue Cond0 = N0->getOperand(0);
6157       SDValue Cond1 = N0->getOperand(1);
6158       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6159                                         N1.getValueType(), Cond1, N1, N2);
6160       if (normalizeToSequence || !InnerSelect.use_empty())
6161         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6162                            InnerSelect);
6163     }
6164 
6165     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6166     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6167       SDValue N1_0 = N1->getOperand(0);
6168       SDValue N1_1 = N1->getOperand(1);
6169       SDValue N1_2 = N1->getOperand(2);
6170       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6171         // Create the actual and node if we can generate good code for it.
6172         if (!normalizeToSequence) {
6173           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6174                                     N0, N1_0);
6175           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6176                              N1_1, N2);
6177         }
6178         // Otherwise see if we can optimize the "and" to a better pattern.
6179         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6180           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6181                              N1_1, N2);
6182       }
6183     }
6184     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6185     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6186       SDValue N2_0 = N2->getOperand(0);
6187       SDValue N2_1 = N2->getOperand(1);
6188       SDValue N2_2 = N2->getOperand(2);
6189       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6190         // Create the actual or node if we can generate good code for it.
6191         if (!normalizeToSequence) {
6192           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6193                                    N0, N2_0);
6194           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6195                              N1, N2_2);
6196         }
6197         // Otherwise see if we can optimize to a better pattern.
6198         if (SDValue Combined = visitORLike(N0, N2_0, N))
6199           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6200                              N1, N2_2);
6201       }
6202     }
6203   }
6204 
6205   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6206   if (VT0 == MVT::i1) {
6207     if (N0->getOpcode() == ISD::XOR) {
6208       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6209         SDValue Cond0 = N0->getOperand(0);
6210         if (C->isOne())
6211           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6212                              Cond0, N2, N1);
6213       }
6214     }
6215   }
6216 
6217   // fold selects based on a setcc into other things, such as min/max/abs
6218   if (N0.getOpcode() == ISD::SETCC) {
6219     // select x, y (fcmp lt x, y) -> fminnum x, y
6220     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6221     //
6222     // This is OK if we don't care about what happens if either operand is a
6223     // NaN.
6224     //
6225 
6226     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6227     // no signed zeros as well as no nans.
6228     const TargetOptions &Options = DAG.getTarget().Options;
6229     if (Options.UnsafeFPMath &&
6230         VT.isFloatingPoint() && N0.hasOneUse() &&
6231         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6232       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6233 
6234       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6235                                                 N0.getOperand(1), N1, N2, CC,
6236                                                 TLI, DAG))
6237         return FMinMax;
6238     }
6239 
6240     if ((!LegalOperations &&
6241          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6242         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6243       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6244                          N0.getOperand(0), N0.getOperand(1),
6245                          N1, N2, N0.getOperand(2));
6246     return SimplifySelect(SDLoc(N), N0, N1, N2);
6247   }
6248 
6249   return SDValue();
6250 }
6251 
6252 static
6253 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6254   SDLoc DL(N);
6255   EVT LoVT, HiVT;
6256   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6257 
6258   // Split the inputs.
6259   SDValue Lo, Hi, LL, LH, RL, RH;
6260   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6261   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6262 
6263   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6264   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6265 
6266   return std::make_pair(Lo, Hi);
6267 }
6268 
6269 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6270 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6271 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6272   SDLoc DL(N);
6273   SDValue Cond = N->getOperand(0);
6274   SDValue LHS = N->getOperand(1);
6275   SDValue RHS = N->getOperand(2);
6276   EVT VT = N->getValueType(0);
6277   int NumElems = VT.getVectorNumElements();
6278   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6279          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6280          Cond.getOpcode() == ISD::BUILD_VECTOR);
6281 
6282   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6283   // binary ones here.
6284   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6285     return SDValue();
6286 
6287   // We're sure we have an even number of elements due to the
6288   // concat_vectors we have as arguments to vselect.
6289   // Skip BV elements until we find one that's not an UNDEF
6290   // After we find an UNDEF element, keep looping until we get to half the
6291   // length of the BV and see if all the non-undef nodes are the same.
6292   ConstantSDNode *BottomHalf = nullptr;
6293   for (int i = 0; i < NumElems / 2; ++i) {
6294     if (Cond->getOperand(i)->isUndef())
6295       continue;
6296 
6297     if (BottomHalf == nullptr)
6298       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6299     else if (Cond->getOperand(i).getNode() != BottomHalf)
6300       return SDValue();
6301   }
6302 
6303   // Do the same for the second half of the BuildVector
6304   ConstantSDNode *TopHalf = nullptr;
6305   for (int i = NumElems / 2; i < NumElems; ++i) {
6306     if (Cond->getOperand(i)->isUndef())
6307       continue;
6308 
6309     if (TopHalf == nullptr)
6310       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6311     else if (Cond->getOperand(i).getNode() != TopHalf)
6312       return SDValue();
6313   }
6314 
6315   assert(TopHalf && BottomHalf &&
6316          "One half of the selector was all UNDEFs and the other was all the "
6317          "same value. This should have been addressed before this function.");
6318   return DAG.getNode(
6319       ISD::CONCAT_VECTORS, DL, VT,
6320       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6321       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6322 }
6323 
6324 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6325 
6326   if (Level >= AfterLegalizeTypes)
6327     return SDValue();
6328 
6329   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6330   SDValue Mask = MSC->getMask();
6331   SDValue Data  = MSC->getValue();
6332   SDLoc DL(N);
6333 
6334   // If the MSCATTER data type requires splitting and the mask is provided by a
6335   // SETCC, then split both nodes and its operands before legalization. This
6336   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6337   // and enables future optimizations (e.g. min/max pattern matching on X86).
6338   if (Mask.getOpcode() != ISD::SETCC)
6339     return SDValue();
6340 
6341   // Check if any splitting is required.
6342   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6343       TargetLowering::TypeSplitVector)
6344     return SDValue();
6345   SDValue MaskLo, MaskHi, Lo, Hi;
6346   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6347 
6348   EVT LoVT, HiVT;
6349   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6350 
6351   SDValue Chain = MSC->getChain();
6352 
6353   EVT MemoryVT = MSC->getMemoryVT();
6354   unsigned Alignment = MSC->getOriginalAlignment();
6355 
6356   EVT LoMemVT, HiMemVT;
6357   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6358 
6359   SDValue DataLo, DataHi;
6360   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6361 
6362   SDValue BasePtr = MSC->getBasePtr();
6363   SDValue IndexLo, IndexHi;
6364   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6365 
6366   MachineMemOperand *MMO = DAG.getMachineFunction().
6367     getMachineMemOperand(MSC->getPointerInfo(),
6368                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6369                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6370 
6371   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6372   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6373                             DL, OpsLo, MMO);
6374 
6375   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6376   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6377                             DL, OpsHi, MMO);
6378 
6379   AddToWorklist(Lo.getNode());
6380   AddToWorklist(Hi.getNode());
6381 
6382   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6383 }
6384 
6385 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6386 
6387   if (Level >= AfterLegalizeTypes)
6388     return SDValue();
6389 
6390   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6391   SDValue Mask = MST->getMask();
6392   SDValue Data  = MST->getValue();
6393   EVT VT = Data.getValueType();
6394   SDLoc DL(N);
6395 
6396   // If the MSTORE data type requires splitting and the mask is provided by a
6397   // SETCC, then split both nodes and its operands before legalization. This
6398   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6399   // and enables future optimizations (e.g. min/max pattern matching on X86).
6400   if (Mask.getOpcode() == ISD::SETCC) {
6401 
6402     // Check if any splitting is required.
6403     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6404         TargetLowering::TypeSplitVector)
6405       return SDValue();
6406 
6407     SDValue MaskLo, MaskHi, Lo, Hi;
6408     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6409 
6410     SDValue Chain = MST->getChain();
6411     SDValue Ptr   = MST->getBasePtr();
6412 
6413     EVT MemoryVT = MST->getMemoryVT();
6414     unsigned Alignment = MST->getOriginalAlignment();
6415 
6416     // if Alignment is equal to the vector size,
6417     // take the half of it for the second part
6418     unsigned SecondHalfAlignment =
6419       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6420 
6421     EVT LoMemVT, HiMemVT;
6422     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6423 
6424     SDValue DataLo, DataHi;
6425     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6426 
6427     MachineMemOperand *MMO = DAG.getMachineFunction().
6428       getMachineMemOperand(MST->getPointerInfo(),
6429                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6430                            Alignment, MST->getAAInfo(), MST->getRanges());
6431 
6432     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6433                             MST->isTruncatingStore(),
6434                             MST->isCompressingStore());
6435 
6436     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6437                                      MST->isCompressingStore());
6438 
6439     MMO = DAG.getMachineFunction().
6440       getMachineMemOperand(MST->getPointerInfo(),
6441                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6442                            SecondHalfAlignment, MST->getAAInfo(),
6443                            MST->getRanges());
6444 
6445     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6446                             MST->isTruncatingStore(),
6447                             MST->isCompressingStore());
6448 
6449     AddToWorklist(Lo.getNode());
6450     AddToWorklist(Hi.getNode());
6451 
6452     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6453   }
6454   return SDValue();
6455 }
6456 
6457 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6458 
6459   if (Level >= AfterLegalizeTypes)
6460     return SDValue();
6461 
6462   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6463   SDValue Mask = MGT->getMask();
6464   SDLoc DL(N);
6465 
6466   // If the MGATHER result requires splitting and the mask is provided by a
6467   // SETCC, then split both nodes and its operands before legalization. This
6468   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6469   // and enables future optimizations (e.g. min/max pattern matching on X86).
6470 
6471   if (Mask.getOpcode() != ISD::SETCC)
6472     return SDValue();
6473 
6474   EVT VT = N->getValueType(0);
6475 
6476   // Check if any splitting is required.
6477   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6478       TargetLowering::TypeSplitVector)
6479     return SDValue();
6480 
6481   SDValue MaskLo, MaskHi, Lo, Hi;
6482   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6483 
6484   SDValue Src0 = MGT->getValue();
6485   SDValue Src0Lo, Src0Hi;
6486   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6487 
6488   EVT LoVT, HiVT;
6489   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6490 
6491   SDValue Chain = MGT->getChain();
6492   EVT MemoryVT = MGT->getMemoryVT();
6493   unsigned Alignment = MGT->getOriginalAlignment();
6494 
6495   EVT LoMemVT, HiMemVT;
6496   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6497 
6498   SDValue BasePtr = MGT->getBasePtr();
6499   SDValue Index = MGT->getIndex();
6500   SDValue IndexLo, IndexHi;
6501   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6502 
6503   MachineMemOperand *MMO = DAG.getMachineFunction().
6504     getMachineMemOperand(MGT->getPointerInfo(),
6505                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6506                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6507 
6508   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6509   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6510                             MMO);
6511 
6512   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6513   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6514                             MMO);
6515 
6516   AddToWorklist(Lo.getNode());
6517   AddToWorklist(Hi.getNode());
6518 
6519   // Build a factor node to remember that this load is independent of the
6520   // other one.
6521   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6522                       Hi.getValue(1));
6523 
6524   // Legalized the chain result - switch anything that used the old chain to
6525   // use the new one.
6526   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6527 
6528   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6529 
6530   SDValue RetOps[] = { GatherRes, Chain };
6531   return DAG.getMergeValues(RetOps, DL);
6532 }
6533 
6534 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6535 
6536   if (Level >= AfterLegalizeTypes)
6537     return SDValue();
6538 
6539   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6540   SDValue Mask = MLD->getMask();
6541   SDLoc DL(N);
6542 
6543   // If the MLOAD result requires splitting and the mask is provided by a
6544   // SETCC, then split both nodes and its operands before legalization. This
6545   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6546   // and enables future optimizations (e.g. min/max pattern matching on X86).
6547 
6548   if (Mask.getOpcode() == ISD::SETCC) {
6549     EVT VT = N->getValueType(0);
6550 
6551     // Check if any splitting is required.
6552     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6553         TargetLowering::TypeSplitVector)
6554       return SDValue();
6555 
6556     SDValue MaskLo, MaskHi, Lo, Hi;
6557     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6558 
6559     SDValue Src0 = MLD->getSrc0();
6560     SDValue Src0Lo, Src0Hi;
6561     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6562 
6563     EVT LoVT, HiVT;
6564     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6565 
6566     SDValue Chain = MLD->getChain();
6567     SDValue Ptr   = MLD->getBasePtr();
6568     EVT MemoryVT = MLD->getMemoryVT();
6569     unsigned Alignment = MLD->getOriginalAlignment();
6570 
6571     // if Alignment is equal to the vector size,
6572     // take the half of it for the second part
6573     unsigned SecondHalfAlignment =
6574       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6575          Alignment/2 : Alignment;
6576 
6577     EVT LoMemVT, HiMemVT;
6578     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6579 
6580     MachineMemOperand *MMO = DAG.getMachineFunction().
6581     getMachineMemOperand(MLD->getPointerInfo(),
6582                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6583                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6584 
6585     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6586                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6587 
6588     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6589                                      MLD->isExpandingLoad());
6590 
6591     MMO = DAG.getMachineFunction().
6592     getMachineMemOperand(MLD->getPointerInfo(),
6593                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6594                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6595 
6596     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6597                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6598 
6599     AddToWorklist(Lo.getNode());
6600     AddToWorklist(Hi.getNode());
6601 
6602     // Build a factor node to remember that this load is independent of the
6603     // other one.
6604     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6605                         Hi.getValue(1));
6606 
6607     // Legalized the chain result - switch anything that used the old chain to
6608     // use the new one.
6609     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6610 
6611     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6612 
6613     SDValue RetOps[] = { LoadRes, Chain };
6614     return DAG.getMergeValues(RetOps, DL);
6615   }
6616   return SDValue();
6617 }
6618 
6619 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6620   SDValue N0 = N->getOperand(0);
6621   SDValue N1 = N->getOperand(1);
6622   SDValue N2 = N->getOperand(2);
6623   SDLoc DL(N);
6624 
6625   // fold (vselect C, X, X) -> X
6626   if (N1 == N2)
6627     return N1;
6628 
6629   // Canonicalize integer abs.
6630   // vselect (setg[te] X,  0),  X, -X ->
6631   // vselect (setgt    X, -1),  X, -X ->
6632   // vselect (setl[te] X,  0), -X,  X ->
6633   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6634   if (N0.getOpcode() == ISD::SETCC) {
6635     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6636     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6637     bool isAbs = false;
6638     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6639 
6640     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6641          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6642         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6643       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6644     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6645              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6646       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6647 
6648     if (isAbs) {
6649       EVT VT = LHS.getValueType();
6650       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6651         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6652 
6653       SDValue Shift = DAG.getNode(
6654           ISD::SRA, DL, VT, LHS,
6655           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6656       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6657       AddToWorklist(Shift.getNode());
6658       AddToWorklist(Add.getNode());
6659       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6660     }
6661   }
6662 
6663   if (SimplifySelectOps(N, N1, N2))
6664     return SDValue(N, 0);  // Don't revisit N.
6665 
6666   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6667   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6668     return N1;
6669   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6670   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6671     return N2;
6672 
6673   // The ConvertSelectToConcatVector function is assuming both the above
6674   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6675   // and addressed.
6676   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6677       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6678       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6679     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6680       return CV;
6681   }
6682 
6683   return SDValue();
6684 }
6685 
6686 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6687   SDValue N0 = N->getOperand(0);
6688   SDValue N1 = N->getOperand(1);
6689   SDValue N2 = N->getOperand(2);
6690   SDValue N3 = N->getOperand(3);
6691   SDValue N4 = N->getOperand(4);
6692   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6693 
6694   // fold select_cc lhs, rhs, x, x, cc -> x
6695   if (N2 == N3)
6696     return N2;
6697 
6698   // Determine if the condition we're dealing with is constant
6699   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6700                                   CC, SDLoc(N), false)) {
6701     AddToWorklist(SCC.getNode());
6702 
6703     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6704       if (!SCCC->isNullValue())
6705         return N2;    // cond always true -> true val
6706       else
6707         return N3;    // cond always false -> false val
6708     } else if (SCC->isUndef()) {
6709       // When the condition is UNDEF, just return the first operand. This is
6710       // coherent the DAG creation, no setcc node is created in this case
6711       return N2;
6712     } else if (SCC.getOpcode() == ISD::SETCC) {
6713       // Fold to a simpler select_cc
6714       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6715                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6716                          SCC.getOperand(2));
6717     }
6718   }
6719 
6720   // If we can fold this based on the true/false value, do so.
6721   if (SimplifySelectOps(N, N2, N3))
6722     return SDValue(N, 0);  // Don't revisit N.
6723 
6724   // fold select_cc into other things, such as min/max/abs
6725   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6726 }
6727 
6728 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6729   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6730                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6731                        SDLoc(N));
6732 }
6733 
6734 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6735   SDValue LHS = N->getOperand(0);
6736   SDValue RHS = N->getOperand(1);
6737   SDValue Carry = N->getOperand(2);
6738   SDValue Cond = N->getOperand(3);
6739 
6740   // If Carry is false, fold to a regular SETCC.
6741   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6742     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6743 
6744   return SDValue();
6745 }
6746 
6747 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
6748   SDValue LHS = N->getOperand(0);
6749   SDValue RHS = N->getOperand(1);
6750   SDValue Carry = N->getOperand(2);
6751   SDValue Cond = N->getOperand(3);
6752 
6753   // If Carry is false, fold to a regular SETCC.
6754   if (isNullConstant(Carry))
6755     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6756 
6757   return SDValue();
6758 }
6759 
6760 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6761 /// a build_vector of constants.
6762 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6763 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6764 /// Vector extends are not folded if operations are legal; this is to
6765 /// avoid introducing illegal build_vector dag nodes.
6766 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6767                                          SelectionDAG &DAG, bool LegalTypes,
6768                                          bool LegalOperations) {
6769   unsigned Opcode = N->getOpcode();
6770   SDValue N0 = N->getOperand(0);
6771   EVT VT = N->getValueType(0);
6772 
6773   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6774          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6775          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6776          && "Expected EXTEND dag node in input!");
6777 
6778   // fold (sext c1) -> c1
6779   // fold (zext c1) -> c1
6780   // fold (aext c1) -> c1
6781   if (isa<ConstantSDNode>(N0))
6782     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6783 
6784   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6785   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6786   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6787   EVT SVT = VT.getScalarType();
6788   if (!(VT.isVector() &&
6789       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6790       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6791     return nullptr;
6792 
6793   // We can fold this node into a build_vector.
6794   unsigned VTBits = SVT.getSizeInBits();
6795   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6796   SmallVector<SDValue, 8> Elts;
6797   unsigned NumElts = VT.getVectorNumElements();
6798   SDLoc DL(N);
6799 
6800   for (unsigned i=0; i != NumElts; ++i) {
6801     SDValue Op = N0->getOperand(i);
6802     if (Op->isUndef()) {
6803       Elts.push_back(DAG.getUNDEF(SVT));
6804       continue;
6805     }
6806 
6807     SDLoc DL(Op);
6808     // Get the constant value and if needed trunc it to the size of the type.
6809     // Nodes like build_vector might have constants wider than the scalar type.
6810     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6811     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6812       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6813     else
6814       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6815   }
6816 
6817   return DAG.getBuildVector(VT, DL, Elts).getNode();
6818 }
6819 
6820 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6821 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6822 // transformation. Returns true if extension are possible and the above
6823 // mentioned transformation is profitable.
6824 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6825                                     unsigned ExtOpc,
6826                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6827                                     const TargetLowering &TLI) {
6828   bool HasCopyToRegUses = false;
6829   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6830   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6831                             UE = N0.getNode()->use_end();
6832        UI != UE; ++UI) {
6833     SDNode *User = *UI;
6834     if (User == N)
6835       continue;
6836     if (UI.getUse().getResNo() != N0.getResNo())
6837       continue;
6838     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6839     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6840       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6841       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6842         // Sign bits will be lost after a zext.
6843         return false;
6844       bool Add = false;
6845       for (unsigned i = 0; i != 2; ++i) {
6846         SDValue UseOp = User->getOperand(i);
6847         if (UseOp == N0)
6848           continue;
6849         if (!isa<ConstantSDNode>(UseOp))
6850           return false;
6851         Add = true;
6852       }
6853       if (Add)
6854         ExtendNodes.push_back(User);
6855       continue;
6856     }
6857     // If truncates aren't free and there are users we can't
6858     // extend, it isn't worthwhile.
6859     if (!isTruncFree)
6860       return false;
6861     // Remember if this value is live-out.
6862     if (User->getOpcode() == ISD::CopyToReg)
6863       HasCopyToRegUses = true;
6864   }
6865 
6866   if (HasCopyToRegUses) {
6867     bool BothLiveOut = false;
6868     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6869          UI != UE; ++UI) {
6870       SDUse &Use = UI.getUse();
6871       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6872         BothLiveOut = true;
6873         break;
6874       }
6875     }
6876     if (BothLiveOut)
6877       // Both unextended and extended values are live out. There had better be
6878       // a good reason for the transformation.
6879       return ExtendNodes.size();
6880   }
6881   return true;
6882 }
6883 
6884 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6885                                   SDValue Trunc, SDValue ExtLoad,
6886                                   const SDLoc &DL, ISD::NodeType ExtType) {
6887   // Extend SetCC uses if necessary.
6888   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6889     SDNode *SetCC = SetCCs[i];
6890     SmallVector<SDValue, 4> Ops;
6891 
6892     for (unsigned j = 0; j != 2; ++j) {
6893       SDValue SOp = SetCC->getOperand(j);
6894       if (SOp == Trunc)
6895         Ops.push_back(ExtLoad);
6896       else
6897         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6898     }
6899 
6900     Ops.push_back(SetCC->getOperand(2));
6901     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6902   }
6903 }
6904 
6905 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6906 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6907   SDValue N0 = N->getOperand(0);
6908   EVT DstVT = N->getValueType(0);
6909   EVT SrcVT = N0.getValueType();
6910 
6911   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6912           N->getOpcode() == ISD::ZERO_EXTEND) &&
6913          "Unexpected node type (not an extend)!");
6914 
6915   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6916   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6917   //   (v8i32 (sext (v8i16 (load x))))
6918   // into:
6919   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6920   //                          (v4i32 (sextload (x + 16)))))
6921   // Where uses of the original load, i.e.:
6922   //   (v8i16 (load x))
6923   // are replaced with:
6924   //   (v8i16 (truncate
6925   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6926   //                            (v4i32 (sextload (x + 16)))))))
6927   //
6928   // This combine is only applicable to illegal, but splittable, vectors.
6929   // All legal types, and illegal non-vector types, are handled elsewhere.
6930   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6931   //
6932   if (N0->getOpcode() != ISD::LOAD)
6933     return SDValue();
6934 
6935   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6936 
6937   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6938       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6939       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6940     return SDValue();
6941 
6942   SmallVector<SDNode *, 4> SetCCs;
6943   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6944     return SDValue();
6945 
6946   ISD::LoadExtType ExtType =
6947       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6948 
6949   // Try to split the vector types to get down to legal types.
6950   EVT SplitSrcVT = SrcVT;
6951   EVT SplitDstVT = DstVT;
6952   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6953          SplitSrcVT.getVectorNumElements() > 1) {
6954     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6955     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6956   }
6957 
6958   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6959     return SDValue();
6960 
6961   SDLoc DL(N);
6962   const unsigned NumSplits =
6963       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6964   const unsigned Stride = SplitSrcVT.getStoreSize();
6965   SmallVector<SDValue, 4> Loads;
6966   SmallVector<SDValue, 4> Chains;
6967 
6968   SDValue BasePtr = LN0->getBasePtr();
6969   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6970     const unsigned Offset = Idx * Stride;
6971     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6972 
6973     SDValue SplitLoad = DAG.getExtLoad(
6974         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6975         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6976         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6977 
6978     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6979                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6980 
6981     Loads.push_back(SplitLoad.getValue(0));
6982     Chains.push_back(SplitLoad.getValue(1));
6983   }
6984 
6985   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6986   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6987 
6988   // Simplify TF.
6989   AddToWorklist(NewChain.getNode());
6990 
6991   CombineTo(N, NewValue);
6992 
6993   // Replace uses of the original load (before extension)
6994   // with a truncate of the concatenated sextloaded vectors.
6995   SDValue Trunc =
6996       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6997   CombineTo(N0.getNode(), Trunc, NewChain);
6998   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6999                   (ISD::NodeType)N->getOpcode());
7000   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7001 }
7002 
7003 /// If we're narrowing or widening the result of a vector select and the final
7004 /// size is the same size as a setcc (compare) feeding the select, then try to
7005 /// apply the cast operation to the select's operands because matching vector
7006 /// sizes for a select condition and other operands should be more efficient.
7007 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7008   unsigned CastOpcode = Cast->getOpcode();
7009   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7010           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7011           CastOpcode == ISD::FP_ROUND) &&
7012          "Unexpected opcode for vector select narrowing/widening");
7013 
7014   // We only do this transform before legal ops because the pattern may be
7015   // obfuscated by target-specific operations after legalization. Do not create
7016   // an illegal select op, however, because that may be difficult to lower.
7017   EVT VT = Cast->getValueType(0);
7018   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7019     return SDValue();
7020 
7021   SDValue VSel = Cast->getOperand(0);
7022   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7023       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7024     return SDValue();
7025 
7026   // Does the setcc have the same vector size as the casted select?
7027   SDValue SetCC = VSel.getOperand(0);
7028   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7029   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7030     return SDValue();
7031 
7032   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7033   SDValue A = VSel.getOperand(1);
7034   SDValue B = VSel.getOperand(2);
7035   SDValue CastA, CastB;
7036   SDLoc DL(Cast);
7037   if (CastOpcode == ISD::FP_ROUND) {
7038     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7039     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7040     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7041   } else {
7042     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7043     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7044   }
7045   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7046 }
7047 
7048 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7049   SDValue N0 = N->getOperand(0);
7050   EVT VT = N->getValueType(0);
7051   SDLoc DL(N);
7052 
7053   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7054                                               LegalOperations))
7055     return SDValue(Res, 0);
7056 
7057   // fold (sext (sext x)) -> (sext x)
7058   // fold (sext (aext x)) -> (sext x)
7059   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7060     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7061 
7062   if (N0.getOpcode() == ISD::TRUNCATE) {
7063     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7064     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7065     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7066       SDNode *oye = N0.getOperand(0).getNode();
7067       if (NarrowLoad.getNode() != N0.getNode()) {
7068         CombineTo(N0.getNode(), NarrowLoad);
7069         // CombineTo deleted the truncate, if needed, but not what's under it.
7070         AddToWorklist(oye);
7071       }
7072       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7073     }
7074 
7075     // See if the value being truncated is already sign extended.  If so, just
7076     // eliminate the trunc/sext pair.
7077     SDValue Op = N0.getOperand(0);
7078     unsigned OpBits   = Op.getScalarValueSizeInBits();
7079     unsigned MidBits  = N0.getScalarValueSizeInBits();
7080     unsigned DestBits = VT.getScalarSizeInBits();
7081     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7082 
7083     if (OpBits == DestBits) {
7084       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7085       // bits, it is already ready.
7086       if (NumSignBits > DestBits-MidBits)
7087         return Op;
7088     } else if (OpBits < DestBits) {
7089       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7090       // bits, just sext from i32.
7091       if (NumSignBits > OpBits-MidBits)
7092         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7093     } else {
7094       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7095       // bits, just truncate to i32.
7096       if (NumSignBits > OpBits-MidBits)
7097         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7098     }
7099 
7100     // fold (sext (truncate x)) -> (sextinreg x).
7101     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7102                                                  N0.getValueType())) {
7103       if (OpBits < DestBits)
7104         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7105       else if (OpBits > DestBits)
7106         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7107       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7108                          DAG.getValueType(N0.getValueType()));
7109     }
7110   }
7111 
7112   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7113   // Only generate vector extloads when 1) they're legal, and 2) they are
7114   // deemed desirable by the target.
7115   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7116       ((!LegalOperations && !VT.isVector() &&
7117         !cast<LoadSDNode>(N0)->isVolatile()) ||
7118        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7119     bool DoXform = true;
7120     SmallVector<SDNode*, 4> SetCCs;
7121     if (!N0.hasOneUse())
7122       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7123     if (VT.isVector())
7124       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7125     if (DoXform) {
7126       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7127       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7128                                        LN0->getBasePtr(), N0.getValueType(),
7129                                        LN0->getMemOperand());
7130       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7131                                   N0.getValueType(), ExtLoad);
7132       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7133       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7134       return CombineTo(N, ExtLoad); // Return N so it doesn't get rechecked!
7135     }
7136   }
7137 
7138   // fold (sext (load x)) to multiple smaller sextloads.
7139   // Only on illegal but splittable vectors.
7140   if (SDValue ExtLoad = CombineExtLoad(N))
7141     return ExtLoad;
7142 
7143   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7144   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7145   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7146       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7147     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7148     EVT MemVT = LN0->getMemoryVT();
7149     if ((!LegalOperations && !LN0->isVolatile()) ||
7150         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7151       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7152                                        LN0->getBasePtr(), MemVT,
7153                                        LN0->getMemOperand());
7154       CombineTo(N, ExtLoad);
7155       CombineTo(N0.getNode(),
7156                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7157                             N0.getValueType(), ExtLoad),
7158                 ExtLoad.getValue(1));
7159       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7160     }
7161   }
7162 
7163   // fold (sext (and/or/xor (load x), cst)) ->
7164   //      (and/or/xor (sextload x), (sext cst))
7165   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7166        N0.getOpcode() == ISD::XOR) &&
7167       isa<LoadSDNode>(N0.getOperand(0)) &&
7168       N0.getOperand(1).getOpcode() == ISD::Constant &&
7169       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7170       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7171     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7172     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7173       bool DoXform = true;
7174       SmallVector<SDNode*, 4> SetCCs;
7175       if (!N0.hasOneUse())
7176         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7177                                           SetCCs, TLI);
7178       if (DoXform) {
7179         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7180                                          LN0->getChain(), LN0->getBasePtr(),
7181                                          LN0->getMemoryVT(),
7182                                          LN0->getMemOperand());
7183         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7184         Mask = Mask.sext(VT.getSizeInBits());
7185         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7186                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7187         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7188                                     SDLoc(N0.getOperand(0)),
7189                                     N0.getOperand(0).getValueType(), ExtLoad);
7190         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7191         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7192         return CombineTo(N, And); // Return N so it doesn't get rechecked!
7193       }
7194     }
7195   }
7196 
7197   if (N0.getOpcode() == ISD::SETCC) {
7198     SDValue N00 = N0.getOperand(0);
7199     SDValue N01 = N0.getOperand(1);
7200     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7201     EVT N00VT = N0.getOperand(0).getValueType();
7202 
7203     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7204     // Only do this before legalize for now.
7205     if (VT.isVector() && !LegalOperations &&
7206         TLI.getBooleanContents(N00VT) ==
7207             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7208       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7209       // of the same size as the compared operands. Only optimize sext(setcc())
7210       // if this is the case.
7211       EVT SVT = getSetCCResultType(N00VT);
7212 
7213       // We know that the # elements of the results is the same as the
7214       // # elements of the compare (and the # elements of the compare result
7215       // for that matter).  Check to see that they are the same size.  If so,
7216       // we know that the element size of the sext'd result matches the
7217       // element size of the compare operands.
7218       if (VT.getSizeInBits() == SVT.getSizeInBits())
7219         return DAG.getSetCC(DL, VT, N00, N01, CC);
7220 
7221       // If the desired elements are smaller or larger than the source
7222       // elements, we can use a matching integer vector type and then
7223       // truncate/sign extend.
7224       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7225       if (SVT == MatchingVecType) {
7226         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7227         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7228       }
7229     }
7230 
7231     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7232     // Here, T can be 1 or -1, depending on the type of the setcc and
7233     // getBooleanContents().
7234     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7235 
7236     // To determine the "true" side of the select, we need to know the high bit
7237     // of the value returned by the setcc if it evaluates to true.
7238     // If the type of the setcc is i1, then the true case of the select is just
7239     // sext(i1 1), that is, -1.
7240     // If the type of the setcc is larger (say, i8) then the value of the high
7241     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7242     // of the appropriate width.
7243     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7244                                            : TLI.getConstTrueVal(DAG, VT, DL);
7245     SDValue Zero = DAG.getConstant(0, DL, VT);
7246     if (SDValue SCC =
7247             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7248       return SCC;
7249 
7250     if (!VT.isVector()) {
7251       EVT SetCCVT = getSetCCResultType(N00VT);
7252       // Don't do this transform for i1 because there's a select transform
7253       // that would reverse it.
7254       // TODO: We should not do this transform at all without a target hook
7255       // because a sext is likely cheaper than a select?
7256       if (SetCCVT.getScalarSizeInBits() != 1 &&
7257           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7258         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7259         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7260       }
7261     }
7262   }
7263 
7264   // fold (sext x) -> (zext x) if the sign bit is known zero.
7265   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7266       DAG.SignBitIsZero(N0))
7267     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7268 
7269   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7270     return NewVSel;
7271 
7272   return SDValue();
7273 }
7274 
7275 // isTruncateOf - If N is a truncate of some other value, return true, record
7276 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7277 // This function computes KnownBits to avoid a duplicated call to
7278 // computeKnownBits in the caller.
7279 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7280                          KnownBits &Known) {
7281   if (N->getOpcode() == ISD::TRUNCATE) {
7282     Op = N->getOperand(0);
7283     DAG.computeKnownBits(Op, Known);
7284     return true;
7285   }
7286 
7287   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7288       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7289     return false;
7290 
7291   SDValue Op0 = N->getOperand(0);
7292   SDValue Op1 = N->getOperand(1);
7293   assert(Op0.getValueType() == Op1.getValueType());
7294 
7295   if (isNullConstant(Op0))
7296     Op = Op1;
7297   else if (isNullConstant(Op1))
7298     Op = Op0;
7299   else
7300     return false;
7301 
7302   DAG.computeKnownBits(Op, Known);
7303 
7304   if (!(Known.Zero | 1).isAllOnesValue())
7305     return false;
7306 
7307   return true;
7308 }
7309 
7310 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7311   SDValue N0 = N->getOperand(0);
7312   EVT VT = N->getValueType(0);
7313 
7314   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7315                                               LegalOperations))
7316     return SDValue(Res, 0);
7317 
7318   // fold (zext (zext x)) -> (zext x)
7319   // fold (zext (aext x)) -> (zext x)
7320   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7321     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7322                        N0.getOperand(0));
7323 
7324   // fold (zext (truncate x)) -> (zext x) or
7325   //      (zext (truncate x)) -> (truncate x)
7326   // This is valid when the truncated bits of x are already zero.
7327   // FIXME: We should extend this to work for vectors too.
7328   SDValue Op;
7329   KnownBits Known;
7330   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7331     APInt TruncatedBits =
7332       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7333       APInt(Op.getValueSizeInBits(), 0) :
7334       APInt::getBitsSet(Op.getValueSizeInBits(),
7335                         N0.getValueSizeInBits(),
7336                         std::min(Op.getValueSizeInBits(),
7337                                  VT.getSizeInBits()));
7338     if (TruncatedBits.isSubsetOf(Known.Zero))
7339       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7340   }
7341 
7342   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7343   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7344   if (N0.getOpcode() == ISD::TRUNCATE) {
7345     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7346       SDNode *oye = N0.getOperand(0).getNode();
7347       if (NarrowLoad.getNode() != N0.getNode()) {
7348         CombineTo(N0.getNode(), NarrowLoad);
7349         // CombineTo deleted the truncate, if needed, but not what's under it.
7350         AddToWorklist(oye);
7351       }
7352       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7353     }
7354   }
7355 
7356   // fold (zext (truncate x)) -> (and x, mask)
7357   if (N0.getOpcode() == ISD::TRUNCATE) {
7358     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7359     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7360     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7361       SDNode *oye = N0.getOperand(0).getNode();
7362       if (NarrowLoad.getNode() != N0.getNode()) {
7363         CombineTo(N0.getNode(), NarrowLoad);
7364         // CombineTo deleted the truncate, if needed, but not what's under it.
7365         AddToWorklist(oye);
7366       }
7367       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7368     }
7369 
7370     EVT SrcVT = N0.getOperand(0).getValueType();
7371     EVT MinVT = N0.getValueType();
7372 
7373     // Try to mask before the extension to avoid having to generate a larger mask,
7374     // possibly over several sub-vectors.
7375     if (SrcVT.bitsLT(VT)) {
7376       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7377                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7378         SDValue Op = N0.getOperand(0);
7379         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7380         AddToWorklist(Op.getNode());
7381         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7382       }
7383     }
7384 
7385     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7386       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7387       AddToWorklist(Op.getNode());
7388       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7389     }
7390   }
7391 
7392   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7393   // if either of the casts is not free.
7394   if (N0.getOpcode() == ISD::AND &&
7395       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7396       N0.getOperand(1).getOpcode() == ISD::Constant &&
7397       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7398                            N0.getValueType()) ||
7399        !TLI.isZExtFree(N0.getValueType(), VT))) {
7400     SDValue X = N0.getOperand(0).getOperand(0);
7401     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7402     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7403     Mask = Mask.zext(VT.getSizeInBits());
7404     SDLoc DL(N);
7405     return DAG.getNode(ISD::AND, DL, VT,
7406                        X, DAG.getConstant(Mask, DL, VT));
7407   }
7408 
7409   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7410   // Only generate vector extloads when 1) they're legal, and 2) they are
7411   // deemed desirable by the target.
7412   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7413       ((!LegalOperations && !VT.isVector() &&
7414         !cast<LoadSDNode>(N0)->isVolatile()) ||
7415        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7416     bool DoXform = true;
7417     SmallVector<SDNode*, 4> SetCCs;
7418     if (!N0.hasOneUse())
7419       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7420     if (VT.isVector())
7421       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7422     if (DoXform) {
7423       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7424       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7425                                        LN0->getChain(),
7426                                        LN0->getBasePtr(), N0.getValueType(),
7427                                        LN0->getMemOperand());
7428 
7429       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7430                                   N0.getValueType(), ExtLoad);
7431       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7432       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7433       return CombineTo(N, ExtLoad); // Return N so it doesn't get rechecked!
7434     }
7435   }
7436 
7437   // fold (zext (load x)) to multiple smaller zextloads.
7438   // Only on illegal but splittable vectors.
7439   if (SDValue ExtLoad = CombineExtLoad(N))
7440     return ExtLoad;
7441 
7442   // fold (zext (and/or/xor (load x), cst)) ->
7443   //      (and/or/xor (zextload x), (zext cst))
7444   // Unless (and (load x) cst) will match as a zextload already and has
7445   // additional users.
7446   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7447        N0.getOpcode() == ISD::XOR) &&
7448       isa<LoadSDNode>(N0.getOperand(0)) &&
7449       N0.getOperand(1).getOpcode() == ISD::Constant &&
7450       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7451       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7452     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7453     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7454       bool DoXform = true;
7455       SmallVector<SDNode*, 4> SetCCs;
7456       if (!N0.hasOneUse()) {
7457         if (N0.getOpcode() == ISD::AND) {
7458           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7459           auto NarrowLoad = false;
7460           EVT LoadResultTy = AndC->getValueType(0);
7461           EVT ExtVT, LoadedVT;
7462           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7463                                NarrowLoad))
7464             DoXform = false;
7465         }
7466         if (DoXform)
7467           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7468                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7469       }
7470       if (DoXform) {
7471         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7472                                          LN0->getChain(), LN0->getBasePtr(),
7473                                          LN0->getMemoryVT(),
7474                                          LN0->getMemOperand());
7475         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7476         Mask = Mask.zext(VT.getSizeInBits());
7477         SDLoc DL(N);
7478         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7479                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7480         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7481                                     SDLoc(N0.getOperand(0)),
7482                                     N0.getOperand(0).getValueType(), ExtLoad);
7483         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7484         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7485         return CombineTo(N, And); // Return N so it doesn't get rechecked!
7486       }
7487     }
7488   }
7489 
7490   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7491   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7492   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7493       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7494     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7495     EVT MemVT = LN0->getMemoryVT();
7496     if ((!LegalOperations && !LN0->isVolatile()) ||
7497         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7498       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7499                                        LN0->getChain(),
7500                                        LN0->getBasePtr(), MemVT,
7501                                        LN0->getMemOperand());
7502       CombineTo(N, ExtLoad);
7503       CombineTo(N0.getNode(),
7504                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7505                             ExtLoad),
7506                 ExtLoad.getValue(1));
7507       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7508     }
7509   }
7510 
7511   if (N0.getOpcode() == ISD::SETCC) {
7512     // Only do this before legalize for now.
7513     if (!LegalOperations && VT.isVector() &&
7514         N0.getValueType().getVectorElementType() == MVT::i1) {
7515       EVT N00VT = N0.getOperand(0).getValueType();
7516       if (getSetCCResultType(N00VT) == N0.getValueType())
7517         return SDValue();
7518 
7519       // We know that the # elements of the results is the same as the #
7520       // elements of the compare (and the # elements of the compare result for
7521       // that matter). Check to see that they are the same size. If so, we know
7522       // that the element size of the sext'd result matches the element size of
7523       // the compare operands.
7524       SDLoc DL(N);
7525       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7526       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7527         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7528         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7529                                      N0.getOperand(1), N0.getOperand(2));
7530         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7531       }
7532 
7533       // If the desired elements are smaller or larger than the source
7534       // elements we can use a matching integer vector type and then
7535       // truncate/sign extend.
7536       EVT MatchingElementType = EVT::getIntegerVT(
7537           *DAG.getContext(), N00VT.getScalarSizeInBits());
7538       EVT MatchingVectorType = EVT::getVectorVT(
7539           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7540       SDValue VsetCC =
7541           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7542                       N0.getOperand(1), N0.getOperand(2));
7543       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7544                          VecOnes);
7545     }
7546 
7547     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7548     SDLoc DL(N);
7549     if (SDValue SCC = SimplifySelectCC(
7550             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7551             DAG.getConstant(0, DL, VT),
7552             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7553       return SCC;
7554   }
7555 
7556   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7557   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7558       isa<ConstantSDNode>(N0.getOperand(1)) &&
7559       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7560       N0.hasOneUse()) {
7561     SDValue ShAmt = N0.getOperand(1);
7562     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7563     if (N0.getOpcode() == ISD::SHL) {
7564       SDValue InnerZExt = N0.getOperand(0);
7565       // If the original shl may be shifting out bits, do not perform this
7566       // transformation.
7567       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7568         InnerZExt.getOperand(0).getValueSizeInBits();
7569       if (ShAmtVal > KnownZeroBits)
7570         return SDValue();
7571     }
7572 
7573     SDLoc DL(N);
7574 
7575     // Ensure that the shift amount is wide enough for the shifted value.
7576     if (VT.getSizeInBits() >= 256)
7577       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7578 
7579     return DAG.getNode(N0.getOpcode(), DL, VT,
7580                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7581                        ShAmt);
7582   }
7583 
7584   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7585     return NewVSel;
7586 
7587   return SDValue();
7588 }
7589 
7590 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7591   SDValue N0 = N->getOperand(0);
7592   EVT VT = N->getValueType(0);
7593 
7594   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7595                                               LegalOperations))
7596     return SDValue(Res, 0);
7597 
7598   // fold (aext (aext x)) -> (aext x)
7599   // fold (aext (zext x)) -> (zext x)
7600   // fold (aext (sext x)) -> (sext x)
7601   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7602       N0.getOpcode() == ISD::ZERO_EXTEND ||
7603       N0.getOpcode() == ISD::SIGN_EXTEND)
7604     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7605 
7606   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7607   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7608   if (N0.getOpcode() == ISD::TRUNCATE) {
7609     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7610       SDNode *oye = N0.getOperand(0).getNode();
7611       if (NarrowLoad.getNode() != N0.getNode()) {
7612         CombineTo(N0.getNode(), NarrowLoad);
7613         // CombineTo deleted the truncate, if needed, but not what's under it.
7614         AddToWorklist(oye);
7615       }
7616       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7617     }
7618   }
7619 
7620   // fold (aext (truncate x))
7621   if (N0.getOpcode() == ISD::TRUNCATE)
7622     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7623 
7624   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7625   // if the trunc is not free.
7626   if (N0.getOpcode() == ISD::AND &&
7627       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7628       N0.getOperand(1).getOpcode() == ISD::Constant &&
7629       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7630                           N0.getValueType())) {
7631     SDLoc DL(N);
7632     SDValue X = N0.getOperand(0).getOperand(0);
7633     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7634     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7635     Mask = Mask.zext(VT.getSizeInBits());
7636     return DAG.getNode(ISD::AND, DL, VT,
7637                        X, DAG.getConstant(Mask, DL, VT));
7638   }
7639 
7640   // fold (aext (load x)) -> (aext (truncate (extload x)))
7641   // None of the supported targets knows how to perform load and any_ext
7642   // on vectors in one instruction.  We only perform this transformation on
7643   // scalars.
7644   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7645       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7646       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7647     bool DoXform = true;
7648     SmallVector<SDNode*, 4> SetCCs;
7649     if (!N0.hasOneUse())
7650       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7651     if (DoXform) {
7652       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7653       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7654                                        LN0->getChain(),
7655                                        LN0->getBasePtr(), N0.getValueType(),
7656                                        LN0->getMemOperand());
7657       CombineTo(N, ExtLoad);
7658       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7659                                   N0.getValueType(), ExtLoad);
7660       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7661       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7662                       ISD::ANY_EXTEND);
7663       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7664     }
7665   }
7666 
7667   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7668   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7669   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7670   if (N0.getOpcode() == ISD::LOAD &&
7671       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7672       N0.hasOneUse()) {
7673     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7674     ISD::LoadExtType ExtType = LN0->getExtensionType();
7675     EVT MemVT = LN0->getMemoryVT();
7676     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7677       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7678                                        VT, LN0->getChain(), LN0->getBasePtr(),
7679                                        MemVT, LN0->getMemOperand());
7680       CombineTo(N, ExtLoad);
7681       CombineTo(N0.getNode(),
7682                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7683                             N0.getValueType(), ExtLoad),
7684                 ExtLoad.getValue(1));
7685       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7686     }
7687   }
7688 
7689   if (N0.getOpcode() == ISD::SETCC) {
7690     // For vectors:
7691     // aext(setcc) -> vsetcc
7692     // aext(setcc) -> truncate(vsetcc)
7693     // aext(setcc) -> aext(vsetcc)
7694     // Only do this before legalize for now.
7695     if (VT.isVector() && !LegalOperations) {
7696       EVT N0VT = N0.getOperand(0).getValueType();
7697         // We know that the # elements of the results is the same as the
7698         // # elements of the compare (and the # elements of the compare result
7699         // for that matter).  Check to see that they are the same size.  If so,
7700         // we know that the element size of the sext'd result matches the
7701         // element size of the compare operands.
7702       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7703         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7704                              N0.getOperand(1),
7705                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7706       // If the desired elements are smaller or larger than the source
7707       // elements we can use a matching integer vector type and then
7708       // truncate/any extend
7709       else {
7710         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7711         SDValue VsetCC =
7712           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7713                         N0.getOperand(1),
7714                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7715         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7716       }
7717     }
7718 
7719     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7720     SDLoc DL(N);
7721     if (SDValue SCC = SimplifySelectCC(
7722             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7723             DAG.getConstant(0, DL, VT),
7724             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7725       return SCC;
7726   }
7727 
7728   return SDValue();
7729 }
7730 
7731 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7732   SDValue N0 = N->getOperand(0);
7733   SDValue N1 = N->getOperand(1);
7734   EVT EVT = cast<VTSDNode>(N1)->getVT();
7735 
7736   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7737   if (N0.getOpcode() == ISD::AssertZext &&
7738       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7739     return N0;
7740 
7741   return SDValue();
7742 }
7743 
7744 /// See if the specified operand can be simplified with the knowledge that only
7745 /// the bits specified by Mask are used.  If so, return the simpler operand,
7746 /// otherwise return a null SDValue.
7747 ///
7748 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7749 /// simplify nodes with multiple uses more aggressively.)
7750 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7751   switch (V.getOpcode()) {
7752   default: break;
7753   case ISD::Constant: {
7754     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7755     assert(CV && "Const value should be ConstSDNode.");
7756     const APInt &CVal = CV->getAPIntValue();
7757     APInt NewVal = CVal & Mask;
7758     if (NewVal != CVal)
7759       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7760     break;
7761   }
7762   case ISD::OR:
7763   case ISD::XOR:
7764     // If the LHS or RHS don't contribute bits to the or, drop them.
7765     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7766       return V.getOperand(1);
7767     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7768       return V.getOperand(0);
7769     break;
7770   case ISD::SRL:
7771     // Only look at single-use SRLs.
7772     if (!V.getNode()->hasOneUse())
7773       break;
7774     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7775       // See if we can recursively simplify the LHS.
7776       unsigned Amt = RHSC->getZExtValue();
7777 
7778       // Watch out for shift count overflow though.
7779       if (Amt >= Mask.getBitWidth()) break;
7780       APInt NewMask = Mask << Amt;
7781       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7782         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7783                            SimplifyLHS, V.getOperand(1));
7784     }
7785     break;
7786   case ISD::AND: {
7787     // X & -1 -> X (ignoring bits which aren't demanded).
7788     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7789     if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7790       return V.getOperand(0);
7791     break;
7792   }
7793   }
7794   return SDValue();
7795 }
7796 
7797 /// If the result of a wider load is shifted to right of N  bits and then
7798 /// truncated to a narrower type and where N is a multiple of number of bits of
7799 /// the narrower type, transform it to a narrower load from address + N / num of
7800 /// bits of new type. If the result is to be extended, also fold the extension
7801 /// to form a extending load.
7802 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7803   unsigned Opc = N->getOpcode();
7804 
7805   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7806   SDValue N0 = N->getOperand(0);
7807   EVT VT = N->getValueType(0);
7808   EVT ExtVT = VT;
7809 
7810   // This transformation isn't valid for vector loads.
7811   if (VT.isVector())
7812     return SDValue();
7813 
7814   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7815   // extended to VT.
7816   if (Opc == ISD::SIGN_EXTEND_INREG) {
7817     ExtType = ISD::SEXTLOAD;
7818     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7819   } else if (Opc == ISD::SRL) {
7820     // Another special-case: SRL is basically zero-extending a narrower value.
7821     ExtType = ISD::ZEXTLOAD;
7822     N0 = SDValue(N, 0);
7823     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7824     if (!N01) return SDValue();
7825     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7826                               VT.getSizeInBits() - N01->getZExtValue());
7827   }
7828   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7829     return SDValue();
7830 
7831   unsigned EVTBits = ExtVT.getSizeInBits();
7832 
7833   // Do not generate loads of non-round integer types since these can
7834   // be expensive (and would be wrong if the type is not byte sized).
7835   if (!ExtVT.isRound())
7836     return SDValue();
7837 
7838   unsigned ShAmt = 0;
7839   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7840     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7841       ShAmt = N01->getZExtValue();
7842       // Is the shift amount a multiple of size of VT?
7843       if ((ShAmt & (EVTBits-1)) == 0) {
7844         N0 = N0.getOperand(0);
7845         // Is the load width a multiple of size of VT?
7846         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7847           return SDValue();
7848       }
7849 
7850       // At this point, we must have a load or else we can't do the transform.
7851       if (!isa<LoadSDNode>(N0)) return SDValue();
7852 
7853       // Because a SRL must be assumed to *need* to zero-extend the high bits
7854       // (as opposed to anyext the high bits), we can't combine the zextload
7855       // lowering of SRL and an sextload.
7856       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7857         return SDValue();
7858 
7859       // If the shift amount is larger than the input type then we're not
7860       // accessing any of the loaded bytes.  If the load was a zextload/extload
7861       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7862       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7863         return SDValue();
7864     }
7865   }
7866 
7867   // If the load is shifted left (and the result isn't shifted back right),
7868   // we can fold the truncate through the shift.
7869   unsigned ShLeftAmt = 0;
7870   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7871       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7872     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7873       ShLeftAmt = N01->getZExtValue();
7874       N0 = N0.getOperand(0);
7875     }
7876   }
7877 
7878   // If we haven't found a load, we can't narrow it.  Don't transform one with
7879   // multiple uses, this would require adding a new load.
7880   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7881     return SDValue();
7882 
7883   // Don't change the width of a volatile load.
7884   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7885   if (LN0->isVolatile())
7886     return SDValue();
7887 
7888   // Verify that we are actually reducing a load width here.
7889   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7890     return SDValue();
7891 
7892   // For the transform to be legal, the load must produce only two values
7893   // (the value loaded and the chain).  Don't transform a pre-increment
7894   // load, for example, which produces an extra value.  Otherwise the
7895   // transformation is not equivalent, and the downstream logic to replace
7896   // uses gets things wrong.
7897   if (LN0->getNumValues() > 2)
7898     return SDValue();
7899 
7900   // If the load that we're shrinking is an extload and we're not just
7901   // discarding the extension we can't simply shrink the load. Bail.
7902   // TODO: It would be possible to merge the extensions in some cases.
7903   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7904       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7905     return SDValue();
7906 
7907   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7908     return SDValue();
7909 
7910   EVT PtrType = N0.getOperand(1).getValueType();
7911 
7912   if (PtrType == MVT::Untyped || PtrType.isExtended())
7913     // It's not possible to generate a constant of extended or untyped type.
7914     return SDValue();
7915 
7916   // For big endian targets, we need to adjust the offset to the pointer to
7917   // load the correct bytes.
7918   if (DAG.getDataLayout().isBigEndian()) {
7919     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7920     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7921     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7922   }
7923 
7924   uint64_t PtrOff = ShAmt / 8;
7925   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7926   SDLoc DL(LN0);
7927   // The original load itself didn't wrap, so an offset within it doesn't.
7928   SDNodeFlags Flags;
7929   Flags.setNoUnsignedWrap(true);
7930   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7931                                PtrType, LN0->getBasePtr(),
7932                                DAG.getConstant(PtrOff, DL, PtrType),
7933                                Flags);
7934   AddToWorklist(NewPtr.getNode());
7935 
7936   SDValue Load;
7937   if (ExtType == ISD::NON_EXTLOAD)
7938     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7939                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7940                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7941   else
7942     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7943                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7944                           NewAlign, LN0->getMemOperand()->getFlags(),
7945                           LN0->getAAInfo());
7946 
7947   // Replace the old load's chain with the new load's chain.
7948   WorklistRemover DeadNodes(*this);
7949   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7950 
7951   // Shift the result left, if we've swallowed a left shift.
7952   SDValue Result = Load;
7953   if (ShLeftAmt != 0) {
7954     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7955     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7956       ShImmTy = VT;
7957     // If the shift amount is as large as the result size (but, presumably,
7958     // no larger than the source) then the useful bits of the result are
7959     // zero; we can't simply return the shortened shift, because the result
7960     // of that operation is undefined.
7961     SDLoc DL(N0);
7962     if (ShLeftAmt >= VT.getSizeInBits())
7963       Result = DAG.getConstant(0, DL, VT);
7964     else
7965       Result = DAG.getNode(ISD::SHL, DL, VT,
7966                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7967   }
7968 
7969   // Return the new loaded value.
7970   return Result;
7971 }
7972 
7973 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7974   SDValue N0 = N->getOperand(0);
7975   SDValue N1 = N->getOperand(1);
7976   EVT VT = N->getValueType(0);
7977   EVT EVT = cast<VTSDNode>(N1)->getVT();
7978   unsigned VTBits = VT.getScalarSizeInBits();
7979   unsigned EVTBits = EVT.getScalarSizeInBits();
7980 
7981   if (N0.isUndef())
7982     return DAG.getUNDEF(VT);
7983 
7984   // fold (sext_in_reg c1) -> c1
7985   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7986     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7987 
7988   // If the input is already sign extended, just drop the extension.
7989   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7990     return N0;
7991 
7992   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7993   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7994       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7995     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7996                        N0.getOperand(0), N1);
7997 
7998   // fold (sext_in_reg (sext x)) -> (sext x)
7999   // fold (sext_in_reg (aext x)) -> (sext x)
8000   // if x is small enough.
8001   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8002     SDValue N00 = N0.getOperand(0);
8003     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8004         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8005       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8006   }
8007 
8008   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8009   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8010        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8011        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8012       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8013     if (!LegalOperations ||
8014         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8015       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8016   }
8017 
8018   // fold (sext_in_reg (zext x)) -> (sext x)
8019   // iff we are extending the source sign bit.
8020   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8021     SDValue N00 = N0.getOperand(0);
8022     if (N00.getScalarValueSizeInBits() == EVTBits &&
8023         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8024       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8025   }
8026 
8027   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8028   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8029     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8030 
8031   // fold operands of sext_in_reg based on knowledge that the top bits are not
8032   // demanded.
8033   if (SimplifyDemandedBits(SDValue(N, 0)))
8034     return SDValue(N, 0);
8035 
8036   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8037   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8038   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8039     return NarrowLoad;
8040 
8041   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8042   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8043   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8044   if (N0.getOpcode() == ISD::SRL) {
8045     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8046       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8047         // We can turn this into an SRA iff the input to the SRL is already sign
8048         // extended enough.
8049         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8050         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8051           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8052                              N0.getOperand(0), N0.getOperand(1));
8053       }
8054   }
8055 
8056   // fold (sext_inreg (extload x)) -> (sextload x)
8057   if (ISD::isEXTLoad(N0.getNode()) &&
8058       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8059       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8060       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8061        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8062     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8063     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8064                                      LN0->getChain(),
8065                                      LN0->getBasePtr(), EVT,
8066                                      LN0->getMemOperand());
8067     CombineTo(N, ExtLoad);
8068     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8069     AddToWorklist(ExtLoad.getNode());
8070     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8071   }
8072   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8073   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8074       N0.hasOneUse() &&
8075       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8076       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8077        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8078     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8079     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8080                                      LN0->getChain(),
8081                                      LN0->getBasePtr(), EVT,
8082                                      LN0->getMemOperand());
8083     CombineTo(N, ExtLoad);
8084     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8085     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8086   }
8087 
8088   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8089   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8090     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8091                                            N0.getOperand(1), false))
8092       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8093                          BSwap, N1);
8094   }
8095 
8096   return SDValue();
8097 }
8098 
8099 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8100   SDValue N0 = N->getOperand(0);
8101   EVT VT = N->getValueType(0);
8102 
8103   if (N0.isUndef())
8104     return DAG.getUNDEF(VT);
8105 
8106   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8107                                               LegalOperations))
8108     return SDValue(Res, 0);
8109 
8110   return SDValue();
8111 }
8112 
8113 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8114   SDValue N0 = N->getOperand(0);
8115   EVT VT = N->getValueType(0);
8116 
8117   if (N0.isUndef())
8118     return DAG.getUNDEF(VT);
8119 
8120   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8121                                               LegalOperations))
8122     return SDValue(Res, 0);
8123 
8124   return SDValue();
8125 }
8126 
8127 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8128   SDValue N0 = N->getOperand(0);
8129   EVT VT = N->getValueType(0);
8130   bool isLE = DAG.getDataLayout().isLittleEndian();
8131 
8132   // noop truncate
8133   if (N0.getValueType() == N->getValueType(0))
8134     return N0;
8135   // fold (truncate c1) -> c1
8136   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8137     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8138   // fold (truncate (truncate x)) -> (truncate x)
8139   if (N0.getOpcode() == ISD::TRUNCATE)
8140     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8141   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8142   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8143       N0.getOpcode() == ISD::SIGN_EXTEND ||
8144       N0.getOpcode() == ISD::ANY_EXTEND) {
8145     // if the source is smaller than the dest, we still need an extend.
8146     if (N0.getOperand(0).getValueType().bitsLT(VT))
8147       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8148     // if the source is larger than the dest, than we just need the truncate.
8149     if (N0.getOperand(0).getValueType().bitsGT(VT))
8150       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8151     // if the source and dest are the same type, we can drop both the extend
8152     // and the truncate.
8153     return N0.getOperand(0);
8154   }
8155 
8156   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8157   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8158     return SDValue();
8159 
8160   // Fold extract-and-trunc into a narrow extract. For example:
8161   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8162   //   i32 y = TRUNCATE(i64 x)
8163   //        -- becomes --
8164   //   v16i8 b = BITCAST (v2i64 val)
8165   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8166   //
8167   // Note: We only run this optimization after type legalization (which often
8168   // creates this pattern) and before operation legalization after which
8169   // we need to be more careful about the vector instructions that we generate.
8170   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8171       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8172 
8173     EVT VecTy = N0.getOperand(0).getValueType();
8174     EVT ExTy = N0.getValueType();
8175     EVT TrTy = N->getValueType(0);
8176 
8177     unsigned NumElem = VecTy.getVectorNumElements();
8178     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8179 
8180     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8181     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8182 
8183     SDValue EltNo = N0->getOperand(1);
8184     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8185       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8186       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8187       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8188 
8189       SDLoc DL(N);
8190       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8191                          DAG.getBitcast(NVT, N0.getOperand(0)),
8192                          DAG.getConstant(Index, DL, IndexTy));
8193     }
8194   }
8195 
8196   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8197   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8198     EVT SrcVT = N0.getValueType();
8199     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8200         TLI.isTruncateFree(SrcVT, VT)) {
8201       SDLoc SL(N0);
8202       SDValue Cond = N0.getOperand(0);
8203       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8204       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8205       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8206     }
8207   }
8208 
8209   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8210   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8211       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8212       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8213     SDValue Amt = N0.getOperand(1);
8214     KnownBits Known;
8215     DAG.computeKnownBits(Amt, Known);
8216     unsigned Size = VT.getScalarSizeInBits();
8217     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8218       SDLoc SL(N);
8219       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8220 
8221       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8222       if (AmtVT != Amt.getValueType()) {
8223         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8224         AddToWorklist(Amt.getNode());
8225       }
8226       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8227     }
8228   }
8229 
8230   // Fold a series of buildvector, bitcast, and truncate if possible.
8231   // For example fold
8232   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8233   //   (2xi32 (buildvector x, y)).
8234   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8235       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8236       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8237       N0.getOperand(0).hasOneUse()) {
8238 
8239     SDValue BuildVect = N0.getOperand(0);
8240     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8241     EVT TruncVecEltTy = VT.getVectorElementType();
8242 
8243     // Check that the element types match.
8244     if (BuildVectEltTy == TruncVecEltTy) {
8245       // Now we only need to compute the offset of the truncated elements.
8246       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8247       unsigned TruncVecNumElts = VT.getVectorNumElements();
8248       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8249 
8250       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8251              "Invalid number of elements");
8252 
8253       SmallVector<SDValue, 8> Opnds;
8254       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8255         Opnds.push_back(BuildVect.getOperand(i));
8256 
8257       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8258     }
8259   }
8260 
8261   // See if we can simplify the input to this truncate through knowledge that
8262   // only the low bits are being used.
8263   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8264   // Currently we only perform this optimization on scalars because vectors
8265   // may have different active low bits.
8266   if (!VT.isVector()) {
8267     if (SDValue Shorter =
8268             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8269                                                      VT.getSizeInBits())))
8270       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8271   }
8272 
8273   // fold (truncate (load x)) -> (smaller load x)
8274   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8275   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8276     if (SDValue Reduced = ReduceLoadWidth(N))
8277       return Reduced;
8278 
8279     // Handle the case where the load remains an extending load even
8280     // after truncation.
8281     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8282       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8283       if (!LN0->isVolatile() &&
8284           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8285         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8286                                          VT, LN0->getChain(), LN0->getBasePtr(),
8287                                          LN0->getMemoryVT(),
8288                                          LN0->getMemOperand());
8289         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8290         return NewLoad;
8291       }
8292     }
8293   }
8294 
8295   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8296   // where ... are all 'undef'.
8297   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8298     SmallVector<EVT, 8> VTs;
8299     SDValue V;
8300     unsigned Idx = 0;
8301     unsigned NumDefs = 0;
8302 
8303     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8304       SDValue X = N0.getOperand(i);
8305       if (!X.isUndef()) {
8306         V = X;
8307         Idx = i;
8308         NumDefs++;
8309       }
8310       // Stop if more than one members are non-undef.
8311       if (NumDefs > 1)
8312         break;
8313       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8314                                      VT.getVectorElementType(),
8315                                      X.getValueType().getVectorNumElements()));
8316     }
8317 
8318     if (NumDefs == 0)
8319       return DAG.getUNDEF(VT);
8320 
8321     if (NumDefs == 1) {
8322       assert(V.getNode() && "The single defined operand is empty!");
8323       SmallVector<SDValue, 8> Opnds;
8324       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8325         if (i != Idx) {
8326           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8327           continue;
8328         }
8329         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8330         AddToWorklist(NV.getNode());
8331         Opnds.push_back(NV);
8332       }
8333       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8334     }
8335   }
8336 
8337   // Fold truncate of a bitcast of a vector to an extract of the low vector
8338   // element.
8339   //
8340   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8341   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8342     SDValue VecSrc = N0.getOperand(0);
8343     EVT SrcVT = VecSrc.getValueType();
8344     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8345         (!LegalOperations ||
8346          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8347       SDLoc SL(N);
8348 
8349       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8350       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8351                          VecSrc, DAG.getConstant(0, SL, IdxVT));
8352     }
8353   }
8354 
8355   // Simplify the operands using demanded-bits information.
8356   if (!VT.isVector() &&
8357       SimplifyDemandedBits(SDValue(N, 0)))
8358     return SDValue(N, 0);
8359 
8360   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8361   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8362   // When the adde's carry is not used.
8363   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8364       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8365       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8366     SDLoc SL(N);
8367     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8368     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8369     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8370     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8371   }
8372 
8373   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8374     return NewVSel;
8375 
8376   return SDValue();
8377 }
8378 
8379 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8380   SDValue Elt = N->getOperand(i);
8381   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8382     return Elt.getNode();
8383   return Elt.getOperand(Elt.getResNo()).getNode();
8384 }
8385 
8386 /// build_pair (load, load) -> load
8387 /// if load locations are consecutive.
8388 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8389   assert(N->getOpcode() == ISD::BUILD_PAIR);
8390 
8391   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8392   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8393   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8394       LD1->getAddressSpace() != LD2->getAddressSpace())
8395     return SDValue();
8396   EVT LD1VT = LD1->getValueType(0);
8397   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8398   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8399       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8400     unsigned Align = LD1->getAlignment();
8401     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8402         VT.getTypeForEVT(*DAG.getContext()));
8403 
8404     if (NewAlign <= Align &&
8405         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8406       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8407                          LD1->getPointerInfo(), Align);
8408   }
8409 
8410   return SDValue();
8411 }
8412 
8413 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8414   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8415   // and Lo parts; on big-endian machines it doesn't.
8416   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8417 }
8418 
8419 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8420                                     const TargetLowering &TLI) {
8421   // If this is not a bitcast to an FP type or if the target doesn't have
8422   // IEEE754-compliant FP logic, we're done.
8423   EVT VT = N->getValueType(0);
8424   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8425     return SDValue();
8426 
8427   // TODO: Use splat values for the constant-checking below and remove this
8428   // restriction.
8429   SDValue N0 = N->getOperand(0);
8430   EVT SourceVT = N0.getValueType();
8431   if (SourceVT.isVector())
8432     return SDValue();
8433 
8434   unsigned FPOpcode;
8435   APInt SignMask;
8436   switch (N0.getOpcode()) {
8437   case ISD::AND:
8438     FPOpcode = ISD::FABS;
8439     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8440     break;
8441   case ISD::XOR:
8442     FPOpcode = ISD::FNEG;
8443     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8444     break;
8445   // TODO: ISD::OR --> ISD::FNABS?
8446   default:
8447     return SDValue();
8448   }
8449 
8450   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8451   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8452   SDValue LogicOp0 = N0.getOperand(0);
8453   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8454   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8455       LogicOp0.getOpcode() == ISD::BITCAST &&
8456       LogicOp0->getOperand(0).getValueType() == VT)
8457     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8458 
8459   return SDValue();
8460 }
8461 
8462 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8463   SDValue N0 = N->getOperand(0);
8464   EVT VT = N->getValueType(0);
8465 
8466   if (N0.isUndef())
8467     return DAG.getUNDEF(VT);
8468 
8469   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8470   // Only do this before legalize, since afterward the target may be depending
8471   // on the bitconvert.
8472   // First check to see if this is all constant.
8473   if (!LegalTypes &&
8474       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8475       VT.isVector()) {
8476     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8477 
8478     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8479     assert(!DestEltVT.isVector() &&
8480            "Element type of vector ValueType must not be vector!");
8481     if (isSimple)
8482       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8483   }
8484 
8485   // If the input is a constant, let getNode fold it.
8486   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8487     // If we can't allow illegal operations, we need to check that this is just
8488     // a fp -> int or int -> conversion and that the resulting operation will
8489     // be legal.
8490     if (!LegalOperations ||
8491         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8492          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8493         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8494          TLI.isOperationLegal(ISD::Constant, VT)))
8495       return DAG.getBitcast(VT, N0);
8496   }
8497 
8498   // (conv (conv x, t1), t2) -> (conv x, t2)
8499   if (N0.getOpcode() == ISD::BITCAST)
8500     return DAG.getBitcast(VT, N0.getOperand(0));
8501 
8502   // fold (conv (load x)) -> (load (conv*)x)
8503   // If the resultant load doesn't need a higher alignment than the original!
8504   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8505       // Do not change the width of a volatile load.
8506       !cast<LoadSDNode>(N0)->isVolatile() &&
8507       // Do not remove the cast if the types differ in endian layout.
8508       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8509           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8510       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8511       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8512     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8513     unsigned OrigAlign = LN0->getAlignment();
8514 
8515     bool Fast = false;
8516     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8517                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8518         Fast) {
8519       SDValue Load =
8520           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8521                       LN0->getPointerInfo(), OrigAlign,
8522                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8523       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8524       return Load;
8525     }
8526   }
8527 
8528   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8529     return V;
8530 
8531   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8532   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8533   //
8534   // For ppc_fp128:
8535   // fold (bitcast (fneg x)) ->
8536   //     flipbit = signbit
8537   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8538   //
8539   // fold (bitcast (fabs x)) ->
8540   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8541   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8542   // This often reduces constant pool loads.
8543   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8544        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8545       N0.getNode()->hasOneUse() && VT.isInteger() &&
8546       !VT.isVector() && !N0.getValueType().isVector()) {
8547     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8548     AddToWorklist(NewConv.getNode());
8549 
8550     SDLoc DL(N);
8551     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8552       assert(VT.getSizeInBits() == 128);
8553       SDValue SignBit = DAG.getConstant(
8554           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8555       SDValue FlipBit;
8556       if (N0.getOpcode() == ISD::FNEG) {
8557         FlipBit = SignBit;
8558         AddToWorklist(FlipBit.getNode());
8559       } else {
8560         assert(N0.getOpcode() == ISD::FABS);
8561         SDValue Hi =
8562             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8563                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8564                                               SDLoc(NewConv)));
8565         AddToWorklist(Hi.getNode());
8566         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8567         AddToWorklist(FlipBit.getNode());
8568       }
8569       SDValue FlipBits =
8570           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8571       AddToWorklist(FlipBits.getNode());
8572       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8573     }
8574     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8575     if (N0.getOpcode() == ISD::FNEG)
8576       return DAG.getNode(ISD::XOR, DL, VT,
8577                          NewConv, DAG.getConstant(SignBit, DL, VT));
8578     assert(N0.getOpcode() == ISD::FABS);
8579     return DAG.getNode(ISD::AND, DL, VT,
8580                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8581   }
8582 
8583   // fold (bitconvert (fcopysign cst, x)) ->
8584   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8585   // Note that we don't handle (copysign x, cst) because this can always be
8586   // folded to an fneg or fabs.
8587   //
8588   // For ppc_fp128:
8589   // fold (bitcast (fcopysign cst, x)) ->
8590   //     flipbit = (and (extract_element
8591   //                     (xor (bitcast cst), (bitcast x)), 0),
8592   //                    signbit)
8593   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8594   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8595       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8596       VT.isInteger() && !VT.isVector()) {
8597     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8598     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8599     if (isTypeLegal(IntXVT)) {
8600       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8601       AddToWorklist(X.getNode());
8602 
8603       // If X has a different width than the result/lhs, sext it or truncate it.
8604       unsigned VTWidth = VT.getSizeInBits();
8605       if (OrigXWidth < VTWidth) {
8606         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8607         AddToWorklist(X.getNode());
8608       } else if (OrigXWidth > VTWidth) {
8609         // To get the sign bit in the right place, we have to shift it right
8610         // before truncating.
8611         SDLoc DL(X);
8612         X = DAG.getNode(ISD::SRL, DL,
8613                         X.getValueType(), X,
8614                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8615                                         X.getValueType()));
8616         AddToWorklist(X.getNode());
8617         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8618         AddToWorklist(X.getNode());
8619       }
8620 
8621       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8622         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8623         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8624         AddToWorklist(Cst.getNode());
8625         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8626         AddToWorklist(X.getNode());
8627         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8628         AddToWorklist(XorResult.getNode());
8629         SDValue XorResult64 = DAG.getNode(
8630             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8631             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8632                                   SDLoc(XorResult)));
8633         AddToWorklist(XorResult64.getNode());
8634         SDValue FlipBit =
8635             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8636                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8637         AddToWorklist(FlipBit.getNode());
8638         SDValue FlipBits =
8639             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8640         AddToWorklist(FlipBits.getNode());
8641         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8642       }
8643       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8644       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8645                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8646       AddToWorklist(X.getNode());
8647 
8648       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8649       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8650                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8651       AddToWorklist(Cst.getNode());
8652 
8653       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8654     }
8655   }
8656 
8657   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8658   if (N0.getOpcode() == ISD::BUILD_PAIR)
8659     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8660       return CombineLD;
8661 
8662   // Remove double bitcasts from shuffles - this is often a legacy of
8663   // XformToShuffleWithZero being used to combine bitmaskings (of
8664   // float vectors bitcast to integer vectors) into shuffles.
8665   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8666   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8667       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8668       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8669       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8670     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8671 
8672     // If operands are a bitcast, peek through if it casts the original VT.
8673     // If operands are a constant, just bitcast back to original VT.
8674     auto PeekThroughBitcast = [&](SDValue Op) {
8675       if (Op.getOpcode() == ISD::BITCAST &&
8676           Op.getOperand(0).getValueType() == VT)
8677         return SDValue(Op.getOperand(0));
8678       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8679           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8680         return DAG.getBitcast(VT, Op);
8681       return SDValue();
8682     };
8683 
8684     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8685     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8686     if (!(SV0 && SV1))
8687       return SDValue();
8688 
8689     int MaskScale =
8690         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8691     SmallVector<int, 8> NewMask;
8692     for (int M : SVN->getMask())
8693       for (int i = 0; i != MaskScale; ++i)
8694         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8695 
8696     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8697     if (!LegalMask) {
8698       std::swap(SV0, SV1);
8699       ShuffleVectorSDNode::commuteMask(NewMask);
8700       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8701     }
8702 
8703     if (LegalMask)
8704       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8705   }
8706 
8707   return SDValue();
8708 }
8709 
8710 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8711   EVT VT = N->getValueType(0);
8712   return CombineConsecutiveLoads(N, VT);
8713 }
8714 
8715 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8716 /// operands. DstEltVT indicates the destination element value type.
8717 SDValue DAGCombiner::
8718 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8719   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8720 
8721   // If this is already the right type, we're done.
8722   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8723 
8724   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8725   unsigned DstBitSize = DstEltVT.getSizeInBits();
8726 
8727   // If this is a conversion of N elements of one type to N elements of another
8728   // type, convert each element.  This handles FP<->INT cases.
8729   if (SrcBitSize == DstBitSize) {
8730     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8731                               BV->getValueType(0).getVectorNumElements());
8732 
8733     // Due to the FP element handling below calling this routine recursively,
8734     // we can end up with a scalar-to-vector node here.
8735     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8736       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8737                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8738 
8739     SmallVector<SDValue, 8> Ops;
8740     for (SDValue Op : BV->op_values()) {
8741       // If the vector element type is not legal, the BUILD_VECTOR operands
8742       // are promoted and implicitly truncated.  Make that explicit here.
8743       if (Op.getValueType() != SrcEltVT)
8744         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8745       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8746       AddToWorklist(Ops.back().getNode());
8747     }
8748     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8749   }
8750 
8751   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8752   // handle annoying details of growing/shrinking FP values, we convert them to
8753   // int first.
8754   if (SrcEltVT.isFloatingPoint()) {
8755     // Convert the input float vector to a int vector where the elements are the
8756     // same sizes.
8757     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8758     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8759     SrcEltVT = IntVT;
8760   }
8761 
8762   // Now we know the input is an integer vector.  If the output is a FP type,
8763   // convert to integer first, then to FP of the right size.
8764   if (DstEltVT.isFloatingPoint()) {
8765     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8766     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8767 
8768     // Next, convert to FP elements of the same size.
8769     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8770   }
8771 
8772   SDLoc DL(BV);
8773 
8774   // Okay, we know the src/dst types are both integers of differing types.
8775   // Handling growing first.
8776   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8777   if (SrcBitSize < DstBitSize) {
8778     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8779 
8780     SmallVector<SDValue, 8> Ops;
8781     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8782          i += NumInputsPerOutput) {
8783       bool isLE = DAG.getDataLayout().isLittleEndian();
8784       APInt NewBits = APInt(DstBitSize, 0);
8785       bool EltIsUndef = true;
8786       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8787         // Shift the previously computed bits over.
8788         NewBits <<= SrcBitSize;
8789         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8790         if (Op.isUndef()) continue;
8791         EltIsUndef = false;
8792 
8793         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8794                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8795       }
8796 
8797       if (EltIsUndef)
8798         Ops.push_back(DAG.getUNDEF(DstEltVT));
8799       else
8800         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8801     }
8802 
8803     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8804     return DAG.getBuildVector(VT, DL, Ops);
8805   }
8806 
8807   // Finally, this must be the case where we are shrinking elements: each input
8808   // turns into multiple outputs.
8809   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8810   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8811                             NumOutputsPerInput*BV->getNumOperands());
8812   SmallVector<SDValue, 8> Ops;
8813 
8814   for (const SDValue &Op : BV->op_values()) {
8815     if (Op.isUndef()) {
8816       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8817       continue;
8818     }
8819 
8820     APInt OpVal = cast<ConstantSDNode>(Op)->
8821                   getAPIntValue().zextOrTrunc(SrcBitSize);
8822 
8823     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8824       APInt ThisVal = OpVal.trunc(DstBitSize);
8825       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8826       OpVal.lshrInPlace(DstBitSize);
8827     }
8828 
8829     // For big endian targets, swap the order of the pieces of each element.
8830     if (DAG.getDataLayout().isBigEndian())
8831       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8832   }
8833 
8834   return DAG.getBuildVector(VT, DL, Ops);
8835 }
8836 
8837 static bool isContractable(SDNode *N) {
8838   SDNodeFlags F = N->getFlags();
8839   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8840 }
8841 
8842 /// Try to perform FMA combining on a given FADD node.
8843 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8844   SDValue N0 = N->getOperand(0);
8845   SDValue N1 = N->getOperand(1);
8846   EVT VT = N->getValueType(0);
8847   SDLoc SL(N);
8848 
8849   const TargetOptions &Options = DAG.getTarget().Options;
8850 
8851   // Floating-point multiply-add with intermediate rounding.
8852   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8853 
8854   // Floating-point multiply-add without intermediate rounding.
8855   bool HasFMA =
8856       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8857       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8858 
8859   // No valid opcode, do not combine.
8860   if (!HasFMAD && !HasFMA)
8861     return SDValue();
8862 
8863   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8864                               Options.UnsafeFPMath || HasFMAD);
8865   // If the addition is not contractable, do not combine.
8866   if (!AllowFusionGlobally && !isContractable(N))
8867     return SDValue();
8868 
8869   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8870   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8871     return SDValue();
8872 
8873   // Always prefer FMAD to FMA for precision.
8874   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8875   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8876   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8877 
8878   // Is the node an FMUL and contractable either due to global flags or
8879   // SDNodeFlags.
8880   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8881     if (N.getOpcode() != ISD::FMUL)
8882       return false;
8883     return AllowFusionGlobally || isContractable(N.getNode());
8884   };
8885   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8886   // prefer to fold the multiply with fewer uses.
8887   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8888     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8889       std::swap(N0, N1);
8890   }
8891 
8892   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8893   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8894     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8895                        N0.getOperand(0), N0.getOperand(1), N1);
8896   }
8897 
8898   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8899   // Note: Commutes FADD operands.
8900   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8901     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8902                        N1.getOperand(0), N1.getOperand(1), N0);
8903   }
8904 
8905   // Look through FP_EXTEND nodes to do more combining.
8906   if (LookThroughFPExt) {
8907     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8908     if (N0.getOpcode() == ISD::FP_EXTEND) {
8909       SDValue N00 = N0.getOperand(0);
8910       if (isContractableFMUL(N00))
8911         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8912                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8913                                        N00.getOperand(0)),
8914                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8915                                        N00.getOperand(1)), N1);
8916     }
8917 
8918     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8919     // Note: Commutes FADD operands.
8920     if (N1.getOpcode() == ISD::FP_EXTEND) {
8921       SDValue N10 = N1.getOperand(0);
8922       if (isContractableFMUL(N10))
8923         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8924                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8925                                        N10.getOperand(0)),
8926                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8927                                        N10.getOperand(1)), N0);
8928     }
8929   }
8930 
8931   // More folding opportunities when target permits.
8932   if (Aggressive) {
8933     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8934     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8935     // are currently only supported on binary nodes.
8936     if (Options.UnsafeFPMath &&
8937         N0.getOpcode() == PreferredFusedOpcode &&
8938         N0.getOperand(2).getOpcode() == ISD::FMUL &&
8939         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8940       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8941                          N0.getOperand(0), N0.getOperand(1),
8942                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8943                                      N0.getOperand(2).getOperand(0),
8944                                      N0.getOperand(2).getOperand(1),
8945                                      N1));
8946     }
8947 
8948     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8949     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8950     // are currently only supported on binary nodes.
8951     if (Options.UnsafeFPMath &&
8952         N1->getOpcode() == PreferredFusedOpcode &&
8953         N1.getOperand(2).getOpcode() == ISD::FMUL &&
8954         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
8955       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8956                          N1.getOperand(0), N1.getOperand(1),
8957                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8958                                      N1.getOperand(2).getOperand(0),
8959                                      N1.getOperand(2).getOperand(1),
8960                                      N0));
8961     }
8962 
8963     if (LookThroughFPExt) {
8964       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8965       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8966       auto FoldFAddFMAFPExtFMul = [&] (
8967           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8968         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8969                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8970                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8971                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8972                                        Z));
8973       };
8974       if (N0.getOpcode() == PreferredFusedOpcode) {
8975         SDValue N02 = N0.getOperand(2);
8976         if (N02.getOpcode() == ISD::FP_EXTEND) {
8977           SDValue N020 = N02.getOperand(0);
8978           if (isContractableFMUL(N020))
8979             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8980                                         N020.getOperand(0), N020.getOperand(1),
8981                                         N1);
8982         }
8983       }
8984 
8985       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8986       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8987       // FIXME: This turns two single-precision and one double-precision
8988       // operation into two double-precision operations, which might not be
8989       // interesting for all targets, especially GPUs.
8990       auto FoldFAddFPExtFMAFMul = [&] (
8991           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8992         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8993                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8994                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8995                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8996                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8997                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8998                                        Z));
8999       };
9000       if (N0.getOpcode() == ISD::FP_EXTEND) {
9001         SDValue N00 = N0.getOperand(0);
9002         if (N00.getOpcode() == PreferredFusedOpcode) {
9003           SDValue N002 = N00.getOperand(2);
9004           if (isContractableFMUL(N002))
9005             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9006                                         N002.getOperand(0), N002.getOperand(1),
9007                                         N1);
9008         }
9009       }
9010 
9011       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9012       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9013       if (N1.getOpcode() == PreferredFusedOpcode) {
9014         SDValue N12 = N1.getOperand(2);
9015         if (N12.getOpcode() == ISD::FP_EXTEND) {
9016           SDValue N120 = N12.getOperand(0);
9017           if (isContractableFMUL(N120))
9018             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9019                                         N120.getOperand(0), N120.getOperand(1),
9020                                         N0);
9021         }
9022       }
9023 
9024       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9025       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9026       // FIXME: This turns two single-precision and one double-precision
9027       // operation into two double-precision operations, which might not be
9028       // interesting for all targets, especially GPUs.
9029       if (N1.getOpcode() == ISD::FP_EXTEND) {
9030         SDValue N10 = N1.getOperand(0);
9031         if (N10.getOpcode() == PreferredFusedOpcode) {
9032           SDValue N102 = N10.getOperand(2);
9033           if (isContractableFMUL(N102))
9034             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9035                                         N102.getOperand(0), N102.getOperand(1),
9036                                         N0);
9037         }
9038       }
9039     }
9040   }
9041 
9042   return SDValue();
9043 }
9044 
9045 /// Try to perform FMA combining on a given FSUB node.
9046 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9047   SDValue N0 = N->getOperand(0);
9048   SDValue N1 = N->getOperand(1);
9049   EVT VT = N->getValueType(0);
9050   SDLoc SL(N);
9051 
9052   const TargetOptions &Options = DAG.getTarget().Options;
9053   // Floating-point multiply-add with intermediate rounding.
9054   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9055 
9056   // Floating-point multiply-add without intermediate rounding.
9057   bool HasFMA =
9058       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9059       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9060 
9061   // No valid opcode, do not combine.
9062   if (!HasFMAD && !HasFMA)
9063     return SDValue();
9064 
9065   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9066                               Options.UnsafeFPMath || HasFMAD);
9067   // If the subtraction is not contractable, do not combine.
9068   if (!AllowFusionGlobally && !isContractable(N))
9069     return SDValue();
9070 
9071   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9072   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9073     return SDValue();
9074 
9075   // Always prefer FMAD to FMA for precision.
9076   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9077   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9078   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9079 
9080   // Is the node an FMUL and contractable either due to global flags or
9081   // SDNodeFlags.
9082   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9083     if (N.getOpcode() != ISD::FMUL)
9084       return false;
9085     return AllowFusionGlobally || isContractable(N.getNode());
9086   };
9087 
9088   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9089   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9090     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9091                        N0.getOperand(0), N0.getOperand(1),
9092                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9093   }
9094 
9095   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9096   // Note: Commutes FSUB operands.
9097   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9098     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9099                        DAG.getNode(ISD::FNEG, SL, VT,
9100                                    N1.getOperand(0)),
9101                        N1.getOperand(1), N0);
9102 
9103   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9104   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9105       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9106     SDValue N00 = N0.getOperand(0).getOperand(0);
9107     SDValue N01 = N0.getOperand(0).getOperand(1);
9108     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9109                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9110                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9111   }
9112 
9113   // Look through FP_EXTEND nodes to do more combining.
9114   if (LookThroughFPExt) {
9115     // fold (fsub (fpext (fmul x, y)), z)
9116     //   -> (fma (fpext x), (fpext y), (fneg z))
9117     if (N0.getOpcode() == ISD::FP_EXTEND) {
9118       SDValue N00 = N0.getOperand(0);
9119       if (isContractableFMUL(N00))
9120         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9121                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9122                                        N00.getOperand(0)),
9123                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9124                                        N00.getOperand(1)),
9125                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9126     }
9127 
9128     // fold (fsub x, (fpext (fmul y, z)))
9129     //   -> (fma (fneg (fpext y)), (fpext z), x)
9130     // Note: Commutes FSUB operands.
9131     if (N1.getOpcode() == ISD::FP_EXTEND) {
9132       SDValue N10 = N1.getOperand(0);
9133       if (isContractableFMUL(N10))
9134         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9135                            DAG.getNode(ISD::FNEG, SL, VT,
9136                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9137                                                    N10.getOperand(0))),
9138                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9139                                        N10.getOperand(1)),
9140                            N0);
9141     }
9142 
9143     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9144     //   -> (fneg (fma (fpext x), (fpext y), z))
9145     // Note: This could be removed with appropriate canonicalization of the
9146     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9147     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9148     // from implementing the canonicalization in visitFSUB.
9149     if (N0.getOpcode() == ISD::FP_EXTEND) {
9150       SDValue N00 = N0.getOperand(0);
9151       if (N00.getOpcode() == ISD::FNEG) {
9152         SDValue N000 = N00.getOperand(0);
9153         if (isContractableFMUL(N000)) {
9154           return DAG.getNode(ISD::FNEG, SL, VT,
9155                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9156                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9157                                                      N000.getOperand(0)),
9158                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9159                                                      N000.getOperand(1)),
9160                                          N1));
9161         }
9162       }
9163     }
9164 
9165     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9166     //   -> (fneg (fma (fpext x)), (fpext y), z)
9167     // Note: This could be removed with appropriate canonicalization of the
9168     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9169     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9170     // from implementing the canonicalization in visitFSUB.
9171     if (N0.getOpcode() == ISD::FNEG) {
9172       SDValue N00 = N0.getOperand(0);
9173       if (N00.getOpcode() == ISD::FP_EXTEND) {
9174         SDValue N000 = N00.getOperand(0);
9175         if (isContractableFMUL(N000)) {
9176           return DAG.getNode(ISD::FNEG, SL, VT,
9177                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9178                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9179                                                      N000.getOperand(0)),
9180                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9181                                                      N000.getOperand(1)),
9182                                          N1));
9183         }
9184       }
9185     }
9186 
9187   }
9188 
9189   // More folding opportunities when target permits.
9190   if (Aggressive) {
9191     // fold (fsub (fma x, y, (fmul u, v)), z)
9192     //   -> (fma x, y (fma u, v, (fneg z)))
9193     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9194     // are currently only supported on binary nodes.
9195     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9196         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9197         N0.getOperand(2)->hasOneUse()) {
9198       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9199                          N0.getOperand(0), N0.getOperand(1),
9200                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9201                                      N0.getOperand(2).getOperand(0),
9202                                      N0.getOperand(2).getOperand(1),
9203                                      DAG.getNode(ISD::FNEG, SL, VT,
9204                                                  N1)));
9205     }
9206 
9207     // fold (fsub x, (fma y, z, (fmul u, v)))
9208     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9209     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9210     // are currently only supported on binary nodes.
9211     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9212         isContractableFMUL(N1.getOperand(2))) {
9213       SDValue N20 = N1.getOperand(2).getOperand(0);
9214       SDValue N21 = N1.getOperand(2).getOperand(1);
9215       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9216                          DAG.getNode(ISD::FNEG, SL, VT,
9217                                      N1.getOperand(0)),
9218                          N1.getOperand(1),
9219                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9220                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9221 
9222                                      N21, N0));
9223     }
9224 
9225     if (LookThroughFPExt) {
9226       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9227       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9228       if (N0.getOpcode() == PreferredFusedOpcode) {
9229         SDValue N02 = N0.getOperand(2);
9230         if (N02.getOpcode() == ISD::FP_EXTEND) {
9231           SDValue N020 = N02.getOperand(0);
9232           if (isContractableFMUL(N020))
9233             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9234                                N0.getOperand(0), N0.getOperand(1),
9235                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9236                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9237                                                        N020.getOperand(0)),
9238                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9239                                                        N020.getOperand(1)),
9240                                            DAG.getNode(ISD::FNEG, SL, VT,
9241                                                        N1)));
9242         }
9243       }
9244 
9245       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9246       //   -> (fma (fpext x), (fpext y),
9247       //           (fma (fpext u), (fpext v), (fneg z)))
9248       // FIXME: This turns two single-precision and one double-precision
9249       // operation into two double-precision operations, which might not be
9250       // interesting for all targets, especially GPUs.
9251       if (N0.getOpcode() == ISD::FP_EXTEND) {
9252         SDValue N00 = N0.getOperand(0);
9253         if (N00.getOpcode() == PreferredFusedOpcode) {
9254           SDValue N002 = N00.getOperand(2);
9255           if (isContractableFMUL(N002))
9256             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9257                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9258                                            N00.getOperand(0)),
9259                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9260                                            N00.getOperand(1)),
9261                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9262                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9263                                                        N002.getOperand(0)),
9264                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9265                                                        N002.getOperand(1)),
9266                                            DAG.getNode(ISD::FNEG, SL, VT,
9267                                                        N1)));
9268         }
9269       }
9270 
9271       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9272       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9273       if (N1.getOpcode() == PreferredFusedOpcode &&
9274         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9275         SDValue N120 = N1.getOperand(2).getOperand(0);
9276         if (isContractableFMUL(N120)) {
9277           SDValue N1200 = N120.getOperand(0);
9278           SDValue N1201 = N120.getOperand(1);
9279           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9280                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9281                              N1.getOperand(1),
9282                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9283                                          DAG.getNode(ISD::FNEG, SL, VT,
9284                                              DAG.getNode(ISD::FP_EXTEND, SL,
9285                                                          VT, N1200)),
9286                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9287                                                      N1201),
9288                                          N0));
9289         }
9290       }
9291 
9292       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9293       //   -> (fma (fneg (fpext y)), (fpext z),
9294       //           (fma (fneg (fpext u)), (fpext v), x))
9295       // FIXME: This turns two single-precision and one double-precision
9296       // operation into two double-precision operations, which might not be
9297       // interesting for all targets, especially GPUs.
9298       if (N1.getOpcode() == ISD::FP_EXTEND &&
9299         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9300         SDValue N100 = N1.getOperand(0).getOperand(0);
9301         SDValue N101 = N1.getOperand(0).getOperand(1);
9302         SDValue N102 = N1.getOperand(0).getOperand(2);
9303         if (isContractableFMUL(N102)) {
9304           SDValue N1020 = N102.getOperand(0);
9305           SDValue N1021 = N102.getOperand(1);
9306           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9307                              DAG.getNode(ISD::FNEG, SL, VT,
9308                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9309                                                      N100)),
9310                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9311                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9312                                          DAG.getNode(ISD::FNEG, SL, VT,
9313                                              DAG.getNode(ISD::FP_EXTEND, SL,
9314                                                          VT, N1020)),
9315                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9316                                                      N1021),
9317                                          N0));
9318         }
9319       }
9320     }
9321   }
9322 
9323   return SDValue();
9324 }
9325 
9326 /// Try to perform FMA combining on a given FMUL node based on the distributive
9327 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9328 /// subtraction instead of addition).
9329 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9330   SDValue N0 = N->getOperand(0);
9331   SDValue N1 = N->getOperand(1);
9332   EVT VT = N->getValueType(0);
9333   SDLoc SL(N);
9334 
9335   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9336 
9337   const TargetOptions &Options = DAG.getTarget().Options;
9338 
9339   // The transforms below are incorrect when x == 0 and y == inf, because the
9340   // intermediate multiplication produces a nan.
9341   if (!Options.NoInfsFPMath)
9342     return SDValue();
9343 
9344   // Floating-point multiply-add without intermediate rounding.
9345   bool HasFMA =
9346       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9347       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9348       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9349 
9350   // Floating-point multiply-add with intermediate rounding. This can result
9351   // in a less precise result due to the changed rounding order.
9352   bool HasFMAD = Options.UnsafeFPMath &&
9353                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9354 
9355   // No valid opcode, do not combine.
9356   if (!HasFMAD && !HasFMA)
9357     return SDValue();
9358 
9359   // Always prefer FMAD to FMA for precision.
9360   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9361   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9362 
9363   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9364   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9365   auto FuseFADD = [&](SDValue X, SDValue Y) {
9366     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9367       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9368       if (XC1 && XC1->isExactlyValue(+1.0))
9369         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9370       if (XC1 && XC1->isExactlyValue(-1.0))
9371         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9372                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9373     }
9374     return SDValue();
9375   };
9376 
9377   if (SDValue FMA = FuseFADD(N0, N1))
9378     return FMA;
9379   if (SDValue FMA = FuseFADD(N1, N0))
9380     return FMA;
9381 
9382   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9383   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9384   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9385   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9386   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9387     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9388       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9389       if (XC0 && XC0->isExactlyValue(+1.0))
9390         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9391                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9392                            Y);
9393       if (XC0 && XC0->isExactlyValue(-1.0))
9394         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9395                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9396                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9397 
9398       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9399       if (XC1 && XC1->isExactlyValue(+1.0))
9400         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9401                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9402       if (XC1 && XC1->isExactlyValue(-1.0))
9403         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9404     }
9405     return SDValue();
9406   };
9407 
9408   if (SDValue FMA = FuseFSUB(N0, N1))
9409     return FMA;
9410   if (SDValue FMA = FuseFSUB(N1, N0))
9411     return FMA;
9412 
9413   return SDValue();
9414 }
9415 
9416 static bool isFMulNegTwo(SDValue &N) {
9417   if (N.getOpcode() != ISD::FMUL)
9418     return false;
9419   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9420     return CFP->isExactlyValue(-2.0);
9421   return false;
9422 }
9423 
9424 SDValue DAGCombiner::visitFADD(SDNode *N) {
9425   SDValue N0 = N->getOperand(0);
9426   SDValue N1 = N->getOperand(1);
9427   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9428   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9429   EVT VT = N->getValueType(0);
9430   SDLoc DL(N);
9431   const TargetOptions &Options = DAG.getTarget().Options;
9432   const SDNodeFlags Flags = N->getFlags();
9433 
9434   // fold vector ops
9435   if (VT.isVector())
9436     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9437       return FoldedVOp;
9438 
9439   // fold (fadd c1, c2) -> c1 + c2
9440   if (N0CFP && N1CFP)
9441     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9442 
9443   // canonicalize constant to RHS
9444   if (N0CFP && !N1CFP)
9445     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9446 
9447   if (SDValue NewSel = foldBinOpIntoSelect(N))
9448     return NewSel;
9449 
9450   // fold (fadd A, (fneg B)) -> (fsub A, B)
9451   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9452       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9453     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9454                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9455 
9456   // fold (fadd (fneg A), B) -> (fsub B, A)
9457   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9458       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9459     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9460                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9461 
9462   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9463   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9464   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9465       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9466     bool N1IsFMul = isFMulNegTwo(N1);
9467     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9468     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9469     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9470   }
9471 
9472   // FIXME: Auto-upgrade the target/function-level option.
9473   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9474     // fold (fadd A, 0) -> A
9475     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9476       if (N1C->isZero())
9477         return N0;
9478   }
9479 
9480   // If 'unsafe math' is enabled, fold lots of things.
9481   if (Options.UnsafeFPMath) {
9482     // No FP constant should be created after legalization as Instruction
9483     // Selection pass has a hard time dealing with FP constants.
9484     bool AllowNewConst = (Level < AfterLegalizeDAG);
9485 
9486     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9487     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9488         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9489       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9490                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9491                                      Flags),
9492                          Flags);
9493 
9494     // If allowed, fold (fadd (fneg x), x) -> 0.0
9495     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9496       return DAG.getConstantFP(0.0, DL, VT);
9497 
9498     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9499     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9500       return DAG.getConstantFP(0.0, DL, VT);
9501 
9502     // We can fold chains of FADD's of the same value into multiplications.
9503     // This transform is not safe in general because we are reducing the number
9504     // of rounding steps.
9505     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9506       if (N0.getOpcode() == ISD::FMUL) {
9507         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9508         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9509 
9510         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9511         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9512           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9513                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9514           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9515         }
9516 
9517         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9518         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9519             N1.getOperand(0) == N1.getOperand(1) &&
9520             N0.getOperand(0) == N1.getOperand(0)) {
9521           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9522                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9523           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9524         }
9525       }
9526 
9527       if (N1.getOpcode() == ISD::FMUL) {
9528         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9529         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9530 
9531         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9532         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9533           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9534                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9535           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9536         }
9537 
9538         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9539         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9540             N0.getOperand(0) == N0.getOperand(1) &&
9541             N1.getOperand(0) == N0.getOperand(0)) {
9542           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9543                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9544           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9545         }
9546       }
9547 
9548       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9549         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9550         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9551         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9552             (N0.getOperand(0) == N1)) {
9553           return DAG.getNode(ISD::FMUL, DL, VT,
9554                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9555         }
9556       }
9557 
9558       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9559         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9560         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9561         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9562             N1.getOperand(0) == N0) {
9563           return DAG.getNode(ISD::FMUL, DL, VT,
9564                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9565         }
9566       }
9567 
9568       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9569       if (AllowNewConst &&
9570           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9571           N0.getOperand(0) == N0.getOperand(1) &&
9572           N1.getOperand(0) == N1.getOperand(1) &&
9573           N0.getOperand(0) == N1.getOperand(0)) {
9574         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9575                            DAG.getConstantFP(4.0, DL, VT), Flags);
9576       }
9577     }
9578   } // enable-unsafe-fp-math
9579 
9580   // FADD -> FMA combines:
9581   if (SDValue Fused = visitFADDForFMACombine(N)) {
9582     AddToWorklist(Fused.getNode());
9583     return Fused;
9584   }
9585   return SDValue();
9586 }
9587 
9588 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9589   SDValue N0 = N->getOperand(0);
9590   SDValue N1 = N->getOperand(1);
9591   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9592   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9593   EVT VT = N->getValueType(0);
9594   SDLoc DL(N);
9595   const TargetOptions &Options = DAG.getTarget().Options;
9596   const SDNodeFlags Flags = N->getFlags();
9597 
9598   // fold vector ops
9599   if (VT.isVector())
9600     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9601       return FoldedVOp;
9602 
9603   // fold (fsub c1, c2) -> c1-c2
9604   if (N0CFP && N1CFP)
9605     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9606 
9607   if (SDValue NewSel = foldBinOpIntoSelect(N))
9608     return NewSel;
9609 
9610   // fold (fsub A, (fneg B)) -> (fadd A, B)
9611   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9612     return DAG.getNode(ISD::FADD, DL, VT, N0,
9613                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9614 
9615   // FIXME: Auto-upgrade the target/function-level option.
9616   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9617     // (fsub 0, B) -> -B
9618     if (N0CFP && N0CFP->isZero()) {
9619       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9620         return GetNegatedExpression(N1, DAG, LegalOperations);
9621       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9622         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9623     }
9624   }
9625 
9626   // If 'unsafe math' is enabled, fold lots of things.
9627   if (Options.UnsafeFPMath) {
9628     // (fsub A, 0) -> A
9629     if (N1CFP && N1CFP->isZero())
9630       return N0;
9631 
9632     // (fsub x, x) -> 0.0
9633     if (N0 == N1)
9634       return DAG.getConstantFP(0.0f, DL, VT);
9635 
9636     // (fsub x, (fadd x, y)) -> (fneg y)
9637     // (fsub x, (fadd y, x)) -> (fneg y)
9638     if (N1.getOpcode() == ISD::FADD) {
9639       SDValue N10 = N1->getOperand(0);
9640       SDValue N11 = N1->getOperand(1);
9641 
9642       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9643         return GetNegatedExpression(N11, DAG, LegalOperations);
9644 
9645       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9646         return GetNegatedExpression(N10, DAG, LegalOperations);
9647     }
9648   }
9649 
9650   // FSUB -> FMA combines:
9651   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9652     AddToWorklist(Fused.getNode());
9653     return Fused;
9654   }
9655 
9656   return SDValue();
9657 }
9658 
9659 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9660   SDValue N0 = N->getOperand(0);
9661   SDValue N1 = N->getOperand(1);
9662   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9663   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9664   EVT VT = N->getValueType(0);
9665   SDLoc DL(N);
9666   const TargetOptions &Options = DAG.getTarget().Options;
9667   const SDNodeFlags Flags = N->getFlags();
9668 
9669   // fold vector ops
9670   if (VT.isVector()) {
9671     // This just handles C1 * C2 for vectors. Other vector folds are below.
9672     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9673       return FoldedVOp;
9674   }
9675 
9676   // fold (fmul c1, c2) -> c1*c2
9677   if (N0CFP && N1CFP)
9678     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9679 
9680   // canonicalize constant to RHS
9681   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9682      !isConstantFPBuildVectorOrConstantFP(N1))
9683     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9684 
9685   // fold (fmul A, 1.0) -> A
9686   if (N1CFP && N1CFP->isExactlyValue(1.0))
9687     return N0;
9688 
9689   if (SDValue NewSel = foldBinOpIntoSelect(N))
9690     return NewSel;
9691 
9692   if (Options.UnsafeFPMath) {
9693     // fold (fmul A, 0) -> 0
9694     if (N1CFP && N1CFP->isZero())
9695       return N1;
9696 
9697     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9698     if (N0.getOpcode() == ISD::FMUL) {
9699       // Fold scalars or any vector constants (not just splats).
9700       // This fold is done in general by InstCombine, but extra fmul insts
9701       // may have been generated during lowering.
9702       SDValue N00 = N0.getOperand(0);
9703       SDValue N01 = N0.getOperand(1);
9704       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9705       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9706       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9707 
9708       // Check 1: Make sure that the first operand of the inner multiply is NOT
9709       // a constant. Otherwise, we may induce infinite looping.
9710       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9711         // Check 2: Make sure that the second operand of the inner multiply and
9712         // the second operand of the outer multiply are constants.
9713         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9714             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9715           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9716           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9717         }
9718       }
9719     }
9720 
9721     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9722     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9723     // during an early run of DAGCombiner can prevent folding with fmuls
9724     // inserted during lowering.
9725     if (N0.getOpcode() == ISD::FADD &&
9726         (N0.getOperand(0) == N0.getOperand(1)) &&
9727         N0.hasOneUse()) {
9728       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9729       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9730       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9731     }
9732   }
9733 
9734   // fold (fmul X, 2.0) -> (fadd X, X)
9735   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9736     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9737 
9738   // fold (fmul X, -1.0) -> (fneg X)
9739   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9740     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9741       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9742 
9743   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9744   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9745     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9746       // Both can be negated for free, check to see if at least one is cheaper
9747       // negated.
9748       if (LHSNeg == 2 || RHSNeg == 2)
9749         return DAG.getNode(ISD::FMUL, DL, VT,
9750                            GetNegatedExpression(N0, DAG, LegalOperations),
9751                            GetNegatedExpression(N1, DAG, LegalOperations),
9752                            Flags);
9753     }
9754   }
9755 
9756   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
9757   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
9758   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
9759       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
9760       TLI.isOperationLegal(ISD::FABS, VT)) {
9761     SDValue Select = N0, X = N1;
9762     if (Select.getOpcode() != ISD::SELECT)
9763       std::swap(Select, X);
9764 
9765     SDValue Cond = Select.getOperand(0);
9766     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
9767     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
9768 
9769     if (TrueOpnd && FalseOpnd &&
9770         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
9771         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
9772         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
9773       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9774       switch (CC) {
9775       default: break;
9776       case ISD::SETOLT:
9777       case ISD::SETULT:
9778       case ISD::SETOLE:
9779       case ISD::SETULE:
9780       case ISD::SETLT:
9781       case ISD::SETLE:
9782         std::swap(TrueOpnd, FalseOpnd);
9783         // Fall through
9784       case ISD::SETOGT:
9785       case ISD::SETUGT:
9786       case ISD::SETOGE:
9787       case ISD::SETUGE:
9788       case ISD::SETGT:
9789       case ISD::SETGE:
9790         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
9791             TLI.isOperationLegal(ISD::FNEG, VT))
9792           return DAG.getNode(ISD::FNEG, DL, VT,
9793                    DAG.getNode(ISD::FABS, DL, VT, X));
9794         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
9795           return DAG.getNode(ISD::FABS, DL, VT, X);
9796 
9797         break;
9798       }
9799     }
9800   }
9801 
9802   // FMUL -> FMA combines:
9803   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9804     AddToWorklist(Fused.getNode());
9805     return Fused;
9806   }
9807 
9808   return SDValue();
9809 }
9810 
9811 SDValue DAGCombiner::visitFMA(SDNode *N) {
9812   SDValue N0 = N->getOperand(0);
9813   SDValue N1 = N->getOperand(1);
9814   SDValue N2 = N->getOperand(2);
9815   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9816   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9817   EVT VT = N->getValueType(0);
9818   SDLoc DL(N);
9819   const TargetOptions &Options = DAG.getTarget().Options;
9820 
9821   // Constant fold FMA.
9822   if (isa<ConstantFPSDNode>(N0) &&
9823       isa<ConstantFPSDNode>(N1) &&
9824       isa<ConstantFPSDNode>(N2)) {
9825     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9826   }
9827 
9828   if (Options.UnsafeFPMath) {
9829     if (N0CFP && N0CFP->isZero())
9830       return N2;
9831     if (N1CFP && N1CFP->isZero())
9832       return N2;
9833   }
9834   // TODO: The FMA node should have flags that propagate to these nodes.
9835   if (N0CFP && N0CFP->isExactlyValue(1.0))
9836     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9837   if (N1CFP && N1CFP->isExactlyValue(1.0))
9838     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9839 
9840   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9841   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9842      !isConstantFPBuildVectorOrConstantFP(N1))
9843     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9844 
9845   // TODO: FMA nodes should have flags that propagate to the created nodes.
9846   // For now, create a Flags object for use with all unsafe math transforms.
9847   SDNodeFlags Flags;
9848   Flags.setUnsafeAlgebra(true);
9849 
9850   if (Options.UnsafeFPMath) {
9851     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9852     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9853         isConstantFPBuildVectorOrConstantFP(N1) &&
9854         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9855       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9856                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9857                                      Flags), Flags);
9858     }
9859 
9860     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9861     if (N0.getOpcode() == ISD::FMUL &&
9862         isConstantFPBuildVectorOrConstantFP(N1) &&
9863         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9864       return DAG.getNode(ISD::FMA, DL, VT,
9865                          N0.getOperand(0),
9866                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9867                                      Flags),
9868                          N2);
9869     }
9870   }
9871 
9872   // (fma x, 1, y) -> (fadd x, y)
9873   // (fma x, -1, y) -> (fadd (fneg x), y)
9874   if (N1CFP) {
9875     if (N1CFP->isExactlyValue(1.0))
9876       // TODO: The FMA node should have flags that propagate to this node.
9877       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9878 
9879     if (N1CFP->isExactlyValue(-1.0) &&
9880         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9881       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9882       AddToWorklist(RHSNeg.getNode());
9883       // TODO: The FMA node should have flags that propagate to this node.
9884       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9885     }
9886   }
9887 
9888   if (Options.UnsafeFPMath) {
9889     // (fma x, c, x) -> (fmul x, (c+1))
9890     if (N1CFP && N0 == N2) {
9891       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9892                          DAG.getNode(ISD::FADD, DL, VT, N1,
9893                                      DAG.getConstantFP(1.0, DL, VT), Flags),
9894                          Flags);
9895     }
9896 
9897     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9898     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9899       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9900                          DAG.getNode(ISD::FADD, DL, VT, N1,
9901                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
9902                          Flags);
9903     }
9904   }
9905 
9906   return SDValue();
9907 }
9908 
9909 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9910 // reciprocal.
9911 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9912 // Notice that this is not always beneficial. One reason is different targets
9913 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9914 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9915 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9916 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9917   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9918   const SDNodeFlags Flags = N->getFlags();
9919   if (!UnsafeMath && !Flags.hasAllowReciprocal())
9920     return SDValue();
9921 
9922   // Skip if current node is a reciprocal.
9923   SDValue N0 = N->getOperand(0);
9924   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9925   if (N0CFP && N0CFP->isExactlyValue(1.0))
9926     return SDValue();
9927 
9928   // Exit early if the target does not want this transform or if there can't
9929   // possibly be enough uses of the divisor to make the transform worthwhile.
9930   SDValue N1 = N->getOperand(1);
9931   unsigned MinUses = TLI.combineRepeatedFPDivisors();
9932   if (!MinUses || N1->use_size() < MinUses)
9933     return SDValue();
9934 
9935   // Find all FDIV users of the same divisor.
9936   // Use a set because duplicates may be present in the user list.
9937   SetVector<SDNode *> Users;
9938   for (auto *U : N1->uses()) {
9939     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9940       // This division is eligible for optimization only if global unsafe math
9941       // is enabled or if this division allows reciprocal formation.
9942       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
9943         Users.insert(U);
9944     }
9945   }
9946 
9947   // Now that we have the actual number of divisor uses, make sure it meets
9948   // the minimum threshold specified by the target.
9949   if (Users.size() < MinUses)
9950     return SDValue();
9951 
9952   EVT VT = N->getValueType(0);
9953   SDLoc DL(N);
9954   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9955   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9956 
9957   // Dividend / Divisor -> Dividend * Reciprocal
9958   for (auto *U : Users) {
9959     SDValue Dividend = U->getOperand(0);
9960     if (Dividend != FPOne) {
9961       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9962                                     Reciprocal, Flags);
9963       CombineTo(U, NewNode);
9964     } else if (U != Reciprocal.getNode()) {
9965       // In the absence of fast-math-flags, this user node is always the
9966       // same node as Reciprocal, but with FMF they may be different nodes.
9967       CombineTo(U, Reciprocal);
9968     }
9969   }
9970   return SDValue(N, 0);  // N was replaced.
9971 }
9972 
9973 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9974   SDValue N0 = N->getOperand(0);
9975   SDValue N1 = N->getOperand(1);
9976   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9977   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9978   EVT VT = N->getValueType(0);
9979   SDLoc DL(N);
9980   const TargetOptions &Options = DAG.getTarget().Options;
9981   SDNodeFlags Flags = N->getFlags();
9982 
9983   // fold vector ops
9984   if (VT.isVector())
9985     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9986       return FoldedVOp;
9987 
9988   // fold (fdiv c1, c2) -> c1/c2
9989   if (N0CFP && N1CFP)
9990     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9991 
9992   if (SDValue NewSel = foldBinOpIntoSelect(N))
9993     return NewSel;
9994 
9995   if (Options.UnsafeFPMath) {
9996     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9997     if (N1CFP) {
9998       // Compute the reciprocal 1.0 / c2.
9999       const APFloat &N1APF = N1CFP->getValueAPF();
10000       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10001       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10002       // Only do the transform if the reciprocal is a legal fp immediate that
10003       // isn't too nasty (eg NaN, denormal, ...).
10004       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10005           (!LegalOperations ||
10006            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10007            // backend)... we should handle this gracefully after Legalize.
10008            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10009            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10010            TLI.isFPImmLegal(Recip, VT)))
10011         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10012                            DAG.getConstantFP(Recip, DL, VT), Flags);
10013     }
10014 
10015     // If this FDIV is part of a reciprocal square root, it may be folded
10016     // into a target-specific square root estimate instruction.
10017     if (N1.getOpcode() == ISD::FSQRT) {
10018       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10019         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10020       }
10021     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10022                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10023       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10024                                           Flags)) {
10025         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10026         AddToWorklist(RV.getNode());
10027         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10028       }
10029     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10030                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10031       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10032                                           Flags)) {
10033         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10034         AddToWorklist(RV.getNode());
10035         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10036       }
10037     } else if (N1.getOpcode() == ISD::FMUL) {
10038       // Look through an FMUL. Even though this won't remove the FDIV directly,
10039       // it's still worthwhile to get rid of the FSQRT if possible.
10040       SDValue SqrtOp;
10041       SDValue OtherOp;
10042       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10043         SqrtOp = N1.getOperand(0);
10044         OtherOp = N1.getOperand(1);
10045       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10046         SqrtOp = N1.getOperand(1);
10047         OtherOp = N1.getOperand(0);
10048       }
10049       if (SqrtOp.getNode()) {
10050         // We found a FSQRT, so try to make this fold:
10051         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10052         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10053           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10054           AddToWorklist(RV.getNode());
10055           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10056         }
10057       }
10058     }
10059 
10060     // Fold into a reciprocal estimate and multiply instead of a real divide.
10061     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10062       AddToWorklist(RV.getNode());
10063       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10064     }
10065   }
10066 
10067   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10068   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10069     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10070       // Both can be negated for free, check to see if at least one is cheaper
10071       // negated.
10072       if (LHSNeg == 2 || RHSNeg == 2)
10073         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10074                            GetNegatedExpression(N0, DAG, LegalOperations),
10075                            GetNegatedExpression(N1, DAG, LegalOperations),
10076                            Flags);
10077     }
10078   }
10079 
10080   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10081     return CombineRepeatedDivisors;
10082 
10083   return SDValue();
10084 }
10085 
10086 SDValue DAGCombiner::visitFREM(SDNode *N) {
10087   SDValue N0 = N->getOperand(0);
10088   SDValue N1 = N->getOperand(1);
10089   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10090   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10091   EVT VT = N->getValueType(0);
10092 
10093   // fold (frem c1, c2) -> fmod(c1,c2)
10094   if (N0CFP && N1CFP)
10095     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10096 
10097   if (SDValue NewSel = foldBinOpIntoSelect(N))
10098     return NewSel;
10099 
10100   return SDValue();
10101 }
10102 
10103 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10104   if (!DAG.getTarget().Options.UnsafeFPMath)
10105     return SDValue();
10106 
10107   SDValue N0 = N->getOperand(0);
10108   if (TLI.isFsqrtCheap(N0, DAG))
10109     return SDValue();
10110 
10111   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10112   // For now, create a Flags object for use with all unsafe math transforms.
10113   SDNodeFlags Flags;
10114   Flags.setUnsafeAlgebra(true);
10115   return buildSqrtEstimate(N0, Flags);
10116 }
10117 
10118 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10119 /// copysign(x, fp_round(y)) -> copysign(x, y)
10120 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10121   SDValue N1 = N->getOperand(1);
10122   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10123        N1.getOpcode() == ISD::FP_ROUND)) {
10124     // Do not optimize out type conversion of f128 type yet.
10125     // For some targets like x86_64, configuration is changed to keep one f128
10126     // value in one SSE register, but instruction selection cannot handle
10127     // FCOPYSIGN on SSE registers yet.
10128     EVT N1VT = N1->getValueType(0);
10129     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10130     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10131   }
10132   return false;
10133 }
10134 
10135 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10136   SDValue N0 = N->getOperand(0);
10137   SDValue N1 = N->getOperand(1);
10138   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10139   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10140   EVT VT = N->getValueType(0);
10141 
10142   if (N0CFP && N1CFP) // Constant fold
10143     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10144 
10145   if (N1CFP) {
10146     const APFloat &V = N1CFP->getValueAPF();
10147     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10148     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10149     if (!V.isNegative()) {
10150       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10151         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10152     } else {
10153       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10154         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10155                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10156     }
10157   }
10158 
10159   // copysign(fabs(x), y) -> copysign(x, y)
10160   // copysign(fneg(x), y) -> copysign(x, y)
10161   // copysign(copysign(x,z), y) -> copysign(x, y)
10162   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10163       N0.getOpcode() == ISD::FCOPYSIGN)
10164     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10165 
10166   // copysign(x, abs(y)) -> abs(x)
10167   if (N1.getOpcode() == ISD::FABS)
10168     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10169 
10170   // copysign(x, copysign(y,z)) -> copysign(x, z)
10171   if (N1.getOpcode() == ISD::FCOPYSIGN)
10172     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10173 
10174   // copysign(x, fp_extend(y)) -> copysign(x, y)
10175   // copysign(x, fp_round(y)) -> copysign(x, y)
10176   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10177     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10178 
10179   return SDValue();
10180 }
10181 
10182 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10183   SDValue N0 = N->getOperand(0);
10184   EVT VT = N->getValueType(0);
10185   EVT OpVT = N0.getValueType();
10186 
10187   // fold (sint_to_fp c1) -> c1fp
10188   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10189       // ...but only if the target supports immediate floating-point values
10190       (!LegalOperations ||
10191        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10192     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10193 
10194   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10195   // but UINT_TO_FP is legal on this target, try to convert.
10196   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10197       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10198     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10199     if (DAG.SignBitIsZero(N0))
10200       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10201   }
10202 
10203   // The next optimizations are desirable only if SELECT_CC can be lowered.
10204   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10205     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10206     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10207         !VT.isVector() &&
10208         (!LegalOperations ||
10209          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10210       SDLoc DL(N);
10211       SDValue Ops[] =
10212         { N0.getOperand(0), N0.getOperand(1),
10213           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10214           N0.getOperand(2) };
10215       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10216     }
10217 
10218     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10219     //      (select_cc x, y, 1.0, 0.0,, cc)
10220     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10221         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10222         (!LegalOperations ||
10223          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10224       SDLoc DL(N);
10225       SDValue Ops[] =
10226         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10227           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10228           N0.getOperand(0).getOperand(2) };
10229       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10230     }
10231   }
10232 
10233   return SDValue();
10234 }
10235 
10236 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10237   SDValue N0 = N->getOperand(0);
10238   EVT VT = N->getValueType(0);
10239   EVT OpVT = N0.getValueType();
10240 
10241   // fold (uint_to_fp c1) -> c1fp
10242   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10243       // ...but only if the target supports immediate floating-point values
10244       (!LegalOperations ||
10245        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10246     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10247 
10248   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10249   // but SINT_TO_FP is legal on this target, try to convert.
10250   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10251       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10252     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10253     if (DAG.SignBitIsZero(N0))
10254       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10255   }
10256 
10257   // The next optimizations are desirable only if SELECT_CC can be lowered.
10258   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10259     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10260 
10261     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10262         (!LegalOperations ||
10263          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10264       SDLoc DL(N);
10265       SDValue Ops[] =
10266         { N0.getOperand(0), N0.getOperand(1),
10267           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10268           N0.getOperand(2) };
10269       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10270     }
10271   }
10272 
10273   return SDValue();
10274 }
10275 
10276 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10277 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10278   SDValue N0 = N->getOperand(0);
10279   EVT VT = N->getValueType(0);
10280 
10281   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10282     return SDValue();
10283 
10284   SDValue Src = N0.getOperand(0);
10285   EVT SrcVT = Src.getValueType();
10286   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10287   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10288 
10289   // We can safely assume the conversion won't overflow the output range,
10290   // because (for example) (uint8_t)18293.f is undefined behavior.
10291 
10292   // Since we can assume the conversion won't overflow, our decision as to
10293   // whether the input will fit in the float should depend on the minimum
10294   // of the input range and output range.
10295 
10296   // This means this is also safe for a signed input and unsigned output, since
10297   // a negative input would lead to undefined behavior.
10298   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10299   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10300   unsigned ActualSize = std::min(InputSize, OutputSize);
10301   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10302 
10303   // We can only fold away the float conversion if the input range can be
10304   // represented exactly in the float range.
10305   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10306     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10307       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10308                                                        : ISD::ZERO_EXTEND;
10309       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10310     }
10311     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10312       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10313     return DAG.getBitcast(VT, Src);
10314   }
10315   return SDValue();
10316 }
10317 
10318 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10319   SDValue N0 = N->getOperand(0);
10320   EVT VT = N->getValueType(0);
10321 
10322   // fold (fp_to_sint c1fp) -> c1
10323   if (isConstantFPBuildVectorOrConstantFP(N0))
10324     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10325 
10326   return FoldIntToFPToInt(N, DAG);
10327 }
10328 
10329 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10330   SDValue N0 = N->getOperand(0);
10331   EVT VT = N->getValueType(0);
10332 
10333   // fold (fp_to_uint c1fp) -> c1
10334   if (isConstantFPBuildVectorOrConstantFP(N0))
10335     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10336 
10337   return FoldIntToFPToInt(N, DAG);
10338 }
10339 
10340 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10341   SDValue N0 = N->getOperand(0);
10342   SDValue N1 = N->getOperand(1);
10343   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10344   EVT VT = N->getValueType(0);
10345 
10346   // fold (fp_round c1fp) -> c1fp
10347   if (N0CFP)
10348     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10349 
10350   // fold (fp_round (fp_extend x)) -> x
10351   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10352     return N0.getOperand(0);
10353 
10354   // fold (fp_round (fp_round x)) -> (fp_round x)
10355   if (N0.getOpcode() == ISD::FP_ROUND) {
10356     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10357     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10358 
10359     // Skip this folding if it results in an fp_round from f80 to f16.
10360     //
10361     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10362     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10363     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10364     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10365     // x86.
10366     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10367       return SDValue();
10368 
10369     // If the first fp_round isn't a value preserving truncation, it might
10370     // introduce a tie in the second fp_round, that wouldn't occur in the
10371     // single-step fp_round we want to fold to.
10372     // In other words, double rounding isn't the same as rounding.
10373     // Also, this is a value preserving truncation iff both fp_round's are.
10374     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10375       SDLoc DL(N);
10376       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10377                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10378     }
10379   }
10380 
10381   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10382   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10383     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10384                               N0.getOperand(0), N1);
10385     AddToWorklist(Tmp.getNode());
10386     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10387                        Tmp, N0.getOperand(1));
10388   }
10389 
10390   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10391     return NewVSel;
10392 
10393   return SDValue();
10394 }
10395 
10396 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10397   SDValue N0 = N->getOperand(0);
10398   EVT VT = N->getValueType(0);
10399   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10400   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10401 
10402   // fold (fp_round_inreg c1fp) -> c1fp
10403   if (N0CFP && isTypeLegal(EVT)) {
10404     SDLoc DL(N);
10405     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10406     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10407   }
10408 
10409   return SDValue();
10410 }
10411 
10412 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10413   SDValue N0 = N->getOperand(0);
10414   EVT VT = N->getValueType(0);
10415 
10416   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10417   if (N->hasOneUse() &&
10418       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10419     return SDValue();
10420 
10421   // fold (fp_extend c1fp) -> c1fp
10422   if (isConstantFPBuildVectorOrConstantFP(N0))
10423     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10424 
10425   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10426   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10427       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10428     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10429 
10430   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10431   // value of X.
10432   if (N0.getOpcode() == ISD::FP_ROUND
10433       && N0.getConstantOperandVal(1) == 1) {
10434     SDValue In = N0.getOperand(0);
10435     if (In.getValueType() == VT) return In;
10436     if (VT.bitsLT(In.getValueType()))
10437       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10438                          In, N0.getOperand(1));
10439     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10440   }
10441 
10442   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10443   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10444        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10445     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10446     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10447                                      LN0->getChain(),
10448                                      LN0->getBasePtr(), N0.getValueType(),
10449                                      LN0->getMemOperand());
10450     CombineTo(N, ExtLoad);
10451     CombineTo(N0.getNode(),
10452               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10453                           N0.getValueType(), ExtLoad,
10454                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10455               ExtLoad.getValue(1));
10456     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10457   }
10458 
10459   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10460     return NewVSel;
10461 
10462   return SDValue();
10463 }
10464 
10465 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10466   SDValue N0 = N->getOperand(0);
10467   EVT VT = N->getValueType(0);
10468 
10469   // fold (fceil c1) -> fceil(c1)
10470   if (isConstantFPBuildVectorOrConstantFP(N0))
10471     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10472 
10473   return SDValue();
10474 }
10475 
10476 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10477   SDValue N0 = N->getOperand(0);
10478   EVT VT = N->getValueType(0);
10479 
10480   // fold (ftrunc c1) -> ftrunc(c1)
10481   if (isConstantFPBuildVectorOrConstantFP(N0))
10482     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10483 
10484   return SDValue();
10485 }
10486 
10487 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10488   SDValue N0 = N->getOperand(0);
10489   EVT VT = N->getValueType(0);
10490 
10491   // fold (ffloor c1) -> ffloor(c1)
10492   if (isConstantFPBuildVectorOrConstantFP(N0))
10493     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10494 
10495   return SDValue();
10496 }
10497 
10498 // FIXME: FNEG and FABS have a lot in common; refactor.
10499 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10500   SDValue N0 = N->getOperand(0);
10501   EVT VT = N->getValueType(0);
10502 
10503   // Constant fold FNEG.
10504   if (isConstantFPBuildVectorOrConstantFP(N0))
10505     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10506 
10507   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10508                          &DAG.getTarget().Options))
10509     return GetNegatedExpression(N0, DAG, LegalOperations);
10510 
10511   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10512   // constant pool values.
10513   if (!TLI.isFNegFree(VT) &&
10514       N0.getOpcode() == ISD::BITCAST &&
10515       N0.getNode()->hasOneUse()) {
10516     SDValue Int = N0.getOperand(0);
10517     EVT IntVT = Int.getValueType();
10518     if (IntVT.isInteger() && !IntVT.isVector()) {
10519       APInt SignMask;
10520       if (N0.getValueType().isVector()) {
10521         // For a vector, get a mask such as 0x80... per scalar element
10522         // and splat it.
10523         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10524         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10525       } else {
10526         // For a scalar, just generate 0x80...
10527         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10528       }
10529       SDLoc DL0(N0);
10530       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10531                         DAG.getConstant(SignMask, DL0, IntVT));
10532       AddToWorklist(Int.getNode());
10533       return DAG.getBitcast(VT, Int);
10534     }
10535   }
10536 
10537   // (fneg (fmul c, x)) -> (fmul -c, x)
10538   if (N0.getOpcode() == ISD::FMUL &&
10539       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10540     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10541     if (CFP1) {
10542       APFloat CVal = CFP1->getValueAPF();
10543       CVal.changeSign();
10544       if (Level >= AfterLegalizeDAG &&
10545           (TLI.isFPImmLegal(CVal, VT) ||
10546            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10547         return DAG.getNode(
10548             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10549             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10550             N0->getFlags());
10551     }
10552   }
10553 
10554   return SDValue();
10555 }
10556 
10557 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10558   SDValue N0 = N->getOperand(0);
10559   SDValue N1 = N->getOperand(1);
10560   EVT VT = N->getValueType(0);
10561   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10562   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10563 
10564   if (N0CFP && N1CFP) {
10565     const APFloat &C0 = N0CFP->getValueAPF();
10566     const APFloat &C1 = N1CFP->getValueAPF();
10567     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10568   }
10569 
10570   // Canonicalize to constant on RHS.
10571   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10572      !isConstantFPBuildVectorOrConstantFP(N1))
10573     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10574 
10575   return SDValue();
10576 }
10577 
10578 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10579   SDValue N0 = N->getOperand(0);
10580   SDValue N1 = N->getOperand(1);
10581   EVT VT = N->getValueType(0);
10582   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10583   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10584 
10585   if (N0CFP && N1CFP) {
10586     const APFloat &C0 = N0CFP->getValueAPF();
10587     const APFloat &C1 = N1CFP->getValueAPF();
10588     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10589   }
10590 
10591   // Canonicalize to constant on RHS.
10592   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10593      !isConstantFPBuildVectorOrConstantFP(N1))
10594     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10595 
10596   return SDValue();
10597 }
10598 
10599 SDValue DAGCombiner::visitFABS(SDNode *N) {
10600   SDValue N0 = N->getOperand(0);
10601   EVT VT = N->getValueType(0);
10602 
10603   // fold (fabs c1) -> fabs(c1)
10604   if (isConstantFPBuildVectorOrConstantFP(N0))
10605     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10606 
10607   // fold (fabs (fabs x)) -> (fabs x)
10608   if (N0.getOpcode() == ISD::FABS)
10609     return N->getOperand(0);
10610 
10611   // fold (fabs (fneg x)) -> (fabs x)
10612   // fold (fabs (fcopysign x, y)) -> (fabs x)
10613   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10614     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10615 
10616   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10617   // constant pool values.
10618   if (!TLI.isFAbsFree(VT) &&
10619       N0.getOpcode() == ISD::BITCAST &&
10620       N0.getNode()->hasOneUse()) {
10621     SDValue Int = N0.getOperand(0);
10622     EVT IntVT = Int.getValueType();
10623     if (IntVT.isInteger() && !IntVT.isVector()) {
10624       APInt SignMask;
10625       if (N0.getValueType().isVector()) {
10626         // For a vector, get a mask such as 0x7f... per scalar element
10627         // and splat it.
10628         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10629         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10630       } else {
10631         // For a scalar, just generate 0x7f...
10632         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10633       }
10634       SDLoc DL(N0);
10635       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10636                         DAG.getConstant(SignMask, DL, IntVT));
10637       AddToWorklist(Int.getNode());
10638       return DAG.getBitcast(N->getValueType(0), Int);
10639     }
10640   }
10641 
10642   return SDValue();
10643 }
10644 
10645 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10646   SDValue Chain = N->getOperand(0);
10647   SDValue N1 = N->getOperand(1);
10648   SDValue N2 = N->getOperand(2);
10649 
10650   // If N is a constant we could fold this into a fallthrough or unconditional
10651   // branch. However that doesn't happen very often in normal code, because
10652   // Instcombine/SimplifyCFG should have handled the available opportunities.
10653   // If we did this folding here, it would be necessary to update the
10654   // MachineBasicBlock CFG, which is awkward.
10655 
10656   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10657   // on the target.
10658   if (N1.getOpcode() == ISD::SETCC &&
10659       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10660                                    N1.getOperand(0).getValueType())) {
10661     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10662                        Chain, N1.getOperand(2),
10663                        N1.getOperand(0), N1.getOperand(1), N2);
10664   }
10665 
10666   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10667       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10668        (N1.getOperand(0).hasOneUse() &&
10669         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10670     SDNode *Trunc = nullptr;
10671     if (N1.getOpcode() == ISD::TRUNCATE) {
10672       // Look pass the truncate.
10673       Trunc = N1.getNode();
10674       N1 = N1.getOperand(0);
10675     }
10676 
10677     // Match this pattern so that we can generate simpler code:
10678     //
10679     //   %a = ...
10680     //   %b = and i32 %a, 2
10681     //   %c = srl i32 %b, 1
10682     //   brcond i32 %c ...
10683     //
10684     // into
10685     //
10686     //   %a = ...
10687     //   %b = and i32 %a, 2
10688     //   %c = setcc eq %b, 0
10689     //   brcond %c ...
10690     //
10691     // This applies only when the AND constant value has one bit set and the
10692     // SRL constant is equal to the log2 of the AND constant. The back-end is
10693     // smart enough to convert the result into a TEST/JMP sequence.
10694     SDValue Op0 = N1.getOperand(0);
10695     SDValue Op1 = N1.getOperand(1);
10696 
10697     if (Op0.getOpcode() == ISD::AND &&
10698         Op1.getOpcode() == ISD::Constant) {
10699       SDValue AndOp1 = Op0.getOperand(1);
10700 
10701       if (AndOp1.getOpcode() == ISD::Constant) {
10702         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10703 
10704         if (AndConst.isPowerOf2() &&
10705             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10706           SDLoc DL(N);
10707           SDValue SetCC =
10708             DAG.getSetCC(DL,
10709                          getSetCCResultType(Op0.getValueType()),
10710                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10711                          ISD::SETNE);
10712 
10713           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10714                                           MVT::Other, Chain, SetCC, N2);
10715           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10716           // will convert it back to (X & C1) >> C2.
10717           CombineTo(N, NewBRCond, false);
10718           // Truncate is dead.
10719           if (Trunc)
10720             deleteAndRecombine(Trunc);
10721           // Replace the uses of SRL with SETCC
10722           WorklistRemover DeadNodes(*this);
10723           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10724           deleteAndRecombine(N1.getNode());
10725           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10726         }
10727       }
10728     }
10729 
10730     if (Trunc)
10731       // Restore N1 if the above transformation doesn't match.
10732       N1 = N->getOperand(1);
10733   }
10734 
10735   // Transform br(xor(x, y)) -> br(x != y)
10736   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10737   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10738     SDNode *TheXor = N1.getNode();
10739     SDValue Op0 = TheXor->getOperand(0);
10740     SDValue Op1 = TheXor->getOperand(1);
10741     if (Op0.getOpcode() == Op1.getOpcode()) {
10742       // Avoid missing important xor optimizations.
10743       if (SDValue Tmp = visitXOR(TheXor)) {
10744         if (Tmp.getNode() != TheXor) {
10745           DEBUG(dbgs() << "\nReplacing.8 ";
10746                 TheXor->dump(&DAG);
10747                 dbgs() << "\nWith: ";
10748                 Tmp.getNode()->dump(&DAG);
10749                 dbgs() << '\n');
10750           WorklistRemover DeadNodes(*this);
10751           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10752           deleteAndRecombine(TheXor);
10753           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10754                              MVT::Other, Chain, Tmp, N2);
10755         }
10756 
10757         // visitXOR has changed XOR's operands or replaced the XOR completely,
10758         // bail out.
10759         return SDValue(N, 0);
10760       }
10761     }
10762 
10763     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10764       bool Equal = false;
10765       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10766           Op0.getOpcode() == ISD::XOR) {
10767         TheXor = Op0.getNode();
10768         Equal = true;
10769       }
10770 
10771       EVT SetCCVT = N1.getValueType();
10772       if (LegalTypes)
10773         SetCCVT = getSetCCResultType(SetCCVT);
10774       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10775                                    SetCCVT,
10776                                    Op0, Op1,
10777                                    Equal ? ISD::SETEQ : ISD::SETNE);
10778       // Replace the uses of XOR with SETCC
10779       WorklistRemover DeadNodes(*this);
10780       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10781       deleteAndRecombine(N1.getNode());
10782       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10783                          MVT::Other, Chain, SetCC, N2);
10784     }
10785   }
10786 
10787   return SDValue();
10788 }
10789 
10790 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10791 //
10792 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10793   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10794   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10795 
10796   // If N is a constant we could fold this into a fallthrough or unconditional
10797   // branch. However that doesn't happen very often in normal code, because
10798   // Instcombine/SimplifyCFG should have handled the available opportunities.
10799   // If we did this folding here, it would be necessary to update the
10800   // MachineBasicBlock CFG, which is awkward.
10801 
10802   // Use SimplifySetCC to simplify SETCC's.
10803   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10804                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10805                                false);
10806   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10807 
10808   // fold to a simpler setcc
10809   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10810     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10811                        N->getOperand(0), Simp.getOperand(2),
10812                        Simp.getOperand(0), Simp.getOperand(1),
10813                        N->getOperand(4));
10814 
10815   return SDValue();
10816 }
10817 
10818 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10819 /// and that N may be folded in the load / store addressing mode.
10820 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10821                                     SelectionDAG &DAG,
10822                                     const TargetLowering &TLI) {
10823   EVT VT;
10824   unsigned AS;
10825 
10826   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10827     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10828       return false;
10829     VT = LD->getMemoryVT();
10830     AS = LD->getAddressSpace();
10831   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10832     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10833       return false;
10834     VT = ST->getMemoryVT();
10835     AS = ST->getAddressSpace();
10836   } else
10837     return false;
10838 
10839   TargetLowering::AddrMode AM;
10840   if (N->getOpcode() == ISD::ADD) {
10841     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10842     if (Offset)
10843       // [reg +/- imm]
10844       AM.BaseOffs = Offset->getSExtValue();
10845     else
10846       // [reg +/- reg]
10847       AM.Scale = 1;
10848   } else if (N->getOpcode() == ISD::SUB) {
10849     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10850     if (Offset)
10851       // [reg +/- imm]
10852       AM.BaseOffs = -Offset->getSExtValue();
10853     else
10854       // [reg +/- reg]
10855       AM.Scale = 1;
10856   } else
10857     return false;
10858 
10859   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10860                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10861 }
10862 
10863 /// Try turning a load/store into a pre-indexed load/store when the base
10864 /// pointer is an add or subtract and it has other uses besides the load/store.
10865 /// After the transformation, the new indexed load/store has effectively folded
10866 /// the add/subtract in and all of its other uses are redirected to the
10867 /// new load/store.
10868 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10869   if (Level < AfterLegalizeDAG)
10870     return false;
10871 
10872   bool isLoad = true;
10873   SDValue Ptr;
10874   EVT VT;
10875   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10876     if (LD->isIndexed())
10877       return false;
10878     VT = LD->getMemoryVT();
10879     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10880         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10881       return false;
10882     Ptr = LD->getBasePtr();
10883   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10884     if (ST->isIndexed())
10885       return false;
10886     VT = ST->getMemoryVT();
10887     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10888         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10889       return false;
10890     Ptr = ST->getBasePtr();
10891     isLoad = false;
10892   } else {
10893     return false;
10894   }
10895 
10896   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10897   // out.  There is no reason to make this a preinc/predec.
10898   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10899       Ptr.getNode()->hasOneUse())
10900     return false;
10901 
10902   // Ask the target to do addressing mode selection.
10903   SDValue BasePtr;
10904   SDValue Offset;
10905   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10906   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10907     return false;
10908 
10909   // Backends without true r+i pre-indexed forms may need to pass a
10910   // constant base with a variable offset so that constant coercion
10911   // will work with the patterns in canonical form.
10912   bool Swapped = false;
10913   if (isa<ConstantSDNode>(BasePtr)) {
10914     std::swap(BasePtr, Offset);
10915     Swapped = true;
10916   }
10917 
10918   // Don't create a indexed load / store with zero offset.
10919   if (isNullConstant(Offset))
10920     return false;
10921 
10922   // Try turning it into a pre-indexed load / store except when:
10923   // 1) The new base ptr is a frame index.
10924   // 2) If N is a store and the new base ptr is either the same as or is a
10925   //    predecessor of the value being stored.
10926   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10927   //    that would create a cycle.
10928   // 4) All uses are load / store ops that use it as old base ptr.
10929 
10930   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
10931   // (plus the implicit offset) to a register to preinc anyway.
10932   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10933     return false;
10934 
10935   // Check #2.
10936   if (!isLoad) {
10937     SDValue Val = cast<StoreSDNode>(N)->getValue();
10938     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10939       return false;
10940   }
10941 
10942   // Caches for hasPredecessorHelper.
10943   SmallPtrSet<const SDNode *, 32> Visited;
10944   SmallVector<const SDNode *, 16> Worklist;
10945   Worklist.push_back(N);
10946 
10947   // If the offset is a constant, there may be other adds of constants that
10948   // can be folded with this one. We should do this to avoid having to keep
10949   // a copy of the original base pointer.
10950   SmallVector<SDNode *, 16> OtherUses;
10951   if (isa<ConstantSDNode>(Offset))
10952     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10953                               UE = BasePtr.getNode()->use_end();
10954          UI != UE; ++UI) {
10955       SDUse &Use = UI.getUse();
10956       // Skip the use that is Ptr and uses of other results from BasePtr's
10957       // node (important for nodes that return multiple results).
10958       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10959         continue;
10960 
10961       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10962         continue;
10963 
10964       if (Use.getUser()->getOpcode() != ISD::ADD &&
10965           Use.getUser()->getOpcode() != ISD::SUB) {
10966         OtherUses.clear();
10967         break;
10968       }
10969 
10970       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10971       if (!isa<ConstantSDNode>(Op1)) {
10972         OtherUses.clear();
10973         break;
10974       }
10975 
10976       // FIXME: In some cases, we can be smarter about this.
10977       if (Op1.getValueType() != Offset.getValueType()) {
10978         OtherUses.clear();
10979         break;
10980       }
10981 
10982       OtherUses.push_back(Use.getUser());
10983     }
10984 
10985   if (Swapped)
10986     std::swap(BasePtr, Offset);
10987 
10988   // Now check for #3 and #4.
10989   bool RealUse = false;
10990 
10991   for (SDNode *Use : Ptr.getNode()->uses()) {
10992     if (Use == N)
10993       continue;
10994     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10995       return false;
10996 
10997     // If Ptr may be folded in addressing mode of other use, then it's
10998     // not profitable to do this transformation.
10999     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11000       RealUse = true;
11001   }
11002 
11003   if (!RealUse)
11004     return false;
11005 
11006   SDValue Result;
11007   if (isLoad)
11008     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11009                                 BasePtr, Offset, AM);
11010   else
11011     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11012                                  BasePtr, Offset, AM);
11013   ++PreIndexedNodes;
11014   ++NodesCombined;
11015   DEBUG(dbgs() << "\nReplacing.4 ";
11016         N->dump(&DAG);
11017         dbgs() << "\nWith: ";
11018         Result.getNode()->dump(&DAG);
11019         dbgs() << '\n');
11020   WorklistRemover DeadNodes(*this);
11021   if (isLoad) {
11022     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11023     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11024   } else {
11025     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11026   }
11027 
11028   // Finally, since the node is now dead, remove it from the graph.
11029   deleteAndRecombine(N);
11030 
11031   if (Swapped)
11032     std::swap(BasePtr, Offset);
11033 
11034   // Replace other uses of BasePtr that can be updated to use Ptr
11035   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11036     unsigned OffsetIdx = 1;
11037     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11038       OffsetIdx = 0;
11039     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11040            BasePtr.getNode() && "Expected BasePtr operand");
11041 
11042     // We need to replace ptr0 in the following expression:
11043     //   x0 * offset0 + y0 * ptr0 = t0
11044     // knowing that
11045     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11046     //
11047     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11048     // indexed load/store and the expresion that needs to be re-written.
11049     //
11050     // Therefore, we have:
11051     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11052 
11053     ConstantSDNode *CN =
11054       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11055     int X0, X1, Y0, Y1;
11056     const APInt &Offset0 = CN->getAPIntValue();
11057     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11058 
11059     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11060     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11061     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11062     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11063 
11064     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11065 
11066     APInt CNV = Offset0;
11067     if (X0 < 0) CNV = -CNV;
11068     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11069     else CNV = CNV - Offset1;
11070 
11071     SDLoc DL(OtherUses[i]);
11072 
11073     // We can now generate the new expression.
11074     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11075     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11076 
11077     SDValue NewUse = DAG.getNode(Opcode,
11078                                  DL,
11079                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11080     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11081     deleteAndRecombine(OtherUses[i]);
11082   }
11083 
11084   // Replace the uses of Ptr with uses of the updated base value.
11085   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11086   deleteAndRecombine(Ptr.getNode());
11087 
11088   return true;
11089 }
11090 
11091 /// Try to combine a load/store with a add/sub of the base pointer node into a
11092 /// post-indexed load/store. The transformation folded the add/subtract into the
11093 /// new indexed load/store effectively and all of its uses are redirected to the
11094 /// new load/store.
11095 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11096   if (Level < AfterLegalizeDAG)
11097     return false;
11098 
11099   bool isLoad = true;
11100   SDValue Ptr;
11101   EVT VT;
11102   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11103     if (LD->isIndexed())
11104       return false;
11105     VT = LD->getMemoryVT();
11106     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11107         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11108       return false;
11109     Ptr = LD->getBasePtr();
11110   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11111     if (ST->isIndexed())
11112       return false;
11113     VT = ST->getMemoryVT();
11114     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11115         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11116       return false;
11117     Ptr = ST->getBasePtr();
11118     isLoad = false;
11119   } else {
11120     return false;
11121   }
11122 
11123   if (Ptr.getNode()->hasOneUse())
11124     return false;
11125 
11126   for (SDNode *Op : Ptr.getNode()->uses()) {
11127     if (Op == N ||
11128         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11129       continue;
11130 
11131     SDValue BasePtr;
11132     SDValue Offset;
11133     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11134     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11135       // Don't create a indexed load / store with zero offset.
11136       if (isNullConstant(Offset))
11137         continue;
11138 
11139       // Try turning it into a post-indexed load / store except when
11140       // 1) All uses are load / store ops that use it as base ptr (and
11141       //    it may be folded as addressing mmode).
11142       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11143       //    nor a successor of N. Otherwise, if Op is folded that would
11144       //    create a cycle.
11145 
11146       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11147         continue;
11148 
11149       // Check for #1.
11150       bool TryNext = false;
11151       for (SDNode *Use : BasePtr.getNode()->uses()) {
11152         if (Use == Ptr.getNode())
11153           continue;
11154 
11155         // If all the uses are load / store addresses, then don't do the
11156         // transformation.
11157         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11158           bool RealUse = false;
11159           for (SDNode *UseUse : Use->uses()) {
11160             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11161               RealUse = true;
11162           }
11163 
11164           if (!RealUse) {
11165             TryNext = true;
11166             break;
11167           }
11168         }
11169       }
11170 
11171       if (TryNext)
11172         continue;
11173 
11174       // Check for #2
11175       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11176         SDValue Result = isLoad
11177           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11178                                BasePtr, Offset, AM)
11179           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11180                                 BasePtr, Offset, AM);
11181         ++PostIndexedNodes;
11182         ++NodesCombined;
11183         DEBUG(dbgs() << "\nReplacing.5 ";
11184               N->dump(&DAG);
11185               dbgs() << "\nWith: ";
11186               Result.getNode()->dump(&DAG);
11187               dbgs() << '\n');
11188         WorklistRemover DeadNodes(*this);
11189         if (isLoad) {
11190           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11191           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11192         } else {
11193           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11194         }
11195 
11196         // Finally, since the node is now dead, remove it from the graph.
11197         deleteAndRecombine(N);
11198 
11199         // Replace the uses of Use with uses of the updated base value.
11200         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11201                                       Result.getValue(isLoad ? 1 : 0));
11202         deleteAndRecombine(Op);
11203         return true;
11204       }
11205     }
11206   }
11207 
11208   return false;
11209 }
11210 
11211 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11212 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11213   ISD::MemIndexedMode AM = LD->getAddressingMode();
11214   assert(AM != ISD::UNINDEXED);
11215   SDValue BP = LD->getOperand(1);
11216   SDValue Inc = LD->getOperand(2);
11217 
11218   // Some backends use TargetConstants for load offsets, but don't expect
11219   // TargetConstants in general ADD nodes. We can convert these constants into
11220   // regular Constants (if the constant is not opaque).
11221   assert((Inc.getOpcode() != ISD::TargetConstant ||
11222           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11223          "Cannot split out indexing using opaque target constants");
11224   if (Inc.getOpcode() == ISD::TargetConstant) {
11225     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11226     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11227                           ConstInc->getValueType(0));
11228   }
11229 
11230   unsigned Opc =
11231       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11232   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11233 }
11234 
11235 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11236   LoadSDNode *LD  = cast<LoadSDNode>(N);
11237   SDValue Chain = LD->getChain();
11238   SDValue Ptr   = LD->getBasePtr();
11239 
11240   // If load is not volatile and there are no uses of the loaded value (and
11241   // the updated indexed value in case of indexed loads), change uses of the
11242   // chain value into uses of the chain input (i.e. delete the dead load).
11243   if (!LD->isVolatile()) {
11244     if (N->getValueType(1) == MVT::Other) {
11245       // Unindexed loads.
11246       if (!N->hasAnyUseOfValue(0)) {
11247         // It's not safe to use the two value CombineTo variant here. e.g.
11248         // v1, chain2 = load chain1, loc
11249         // v2, chain3 = load chain2, loc
11250         // v3         = add v2, c
11251         // Now we replace use of chain2 with chain1.  This makes the second load
11252         // isomorphic to the one we are deleting, and thus makes this load live.
11253         DEBUG(dbgs() << "\nReplacing.6 ";
11254               N->dump(&DAG);
11255               dbgs() << "\nWith chain: ";
11256               Chain.getNode()->dump(&DAG);
11257               dbgs() << "\n");
11258         WorklistRemover DeadNodes(*this);
11259         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11260         AddUsersToWorklist(Chain.getNode());
11261         if (N->use_empty())
11262           deleteAndRecombine(N);
11263 
11264         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11265       }
11266     } else {
11267       // Indexed loads.
11268       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11269 
11270       // If this load has an opaque TargetConstant offset, then we cannot split
11271       // the indexing into an add/sub directly (that TargetConstant may not be
11272       // valid for a different type of node, and we cannot convert an opaque
11273       // target constant into a regular constant).
11274       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11275                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11276 
11277       if (!N->hasAnyUseOfValue(0) &&
11278           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11279         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11280         SDValue Index;
11281         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11282           Index = SplitIndexingFromLoad(LD);
11283           // Try to fold the base pointer arithmetic into subsequent loads and
11284           // stores.
11285           AddUsersToWorklist(N);
11286         } else
11287           Index = DAG.getUNDEF(N->getValueType(1));
11288         DEBUG(dbgs() << "\nReplacing.7 ";
11289               N->dump(&DAG);
11290               dbgs() << "\nWith: ";
11291               Undef.getNode()->dump(&DAG);
11292               dbgs() << " and 2 other values\n");
11293         WorklistRemover DeadNodes(*this);
11294         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11295         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11296         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11297         deleteAndRecombine(N);
11298         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11299       }
11300     }
11301   }
11302 
11303   // If this load is directly stored, replace the load value with the stored
11304   // value.
11305   // TODO: Handle store large -> read small portion.
11306   // TODO: Handle TRUNCSTORE/LOADEXT
11307   if (OptLevel != CodeGenOpt::None &&
11308       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11309     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11310       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11311       if (PrevST->getBasePtr() == Ptr &&
11312           PrevST->getValue().getValueType() == N->getValueType(0))
11313         return CombineTo(N, PrevST->getOperand(1), Chain);
11314     }
11315   }
11316 
11317   // Try to infer better alignment information than the load already has.
11318   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11319     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11320       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11321         SDValue NewLoad = DAG.getExtLoad(
11322             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11323             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11324             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11325         if (NewLoad.getNode() != N)
11326           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11327       }
11328     }
11329   }
11330 
11331   if (LD->isUnindexed()) {
11332     // Walk up chain skipping non-aliasing memory nodes.
11333     SDValue BetterChain = FindBetterChain(N, Chain);
11334 
11335     // If there is a better chain.
11336     if (Chain != BetterChain) {
11337       SDValue ReplLoad;
11338 
11339       // Replace the chain to void dependency.
11340       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11341         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11342                                BetterChain, Ptr, LD->getMemOperand());
11343       } else {
11344         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11345                                   LD->getValueType(0),
11346                                   BetterChain, Ptr, LD->getMemoryVT(),
11347                                   LD->getMemOperand());
11348       }
11349 
11350       // Create token factor to keep old chain connected.
11351       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11352                                   MVT::Other, Chain, ReplLoad.getValue(1));
11353 
11354       // Make sure the new and old chains are cleaned up.
11355       AddToWorklist(Token.getNode());
11356 
11357       // Replace uses with load result and token factor. Don't add users
11358       // to work list.
11359       return CombineTo(N, ReplLoad.getValue(0), Token, false);
11360     }
11361   }
11362 
11363   // Try transforming N to an indexed load.
11364   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11365     return SDValue(N, 0);
11366 
11367   // Try to slice up N to more direct loads if the slices are mapped to
11368   // different register banks or pairing can take place.
11369   if (SliceUpLoad(N))
11370     return SDValue(N, 0);
11371 
11372   return SDValue();
11373 }
11374 
11375 namespace {
11376 /// \brief Helper structure used to slice a load in smaller loads.
11377 /// Basically a slice is obtained from the following sequence:
11378 /// Origin = load Ty1, Base
11379 /// Shift = srl Ty1 Origin, CstTy Amount
11380 /// Inst = trunc Shift to Ty2
11381 ///
11382 /// Then, it will be rewriten into:
11383 /// Slice = load SliceTy, Base + SliceOffset
11384 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11385 ///
11386 /// SliceTy is deduced from the number of bits that are actually used to
11387 /// build Inst.
11388 struct LoadedSlice {
11389   /// \brief Helper structure used to compute the cost of a slice.
11390   struct Cost {
11391     /// Are we optimizing for code size.
11392     bool ForCodeSize;
11393     /// Various cost.
11394     unsigned Loads;
11395     unsigned Truncates;
11396     unsigned CrossRegisterBanksCopies;
11397     unsigned ZExts;
11398     unsigned Shift;
11399 
11400     Cost(bool ForCodeSize = false)
11401         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11402           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11403 
11404     /// \brief Get the cost of one isolated slice.
11405     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11406         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11407           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11408       EVT TruncType = LS.Inst->getValueType(0);
11409       EVT LoadedType = LS.getLoadedType();
11410       if (TruncType != LoadedType &&
11411           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11412         ZExts = 1;
11413     }
11414 
11415     /// \brief Account for slicing gain in the current cost.
11416     /// Slicing provide a few gains like removing a shift or a
11417     /// truncate. This method allows to grow the cost of the original
11418     /// load with the gain from this slice.
11419     void addSliceGain(const LoadedSlice &LS) {
11420       // Each slice saves a truncate.
11421       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11422       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11423                               LS.Inst->getValueType(0)))
11424         ++Truncates;
11425       // If there is a shift amount, this slice gets rid of it.
11426       if (LS.Shift)
11427         ++Shift;
11428       // If this slice can merge a cross register bank copy, account for it.
11429       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11430         ++CrossRegisterBanksCopies;
11431     }
11432 
11433     Cost &operator+=(const Cost &RHS) {
11434       Loads += RHS.Loads;
11435       Truncates += RHS.Truncates;
11436       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11437       ZExts += RHS.ZExts;
11438       Shift += RHS.Shift;
11439       return *this;
11440     }
11441 
11442     bool operator==(const Cost &RHS) const {
11443       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11444              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11445              ZExts == RHS.ZExts && Shift == RHS.Shift;
11446     }
11447 
11448     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11449 
11450     bool operator<(const Cost &RHS) const {
11451       // Assume cross register banks copies are as expensive as loads.
11452       // FIXME: Do we want some more target hooks?
11453       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11454       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11455       // Unless we are optimizing for code size, consider the
11456       // expensive operation first.
11457       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11458         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11459       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11460              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11461     }
11462 
11463     bool operator>(const Cost &RHS) const { return RHS < *this; }
11464 
11465     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11466 
11467     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11468   };
11469   // The last instruction that represent the slice. This should be a
11470   // truncate instruction.
11471   SDNode *Inst;
11472   // The original load instruction.
11473   LoadSDNode *Origin;
11474   // The right shift amount in bits from the original load.
11475   unsigned Shift;
11476   // The DAG from which Origin came from.
11477   // This is used to get some contextual information about legal types, etc.
11478   SelectionDAG *DAG;
11479 
11480   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11481               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11482       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11483 
11484   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11485   /// \return Result is \p BitWidth and has used bits set to 1 and
11486   ///         not used bits set to 0.
11487   APInt getUsedBits() const {
11488     // Reproduce the trunc(lshr) sequence:
11489     // - Start from the truncated value.
11490     // - Zero extend to the desired bit width.
11491     // - Shift left.
11492     assert(Origin && "No original load to compare against.");
11493     unsigned BitWidth = Origin->getValueSizeInBits(0);
11494     assert(Inst && "This slice is not bound to an instruction");
11495     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11496            "Extracted slice is bigger than the whole type!");
11497     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11498     UsedBits.setAllBits();
11499     UsedBits = UsedBits.zext(BitWidth);
11500     UsedBits <<= Shift;
11501     return UsedBits;
11502   }
11503 
11504   /// \brief Get the size of the slice to be loaded in bytes.
11505   unsigned getLoadedSize() const {
11506     unsigned SliceSize = getUsedBits().countPopulation();
11507     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11508     return SliceSize / 8;
11509   }
11510 
11511   /// \brief Get the type that will be loaded for this slice.
11512   /// Note: This may not be the final type for the slice.
11513   EVT getLoadedType() const {
11514     assert(DAG && "Missing context");
11515     LLVMContext &Ctxt = *DAG->getContext();
11516     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11517   }
11518 
11519   /// \brief Get the alignment of the load used for this slice.
11520   unsigned getAlignment() const {
11521     unsigned Alignment = Origin->getAlignment();
11522     unsigned Offset = getOffsetFromBase();
11523     if (Offset != 0)
11524       Alignment = MinAlign(Alignment, Alignment + Offset);
11525     return Alignment;
11526   }
11527 
11528   /// \brief Check if this slice can be rewritten with legal operations.
11529   bool isLegal() const {
11530     // An invalid slice is not legal.
11531     if (!Origin || !Inst || !DAG)
11532       return false;
11533 
11534     // Offsets are for indexed load only, we do not handle that.
11535     if (!Origin->getOffset().isUndef())
11536       return false;
11537 
11538     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11539 
11540     // Check that the type is legal.
11541     EVT SliceType = getLoadedType();
11542     if (!TLI.isTypeLegal(SliceType))
11543       return false;
11544 
11545     // Check that the load is legal for this type.
11546     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11547       return false;
11548 
11549     // Check that the offset can be computed.
11550     // 1. Check its type.
11551     EVT PtrType = Origin->getBasePtr().getValueType();
11552     if (PtrType == MVT::Untyped || PtrType.isExtended())
11553       return false;
11554 
11555     // 2. Check that it fits in the immediate.
11556     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11557       return false;
11558 
11559     // 3. Check that the computation is legal.
11560     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11561       return false;
11562 
11563     // Check that the zext is legal if it needs one.
11564     EVT TruncateType = Inst->getValueType(0);
11565     if (TruncateType != SliceType &&
11566         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11567       return false;
11568 
11569     return true;
11570   }
11571 
11572   /// \brief Get the offset in bytes of this slice in the original chunk of
11573   /// bits.
11574   /// \pre DAG != nullptr.
11575   uint64_t getOffsetFromBase() const {
11576     assert(DAG && "Missing context.");
11577     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11578     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11579     uint64_t Offset = Shift / 8;
11580     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11581     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11582            "The size of the original loaded type is not a multiple of a"
11583            " byte.");
11584     // If Offset is bigger than TySizeInBytes, it means we are loading all
11585     // zeros. This should have been optimized before in the process.
11586     assert(TySizeInBytes > Offset &&
11587            "Invalid shift amount for given loaded size");
11588     if (IsBigEndian)
11589       Offset = TySizeInBytes - Offset - getLoadedSize();
11590     return Offset;
11591   }
11592 
11593   /// \brief Generate the sequence of instructions to load the slice
11594   /// represented by this object and redirect the uses of this slice to
11595   /// this new sequence of instructions.
11596   /// \pre this->Inst && this->Origin are valid Instructions and this
11597   /// object passed the legal check: LoadedSlice::isLegal returned true.
11598   /// \return The last instruction of the sequence used to load the slice.
11599   SDValue loadSlice() const {
11600     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11601     const SDValue &OldBaseAddr = Origin->getBasePtr();
11602     SDValue BaseAddr = OldBaseAddr;
11603     // Get the offset in that chunk of bytes w.r.t. the endianness.
11604     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11605     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11606     if (Offset) {
11607       // BaseAddr = BaseAddr + Offset.
11608       EVT ArithType = BaseAddr.getValueType();
11609       SDLoc DL(Origin);
11610       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11611                               DAG->getConstant(Offset, DL, ArithType));
11612     }
11613 
11614     // Create the type of the loaded slice according to its size.
11615     EVT SliceType = getLoadedType();
11616 
11617     // Create the load for the slice.
11618     SDValue LastInst =
11619         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11620                      Origin->getPointerInfo().getWithOffset(Offset),
11621                      getAlignment(), Origin->getMemOperand()->getFlags());
11622     // If the final type is not the same as the loaded type, this means that
11623     // we have to pad with zero. Create a zero extend for that.
11624     EVT FinalType = Inst->getValueType(0);
11625     if (SliceType != FinalType)
11626       LastInst =
11627           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11628     return LastInst;
11629   }
11630 
11631   /// \brief Check if this slice can be merged with an expensive cross register
11632   /// bank copy. E.g.,
11633   /// i = load i32
11634   /// f = bitcast i32 i to float
11635   bool canMergeExpensiveCrossRegisterBankCopy() const {
11636     if (!Inst || !Inst->hasOneUse())
11637       return false;
11638     SDNode *Use = *Inst->use_begin();
11639     if (Use->getOpcode() != ISD::BITCAST)
11640       return false;
11641     assert(DAG && "Missing context");
11642     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11643     EVT ResVT = Use->getValueType(0);
11644     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11645     const TargetRegisterClass *ArgRC =
11646         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11647     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11648       return false;
11649 
11650     // At this point, we know that we perform a cross-register-bank copy.
11651     // Check if it is expensive.
11652     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11653     // Assume bitcasts are cheap, unless both register classes do not
11654     // explicitly share a common sub class.
11655     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11656       return false;
11657 
11658     // Check if it will be merged with the load.
11659     // 1. Check the alignment constraint.
11660     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11661         ResVT.getTypeForEVT(*DAG->getContext()));
11662 
11663     if (RequiredAlignment > getAlignment())
11664       return false;
11665 
11666     // 2. Check that the load is a legal operation for that type.
11667     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11668       return false;
11669 
11670     // 3. Check that we do not have a zext in the way.
11671     if (Inst->getValueType(0) != getLoadedType())
11672       return false;
11673 
11674     return true;
11675   }
11676 };
11677 }
11678 
11679 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11680 /// \p UsedBits looks like 0..0 1..1 0..0.
11681 static bool areUsedBitsDense(const APInt &UsedBits) {
11682   // If all the bits are one, this is dense!
11683   if (UsedBits.isAllOnesValue())
11684     return true;
11685 
11686   // Get rid of the unused bits on the right.
11687   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11688   // Get rid of the unused bits on the left.
11689   if (NarrowedUsedBits.countLeadingZeros())
11690     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11691   // Check that the chunk of bits is completely used.
11692   return NarrowedUsedBits.isAllOnesValue();
11693 }
11694 
11695 /// \brief Check whether or not \p First and \p Second are next to each other
11696 /// in memory. This means that there is no hole between the bits loaded
11697 /// by \p First and the bits loaded by \p Second.
11698 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11699                                      const LoadedSlice &Second) {
11700   assert(First.Origin == Second.Origin && First.Origin &&
11701          "Unable to match different memory origins.");
11702   APInt UsedBits = First.getUsedBits();
11703   assert((UsedBits & Second.getUsedBits()) == 0 &&
11704          "Slices are not supposed to overlap.");
11705   UsedBits |= Second.getUsedBits();
11706   return areUsedBitsDense(UsedBits);
11707 }
11708 
11709 /// \brief Adjust the \p GlobalLSCost according to the target
11710 /// paring capabilities and the layout of the slices.
11711 /// \pre \p GlobalLSCost should account for at least as many loads as
11712 /// there is in the slices in \p LoadedSlices.
11713 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11714                                  LoadedSlice::Cost &GlobalLSCost) {
11715   unsigned NumberOfSlices = LoadedSlices.size();
11716   // If there is less than 2 elements, no pairing is possible.
11717   if (NumberOfSlices < 2)
11718     return;
11719 
11720   // Sort the slices so that elements that are likely to be next to each
11721   // other in memory are next to each other in the list.
11722   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11723             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11724     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11725     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11726   });
11727   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11728   // First (resp. Second) is the first (resp. Second) potentially candidate
11729   // to be placed in a paired load.
11730   const LoadedSlice *First = nullptr;
11731   const LoadedSlice *Second = nullptr;
11732   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11733                 // Set the beginning of the pair.
11734                                                            First = Second) {
11735 
11736     Second = &LoadedSlices[CurrSlice];
11737 
11738     // If First is NULL, it means we start a new pair.
11739     // Get to the next slice.
11740     if (!First)
11741       continue;
11742 
11743     EVT LoadedType = First->getLoadedType();
11744 
11745     // If the types of the slices are different, we cannot pair them.
11746     if (LoadedType != Second->getLoadedType())
11747       continue;
11748 
11749     // Check if the target supplies paired loads for this type.
11750     unsigned RequiredAlignment = 0;
11751     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11752       // move to the next pair, this type is hopeless.
11753       Second = nullptr;
11754       continue;
11755     }
11756     // Check if we meet the alignment requirement.
11757     if (RequiredAlignment > First->getAlignment())
11758       continue;
11759 
11760     // Check that both loads are next to each other in memory.
11761     if (!areSlicesNextToEachOther(*First, *Second))
11762       continue;
11763 
11764     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11765     --GlobalLSCost.Loads;
11766     // Move to the next pair.
11767     Second = nullptr;
11768   }
11769 }
11770 
11771 /// \brief Check the profitability of all involved LoadedSlice.
11772 /// Currently, it is considered profitable if there is exactly two
11773 /// involved slices (1) which are (2) next to each other in memory, and
11774 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11775 ///
11776 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11777 /// the elements themselves.
11778 ///
11779 /// FIXME: When the cost model will be mature enough, we can relax
11780 /// constraints (1) and (2).
11781 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11782                                 const APInt &UsedBits, bool ForCodeSize) {
11783   unsigned NumberOfSlices = LoadedSlices.size();
11784   if (StressLoadSlicing)
11785     return NumberOfSlices > 1;
11786 
11787   // Check (1).
11788   if (NumberOfSlices != 2)
11789     return false;
11790 
11791   // Check (2).
11792   if (!areUsedBitsDense(UsedBits))
11793     return false;
11794 
11795   // Check (3).
11796   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11797   // The original code has one big load.
11798   OrigCost.Loads = 1;
11799   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11800     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11801     // Accumulate the cost of all the slices.
11802     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11803     GlobalSlicingCost += SliceCost;
11804 
11805     // Account as cost in the original configuration the gain obtained
11806     // with the current slices.
11807     OrigCost.addSliceGain(LS);
11808   }
11809 
11810   // If the target supports paired load, adjust the cost accordingly.
11811   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11812   return OrigCost > GlobalSlicingCost;
11813 }
11814 
11815 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11816 /// operations, split it in the various pieces being extracted.
11817 ///
11818 /// This sort of thing is introduced by SROA.
11819 /// This slicing takes care not to insert overlapping loads.
11820 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11821 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11822   if (Level < AfterLegalizeDAG)
11823     return false;
11824 
11825   LoadSDNode *LD = cast<LoadSDNode>(N);
11826   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11827       !LD->getValueType(0).isInteger())
11828     return false;
11829 
11830   // Keep track of already used bits to detect overlapping values.
11831   // In that case, we will just abort the transformation.
11832   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11833 
11834   SmallVector<LoadedSlice, 4> LoadedSlices;
11835 
11836   // Check if this load is used as several smaller chunks of bits.
11837   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11838   // of computation for each trunc.
11839   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11840        UI != UIEnd; ++UI) {
11841     // Skip the uses of the chain.
11842     if (UI.getUse().getResNo() != 0)
11843       continue;
11844 
11845     SDNode *User = *UI;
11846     unsigned Shift = 0;
11847 
11848     // Check if this is a trunc(lshr).
11849     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11850         isa<ConstantSDNode>(User->getOperand(1))) {
11851       Shift = User->getConstantOperandVal(1);
11852       User = *User->use_begin();
11853     }
11854 
11855     // At this point, User is a Truncate, iff we encountered, trunc or
11856     // trunc(lshr).
11857     if (User->getOpcode() != ISD::TRUNCATE)
11858       return false;
11859 
11860     // The width of the type must be a power of 2 and greater than 8-bits.
11861     // Otherwise the load cannot be represented in LLVM IR.
11862     // Moreover, if we shifted with a non-8-bits multiple, the slice
11863     // will be across several bytes. We do not support that.
11864     unsigned Width = User->getValueSizeInBits(0);
11865     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11866       return 0;
11867 
11868     // Build the slice for this chain of computations.
11869     LoadedSlice LS(User, LD, Shift, &DAG);
11870     APInt CurrentUsedBits = LS.getUsedBits();
11871 
11872     // Check if this slice overlaps with another.
11873     if ((CurrentUsedBits & UsedBits) != 0)
11874       return false;
11875     // Update the bits used globally.
11876     UsedBits |= CurrentUsedBits;
11877 
11878     // Check if the new slice would be legal.
11879     if (!LS.isLegal())
11880       return false;
11881 
11882     // Record the slice.
11883     LoadedSlices.push_back(LS);
11884   }
11885 
11886   // Abort slicing if it does not seem to be profitable.
11887   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11888     return false;
11889 
11890   ++SlicedLoads;
11891 
11892   // Rewrite each chain to use an independent load.
11893   // By construction, each chain can be represented by a unique load.
11894 
11895   // Prepare the argument for the new token factor for all the slices.
11896   SmallVector<SDValue, 8> ArgChains;
11897   for (SmallVectorImpl<LoadedSlice>::const_iterator
11898            LSIt = LoadedSlices.begin(),
11899            LSItEnd = LoadedSlices.end();
11900        LSIt != LSItEnd; ++LSIt) {
11901     SDValue SliceInst = LSIt->loadSlice();
11902     CombineTo(LSIt->Inst, SliceInst, true);
11903     if (SliceInst.getOpcode() != ISD::LOAD)
11904       SliceInst = SliceInst.getOperand(0);
11905     assert(SliceInst->getOpcode() == ISD::LOAD &&
11906            "It takes more than a zext to get to the loaded slice!!");
11907     ArgChains.push_back(SliceInst.getValue(1));
11908   }
11909 
11910   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11911                               ArgChains);
11912   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11913   AddToWorklist(Chain.getNode());
11914   return true;
11915 }
11916 
11917 /// Check to see if V is (and load (ptr), imm), where the load is having
11918 /// specific bytes cleared out.  If so, return the byte size being masked out
11919 /// and the shift amount.
11920 static std::pair<unsigned, unsigned>
11921 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11922   std::pair<unsigned, unsigned> Result(0, 0);
11923 
11924   // Check for the structure we're looking for.
11925   if (V->getOpcode() != ISD::AND ||
11926       !isa<ConstantSDNode>(V->getOperand(1)) ||
11927       !ISD::isNormalLoad(V->getOperand(0).getNode()))
11928     return Result;
11929 
11930   // Check the chain and pointer.
11931   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11932   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
11933 
11934   // The store should be chained directly to the load or be an operand of a
11935   // tokenfactor.
11936   if (LD == Chain.getNode())
11937     ; // ok.
11938   else if (Chain->getOpcode() != ISD::TokenFactor)
11939     return Result; // Fail.
11940   else {
11941     bool isOk = false;
11942     for (const SDValue &ChainOp : Chain->op_values())
11943       if (ChainOp.getNode() == LD) {
11944         isOk = true;
11945         break;
11946       }
11947     if (!isOk) return Result;
11948   }
11949 
11950   // This only handles simple types.
11951   if (V.getValueType() != MVT::i16 &&
11952       V.getValueType() != MVT::i32 &&
11953       V.getValueType() != MVT::i64)
11954     return Result;
11955 
11956   // Check the constant mask.  Invert it so that the bits being masked out are
11957   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
11958   // follow the sign bit for uniformity.
11959   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11960   unsigned NotMaskLZ = countLeadingZeros(NotMask);
11961   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
11962   unsigned NotMaskTZ = countTrailingZeros(NotMask);
11963   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
11964   if (NotMaskLZ == 64) return Result;  // All zero mask.
11965 
11966   // See if we have a continuous run of bits.  If so, we have 0*1+0*
11967   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11968     return Result;
11969 
11970   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11971   if (V.getValueType() != MVT::i64 && NotMaskLZ)
11972     NotMaskLZ -= 64-V.getValueSizeInBits();
11973 
11974   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11975   switch (MaskedBytes) {
11976   case 1:
11977   case 2:
11978   case 4: break;
11979   default: return Result; // All one mask, or 5-byte mask.
11980   }
11981 
11982   // Verify that the first bit starts at a multiple of mask so that the access
11983   // is aligned the same as the access width.
11984   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11985 
11986   Result.first = MaskedBytes;
11987   Result.second = NotMaskTZ/8;
11988   return Result;
11989 }
11990 
11991 
11992 /// Check to see if IVal is something that provides a value as specified by
11993 /// MaskInfo. If so, replace the specified store with a narrower store of
11994 /// truncated IVal.
11995 static SDNode *
11996 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11997                                 SDValue IVal, StoreSDNode *St,
11998                                 DAGCombiner *DC) {
11999   unsigned NumBytes = MaskInfo.first;
12000   unsigned ByteShift = MaskInfo.second;
12001   SelectionDAG &DAG = DC->getDAG();
12002 
12003   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12004   // that uses this.  If not, this is not a replacement.
12005   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12006                                   ByteShift*8, (ByteShift+NumBytes)*8);
12007   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12008 
12009   // Check that it is legal on the target to do this.  It is legal if the new
12010   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12011   // legalization.
12012   MVT VT = MVT::getIntegerVT(NumBytes*8);
12013   if (!DC->isTypeLegal(VT))
12014     return nullptr;
12015 
12016   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12017   // shifted by ByteShift and truncated down to NumBytes.
12018   if (ByteShift) {
12019     SDLoc DL(IVal);
12020     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12021                        DAG.getConstant(ByteShift*8, DL,
12022                                     DC->getShiftAmountTy(IVal.getValueType())));
12023   }
12024 
12025   // Figure out the offset for the store and the alignment of the access.
12026   unsigned StOffset;
12027   unsigned NewAlign = St->getAlignment();
12028 
12029   if (DAG.getDataLayout().isLittleEndian())
12030     StOffset = ByteShift;
12031   else
12032     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12033 
12034   SDValue Ptr = St->getBasePtr();
12035   if (StOffset) {
12036     SDLoc DL(IVal);
12037     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12038                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12039     NewAlign = MinAlign(NewAlign, StOffset);
12040   }
12041 
12042   // Truncate down to the new size.
12043   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12044 
12045   ++OpsNarrowed;
12046   return DAG
12047       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12048                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12049       .getNode();
12050 }
12051 
12052 
12053 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12054 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12055 /// narrowing the load and store if it would end up being a win for performance
12056 /// or code size.
12057 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12058   StoreSDNode *ST  = cast<StoreSDNode>(N);
12059   if (ST->isVolatile())
12060     return SDValue();
12061 
12062   SDValue Chain = ST->getChain();
12063   SDValue Value = ST->getValue();
12064   SDValue Ptr   = ST->getBasePtr();
12065   EVT VT = Value.getValueType();
12066 
12067   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12068     return SDValue();
12069 
12070   unsigned Opc = Value.getOpcode();
12071 
12072   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12073   // is a byte mask indicating a consecutive number of bytes, check to see if
12074   // Y is known to provide just those bytes.  If so, we try to replace the
12075   // load + replace + store sequence with a single (narrower) store, which makes
12076   // the load dead.
12077   if (Opc == ISD::OR) {
12078     std::pair<unsigned, unsigned> MaskedLoad;
12079     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12080     if (MaskedLoad.first)
12081       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12082                                                   Value.getOperand(1), ST,this))
12083         return SDValue(NewST, 0);
12084 
12085     // Or is commutative, so try swapping X and Y.
12086     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12087     if (MaskedLoad.first)
12088       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12089                                                   Value.getOperand(0), ST,this))
12090         return SDValue(NewST, 0);
12091   }
12092 
12093   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12094       Value.getOperand(1).getOpcode() != ISD::Constant)
12095     return SDValue();
12096 
12097   SDValue N0 = Value.getOperand(0);
12098   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12099       Chain == SDValue(N0.getNode(), 1)) {
12100     LoadSDNode *LD = cast<LoadSDNode>(N0);
12101     if (LD->getBasePtr() != Ptr ||
12102         LD->getPointerInfo().getAddrSpace() !=
12103         ST->getPointerInfo().getAddrSpace())
12104       return SDValue();
12105 
12106     // Find the type to narrow it the load / op / store to.
12107     SDValue N1 = Value.getOperand(1);
12108     unsigned BitWidth = N1.getValueSizeInBits();
12109     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12110     if (Opc == ISD::AND)
12111       Imm ^= APInt::getAllOnesValue(BitWidth);
12112     if (Imm == 0 || Imm.isAllOnesValue())
12113       return SDValue();
12114     unsigned ShAmt = Imm.countTrailingZeros();
12115     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12116     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12117     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12118     // The narrowing should be profitable, the load/store operation should be
12119     // legal (or custom) and the store size should be equal to the NewVT width.
12120     while (NewBW < BitWidth &&
12121            (NewVT.getStoreSizeInBits() != NewBW ||
12122             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12123             !TLI.isNarrowingProfitable(VT, NewVT))) {
12124       NewBW = NextPowerOf2(NewBW);
12125       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12126     }
12127     if (NewBW >= BitWidth)
12128       return SDValue();
12129 
12130     // If the lsb changed does not start at the type bitwidth boundary,
12131     // start at the previous one.
12132     if (ShAmt % NewBW)
12133       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12134     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12135                                    std::min(BitWidth, ShAmt + NewBW));
12136     if ((Imm & Mask) == Imm) {
12137       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12138       if (Opc == ISD::AND)
12139         NewImm ^= APInt::getAllOnesValue(NewBW);
12140       uint64_t PtrOff = ShAmt / 8;
12141       // For big endian targets, we need to adjust the offset to the pointer to
12142       // load the correct bytes.
12143       if (DAG.getDataLayout().isBigEndian())
12144         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12145 
12146       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12147       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12148       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12149         return SDValue();
12150 
12151       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12152                                    Ptr.getValueType(), Ptr,
12153                                    DAG.getConstant(PtrOff, SDLoc(LD),
12154                                                    Ptr.getValueType()));
12155       SDValue NewLD =
12156           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12157                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12158                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12159       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12160                                    DAG.getConstant(NewImm, SDLoc(Value),
12161                                                    NewVT));
12162       SDValue NewST =
12163           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12164                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12165 
12166       AddToWorklist(NewPtr.getNode());
12167       AddToWorklist(NewLD.getNode());
12168       AddToWorklist(NewVal.getNode());
12169       WorklistRemover DeadNodes(*this);
12170       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12171       ++OpsNarrowed;
12172       return NewST;
12173     }
12174   }
12175 
12176   return SDValue();
12177 }
12178 
12179 /// For a given floating point load / store pair, if the load value isn't used
12180 /// by any other operations, then consider transforming the pair to integer
12181 /// load / store operations if the target deems the transformation profitable.
12182 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12183   StoreSDNode *ST  = cast<StoreSDNode>(N);
12184   SDValue Chain = ST->getChain();
12185   SDValue Value = ST->getValue();
12186   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12187       Value.hasOneUse() &&
12188       Chain == SDValue(Value.getNode(), 1)) {
12189     LoadSDNode *LD = cast<LoadSDNode>(Value);
12190     EVT VT = LD->getMemoryVT();
12191     if (!VT.isFloatingPoint() ||
12192         VT != ST->getMemoryVT() ||
12193         LD->isNonTemporal() ||
12194         ST->isNonTemporal() ||
12195         LD->getPointerInfo().getAddrSpace() != 0 ||
12196         ST->getPointerInfo().getAddrSpace() != 0)
12197       return SDValue();
12198 
12199     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12200     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12201         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12202         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12203         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12204       return SDValue();
12205 
12206     unsigned LDAlign = LD->getAlignment();
12207     unsigned STAlign = ST->getAlignment();
12208     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12209     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12210     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12211       return SDValue();
12212 
12213     SDValue NewLD =
12214         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12215                     LD->getPointerInfo(), LDAlign);
12216 
12217     SDValue NewST =
12218         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12219                      ST->getPointerInfo(), STAlign);
12220 
12221     AddToWorklist(NewLD.getNode());
12222     AddToWorklist(NewST.getNode());
12223     WorklistRemover DeadNodes(*this);
12224     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12225     ++LdStFP2Int;
12226     return NewST;
12227   }
12228 
12229   return SDValue();
12230 }
12231 
12232 // This is a helper function for visitMUL to check the profitability
12233 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12234 // MulNode is the original multiply, AddNode is (add x, c1),
12235 // and ConstNode is c2.
12236 //
12237 // If the (add x, c1) has multiple uses, we could increase
12238 // the number of adds if we make this transformation.
12239 // It would only be worth doing this if we can remove a
12240 // multiply in the process. Check for that here.
12241 // To illustrate:
12242 //     (A + c1) * c3
12243 //     (A + c2) * c3
12244 // We're checking for cases where we have common "c3 * A" expressions.
12245 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12246                                               SDValue &AddNode,
12247                                               SDValue &ConstNode) {
12248   APInt Val;
12249 
12250   // If the add only has one use, this would be OK to do.
12251   if (AddNode.getNode()->hasOneUse())
12252     return true;
12253 
12254   // Walk all the users of the constant with which we're multiplying.
12255   for (SDNode *Use : ConstNode->uses()) {
12256 
12257     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12258       continue;
12259 
12260     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12261       SDNode *OtherOp;
12262       SDNode *MulVar = AddNode.getOperand(0).getNode();
12263 
12264       // OtherOp is what we're multiplying against the constant.
12265       if (Use->getOperand(0) == ConstNode)
12266         OtherOp = Use->getOperand(1).getNode();
12267       else
12268         OtherOp = Use->getOperand(0).getNode();
12269 
12270       // Check to see if multiply is with the same operand of our "add".
12271       //
12272       //     ConstNode  = CONST
12273       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12274       //     ...
12275       //     AddNode  = (A + c1)  <-- MulVar is A.
12276       //         = AddNode * ConstNode   <-- current visiting instruction.
12277       //
12278       // If we make this transformation, we will have a common
12279       // multiply (ConstNode * A) that we can save.
12280       if (OtherOp == MulVar)
12281         return true;
12282 
12283       // Now check to see if a future expansion will give us a common
12284       // multiply.
12285       //
12286       //     ConstNode  = CONST
12287       //     AddNode    = (A + c1)
12288       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12289       //     ...
12290       //     OtherOp = (A + c2)
12291       //     Use     = OtherOp * ConstNode <-- visiting Use.
12292       //
12293       // If we make this transformation, we will have a common
12294       // multiply (CONST * A) after we also do the same transformation
12295       // to the "t2" instruction.
12296       if (OtherOp->getOpcode() == ISD::ADD &&
12297           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12298           OtherOp->getOperand(0).getNode() == MulVar)
12299         return true;
12300     }
12301   }
12302 
12303   // Didn't find a case where this would be profitable.
12304   return false;
12305 }
12306 
12307 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12308                                          unsigned NumStores) {
12309   SmallVector<SDValue, 8> Chains;
12310   SmallPtrSet<const SDNode *, 8> Visited;
12311   SDLoc StoreDL(StoreNodes[0].MemNode);
12312 
12313   for (unsigned i = 0; i < NumStores; ++i) {
12314     Visited.insert(StoreNodes[i].MemNode);
12315   }
12316 
12317   // don't include nodes that are children
12318   for (unsigned i = 0; i < NumStores; ++i) {
12319     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12320       Chains.push_back(StoreNodes[i].MemNode->getChain());
12321   }
12322 
12323   assert(Chains.size() > 0 && "Chain should have generated a chain");
12324   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12325 }
12326 
12327 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12328     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12329     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12330   // Make sure we have something to merge.
12331   if (NumStores < 2)
12332     return false;
12333 
12334   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12335 
12336   // The latest Node in the DAG.
12337   SDLoc DL(StoreNodes[0].MemNode);
12338 
12339   SDValue StoredVal;
12340   if (UseVector) {
12341     bool IsVec = MemVT.isVector();
12342     unsigned Elts = NumStores;
12343     if (IsVec) {
12344       // When merging vector stores, get the total number of elements.
12345       Elts *= MemVT.getVectorNumElements();
12346     }
12347     // Get the type for the merged vector store.
12348     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12349     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12350 
12351     if (IsConstantSrc) {
12352       SmallVector<SDValue, 8> BuildVector;
12353       for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12354         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12355         SDValue Val = St->getValue();
12356         if (MemVT.getScalarType().isInteger())
12357           if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12358             Val = DAG.getConstant(
12359                 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12360                 SDLoc(CFP), MemVT);
12361         BuildVector.push_back(Val);
12362       }
12363       StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12364     } else {
12365       SmallVector<SDValue, 8> Ops;
12366       for (unsigned i = 0; i < NumStores; ++i) {
12367         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12368         SDValue Val = St->getValue();
12369         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12370         if (Val.getValueType() != MemVT)
12371           return false;
12372         Ops.push_back(Val);
12373       }
12374 
12375       // Build the extracted vector elements back into a vector.
12376       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12377                               DL, Ty, Ops);    }
12378   } else {
12379     // We should always use a vector store when merging extracted vector
12380     // elements, so this path implies a store of constants.
12381     assert(IsConstantSrc && "Merged vector elements should use vector store");
12382 
12383     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12384     APInt StoreInt(SizeInBits, 0);
12385 
12386     // Construct a single integer constant which is made of the smaller
12387     // constant inputs.
12388     bool IsLE = DAG.getDataLayout().isLittleEndian();
12389     for (unsigned i = 0; i < NumStores; ++i) {
12390       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12391       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12392 
12393       SDValue Val = St->getValue();
12394       StoreInt <<= ElementSizeBytes * 8;
12395       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12396         StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12397       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12398         StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12399       } else {
12400         llvm_unreachable("Invalid constant element type");
12401       }
12402     }
12403 
12404     // Create the new Load and Store operations.
12405     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12406     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12407   }
12408 
12409   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12410   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12411 
12412   // make sure we use trunc store if it's necessary to be legal.
12413   SDValue NewStore;
12414   if (UseVector || !UseTrunc) {
12415     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12416                             FirstInChain->getPointerInfo(),
12417                             FirstInChain->getAlignment());
12418   } else { // Must be realized as a trunc store
12419     EVT LegalizedStoredValueTy =
12420         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12421     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12422     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12423     SDValue ExtendedStoreVal =
12424         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12425                         LegalizedStoredValueTy);
12426     NewStore = DAG.getTruncStore(
12427         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12428         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12429         FirstInChain->getAlignment(),
12430         FirstInChain->getMemOperand()->getFlags());
12431   }
12432 
12433   // Replace all merged stores with the new store.
12434   for (unsigned i = 0; i < NumStores; ++i)
12435     CombineTo(StoreNodes[i].MemNode, NewStore);
12436 
12437   AddToWorklist(NewChain.getNode());
12438   return true;
12439 }
12440 
12441 void DAGCombiner::getStoreMergeCandidates(
12442     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12443   // This holds the base pointer, index, and the offset in bytes from the base
12444   // pointer.
12445   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12446   EVT MemVT = St->getMemoryVT();
12447 
12448   // We must have a base and an offset.
12449   if (!BasePtr.getBase().getNode())
12450     return;
12451 
12452   // Do not handle stores to undef base pointers.
12453   if (BasePtr.getBase().isUndef())
12454     return;
12455 
12456   bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12457                        isa<ConstantFPSDNode>(St->getValue());
12458   bool IsExtractVecSrc =
12459       (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12460        St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12461   bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12462   BaseIndexOffset LBasePtr;
12463   // Match on loadbaseptr if relevant.
12464   if (IsLoadSrc)
12465     LBasePtr = BaseIndexOffset::match(
12466         cast<LoadSDNode>(St->getValue())->getBasePtr(), DAG);
12467 
12468   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12469                             int64_t &Offset) -> bool {
12470     if (Other->isVolatile() || Other->isIndexed())
12471       return false;
12472     // We can merge constant floats to equivalent integers
12473     if (Other->getMemoryVT() != MemVT)
12474       if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12475             isa<ConstantFPSDNode>(Other->getValue())))
12476         return false;
12477     if (IsLoadSrc) {
12478       // The Load's Base Ptr must also match
12479       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Other->getValue())) {
12480         auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12481         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12482           return false;
12483       } else
12484         return false;
12485     }
12486     if (IsConstantSrc)
12487       if (!(isa<ConstantSDNode>(Other->getValue()) ||
12488             isa<ConstantFPSDNode>(Other->getValue())))
12489         return false;
12490     if (IsExtractVecSrc)
12491       if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12492             Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12493         return false;
12494     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12495     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
12496   };
12497   // We looking for a root node which is an ancestor to all mergable
12498   // stores. We search up through a load, to our root and then down
12499   // through all children. For instance we will find Store{1,2,3} if
12500   // St is Store1, Store2. or Store3 where the root is not a load
12501   // which always true for nonvolatile ops. TODO: Expand
12502   // the search to find all valid candidates through multiple layers of loads.
12503   //
12504   // Root
12505   // |-------|-------|
12506   // Load    Load    Store3
12507   // |       |
12508   // Store1   Store2
12509   //
12510   // FIXME: We should be able to climb and
12511   // descend TokenFactors to find candidates as well.
12512 
12513   SDNode *RootNode = (St->getChain()).getNode();
12514 
12515   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12516     RootNode = Ldn->getChain().getNode();
12517     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12518       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12519         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12520           if (I2.getOperandNo() == 0)
12521             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12522               BaseIndexOffset Ptr;
12523               int64_t PtrDiff;
12524               if (CandidateMatch(OtherST, Ptr, PtrDiff))
12525                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12526             }
12527   } else
12528     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12529       if (I.getOperandNo() == 0)
12530         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12531           BaseIndexOffset Ptr;
12532           int64_t PtrDiff;
12533           if (CandidateMatch(OtherST, Ptr, PtrDiff))
12534             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12535         }
12536 }
12537 
12538 // We need to check that merging these stores does not cause a loop
12539 // in the DAG. Any store candidate may depend on another candidate
12540 // indirectly through its operand (we already consider dependencies
12541 // through the chain). Check in parallel by searching up from
12542 // non-chain operands of candidates.
12543 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12544     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12545   SmallPtrSet<const SDNode *, 16> Visited;
12546   SmallVector<const SDNode *, 8> Worklist;
12547   // search ops of store candidates
12548   for (unsigned i = 0; i < NumStores; ++i) {
12549     SDNode *n = StoreNodes[i].MemNode;
12550     // Potential loops may happen only through non-chain operands
12551     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12552       Worklist.push_back(n->getOperand(j).getNode());
12553   }
12554   // search through DAG. We can stop early if we find a storenode
12555   for (unsigned i = 0; i < NumStores; ++i) {
12556     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12557       return false;
12558   }
12559   return true;
12560 }
12561 
12562 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12563   if (OptLevel == CodeGenOpt::None)
12564     return false;
12565 
12566   EVT MemVT = St->getMemoryVT();
12567   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12568 
12569   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12570     return false;
12571 
12572   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12573       Attribute::NoImplicitFloat);
12574 
12575   // This function cannot currently deal with non-byte-sized memory sizes.
12576   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12577     return false;
12578 
12579   if (!MemVT.isSimple())
12580     return false;
12581 
12582   // Perform an early exit check. Do not bother looking at stored values that
12583   // are not constants, loads, or extracted vector elements.
12584   SDValue StoredVal = St->getValue();
12585   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12586   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12587                        isa<ConstantFPSDNode>(StoredVal);
12588   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12589                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12590 
12591   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12592     return false;
12593 
12594   // Don't merge vectors into wider vectors if the source data comes from loads.
12595   // TODO: This restriction can be lifted by using logic similar to the
12596   // ExtractVecSrc case.
12597   if (MemVT.isVector() && IsLoadSrc)
12598     return false;
12599 
12600   SmallVector<MemOpLink, 8> StoreNodes;
12601   // Find potential store merge candidates by searching through chain sub-DAG
12602   getStoreMergeCandidates(St, StoreNodes);
12603 
12604   // Check if there is anything to merge.
12605   if (StoreNodes.size() < 2)
12606     return false;
12607 
12608   // Sort the memory operands according to their distance from the
12609   // base pointer.
12610   std::sort(StoreNodes.begin(), StoreNodes.end(),
12611             [](MemOpLink LHS, MemOpLink RHS) {
12612               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12613             });
12614 
12615   // Store Merge attempts to merge the lowest stores. This generally
12616   // works out as if successful, as the remaining stores are checked
12617   // after the first collection of stores is merged. However, in the
12618   // case that a non-mergeable store is found first, e.g., {p[-2],
12619   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12620   // mergeable cases. To prevent this, we prune such stores from the
12621   // front of StoreNodes here.
12622 
12623   bool RV = false;
12624   while (StoreNodes.size() > 1) {
12625     unsigned StartIdx = 0;
12626     while ((StartIdx + 1 < StoreNodes.size()) &&
12627            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12628                StoreNodes[StartIdx + 1].OffsetFromBase)
12629       ++StartIdx;
12630 
12631     // Bail if we don't have enough candidates to merge.
12632     if (StartIdx + 1 >= StoreNodes.size())
12633       return RV;
12634 
12635     if (StartIdx)
12636       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12637 
12638     // Scan the memory operations on the chain and find the first
12639     // non-consecutive store memory address.
12640     unsigned NumConsecutiveStores = 1;
12641     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12642     // Check that the addresses are consecutive starting from the second
12643     // element in the list of stores.
12644     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12645       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12646       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12647         break;
12648       NumConsecutiveStores = i + 1;
12649     }
12650 
12651     if (NumConsecutiveStores < 2) {
12652       StoreNodes.erase(StoreNodes.begin(),
12653                        StoreNodes.begin() + NumConsecutiveStores);
12654       continue;
12655     }
12656 
12657     // Check that we can merge these candidates without causing a cycle
12658     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12659                                                   NumConsecutiveStores)) {
12660       StoreNodes.erase(StoreNodes.begin(),
12661                        StoreNodes.begin() + NumConsecutiveStores);
12662       continue;
12663     }
12664 
12665     // The node with the lowest store address.
12666     LLVMContext &Context = *DAG.getContext();
12667     const DataLayout &DL = DAG.getDataLayout();
12668 
12669     // Store the constants into memory as one consecutive store.
12670     if (IsConstantSrc) {
12671       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12672       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12673       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12674       unsigned LastLegalType = 1;
12675       unsigned LastLegalVectorType = 1;
12676       bool LastIntegerTrunc = false;
12677       bool NonZero = false;
12678       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12679         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12680         SDValue StoredVal = ST->getValue();
12681 
12682         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12683           NonZero |= !C->isNullValue();
12684         } else if (ConstantFPSDNode *C =
12685                        dyn_cast<ConstantFPSDNode>(StoredVal)) {
12686           NonZero |= !C->getConstantFPValue()->isNullValue();
12687         } else {
12688           // Non-constant.
12689           break;
12690         }
12691 
12692         // Find a legal type for the constant store.
12693         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12694         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12695         bool IsFast = false;
12696         if (TLI.isTypeLegal(StoreTy) &&
12697             TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12698             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12699                                    FirstStoreAlign, &IsFast) &&
12700             IsFast) {
12701           LastIntegerTrunc = false;
12702           LastLegalType = i + 1;
12703           // Or check whether a truncstore is legal.
12704         } else if (TLI.getTypeAction(Context, StoreTy) ==
12705                    TargetLowering::TypePromoteInteger) {
12706           EVT LegalizedStoredValueTy =
12707               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12708           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12709               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) &&
12710               TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12711                                      FirstStoreAS, FirstStoreAlign, &IsFast) &&
12712               IsFast) {
12713             LastIntegerTrunc = true;
12714             LastLegalType = i + 1;
12715           }
12716         }
12717 
12718         // We only use vectors if the constant is known to be zero or the target
12719         // allows it and the function is not marked with the noimplicitfloat
12720         // attribute.
12721         if ((!NonZero ||
12722              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12723             !NoVectors) {
12724           // Find a legal type for the vector store.
12725           EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12726           if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) &&
12727               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12728                                      FirstStoreAlign, &IsFast) &&
12729               IsFast)
12730             LastLegalVectorType = i + 1;
12731         }
12732       }
12733 
12734       // Check if we found a legal integer type that creates a meaningful merge.
12735       if (LastLegalType < 2 && LastLegalVectorType < 2) {
12736         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12737         continue;
12738       }
12739 
12740       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12741       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12742 
12743       bool Merged = MergeStoresOfConstantsOrVecElts(
12744           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
12745       if (!Merged) {
12746         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12747         continue;
12748       }
12749       // Remove merged stores for next iteration.
12750       RV = true;
12751       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12752       continue;
12753     }
12754 
12755     // When extracting multiple vector elements, try to store them
12756     // in one vector store rather than a sequence of scalar stores.
12757     if (IsExtractVecSrc) {
12758       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12759       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12760       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12761       unsigned NumStoresToMerge = 1;
12762       bool IsVec = MemVT.isVector();
12763       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12764         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12765         unsigned StoreValOpcode = St->getValue().getOpcode();
12766         // This restriction could be loosened.
12767         // Bail out if any stored values are not elements extracted from a
12768         // vector. It should be possible to handle mixed sources, but load
12769         // sources need more careful handling (see the block of code below that
12770         // handles consecutive loads).
12771         if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12772             StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12773           return RV;
12774 
12775         // Find a legal type for the vector store.
12776         unsigned Elts = i + 1;
12777         if (IsVec) {
12778           // When merging vector stores, get the total number of elements.
12779           Elts *= MemVT.getVectorNumElements();
12780         }
12781         EVT Ty =
12782             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12783         bool IsFast;
12784         if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) &&
12785             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12786                                    FirstStoreAlign, &IsFast) &&
12787             IsFast)
12788           NumStoresToMerge = i + 1;
12789       }
12790 
12791       bool Merged = MergeStoresOfConstantsOrVecElts(
12792           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
12793       if (!Merged) {
12794         StoreNodes.erase(StoreNodes.begin(),
12795                          StoreNodes.begin() + NumStoresToMerge);
12796         continue;
12797       }
12798       // Remove merged stores for next iteration.
12799       StoreNodes.erase(StoreNodes.begin(),
12800                        StoreNodes.begin() + NumStoresToMerge);
12801       RV = true;
12802       continue;
12803     }
12804 
12805     // Below we handle the case of multiple consecutive stores that
12806     // come from multiple consecutive loads. We merge them into a single
12807     // wide load and a single wide store.
12808 
12809     // Look for load nodes which are used by the stored values.
12810     SmallVector<MemOpLink, 8> LoadNodes;
12811 
12812     // Find acceptable loads. Loads need to have the same chain (token factor),
12813     // must not be zext, volatile, indexed, and they must be consecutive.
12814     BaseIndexOffset LdBasePtr;
12815     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12816       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12817       LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12818       if (!Ld)
12819         break;
12820 
12821       // Loads must only have one use.
12822       if (!Ld->hasNUsesOfValue(1, 0))
12823         break;
12824 
12825       // The memory operands must not be volatile.
12826       if (Ld->isVolatile() || Ld->isIndexed())
12827         break;
12828 
12829       // We do not accept ext loads.
12830       if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12831         break;
12832 
12833       // The stored memory type must be the same.
12834       if (Ld->getMemoryVT() != MemVT)
12835         break;
12836 
12837       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12838       // If this is not the first ptr that we check.
12839       int64_t LdOffset = 0;
12840       if (LdBasePtr.getBase().getNode()) {
12841         // The base ptr must be the same.
12842         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
12843           break;
12844       } else {
12845         // Check that all other base pointers are the same as this one.
12846         LdBasePtr = LdPtr;
12847       }
12848 
12849       // We found a potential memory operand to merge.
12850       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
12851     }
12852 
12853     if (LoadNodes.size() < 2) {
12854       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12855       continue;
12856     }
12857 
12858     // If we have load/store pair instructions and we only have two values,
12859     // don't bother merging.
12860     unsigned RequiredAlignment;
12861     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12862         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
12863       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
12864       continue;
12865     }
12866     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12867     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12868     unsigned FirstStoreAlign = FirstInChain->getAlignment();
12869     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12870     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12871     unsigned FirstLoadAlign = FirstLoad->getAlignment();
12872 
12873     // Scan the memory operations on the chain and find the first
12874     // non-consecutive load memory address. These variables hold the index in
12875     // the store node array.
12876     unsigned LastConsecutiveLoad = 1;
12877     // This variable refers to the size and not index in the array.
12878     unsigned LastLegalVectorType = 1;
12879     unsigned LastLegalIntegerType = 1;
12880     bool isDereferenceable = true;
12881     bool DoIntegerTruncate = false;
12882     StartAddress = LoadNodes[0].OffsetFromBase;
12883     SDValue FirstChain = FirstLoad->getChain();
12884     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12885       // All loads must share the same chain.
12886       if (LoadNodes[i].MemNode->getChain() != FirstChain)
12887         break;
12888 
12889       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12890       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12891         break;
12892       LastConsecutiveLoad = i;
12893 
12894       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
12895         isDereferenceable = false;
12896 
12897       // Find a legal type for the vector store.
12898       EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1);
12899       bool IsFastSt, IsFastLd;
12900       if (TLI.isTypeLegal(StoreTy) &&
12901           TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12902           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12903                                  FirstStoreAlign, &IsFastSt) &&
12904           IsFastSt &&
12905           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12906                                  FirstLoadAlign, &IsFastLd) &&
12907           IsFastLd) {
12908         LastLegalVectorType = i + 1;
12909       }
12910 
12911       // Find a legal type for the integer store.
12912       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12913       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12914       if (TLI.isTypeLegal(StoreTy) &&
12915           TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12916           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12917                                  FirstStoreAlign, &IsFastSt) &&
12918           IsFastSt &&
12919           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12920                                  FirstLoadAlign, &IsFastLd) &&
12921           IsFastLd) {
12922         LastLegalIntegerType = i + 1;
12923         DoIntegerTruncate = false;
12924         // Or check whether a truncstore and extload is legal.
12925       } else if (TLI.getTypeAction(Context, StoreTy) ==
12926                  TargetLowering::TypePromoteInteger) {
12927         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
12928         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12929             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) &&
12930             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
12931                                StoreTy) &&
12932             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
12933                                StoreTy) &&
12934             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12935             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12936                                    FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12937             IsFastSt &&
12938             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12939                                    FirstLoadAlign, &IsFastLd) &&
12940             IsFastLd) {
12941           LastLegalIntegerType = i + 1;
12942           DoIntegerTruncate = true;
12943         }
12944       }
12945     }
12946 
12947     // Only use vector types if the vector type is larger than the integer type.
12948     // If they are the same, use integers.
12949     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12950     unsigned LastLegalType =
12951         std::max(LastLegalVectorType, LastLegalIntegerType);
12952 
12953     // We add +1 here because the LastXXX variables refer to location while
12954     // the NumElem refers to array/index size.
12955     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12956     NumElem = std::min(LastLegalType, NumElem);
12957 
12958     if (NumElem < 2) {
12959       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12960       continue;
12961     }
12962 
12963     // Find if it is better to use vectors or integers to load and store
12964     // to memory.
12965     EVT JointMemOpVT;
12966     if (UseVectorTy) {
12967       JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12968     } else {
12969       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12970       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12971     }
12972 
12973     SDLoc LoadDL(LoadNodes[0].MemNode);
12974     SDLoc StoreDL(StoreNodes[0].MemNode);
12975 
12976     // The merged loads are required to have the same incoming chain, so
12977     // using the first's chain is acceptable.
12978 
12979     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12980     AddToWorklist(NewStoreChain.getNode());
12981 
12982     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
12983                                           MachineMemOperand::MODereferenceable:
12984                                           MachineMemOperand::MONone;
12985 
12986     SDValue NewLoad, NewStore;
12987     if (UseVectorTy || !DoIntegerTruncate) {
12988       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12989                             FirstLoad->getBasePtr(),
12990                             FirstLoad->getPointerInfo(), FirstLoadAlign,
12991                             MMOFlags);
12992       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
12993                               FirstInChain->getBasePtr(),
12994                               FirstInChain->getPointerInfo(), FirstStoreAlign);
12995     } else { // This must be the truncstore/extload case
12996       EVT ExtendedTy =
12997           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
12998       NewLoad =
12999           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13000                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13001                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13002       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13003                                    FirstInChain->getBasePtr(),
13004                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13005                                    FirstInChain->getAlignment(),
13006                                    FirstInChain->getMemOperand()->getFlags());
13007     }
13008 
13009     // Transfer chain users from old loads to the new load.
13010     for (unsigned i = 0; i < NumElem; ++i) {
13011       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13012       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13013                                     SDValue(NewLoad.getNode(), 1));
13014     }
13015 
13016     // Replace the all stores with the new store.
13017     for (unsigned i = 0; i < NumElem; ++i)
13018       CombineTo(StoreNodes[i].MemNode, NewStore);
13019     RV = true;
13020     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13021     continue;
13022   }
13023   return RV;
13024 }
13025 
13026 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13027   SDLoc SL(ST);
13028   SDValue ReplStore;
13029 
13030   // Replace the chain to avoid dependency.
13031   if (ST->isTruncatingStore()) {
13032     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13033                                   ST->getBasePtr(), ST->getMemoryVT(),
13034                                   ST->getMemOperand());
13035   } else {
13036     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13037                              ST->getMemOperand());
13038   }
13039 
13040   // Create token to keep both nodes around.
13041   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13042                               MVT::Other, ST->getChain(), ReplStore);
13043 
13044   // Make sure the new and old chains are cleaned up.
13045   AddToWorklist(Token.getNode());
13046 
13047   // Don't add users to work list.
13048   return CombineTo(ST, Token, false);
13049 }
13050 
13051 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13052   SDValue Value = ST->getValue();
13053   if (Value.getOpcode() == ISD::TargetConstantFP)
13054     return SDValue();
13055 
13056   SDLoc DL(ST);
13057 
13058   SDValue Chain = ST->getChain();
13059   SDValue Ptr = ST->getBasePtr();
13060 
13061   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13062 
13063   // NOTE: If the original store is volatile, this transform must not increase
13064   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13065   // processor operation but an i64 (which is not legal) requires two.  So the
13066   // transform should not be done in this case.
13067 
13068   SDValue Tmp;
13069   switch (CFP->getSimpleValueType(0).SimpleTy) {
13070   default:
13071     llvm_unreachable("Unknown FP type");
13072   case MVT::f16:    // We don't do this for these yet.
13073   case MVT::f80:
13074   case MVT::f128:
13075   case MVT::ppcf128:
13076     return SDValue();
13077   case MVT::f32:
13078     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13079         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13080       ;
13081       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13082                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13083                             MVT::i32);
13084       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13085     }
13086 
13087     return SDValue();
13088   case MVT::f64:
13089     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13090          !ST->isVolatile()) ||
13091         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13092       ;
13093       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13094                             getZExtValue(), SDLoc(CFP), MVT::i64);
13095       return DAG.getStore(Chain, DL, Tmp,
13096                           Ptr, ST->getMemOperand());
13097     }
13098 
13099     if (!ST->isVolatile() &&
13100         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13101       // Many FP stores are not made apparent until after legalize, e.g. for
13102       // argument passing.  Since this is so common, custom legalize the
13103       // 64-bit integer store into two 32-bit stores.
13104       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13105       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13106       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13107       if (DAG.getDataLayout().isBigEndian())
13108         std::swap(Lo, Hi);
13109 
13110       unsigned Alignment = ST->getAlignment();
13111       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13112       AAMDNodes AAInfo = ST->getAAInfo();
13113 
13114       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13115                                  ST->getAlignment(), MMOFlags, AAInfo);
13116       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13117                         DAG.getConstant(4, DL, Ptr.getValueType()));
13118       Alignment = MinAlign(Alignment, 4U);
13119       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13120                                  ST->getPointerInfo().getWithOffset(4),
13121                                  Alignment, MMOFlags, AAInfo);
13122       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13123                          St0, St1);
13124     }
13125 
13126     return SDValue();
13127   }
13128 }
13129 
13130 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13131   StoreSDNode *ST  = cast<StoreSDNode>(N);
13132   SDValue Chain = ST->getChain();
13133   SDValue Value = ST->getValue();
13134   SDValue Ptr   = ST->getBasePtr();
13135 
13136   // If this is a store of a bit convert, store the input value if the
13137   // resultant store does not need a higher alignment than the original.
13138   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13139       ST->isUnindexed()) {
13140     EVT SVT = Value.getOperand(0).getValueType();
13141     if (((!LegalOperations && !ST->isVolatile()) ||
13142          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13143         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13144       unsigned OrigAlign = ST->getAlignment();
13145       bool Fast = false;
13146       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13147                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13148           Fast) {
13149         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13150                             ST->getPointerInfo(), OrigAlign,
13151                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13152       }
13153     }
13154   }
13155 
13156   // Turn 'store undef, Ptr' -> nothing.
13157   if (Value.isUndef() && ST->isUnindexed())
13158     return Chain;
13159 
13160   // Try to infer better alignment information than the store already has.
13161   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13162     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13163       if (Align > ST->getAlignment()) {
13164         SDValue NewStore =
13165             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13166                               ST->getMemoryVT(), Align,
13167                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13168         if (NewStore.getNode() != N)
13169           return CombineTo(ST, NewStore, true);
13170       }
13171     }
13172   }
13173 
13174   // Try transforming a pair floating point load / store ops to integer
13175   // load / store ops.
13176   if (SDValue NewST = TransformFPLoadStorePair(N))
13177     return NewST;
13178 
13179   if (ST->isUnindexed()) {
13180     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13181     // adjacent stores.
13182     if (findBetterNeighborChains(ST)) {
13183       // replaceStoreChain uses CombineTo, which handled all of the worklist
13184       // manipulation. Return the original node to not do anything else.
13185       return SDValue(ST, 0);
13186     }
13187     Chain = ST->getChain();
13188   }
13189 
13190   // FIXME: is there such a thing as a truncating indexed store?
13191   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13192       Value.getValueType().isInteger()) {
13193     // See if we can simplify the input to this truncstore with knowledge that
13194     // only the low bits are being used.  For example:
13195     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13196     SDValue Shorter = GetDemandedBits(
13197         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13198                                     ST->getMemoryVT().getScalarSizeInBits()));
13199     AddToWorklist(Value.getNode());
13200     if (Shorter.getNode())
13201       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13202                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13203 
13204     // Otherwise, see if we can simplify the operation with
13205     // SimplifyDemandedBits, which only works if the value has a single use.
13206     if (SimplifyDemandedBits(
13207             Value,
13208             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13209                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13210       // Re-visit the store if anything changed and the store hasn't been merged
13211       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13212       // node back to the worklist if necessary, but we also need to re-visit
13213       // the Store node itself.
13214       if (N->getOpcode() != ISD::DELETED_NODE)
13215         AddToWorklist(N);
13216       return SDValue(N, 0);
13217     }
13218   }
13219 
13220   // If this is a load followed by a store to the same location, then the store
13221   // is dead/noop.
13222   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13223     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13224         ST->isUnindexed() && !ST->isVolatile() &&
13225         // There can't be any side effects between the load and store, such as
13226         // a call or store.
13227         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13228       // The store is dead, remove it.
13229       return Chain;
13230     }
13231   }
13232 
13233   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13234     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13235         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13236         ST->getMemoryVT() == ST1->getMemoryVT()) {
13237       // If this is a store followed by a store with the same value to the same
13238       // location, then the store is dead/noop.
13239       if (ST1->getValue() == Value) {
13240         // The store is dead, remove it.
13241         return Chain;
13242       }
13243 
13244       // If this is a store who's preceeding store to the same location
13245       // and no one other node is chained to that store we can effectively
13246       // drop the store. Do not remove stores to undef as they may be used as
13247       // data sinks.
13248       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13249           !ST1->getBasePtr().isUndef()) {
13250         // ST1 is fully overwritten and can be elided. Combine with it's chain
13251         // value.
13252         CombineTo(ST1, ST1->getChain());
13253         return SDValue();
13254       }
13255     }
13256   }
13257 
13258   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13259   // truncating store.  We can do this even if this is already a truncstore.
13260   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13261       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13262       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13263                             ST->getMemoryVT())) {
13264     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13265                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13266   }
13267 
13268   // Only perform this optimization before the types are legal, because we
13269   // don't want to perform this optimization on every DAGCombine invocation.
13270   if ((TLI.mergeStoresAfterLegalization()) ? Level == AfterLegalizeDAG
13271                                            : !LegalTypes) {
13272     for (;;) {
13273       // There can be multiple store sequences on the same chain.
13274       // Keep trying to merge store sequences until we are unable to do so
13275       // or until we merge the last store on the chain.
13276       bool Changed = MergeConsecutiveStores(ST);
13277       if (!Changed) break;
13278       // Return N as merge only uses CombineTo and no worklist clean
13279       // up is necessary.
13280       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13281         return SDValue(N, 0);
13282     }
13283   }
13284 
13285   // Try transforming N to an indexed store.
13286   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13287     return SDValue(N, 0);
13288 
13289   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13290   //
13291   // Make sure to do this only after attempting to merge stores in order to
13292   //  avoid changing the types of some subset of stores due to visit order,
13293   //  preventing their merging.
13294   if (isa<ConstantFPSDNode>(ST->getValue())) {
13295     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13296       return NewSt;
13297   }
13298 
13299   if (SDValue NewSt = splitMergedValStore(ST))
13300     return NewSt;
13301 
13302   return ReduceLoadOpStoreWidth(N);
13303 }
13304 
13305 /// For the instruction sequence of store below, F and I values
13306 /// are bundled together as an i64 value before being stored into memory.
13307 /// Sometimes it is more efficent to generate separate stores for F and I,
13308 /// which can remove the bitwise instructions or sink them to colder places.
13309 ///
13310 ///   (store (or (zext (bitcast F to i32) to i64),
13311 ///              (shl (zext I to i64), 32)), addr)  -->
13312 ///   (store F, addr) and (store I, addr+4)
13313 ///
13314 /// Similarly, splitting for other merged store can also be beneficial, like:
13315 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13316 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13317 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13318 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13319 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13320 ///
13321 /// We allow each target to determine specifically which kind of splitting is
13322 /// supported.
13323 ///
13324 /// The store patterns are commonly seen from the simple code snippet below
13325 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13326 ///   void goo(const std::pair<int, float> &);
13327 ///   hoo() {
13328 ///     ...
13329 ///     goo(std::make_pair(tmp, ftmp));
13330 ///     ...
13331 ///   }
13332 ///
13333 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13334   if (OptLevel == CodeGenOpt::None)
13335     return SDValue();
13336 
13337   SDValue Val = ST->getValue();
13338   SDLoc DL(ST);
13339 
13340   // Match OR operand.
13341   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13342     return SDValue();
13343 
13344   // Match SHL operand and get Lower and Higher parts of Val.
13345   SDValue Op1 = Val.getOperand(0);
13346   SDValue Op2 = Val.getOperand(1);
13347   SDValue Lo, Hi;
13348   if (Op1.getOpcode() != ISD::SHL) {
13349     std::swap(Op1, Op2);
13350     if (Op1.getOpcode() != ISD::SHL)
13351       return SDValue();
13352   }
13353   Lo = Op2;
13354   Hi = Op1.getOperand(0);
13355   if (!Op1.hasOneUse())
13356     return SDValue();
13357 
13358   // Match shift amount to HalfValBitSize.
13359   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13360   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13361   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13362     return SDValue();
13363 
13364   // Lo and Hi are zero-extended from int with size less equal than 32
13365   // to i64.
13366   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13367       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13368       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13369       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13370       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13371       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13372     return SDValue();
13373 
13374   // Use the EVT of low and high parts before bitcast as the input
13375   // of target query.
13376   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13377                   ? Lo.getOperand(0).getValueType()
13378                   : Lo.getValueType();
13379   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13380                    ? Hi.getOperand(0).getValueType()
13381                    : Hi.getValueType();
13382   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13383     return SDValue();
13384 
13385   // Start to split store.
13386   unsigned Alignment = ST->getAlignment();
13387   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13388   AAMDNodes AAInfo = ST->getAAInfo();
13389 
13390   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13391   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13392   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13393   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13394 
13395   SDValue Chain = ST->getChain();
13396   SDValue Ptr = ST->getBasePtr();
13397   // Lower value store.
13398   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13399                              ST->getAlignment(), MMOFlags, AAInfo);
13400   Ptr =
13401       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13402                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13403   // Higher value store.
13404   SDValue St1 =
13405       DAG.getStore(St0, DL, Hi, Ptr,
13406                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13407                    Alignment / 2, MMOFlags, AAInfo);
13408   return St1;
13409 }
13410 
13411 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13412   SDValue InVec = N->getOperand(0);
13413   SDValue InVal = N->getOperand(1);
13414   SDValue EltNo = N->getOperand(2);
13415   SDLoc DL(N);
13416 
13417   // If the inserted element is an UNDEF, just use the input vector.
13418   if (InVal.isUndef())
13419     return InVec;
13420 
13421   EVT VT = InVec.getValueType();
13422 
13423   // Check that we know which element is being inserted
13424   if (!isa<ConstantSDNode>(EltNo))
13425     return SDValue();
13426   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13427 
13428   // Canonicalize insert_vector_elt dag nodes.
13429   // Example:
13430   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13431   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13432   //
13433   // Do this only if the child insert_vector node has one use; also
13434   // do this only if indices are both constants and Idx1 < Idx0.
13435   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13436       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13437     unsigned OtherElt = InVec.getConstantOperandVal(2);
13438     if (Elt < OtherElt) {
13439       // Swap nodes.
13440       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13441                                   InVec.getOperand(0), InVal, EltNo);
13442       AddToWorklist(NewOp.getNode());
13443       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13444                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13445     }
13446   }
13447 
13448   // If we can't generate a legal BUILD_VECTOR, exit
13449   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13450     return SDValue();
13451 
13452   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13453   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13454   // vector elements.
13455   SmallVector<SDValue, 8> Ops;
13456   // Do not combine these two vectors if the output vector will not replace
13457   // the input vector.
13458   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13459     Ops.append(InVec.getNode()->op_begin(),
13460                InVec.getNode()->op_end());
13461   } else if (InVec.isUndef()) {
13462     unsigned NElts = VT.getVectorNumElements();
13463     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13464   } else {
13465     return SDValue();
13466   }
13467 
13468   // Insert the element
13469   if (Elt < Ops.size()) {
13470     // All the operands of BUILD_VECTOR must have the same type;
13471     // we enforce that here.
13472     EVT OpVT = Ops[0].getValueType();
13473     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13474   }
13475 
13476   // Return the new vector
13477   return DAG.getBuildVector(VT, DL, Ops);
13478 }
13479 
13480 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13481     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13482   assert(!OriginalLoad->isVolatile());
13483 
13484   EVT ResultVT = EVE->getValueType(0);
13485   EVT VecEltVT = InVecVT.getVectorElementType();
13486   unsigned Align = OriginalLoad->getAlignment();
13487   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13488       VecEltVT.getTypeForEVT(*DAG.getContext()));
13489 
13490   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13491     return SDValue();
13492 
13493   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13494     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13495   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13496     return SDValue();
13497 
13498   Align = NewAlign;
13499 
13500   SDValue NewPtr = OriginalLoad->getBasePtr();
13501   SDValue Offset;
13502   EVT PtrType = NewPtr.getValueType();
13503   MachinePointerInfo MPI;
13504   SDLoc DL(EVE);
13505   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13506     int Elt = ConstEltNo->getZExtValue();
13507     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13508     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13509     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13510   } else {
13511     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13512     Offset = DAG.getNode(
13513         ISD::MUL, DL, PtrType, Offset,
13514         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13515     MPI = OriginalLoad->getPointerInfo();
13516   }
13517   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13518 
13519   // The replacement we need to do here is a little tricky: we need to
13520   // replace an extractelement of a load with a load.
13521   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13522   // Note that this replacement assumes that the extractvalue is the only
13523   // use of the load; that's okay because we don't want to perform this
13524   // transformation in other cases anyway.
13525   SDValue Load;
13526   SDValue Chain;
13527   if (ResultVT.bitsGT(VecEltVT)) {
13528     // If the result type of vextract is wider than the load, then issue an
13529     // extending load instead.
13530     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13531                                                   VecEltVT)
13532                                    ? ISD::ZEXTLOAD
13533                                    : ISD::EXTLOAD;
13534     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13535                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13536                           Align, OriginalLoad->getMemOperand()->getFlags(),
13537                           OriginalLoad->getAAInfo());
13538     Chain = Load.getValue(1);
13539   } else {
13540     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13541                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13542                        OriginalLoad->getAAInfo());
13543     Chain = Load.getValue(1);
13544     if (ResultVT.bitsLT(VecEltVT))
13545       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13546     else
13547       Load = DAG.getBitcast(ResultVT, Load);
13548   }
13549   WorklistRemover DeadNodes(*this);
13550   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13551   SDValue To[] = { Load, Chain };
13552   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13553   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13554   // worklist explicitly as well.
13555   AddToWorklist(Load.getNode());
13556   AddUsersToWorklist(Load.getNode()); // Add users too
13557   // Make sure to revisit this node to clean it up; it will usually be dead.
13558   AddToWorklist(EVE);
13559   ++OpsNarrowed;
13560   return SDValue(EVE, 0);
13561 }
13562 
13563 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13564   // (vextract (scalar_to_vector val, 0) -> val
13565   SDValue InVec = N->getOperand(0);
13566   EVT VT = InVec.getValueType();
13567   EVT NVT = N->getValueType(0);
13568 
13569   if (InVec.isUndef())
13570     return DAG.getUNDEF(NVT);
13571 
13572   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13573     // Check if the result type doesn't match the inserted element type. A
13574     // SCALAR_TO_VECTOR may truncate the inserted element and the
13575     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13576     SDValue InOp = InVec.getOperand(0);
13577     if (InOp.getValueType() != NVT) {
13578       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13579       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13580     }
13581     return InOp;
13582   }
13583 
13584   SDValue EltNo = N->getOperand(1);
13585   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13586 
13587   // extract_vector_elt (build_vector x, y), 1 -> y
13588   if (ConstEltNo &&
13589       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13590       TLI.isTypeLegal(VT) &&
13591       (InVec.hasOneUse() ||
13592        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13593     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13594     EVT InEltVT = Elt.getValueType();
13595 
13596     // Sometimes build_vector's scalar input types do not match result type.
13597     if (NVT == InEltVT)
13598       return Elt;
13599 
13600     // TODO: It may be useful to truncate if free if the build_vector implicitly
13601     // converts.
13602   }
13603 
13604   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13605   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13606       ConstEltNo->isNullValue() && VT.isInteger()) {
13607     SDValue BCSrc = InVec.getOperand(0);
13608     if (BCSrc.getValueType().isScalarInteger())
13609       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13610   }
13611 
13612   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13613   //
13614   // This only really matters if the index is non-constant since other combines
13615   // on the constant elements already work.
13616   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13617       EltNo == InVec.getOperand(2)) {
13618     SDValue Elt = InVec.getOperand(1);
13619     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13620   }
13621 
13622   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13623   // We only perform this optimization before the op legalization phase because
13624   // we may introduce new vector instructions which are not backed by TD
13625   // patterns. For example on AVX, extracting elements from a wide vector
13626   // without using extract_subvector. However, if we can find an underlying
13627   // scalar value, then we can always use that.
13628   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13629     int NumElem = VT.getVectorNumElements();
13630     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13631     // Find the new index to extract from.
13632     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13633 
13634     // Extracting an undef index is undef.
13635     if (OrigElt == -1)
13636       return DAG.getUNDEF(NVT);
13637 
13638     // Select the right vector half to extract from.
13639     SDValue SVInVec;
13640     if (OrigElt < NumElem) {
13641       SVInVec = InVec->getOperand(0);
13642     } else {
13643       SVInVec = InVec->getOperand(1);
13644       OrigElt -= NumElem;
13645     }
13646 
13647     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13648       SDValue InOp = SVInVec.getOperand(OrigElt);
13649       if (InOp.getValueType() != NVT) {
13650         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13651         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13652       }
13653 
13654       return InOp;
13655     }
13656 
13657     // FIXME: We should handle recursing on other vector shuffles and
13658     // scalar_to_vector here as well.
13659 
13660     if (!LegalOperations) {
13661       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13662       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13663                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13664     }
13665   }
13666 
13667   bool BCNumEltsChanged = false;
13668   EVT ExtVT = VT.getVectorElementType();
13669   EVT LVT = ExtVT;
13670 
13671   // If the result of load has to be truncated, then it's not necessarily
13672   // profitable.
13673   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13674     return SDValue();
13675 
13676   if (InVec.getOpcode() == ISD::BITCAST) {
13677     // Don't duplicate a load with other uses.
13678     if (!InVec.hasOneUse())
13679       return SDValue();
13680 
13681     EVT BCVT = InVec.getOperand(0).getValueType();
13682     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13683       return SDValue();
13684     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13685       BCNumEltsChanged = true;
13686     InVec = InVec.getOperand(0);
13687     ExtVT = BCVT.getVectorElementType();
13688   }
13689 
13690   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13691   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13692       ISD::isNormalLoad(InVec.getNode()) &&
13693       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13694     SDValue Index = N->getOperand(1);
13695     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13696       if (!OrigLoad->isVolatile()) {
13697         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13698                                                              OrigLoad);
13699       }
13700     }
13701   }
13702 
13703   // Perform only after legalization to ensure build_vector / vector_shuffle
13704   // optimizations have already been done.
13705   if (!LegalOperations) return SDValue();
13706 
13707   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13708   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13709   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13710 
13711   if (ConstEltNo) {
13712     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13713 
13714     LoadSDNode *LN0 = nullptr;
13715     const ShuffleVectorSDNode *SVN = nullptr;
13716     if (ISD::isNormalLoad(InVec.getNode())) {
13717       LN0 = cast<LoadSDNode>(InVec);
13718     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13719                InVec.getOperand(0).getValueType() == ExtVT &&
13720                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13721       // Don't duplicate a load with other uses.
13722       if (!InVec.hasOneUse())
13723         return SDValue();
13724 
13725       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13726     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13727       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13728       // =>
13729       // (load $addr+1*size)
13730 
13731       // Don't duplicate a load with other uses.
13732       if (!InVec.hasOneUse())
13733         return SDValue();
13734 
13735       // If the bit convert changed the number of elements, it is unsafe
13736       // to examine the mask.
13737       if (BCNumEltsChanged)
13738         return SDValue();
13739 
13740       // Select the input vector, guarding against out of range extract vector.
13741       unsigned NumElems = VT.getVectorNumElements();
13742       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13743       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13744 
13745       if (InVec.getOpcode() == ISD::BITCAST) {
13746         // Don't duplicate a load with other uses.
13747         if (!InVec.hasOneUse())
13748           return SDValue();
13749 
13750         InVec = InVec.getOperand(0);
13751       }
13752       if (ISD::isNormalLoad(InVec.getNode())) {
13753         LN0 = cast<LoadSDNode>(InVec);
13754         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13755         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13756       }
13757     }
13758 
13759     // Make sure we found a non-volatile load and the extractelement is
13760     // the only use.
13761     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13762       return SDValue();
13763 
13764     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13765     if (Elt == -1)
13766       return DAG.getUNDEF(LVT);
13767 
13768     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13769   }
13770 
13771   return SDValue();
13772 }
13773 
13774 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13775 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13776   // We perform this optimization post type-legalization because
13777   // the type-legalizer often scalarizes integer-promoted vectors.
13778   // Performing this optimization before may create bit-casts which
13779   // will be type-legalized to complex code sequences.
13780   // We perform this optimization only before the operation legalizer because we
13781   // may introduce illegal operations.
13782   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13783     return SDValue();
13784 
13785   unsigned NumInScalars = N->getNumOperands();
13786   SDLoc DL(N);
13787   EVT VT = N->getValueType(0);
13788 
13789   // Check to see if this is a BUILD_VECTOR of a bunch of values
13790   // which come from any_extend or zero_extend nodes. If so, we can create
13791   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13792   // optimizations. We do not handle sign-extend because we can't fill the sign
13793   // using shuffles.
13794   EVT SourceType = MVT::Other;
13795   bool AllAnyExt = true;
13796 
13797   for (unsigned i = 0; i != NumInScalars; ++i) {
13798     SDValue In = N->getOperand(i);
13799     // Ignore undef inputs.
13800     if (In.isUndef()) continue;
13801 
13802     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13803     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13804 
13805     // Abort if the element is not an extension.
13806     if (!ZeroExt && !AnyExt) {
13807       SourceType = MVT::Other;
13808       break;
13809     }
13810 
13811     // The input is a ZeroExt or AnyExt. Check the original type.
13812     EVT InTy = In.getOperand(0).getValueType();
13813 
13814     // Check that all of the widened source types are the same.
13815     if (SourceType == MVT::Other)
13816       // First time.
13817       SourceType = InTy;
13818     else if (InTy != SourceType) {
13819       // Multiple income types. Abort.
13820       SourceType = MVT::Other;
13821       break;
13822     }
13823 
13824     // Check if all of the extends are ANY_EXTENDs.
13825     AllAnyExt &= AnyExt;
13826   }
13827 
13828   // In order to have valid types, all of the inputs must be extended from the
13829   // same source type and all of the inputs must be any or zero extend.
13830   // Scalar sizes must be a power of two.
13831   EVT OutScalarTy = VT.getScalarType();
13832   bool ValidTypes = SourceType != MVT::Other &&
13833                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13834                  isPowerOf2_32(SourceType.getSizeInBits());
13835 
13836   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13837   // turn into a single shuffle instruction.
13838   if (!ValidTypes)
13839     return SDValue();
13840 
13841   bool isLE = DAG.getDataLayout().isLittleEndian();
13842   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13843   assert(ElemRatio > 1 && "Invalid element size ratio");
13844   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13845                                DAG.getConstant(0, DL, SourceType);
13846 
13847   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13848   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13849 
13850   // Populate the new build_vector
13851   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13852     SDValue Cast = N->getOperand(i);
13853     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13854             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13855             Cast.isUndef()) && "Invalid cast opcode");
13856     SDValue In;
13857     if (Cast.isUndef())
13858       In = DAG.getUNDEF(SourceType);
13859     else
13860       In = Cast->getOperand(0);
13861     unsigned Index = isLE ? (i * ElemRatio) :
13862                             (i * ElemRatio + (ElemRatio - 1));
13863 
13864     assert(Index < Ops.size() && "Invalid index");
13865     Ops[Index] = In;
13866   }
13867 
13868   // The type of the new BUILD_VECTOR node.
13869   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13870   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13871          "Invalid vector size");
13872   // Check if the new vector type is legal.
13873   if (!isTypeLegal(VecVT)) return SDValue();
13874 
13875   // Make the new BUILD_VECTOR.
13876   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13877 
13878   // The new BUILD_VECTOR node has the potential to be further optimized.
13879   AddToWorklist(BV.getNode());
13880   // Bitcast to the desired type.
13881   return DAG.getBitcast(VT, BV);
13882 }
13883 
13884 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13885   EVT VT = N->getValueType(0);
13886 
13887   unsigned NumInScalars = N->getNumOperands();
13888   SDLoc DL(N);
13889 
13890   EVT SrcVT = MVT::Other;
13891   unsigned Opcode = ISD::DELETED_NODE;
13892   unsigned NumDefs = 0;
13893 
13894   for (unsigned i = 0; i != NumInScalars; ++i) {
13895     SDValue In = N->getOperand(i);
13896     unsigned Opc = In.getOpcode();
13897 
13898     if (Opc == ISD::UNDEF)
13899       continue;
13900 
13901     // If all scalar values are floats and converted from integers.
13902     if (Opcode == ISD::DELETED_NODE &&
13903         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13904       Opcode = Opc;
13905     }
13906 
13907     if (Opc != Opcode)
13908       return SDValue();
13909 
13910     EVT InVT = In.getOperand(0).getValueType();
13911 
13912     // If all scalar values are typed differently, bail out. It's chosen to
13913     // simplify BUILD_VECTOR of integer types.
13914     if (SrcVT == MVT::Other)
13915       SrcVT = InVT;
13916     if (SrcVT != InVT)
13917       return SDValue();
13918     NumDefs++;
13919   }
13920 
13921   // If the vector has just one element defined, it's not worth to fold it into
13922   // a vectorized one.
13923   if (NumDefs < 2)
13924     return SDValue();
13925 
13926   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13927          && "Should only handle conversion from integer to float.");
13928   assert(SrcVT != MVT::Other && "Cannot determine source type!");
13929 
13930   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13931 
13932   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13933     return SDValue();
13934 
13935   // Just because the floating-point vector type is legal does not necessarily
13936   // mean that the corresponding integer vector type is.
13937   if (!isTypeLegal(NVT))
13938     return SDValue();
13939 
13940   SmallVector<SDValue, 8> Opnds;
13941   for (unsigned i = 0; i != NumInScalars; ++i) {
13942     SDValue In = N->getOperand(i);
13943 
13944     if (In.isUndef())
13945       Opnds.push_back(DAG.getUNDEF(SrcVT));
13946     else
13947       Opnds.push_back(In.getOperand(0));
13948   }
13949   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13950   AddToWorklist(BV.getNode());
13951 
13952   return DAG.getNode(Opcode, DL, VT, BV);
13953 }
13954 
13955 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13956                                            ArrayRef<int> VectorMask,
13957                                            SDValue VecIn1, SDValue VecIn2,
13958                                            unsigned LeftIdx) {
13959   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13960   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13961 
13962   EVT VT = N->getValueType(0);
13963   EVT InVT1 = VecIn1.getValueType();
13964   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13965 
13966   unsigned Vec2Offset = InVT1.getVectorNumElements();
13967   unsigned NumElems = VT.getVectorNumElements();
13968   unsigned ShuffleNumElems = NumElems;
13969 
13970   // We can't generate a shuffle node with mismatched input and output types.
13971   // Try to make the types match the type of the output.
13972   if (InVT1 != VT || InVT2 != VT) {
13973     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13974       // If the output vector length is a multiple of both input lengths,
13975       // we can concatenate them and pad the rest with undefs.
13976       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13977       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13978       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13979       ConcatOps[0] = VecIn1;
13980       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13981       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13982       VecIn2 = SDValue();
13983     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13984       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13985         return SDValue();
13986 
13987       if (!VecIn2.getNode()) {
13988         // If we only have one input vector, and it's twice the size of the
13989         // output, split it in two.
13990         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13991                              DAG.getConstant(NumElems, DL, IdxTy));
13992         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13993         // Since we now have shorter input vectors, adjust the offset of the
13994         // second vector's start.
13995         Vec2Offset = NumElems;
13996       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13997         // VecIn1 is wider than the output, and we have another, possibly
13998         // smaller input. Pad the smaller input with undefs, shuffle at the
13999         // input vector width, and extract the output.
14000         // The shuffle type is different than VT, so check legality again.
14001         if (LegalOperations &&
14002             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14003           return SDValue();
14004 
14005         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14006         // lower it back into a BUILD_VECTOR. So if the inserted type is
14007         // illegal, don't even try.
14008         if (InVT1 != InVT2) {
14009           if (!TLI.isTypeLegal(InVT2))
14010             return SDValue();
14011           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14012                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14013         }
14014         ShuffleNumElems = NumElems * 2;
14015       } else {
14016         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14017         // than VecIn1. We can't handle this for now - this case will disappear
14018         // when we start sorting the vectors by type.
14019         return SDValue();
14020       }
14021     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14022                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14023       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14024       ConcatOps[0] = VecIn2;
14025       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14026     } else {
14027       // TODO: Support cases where the length mismatch isn't exactly by a
14028       // factor of 2.
14029       // TODO: Move this check upwards, so that if we have bad type
14030       // mismatches, we don't create any DAG nodes.
14031       return SDValue();
14032     }
14033   }
14034 
14035   // Initialize mask to undef.
14036   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14037 
14038   // Only need to run up to the number of elements actually used, not the
14039   // total number of elements in the shuffle - if we are shuffling a wider
14040   // vector, the high lanes should be set to undef.
14041   for (unsigned i = 0; i != NumElems; ++i) {
14042     if (VectorMask[i] <= 0)
14043       continue;
14044 
14045     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14046     if (VectorMask[i] == (int)LeftIdx) {
14047       Mask[i] = ExtIndex;
14048     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14049       Mask[i] = Vec2Offset + ExtIndex;
14050     }
14051   }
14052 
14053   // The type the input vectors may have changed above.
14054   InVT1 = VecIn1.getValueType();
14055 
14056   // If we already have a VecIn2, it should have the same type as VecIn1.
14057   // If we don't, get an undef/zero vector of the appropriate type.
14058   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14059   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14060 
14061   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14062   if (ShuffleNumElems > NumElems)
14063     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14064 
14065   return Shuffle;
14066 }
14067 
14068 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14069 // operations. If the types of the vectors we're extracting from allow it,
14070 // turn this into a vector_shuffle node.
14071 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14072   SDLoc DL(N);
14073   EVT VT = N->getValueType(0);
14074 
14075   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14076   if (!isTypeLegal(VT))
14077     return SDValue();
14078 
14079   // May only combine to shuffle after legalize if shuffle is legal.
14080   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14081     return SDValue();
14082 
14083   bool UsesZeroVector = false;
14084   unsigned NumElems = N->getNumOperands();
14085 
14086   // Record, for each element of the newly built vector, which input vector
14087   // that element comes from. -1 stands for undef, 0 for the zero vector,
14088   // and positive values for the input vectors.
14089   // VectorMask maps each element to its vector number, and VecIn maps vector
14090   // numbers to their initial SDValues.
14091 
14092   SmallVector<int, 8> VectorMask(NumElems, -1);
14093   SmallVector<SDValue, 8> VecIn;
14094   VecIn.push_back(SDValue());
14095 
14096   for (unsigned i = 0; i != NumElems; ++i) {
14097     SDValue Op = N->getOperand(i);
14098 
14099     if (Op.isUndef())
14100       continue;
14101 
14102     // See if we can use a blend with a zero vector.
14103     // TODO: Should we generalize this to a blend with an arbitrary constant
14104     // vector?
14105     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14106       UsesZeroVector = true;
14107       VectorMask[i] = 0;
14108       continue;
14109     }
14110 
14111     // Not an undef or zero. If the input is something other than an
14112     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14113     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14114         !isa<ConstantSDNode>(Op.getOperand(1)))
14115       return SDValue();
14116 
14117     SDValue ExtractedFromVec = Op.getOperand(0);
14118 
14119     // All inputs must have the same element type as the output.
14120     if (VT.getVectorElementType() !=
14121         ExtractedFromVec.getValueType().getVectorElementType())
14122       return SDValue();
14123 
14124     // Have we seen this input vector before?
14125     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14126     // a map back from SDValues to numbers isn't worth it.
14127     unsigned Idx = std::distance(
14128         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14129     if (Idx == VecIn.size())
14130       VecIn.push_back(ExtractedFromVec);
14131 
14132     VectorMask[i] = Idx;
14133   }
14134 
14135   // If we didn't find at least one input vector, bail out.
14136   if (VecIn.size() < 2)
14137     return SDValue();
14138 
14139   // TODO: We want to sort the vectors by descending length, so that adjacent
14140   // pairs have similar length, and the longer vector is always first in the
14141   // pair.
14142 
14143   // TODO: Should this fire if some of the input vectors has illegal type (like
14144   // it does now), or should we let legalization run its course first?
14145 
14146   // Shuffle phase:
14147   // Take pairs of vectors, and shuffle them so that the result has elements
14148   // from these vectors in the correct places.
14149   // For example, given:
14150   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14151   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14152   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14153   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14154   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14155   // We will generate:
14156   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14157   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14158   SmallVector<SDValue, 4> Shuffles;
14159   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14160     unsigned LeftIdx = 2 * In + 1;
14161     SDValue VecLeft = VecIn[LeftIdx];
14162     SDValue VecRight =
14163         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14164 
14165     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14166                                                 VecRight, LeftIdx))
14167       Shuffles.push_back(Shuffle);
14168     else
14169       return SDValue();
14170   }
14171 
14172   // If we need the zero vector as an "ingredient" in the blend tree, add it
14173   // to the list of shuffles.
14174   if (UsesZeroVector)
14175     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14176                                       : DAG.getConstantFP(0.0, DL, VT));
14177 
14178   // If we only have one shuffle, we're done.
14179   if (Shuffles.size() == 1)
14180     return Shuffles[0];
14181 
14182   // Update the vector mask to point to the post-shuffle vectors.
14183   for (int &Vec : VectorMask)
14184     if (Vec == 0)
14185       Vec = Shuffles.size() - 1;
14186     else
14187       Vec = (Vec - 1) / 2;
14188 
14189   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14190   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14191   // generate:
14192   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14193   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14194   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14195   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14196   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14197   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14198   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14199 
14200   // Make sure the initial size of the shuffle list is even.
14201   if (Shuffles.size() % 2)
14202     Shuffles.push_back(DAG.getUNDEF(VT));
14203 
14204   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14205     if (CurSize % 2) {
14206       Shuffles[CurSize] = DAG.getUNDEF(VT);
14207       CurSize++;
14208     }
14209     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14210       int Left = 2 * In;
14211       int Right = 2 * In + 1;
14212       SmallVector<int, 8> Mask(NumElems, -1);
14213       for (unsigned i = 0; i != NumElems; ++i) {
14214         if (VectorMask[i] == Left) {
14215           Mask[i] = i;
14216           VectorMask[i] = In;
14217         } else if (VectorMask[i] == Right) {
14218           Mask[i] = i + NumElems;
14219           VectorMask[i] = In;
14220         }
14221       }
14222 
14223       Shuffles[In] =
14224           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14225     }
14226   }
14227 
14228   return Shuffles[0];
14229 }
14230 
14231 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14232   EVT VT = N->getValueType(0);
14233 
14234   // A vector built entirely of undefs is undef.
14235   if (ISD::allOperandsUndef(N))
14236     return DAG.getUNDEF(VT);
14237 
14238   // Check if we can express BUILD VECTOR via subvector extract.
14239   if (!LegalTypes && (N->getNumOperands() > 1)) {
14240     SDValue Op0 = N->getOperand(0);
14241     auto checkElem = [&](SDValue Op) -> uint64_t {
14242       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14243           (Op0.getOperand(0) == Op.getOperand(0)))
14244         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14245           return CNode->getZExtValue();
14246       return -1;
14247     };
14248 
14249     int Offset = checkElem(Op0);
14250     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14251       if (Offset + i != checkElem(N->getOperand(i))) {
14252         Offset = -1;
14253         break;
14254       }
14255     }
14256 
14257     if ((Offset == 0) &&
14258         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14259       return Op0.getOperand(0);
14260     if ((Offset != -1) &&
14261         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14262          0)) // IDX must be multiple of output size.
14263       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14264                          Op0.getOperand(0), Op0.getOperand(1));
14265   }
14266 
14267   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14268     return V;
14269 
14270   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14271     return V;
14272 
14273   if (SDValue V = reduceBuildVecToShuffle(N))
14274     return V;
14275 
14276   return SDValue();
14277 }
14278 
14279 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14280   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14281   EVT OpVT = N->getOperand(0).getValueType();
14282 
14283   // If the operands are legal vectors, leave them alone.
14284   if (TLI.isTypeLegal(OpVT))
14285     return SDValue();
14286 
14287   SDLoc DL(N);
14288   EVT VT = N->getValueType(0);
14289   SmallVector<SDValue, 8> Ops;
14290 
14291   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14292   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14293 
14294   // Keep track of what we encounter.
14295   bool AnyInteger = false;
14296   bool AnyFP = false;
14297   for (const SDValue &Op : N->ops()) {
14298     if (ISD::BITCAST == Op.getOpcode() &&
14299         !Op.getOperand(0).getValueType().isVector())
14300       Ops.push_back(Op.getOperand(0));
14301     else if (ISD::UNDEF == Op.getOpcode())
14302       Ops.push_back(ScalarUndef);
14303     else
14304       return SDValue();
14305 
14306     // Note whether we encounter an integer or floating point scalar.
14307     // If it's neither, bail out, it could be something weird like x86mmx.
14308     EVT LastOpVT = Ops.back().getValueType();
14309     if (LastOpVT.isFloatingPoint())
14310       AnyFP = true;
14311     else if (LastOpVT.isInteger())
14312       AnyInteger = true;
14313     else
14314       return SDValue();
14315   }
14316 
14317   // If any of the operands is a floating point scalar bitcast to a vector,
14318   // use floating point types throughout, and bitcast everything.
14319   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14320   if (AnyFP) {
14321     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14322     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14323     if (AnyInteger) {
14324       for (SDValue &Op : Ops) {
14325         if (Op.getValueType() == SVT)
14326           continue;
14327         if (Op.isUndef())
14328           Op = ScalarUndef;
14329         else
14330           Op = DAG.getBitcast(SVT, Op);
14331       }
14332     }
14333   }
14334 
14335   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14336                                VT.getSizeInBits() / SVT.getSizeInBits());
14337   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14338 }
14339 
14340 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14341 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14342 // most two distinct vectors the same size as the result, attempt to turn this
14343 // into a legal shuffle.
14344 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14345   EVT VT = N->getValueType(0);
14346   EVT OpVT = N->getOperand(0).getValueType();
14347   int NumElts = VT.getVectorNumElements();
14348   int NumOpElts = OpVT.getVectorNumElements();
14349 
14350   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14351   SmallVector<int, 8> Mask;
14352 
14353   for (SDValue Op : N->ops()) {
14354     // Peek through any bitcast.
14355     while (Op.getOpcode() == ISD::BITCAST)
14356       Op = Op.getOperand(0);
14357 
14358     // UNDEF nodes convert to UNDEF shuffle mask values.
14359     if (Op.isUndef()) {
14360       Mask.append((unsigned)NumOpElts, -1);
14361       continue;
14362     }
14363 
14364     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14365       return SDValue();
14366 
14367     // What vector are we extracting the subvector from and at what index?
14368     SDValue ExtVec = Op.getOperand(0);
14369 
14370     // We want the EVT of the original extraction to correctly scale the
14371     // extraction index.
14372     EVT ExtVT = ExtVec.getValueType();
14373 
14374     // Peek through any bitcast.
14375     while (ExtVec.getOpcode() == ISD::BITCAST)
14376       ExtVec = ExtVec.getOperand(0);
14377 
14378     // UNDEF nodes convert to UNDEF shuffle mask values.
14379     if (ExtVec.isUndef()) {
14380       Mask.append((unsigned)NumOpElts, -1);
14381       continue;
14382     }
14383 
14384     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14385       return SDValue();
14386     int ExtIdx = Op.getConstantOperandVal(1);
14387 
14388     // Ensure that we are extracting a subvector from a vector the same
14389     // size as the result.
14390     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14391       return SDValue();
14392 
14393     // Scale the subvector index to account for any bitcast.
14394     int NumExtElts = ExtVT.getVectorNumElements();
14395     if (0 == (NumExtElts % NumElts))
14396       ExtIdx /= (NumExtElts / NumElts);
14397     else if (0 == (NumElts % NumExtElts))
14398       ExtIdx *= (NumElts / NumExtElts);
14399     else
14400       return SDValue();
14401 
14402     // At most we can reference 2 inputs in the final shuffle.
14403     if (SV0.isUndef() || SV0 == ExtVec) {
14404       SV0 = ExtVec;
14405       for (int i = 0; i != NumOpElts; ++i)
14406         Mask.push_back(i + ExtIdx);
14407     } else if (SV1.isUndef() || SV1 == ExtVec) {
14408       SV1 = ExtVec;
14409       for (int i = 0; i != NumOpElts; ++i)
14410         Mask.push_back(i + ExtIdx + NumElts);
14411     } else {
14412       return SDValue();
14413     }
14414   }
14415 
14416   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14417     return SDValue();
14418 
14419   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14420                               DAG.getBitcast(VT, SV1), Mask);
14421 }
14422 
14423 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14424   // If we only have one input vector, we don't need to do any concatenation.
14425   if (N->getNumOperands() == 1)
14426     return N->getOperand(0);
14427 
14428   // Check if all of the operands are undefs.
14429   EVT VT = N->getValueType(0);
14430   if (ISD::allOperandsUndef(N))
14431     return DAG.getUNDEF(VT);
14432 
14433   // Optimize concat_vectors where all but the first of the vectors are undef.
14434   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14435         return Op.isUndef();
14436       })) {
14437     SDValue In = N->getOperand(0);
14438     assert(In.getValueType().isVector() && "Must concat vectors");
14439 
14440     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14441     if (In->getOpcode() == ISD::BITCAST &&
14442         !In->getOperand(0)->getValueType(0).isVector()) {
14443       SDValue Scalar = In->getOperand(0);
14444 
14445       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14446       // look through the trunc so we can still do the transform:
14447       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14448       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14449           !TLI.isTypeLegal(Scalar.getValueType()) &&
14450           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14451         Scalar = Scalar->getOperand(0);
14452 
14453       EVT SclTy = Scalar->getValueType(0);
14454 
14455       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14456         return SDValue();
14457 
14458       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14459       if (VNTNumElms < 2)
14460         return SDValue();
14461 
14462       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14463       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14464         return SDValue();
14465 
14466       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14467       return DAG.getBitcast(VT, Res);
14468     }
14469   }
14470 
14471   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14472   // We have already tested above for an UNDEF only concatenation.
14473   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14474   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14475   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14476     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14477   };
14478   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14479     SmallVector<SDValue, 8> Opnds;
14480     EVT SVT = VT.getScalarType();
14481 
14482     EVT MinVT = SVT;
14483     if (!SVT.isFloatingPoint()) {
14484       // If BUILD_VECTOR are from built from integer, they may have different
14485       // operand types. Get the smallest type and truncate all operands to it.
14486       bool FoundMinVT = false;
14487       for (const SDValue &Op : N->ops())
14488         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14489           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14490           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14491           FoundMinVT = true;
14492         }
14493       assert(FoundMinVT && "Concat vector type mismatch");
14494     }
14495 
14496     for (const SDValue &Op : N->ops()) {
14497       EVT OpVT = Op.getValueType();
14498       unsigned NumElts = OpVT.getVectorNumElements();
14499 
14500       if (ISD::UNDEF == Op.getOpcode())
14501         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14502 
14503       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14504         if (SVT.isFloatingPoint()) {
14505           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14506           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14507         } else {
14508           for (unsigned i = 0; i != NumElts; ++i)
14509             Opnds.push_back(
14510                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14511         }
14512       }
14513     }
14514 
14515     assert(VT.getVectorNumElements() == Opnds.size() &&
14516            "Concat vector type mismatch");
14517     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14518   }
14519 
14520   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14521   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14522     return V;
14523 
14524   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14525   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14526     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14527       return V;
14528 
14529   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14530   // nodes often generate nop CONCAT_VECTOR nodes.
14531   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14532   // place the incoming vectors at the exact same location.
14533   SDValue SingleSource = SDValue();
14534   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14535 
14536   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14537     SDValue Op = N->getOperand(i);
14538 
14539     if (Op.isUndef())
14540       continue;
14541 
14542     // Check if this is the identity extract:
14543     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14544       return SDValue();
14545 
14546     // Find the single incoming vector for the extract_subvector.
14547     if (SingleSource.getNode()) {
14548       if (Op.getOperand(0) != SingleSource)
14549         return SDValue();
14550     } else {
14551       SingleSource = Op.getOperand(0);
14552 
14553       // Check the source type is the same as the type of the result.
14554       // If not, this concat may extend the vector, so we can not
14555       // optimize it away.
14556       if (SingleSource.getValueType() != N->getValueType(0))
14557         return SDValue();
14558     }
14559 
14560     unsigned IdentityIndex = i * PartNumElem;
14561     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14562     // The extract index must be constant.
14563     if (!CS)
14564       return SDValue();
14565 
14566     // Check that we are reading from the identity index.
14567     if (CS->getZExtValue() != IdentityIndex)
14568       return SDValue();
14569   }
14570 
14571   if (SingleSource.getNode())
14572     return SingleSource;
14573 
14574   return SDValue();
14575 }
14576 
14577 /// If we are extracting a subvector produced by a wide binary operator with at
14578 /// at least one operand that was the result of a vector concatenation, then try
14579 /// to use the narrow vector operands directly to avoid the concatenation and
14580 /// extraction.
14581 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
14582   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
14583   // some of these bailouts with other transforms.
14584 
14585   // The extract index must be a constant, so we can map it to a concat operand.
14586   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14587   if (!ExtractIndex)
14588     return SDValue();
14589 
14590   // Only handle the case where we are doubling and then halving. A larger ratio
14591   // may require more than two narrow binops to replace the wide binop.
14592   EVT VT = Extract->getValueType(0);
14593   unsigned NumElems = VT.getVectorNumElements();
14594   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
14595          "Extract index is not a multiple of the vector length.");
14596   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
14597     return SDValue();
14598 
14599   // We are looking for an optionally bitcasted wide vector binary operator
14600   // feeding an extract subvector.
14601   SDValue BinOp = Extract->getOperand(0);
14602   if (BinOp.getOpcode() == ISD::BITCAST)
14603     BinOp = BinOp.getOperand(0);
14604 
14605   // TODO: The motivating case for this transform is an x86 AVX1 target. That
14606   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
14607   // flavors, but no other 256-bit integer support. This could be extended to
14608   // handle any binop, but that may require fixing/adding other folds to avoid
14609   // codegen regressions.
14610   unsigned BOpcode = BinOp.getOpcode();
14611   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
14612     return SDValue();
14613 
14614   // The binop must be a vector type, so we can chop it in half.
14615   EVT WideBVT = BinOp.getValueType();
14616   if (!WideBVT.isVector())
14617     return SDValue();
14618 
14619   // Bail out if the target does not support a narrower version of the binop.
14620   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
14621                                    WideBVT.getVectorNumElements() / 2);
14622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14623   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
14624     return SDValue();
14625 
14626   // Peek through bitcasts of the binary operator operands if needed.
14627   SDValue LHS = BinOp.getOperand(0);
14628   if (LHS.getOpcode() == ISD::BITCAST)
14629     LHS = LHS.getOperand(0);
14630 
14631   SDValue RHS = BinOp.getOperand(1);
14632   if (RHS.getOpcode() == ISD::BITCAST)
14633     RHS = RHS.getOperand(0);
14634 
14635   // We need at least one concatenation operation of a binop operand to make
14636   // this transform worthwhile. The concat must double the input vector sizes.
14637   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
14638   bool ConcatL =
14639       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
14640   bool ConcatR =
14641       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
14642   if (!ConcatL && !ConcatR)
14643     return SDValue();
14644 
14645   // If one of the binop operands was not the result of a concat, we must
14646   // extract a half-sized operand for our new narrow binop. We can't just reuse
14647   // the original extract index operand because we may have bitcasted.
14648   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
14649   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
14650   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
14651   SDLoc DL(Extract);
14652 
14653   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
14654   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
14655   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
14656   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
14657                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14658                                     BinOp.getOperand(0),
14659                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14660 
14661   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
14662                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14663                                     BinOp.getOperand(1),
14664                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14665 
14666   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
14667   return DAG.getBitcast(VT, NarrowBinOp);
14668 }
14669 
14670 /// If we are extracting a subvector from a wide vector load, convert to a
14671 /// narrow load to eliminate the extraction:
14672 /// (extract_subvector (load wide vector)) --> (load narrow vector)
14673 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
14674   // TODO: Add support for big-endian. The offset calculation must be adjusted.
14675   if (DAG.getDataLayout().isBigEndian())
14676     return SDValue();
14677 
14678   // TODO: The one-use check is overly conservative. Check the cost of the
14679   // extract instead or remove that condition entirely.
14680   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
14681   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14682   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
14683       !ExtIdx)
14684     return SDValue();
14685 
14686   // The narrow load will be offset from the base address of the old load if
14687   // we are extracting from something besides index 0 (little-endian).
14688   EVT VT = Extract->getValueType(0);
14689   SDLoc DL(Extract);
14690   SDValue BaseAddr = Ld->getOperand(1);
14691   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
14692 
14693   // TODO: Use "BaseIndexOffset" to make this more effective.
14694   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
14695   MachineFunction &MF = DAG.getMachineFunction();
14696   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
14697                                                    VT.getStoreSize());
14698   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
14699   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
14700   return NewLd;
14701 }
14702 
14703 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14704   EVT NVT = N->getValueType(0);
14705   SDValue V = N->getOperand(0);
14706 
14707   // Extract from UNDEF is UNDEF.
14708   if (V.isUndef())
14709     return DAG.getUNDEF(NVT);
14710 
14711   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
14712     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
14713       return NarrowLoad;
14714 
14715   // Combine:
14716   //    (extract_subvec (concat V1, V2, ...), i)
14717   // Into:
14718   //    Vi if possible
14719   // Only operand 0 is checked as 'concat' assumes all inputs of the same
14720   // type.
14721   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14722       isa<ConstantSDNode>(N->getOperand(1)) &&
14723       V->getOperand(0).getValueType() == NVT) {
14724     unsigned Idx = N->getConstantOperandVal(1);
14725     unsigned NumElems = NVT.getVectorNumElements();
14726     assert((Idx % NumElems) == 0 &&
14727            "IDX in concat is not a multiple of the result vector length.");
14728     return V->getOperand(Idx / NumElems);
14729   }
14730 
14731   // Skip bitcasting
14732   if (V->getOpcode() == ISD::BITCAST)
14733     V = V.getOperand(0);
14734 
14735   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14736     // Handle only simple case where vector being inserted and vector
14737     // being extracted are of same size.
14738     EVT SmallVT = V->getOperand(1).getValueType();
14739     if (!NVT.bitsEq(SmallVT))
14740       return SDValue();
14741 
14742     // Only handle cases where both indexes are constants.
14743     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14744     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14745 
14746     if (InsIdx && ExtIdx) {
14747       // Combine:
14748       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14749       // Into:
14750       //    indices are equal or bit offsets are equal => V1
14751       //    otherwise => (extract_subvec V1, ExtIdx)
14752       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14753           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14754         return DAG.getBitcast(NVT, V->getOperand(1));
14755       return DAG.getNode(
14756           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14757           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14758           N->getOperand(1));
14759     }
14760   }
14761 
14762   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
14763     return NarrowBOp;
14764 
14765   return SDValue();
14766 }
14767 
14768 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14769                                                  SDValue V, SelectionDAG &DAG) {
14770   SDLoc DL(V);
14771   EVT VT = V.getValueType();
14772 
14773   switch (V.getOpcode()) {
14774   default:
14775     return V;
14776 
14777   case ISD::CONCAT_VECTORS: {
14778     EVT OpVT = V->getOperand(0).getValueType();
14779     int OpSize = OpVT.getVectorNumElements();
14780     SmallBitVector OpUsedElements(OpSize, false);
14781     bool FoundSimplification = false;
14782     SmallVector<SDValue, 4> NewOps;
14783     NewOps.reserve(V->getNumOperands());
14784     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14785       SDValue Op = V->getOperand(i);
14786       bool OpUsed = false;
14787       for (int j = 0; j < OpSize; ++j)
14788         if (UsedElements[i * OpSize + j]) {
14789           OpUsedElements[j] = true;
14790           OpUsed = true;
14791         }
14792       NewOps.push_back(
14793           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14794                  : DAG.getUNDEF(OpVT));
14795       FoundSimplification |= Op == NewOps.back();
14796       OpUsedElements.reset();
14797     }
14798     if (FoundSimplification)
14799       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14800     return V;
14801   }
14802 
14803   case ISD::INSERT_SUBVECTOR: {
14804     SDValue BaseV = V->getOperand(0);
14805     SDValue SubV = V->getOperand(1);
14806     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14807     if (!IdxN)
14808       return V;
14809 
14810     int SubSize = SubV.getValueType().getVectorNumElements();
14811     int Idx = IdxN->getZExtValue();
14812     bool SubVectorUsed = false;
14813     SmallBitVector SubUsedElements(SubSize, false);
14814     for (int i = 0; i < SubSize; ++i)
14815       if (UsedElements[i + Idx]) {
14816         SubVectorUsed = true;
14817         SubUsedElements[i] = true;
14818         UsedElements[i + Idx] = false;
14819       }
14820 
14821     // Now recurse on both the base and sub vectors.
14822     SDValue SimplifiedSubV =
14823         SubVectorUsed
14824             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14825             : DAG.getUNDEF(SubV.getValueType());
14826     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14827     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14828       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14829                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14830     return V;
14831   }
14832   }
14833 }
14834 
14835 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14836                                        SDValue N1, SelectionDAG &DAG) {
14837   EVT VT = SVN->getValueType(0);
14838   int NumElts = VT.getVectorNumElements();
14839   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14840   for (int M : SVN->getMask())
14841     if (M >= 0 && M < NumElts)
14842       N0UsedElements[M] = true;
14843     else if (M >= NumElts)
14844       N1UsedElements[M - NumElts] = true;
14845 
14846   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14847   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14848   if (S0 == N0 && S1 == N1)
14849     return SDValue();
14850 
14851   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14852 }
14853 
14854 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14855 // or turn a shuffle of a single concat into simpler shuffle then concat.
14856 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14857   EVT VT = N->getValueType(0);
14858   unsigned NumElts = VT.getVectorNumElements();
14859 
14860   SDValue N0 = N->getOperand(0);
14861   SDValue N1 = N->getOperand(1);
14862   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14863 
14864   SmallVector<SDValue, 4> Ops;
14865   EVT ConcatVT = N0.getOperand(0).getValueType();
14866   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14867   unsigned NumConcats = NumElts / NumElemsPerConcat;
14868 
14869   // Special case: shuffle(concat(A,B)) can be more efficiently represented
14870   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14871   // half vector elements.
14872   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14873       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14874                   SVN->getMask().end(), [](int i) { return i == -1; })) {
14875     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14876                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14877     N1 = DAG.getUNDEF(ConcatVT);
14878     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14879   }
14880 
14881   // Look at every vector that's inserted. We're looking for exact
14882   // subvector-sized copies from a concatenated vector
14883   for (unsigned I = 0; I != NumConcats; ++I) {
14884     // Make sure we're dealing with a copy.
14885     unsigned Begin = I * NumElemsPerConcat;
14886     bool AllUndef = true, NoUndef = true;
14887     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14888       if (SVN->getMaskElt(J) >= 0)
14889         AllUndef = false;
14890       else
14891         NoUndef = false;
14892     }
14893 
14894     if (NoUndef) {
14895       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14896         return SDValue();
14897 
14898       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14899         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14900           return SDValue();
14901 
14902       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14903       if (FirstElt < N0.getNumOperands())
14904         Ops.push_back(N0.getOperand(FirstElt));
14905       else
14906         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14907 
14908     } else if (AllUndef) {
14909       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14910     } else { // Mixed with general masks and undefs, can't do optimization.
14911       return SDValue();
14912     }
14913   }
14914 
14915   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14916 }
14917 
14918 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14919 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14920 //
14921 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14922 // a simplification in some sense, but it isn't appropriate in general: some
14923 // BUILD_VECTORs are substantially cheaper than others. The general case
14924 // of a BUILD_VECTOR requires inserting each element individually (or
14925 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14926 // all constants is a single constant pool load.  A BUILD_VECTOR where each
14927 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
14928 // are undef lowers to a small number of element insertions.
14929 //
14930 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14931 // We don't fold shuffles where one side is a non-zero constant, and we don't
14932 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14933 // non-constant operands. This seems to work out reasonably well in practice.
14934 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14935                                        SelectionDAG &DAG,
14936                                        const TargetLowering &TLI) {
14937   EVT VT = SVN->getValueType(0);
14938   unsigned NumElts = VT.getVectorNumElements();
14939   SDValue N0 = SVN->getOperand(0);
14940   SDValue N1 = SVN->getOperand(1);
14941 
14942   if (!N0->hasOneUse() || !N1->hasOneUse())
14943     return SDValue();
14944   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14945   // discussed above.
14946   if (!N1.isUndef()) {
14947     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14948     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14949     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14950       return SDValue();
14951     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14952       return SDValue();
14953   }
14954 
14955   SmallVector<SDValue, 8> Ops;
14956   SmallSet<SDValue, 16> DuplicateOps;
14957   for (int M : SVN->getMask()) {
14958     SDValue Op = DAG.getUNDEF(VT.getScalarType());
14959     if (M >= 0) {
14960       int Idx = M < (int)NumElts ? M : M - NumElts;
14961       SDValue &S = (M < (int)NumElts ? N0 : N1);
14962       if (S.getOpcode() == ISD::BUILD_VECTOR) {
14963         Op = S.getOperand(Idx);
14964       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14965         if (Idx == 0)
14966           Op = S.getOperand(0);
14967       } else {
14968         // Operand can't be combined - bail out.
14969         return SDValue();
14970       }
14971     }
14972 
14973     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14974     // fine, but it's likely to generate low-quality code if the target can't
14975     // reconstruct an appropriate shuffle.
14976     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14977       if (!DuplicateOps.insert(Op).second)
14978         return SDValue();
14979 
14980     Ops.push_back(Op);
14981   }
14982   // BUILD_VECTOR requires all inputs to be of the same type, find the
14983   // maximum type and extend them all.
14984   EVT SVT = VT.getScalarType();
14985   if (SVT.isInteger())
14986     for (SDValue &Op : Ops)
14987       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14988   if (SVT != VT.getScalarType())
14989     for (SDValue &Op : Ops)
14990       Op = TLI.isZExtFree(Op.getValueType(), SVT)
14991                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14992                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14993   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14994 }
14995 
14996 // Match shuffles that can be converted to any_vector_extend_in_reg.
14997 // This is often generated during legalization.
14998 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14999 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15000 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15001                                             SelectionDAG &DAG,
15002                                             const TargetLowering &TLI,
15003                                             bool LegalOperations) {
15004   EVT VT = SVN->getValueType(0);
15005   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15006 
15007   // TODO Add support for big-endian when we have a test case.
15008   if (!VT.isInteger() || IsBigEndian)
15009     return SDValue();
15010 
15011   unsigned NumElts = VT.getVectorNumElements();
15012   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15013   ArrayRef<int> Mask = SVN->getMask();
15014   SDValue N0 = SVN->getOperand(0);
15015 
15016   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15017   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15018     for (unsigned i = 0; i != NumElts; ++i) {
15019       if (Mask[i] < 0)
15020         continue;
15021       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15022         continue;
15023       return false;
15024     }
15025     return true;
15026   };
15027 
15028   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15029   // power-of-2 extensions as they are the most likely.
15030   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15031     if (!isAnyExtend(Scale))
15032       continue;
15033 
15034     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15035     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15036     if (!LegalOperations ||
15037         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15038       return DAG.getBitcast(VT,
15039                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15040   }
15041 
15042   return SDValue();
15043 }
15044 
15045 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15046 // each source element of a large type into the lowest elements of a smaller
15047 // destination type. This is often generated during legalization.
15048 // If the source node itself was a '*_extend_vector_inreg' node then we should
15049 // then be able to remove it.
15050 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15051                                         SelectionDAG &DAG) {
15052   EVT VT = SVN->getValueType(0);
15053   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15054 
15055   // TODO Add support for big-endian when we have a test case.
15056   if (!VT.isInteger() || IsBigEndian)
15057     return SDValue();
15058 
15059   SDValue N0 = SVN->getOperand(0);
15060   while (N0.getOpcode() == ISD::BITCAST)
15061     N0 = N0.getOperand(0);
15062 
15063   unsigned Opcode = N0.getOpcode();
15064   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15065       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15066       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15067     return SDValue();
15068 
15069   SDValue N00 = N0.getOperand(0);
15070   ArrayRef<int> Mask = SVN->getMask();
15071   unsigned NumElts = VT.getVectorNumElements();
15072   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15073   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15074   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15075 
15076   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15077     return SDValue();
15078   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15079 
15080   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15081   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15082   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15083   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15084     for (unsigned i = 0; i != NumElts; ++i) {
15085       if (Mask[i] < 0)
15086         continue;
15087       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15088         continue;
15089       return false;
15090     }
15091     return true;
15092   };
15093 
15094   // At the moment we just handle the case where we've truncated back to the
15095   // same size as before the extension.
15096   // TODO: handle more extension/truncation cases as cases arise.
15097   if (EltSizeInBits != ExtSrcSizeInBits)
15098     return SDValue();
15099 
15100   // We can remove *extend_vector_inreg only if the truncation happens at
15101   // the same scale as the extension.
15102   if (isTruncate(ExtScale))
15103     return DAG.getBitcast(VT, N00);
15104 
15105   return SDValue();
15106 }
15107 
15108 // Combine shuffles of splat-shuffles of the form:
15109 // shuffle (shuffle V, undef, splat-mask), undef, M
15110 // If splat-mask contains undef elements, we need to be careful about
15111 // introducing undef's in the folded mask which are not the result of composing
15112 // the masks of the shuffles.
15113 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15114                                      ShuffleVectorSDNode *Splat,
15115                                      SelectionDAG &DAG) {
15116   ArrayRef<int> SplatMask = Splat->getMask();
15117   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15118 
15119   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15120   // every undef mask element in the splat-shuffle has a corresponding undef
15121   // element in the user-shuffle's mask or if the composition of mask elements
15122   // would result in undef.
15123   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15124   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15125   //   In this case it is not legal to simplify to the splat-shuffle because we
15126   //   may be exposing the users of the shuffle an undef element at index 1
15127   //   which was not there before the combine.
15128   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15129   //   In this case the composition of masks yields SplatMask, so it's ok to
15130   //   simplify to the splat-shuffle.
15131   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15132   //   In this case the composed mask includes all undef elements of SplatMask
15133   //   and in addition sets element zero to undef. It is safe to simplify to
15134   //   the splat-shuffle.
15135   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15136                                        ArrayRef<int> SplatMask) {
15137     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15138       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15139           SplatMask[UserMask[i]] != -1)
15140         return false;
15141     return true;
15142   };
15143   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15144     return SDValue(Splat, 0);
15145 
15146   // Create a new shuffle with a mask that is composed of the two shuffles'
15147   // masks.
15148   SmallVector<int, 32> NewMask;
15149   for (int Idx : UserMask)
15150     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15151 
15152   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15153                               Splat->getOperand(0), Splat->getOperand(1),
15154                               NewMask);
15155 }
15156 
15157 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15158   EVT VT = N->getValueType(0);
15159   unsigned NumElts = VT.getVectorNumElements();
15160 
15161   SDValue N0 = N->getOperand(0);
15162   SDValue N1 = N->getOperand(1);
15163 
15164   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15165 
15166   // Canonicalize shuffle undef, undef -> undef
15167   if (N0.isUndef() && N1.isUndef())
15168     return DAG.getUNDEF(VT);
15169 
15170   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15171 
15172   // Canonicalize shuffle v, v -> v, undef
15173   if (N0 == N1) {
15174     SmallVector<int, 8> NewMask;
15175     for (unsigned i = 0; i != NumElts; ++i) {
15176       int Idx = SVN->getMaskElt(i);
15177       if (Idx >= (int)NumElts) Idx -= NumElts;
15178       NewMask.push_back(Idx);
15179     }
15180     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15181   }
15182 
15183   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15184   if (N0.isUndef())
15185     return DAG.getCommutedVectorShuffle(*SVN);
15186 
15187   // Remove references to rhs if it is undef
15188   if (N1.isUndef()) {
15189     bool Changed = false;
15190     SmallVector<int, 8> NewMask;
15191     for (unsigned i = 0; i != NumElts; ++i) {
15192       int Idx = SVN->getMaskElt(i);
15193       if (Idx >= (int)NumElts) {
15194         Idx = -1;
15195         Changed = true;
15196       }
15197       NewMask.push_back(Idx);
15198     }
15199     if (Changed)
15200       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15201   }
15202 
15203   // A shuffle of a single vector that is a splat can always be folded.
15204   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15205     if (N1->isUndef() && N0Shuf->isSplat())
15206       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15207 
15208   // If it is a splat, check if the argument vector is another splat or a
15209   // build_vector.
15210   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15211     SDNode *V = N0.getNode();
15212 
15213     // If this is a bit convert that changes the element type of the vector but
15214     // not the number of vector elements, look through it.  Be careful not to
15215     // look though conversions that change things like v4f32 to v2f64.
15216     if (V->getOpcode() == ISD::BITCAST) {
15217       SDValue ConvInput = V->getOperand(0);
15218       if (ConvInput.getValueType().isVector() &&
15219           ConvInput.getValueType().getVectorNumElements() == NumElts)
15220         V = ConvInput.getNode();
15221     }
15222 
15223     if (V->getOpcode() == ISD::BUILD_VECTOR) {
15224       assert(V->getNumOperands() == NumElts &&
15225              "BUILD_VECTOR has wrong number of operands");
15226       SDValue Base;
15227       bool AllSame = true;
15228       for (unsigned i = 0; i != NumElts; ++i) {
15229         if (!V->getOperand(i).isUndef()) {
15230           Base = V->getOperand(i);
15231           break;
15232         }
15233       }
15234       // Splat of <u, u, u, u>, return <u, u, u, u>
15235       if (!Base.getNode())
15236         return N0;
15237       for (unsigned i = 0; i != NumElts; ++i) {
15238         if (V->getOperand(i) != Base) {
15239           AllSame = false;
15240           break;
15241         }
15242       }
15243       // Splat of <x, x, x, x>, return <x, x, x, x>
15244       if (AllSame)
15245         return N0;
15246 
15247       // Canonicalize any other splat as a build_vector.
15248       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15249       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15250       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15251 
15252       // We may have jumped through bitcasts, so the type of the
15253       // BUILD_VECTOR may not match the type of the shuffle.
15254       if (V->getValueType(0) != VT)
15255         NewBV = DAG.getBitcast(VT, NewBV);
15256       return NewBV;
15257     }
15258   }
15259 
15260   // There are various patterns used to build up a vector from smaller vectors,
15261   // subvectors, or elements. Scan chains of these and replace unused insertions
15262   // or components with undef.
15263   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15264     return S;
15265 
15266   // Match shuffles that can be converted to any_vector_extend_in_reg.
15267   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
15268     return V;
15269 
15270   // Combine "truncate_vector_in_reg" style shuffles.
15271   if (SDValue V = combineTruncationShuffle(SVN, DAG))
15272     return V;
15273 
15274   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15275       Level < AfterLegalizeVectorOps &&
15276       (N1.isUndef() ||
15277       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15278        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15279     if (SDValue V = partitionShuffleOfConcats(N, DAG))
15280       return V;
15281   }
15282 
15283   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15284   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15285   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15286     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15287       return Res;
15288 
15289   // If this shuffle only has a single input that is a bitcasted shuffle,
15290   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15291   // back to their original types.
15292   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15293       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15294       TLI.isTypeLegal(VT)) {
15295 
15296     // Peek through the bitcast only if there is one user.
15297     SDValue BC0 = N0;
15298     while (BC0.getOpcode() == ISD::BITCAST) {
15299       if (!BC0.hasOneUse())
15300         break;
15301       BC0 = BC0.getOperand(0);
15302     }
15303 
15304     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15305       if (Scale == 1)
15306         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15307 
15308       SmallVector<int, 8> NewMask;
15309       for (int M : Mask)
15310         for (int s = 0; s != Scale; ++s)
15311           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15312       return NewMask;
15313     };
15314 
15315     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15316       EVT SVT = VT.getScalarType();
15317       EVT InnerVT = BC0->getValueType(0);
15318       EVT InnerSVT = InnerVT.getScalarType();
15319 
15320       // Determine which shuffle works with the smaller scalar type.
15321       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15322       EVT ScaleSVT = ScaleVT.getScalarType();
15323 
15324       if (TLI.isTypeLegal(ScaleVT) &&
15325           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15326           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15327 
15328         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15329         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15330 
15331         // Scale the shuffle masks to the smaller scalar type.
15332         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15333         SmallVector<int, 8> InnerMask =
15334             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15335         SmallVector<int, 8> OuterMask =
15336             ScaleShuffleMask(SVN->getMask(), OuterScale);
15337 
15338         // Merge the shuffle masks.
15339         SmallVector<int, 8> NewMask;
15340         for (int M : OuterMask)
15341           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15342 
15343         // Test for shuffle mask legality over both commutations.
15344         SDValue SV0 = BC0->getOperand(0);
15345         SDValue SV1 = BC0->getOperand(1);
15346         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15347         if (!LegalMask) {
15348           std::swap(SV0, SV1);
15349           ShuffleVectorSDNode::commuteMask(NewMask);
15350           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15351         }
15352 
15353         if (LegalMask) {
15354           SV0 = DAG.getBitcast(ScaleVT, SV0);
15355           SV1 = DAG.getBitcast(ScaleVT, SV1);
15356           return DAG.getBitcast(
15357               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15358         }
15359       }
15360     }
15361   }
15362 
15363   // Canonicalize shuffles according to rules:
15364   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15365   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15366   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15367   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15368       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15369       TLI.isTypeLegal(VT)) {
15370     // The incoming shuffle must be of the same type as the result of the
15371     // current shuffle.
15372     assert(N1->getOperand(0).getValueType() == VT &&
15373            "Shuffle types don't match");
15374 
15375     SDValue SV0 = N1->getOperand(0);
15376     SDValue SV1 = N1->getOperand(1);
15377     bool HasSameOp0 = N0 == SV0;
15378     bool IsSV1Undef = SV1.isUndef();
15379     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15380       // Commute the operands of this shuffle so that next rule
15381       // will trigger.
15382       return DAG.getCommutedVectorShuffle(*SVN);
15383   }
15384 
15385   // Try to fold according to rules:
15386   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15387   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15388   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15389   // Don't try to fold shuffles with illegal type.
15390   // Only fold if this shuffle is the only user of the other shuffle.
15391   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15392       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15393     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15394 
15395     // Don't try to fold splats; they're likely to simplify somehow, or they
15396     // might be free.
15397     if (OtherSV->isSplat())
15398       return SDValue();
15399 
15400     // The incoming shuffle must be of the same type as the result of the
15401     // current shuffle.
15402     assert(OtherSV->getOperand(0).getValueType() == VT &&
15403            "Shuffle types don't match");
15404 
15405     SDValue SV0, SV1;
15406     SmallVector<int, 4> Mask;
15407     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15408     // operand, and SV1 as the second operand.
15409     for (unsigned i = 0; i != NumElts; ++i) {
15410       int Idx = SVN->getMaskElt(i);
15411       if (Idx < 0) {
15412         // Propagate Undef.
15413         Mask.push_back(Idx);
15414         continue;
15415       }
15416 
15417       SDValue CurrentVec;
15418       if (Idx < (int)NumElts) {
15419         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15420         // shuffle mask to identify which vector is actually referenced.
15421         Idx = OtherSV->getMaskElt(Idx);
15422         if (Idx < 0) {
15423           // Propagate Undef.
15424           Mask.push_back(Idx);
15425           continue;
15426         }
15427 
15428         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15429                                            : OtherSV->getOperand(1);
15430       } else {
15431         // This shuffle index references an element within N1.
15432         CurrentVec = N1;
15433       }
15434 
15435       // Simple case where 'CurrentVec' is UNDEF.
15436       if (CurrentVec.isUndef()) {
15437         Mask.push_back(-1);
15438         continue;
15439       }
15440 
15441       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15442       // will be the first or second operand of the combined shuffle.
15443       Idx = Idx % NumElts;
15444       if (!SV0.getNode() || SV0 == CurrentVec) {
15445         // Ok. CurrentVec is the left hand side.
15446         // Update the mask accordingly.
15447         SV0 = CurrentVec;
15448         Mask.push_back(Idx);
15449         continue;
15450       }
15451 
15452       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15453       if (SV1.getNode() && SV1 != CurrentVec)
15454         return SDValue();
15455 
15456       // Ok. CurrentVec is the right hand side.
15457       // Update the mask accordingly.
15458       SV1 = CurrentVec;
15459       Mask.push_back(Idx + NumElts);
15460     }
15461 
15462     // Check if all indices in Mask are Undef. In case, propagate Undef.
15463     bool isUndefMask = true;
15464     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15465       isUndefMask &= Mask[i] < 0;
15466 
15467     if (isUndefMask)
15468       return DAG.getUNDEF(VT);
15469 
15470     if (!SV0.getNode())
15471       SV0 = DAG.getUNDEF(VT);
15472     if (!SV1.getNode())
15473       SV1 = DAG.getUNDEF(VT);
15474 
15475     // Avoid introducing shuffles with illegal mask.
15476     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15477       ShuffleVectorSDNode::commuteMask(Mask);
15478 
15479       if (!TLI.isShuffleMaskLegal(Mask, VT))
15480         return SDValue();
15481 
15482       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15483       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15484       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15485       std::swap(SV0, SV1);
15486     }
15487 
15488     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15489     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15490     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15491     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15492   }
15493 
15494   return SDValue();
15495 }
15496 
15497 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15498   SDValue InVal = N->getOperand(0);
15499   EVT VT = N->getValueType(0);
15500 
15501   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15502   // with a VECTOR_SHUFFLE.
15503   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15504     SDValue InVec = InVal->getOperand(0);
15505     SDValue EltNo = InVal->getOperand(1);
15506 
15507     // FIXME: We could support implicit truncation if the shuffle can be
15508     // scaled to a smaller vector scalar type.
15509     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15510     if (C0 && VT == InVec.getValueType() &&
15511         VT.getScalarType() == InVal.getValueType()) {
15512       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15513       int Elt = C0->getZExtValue();
15514       NewMask[0] = Elt;
15515 
15516       if (TLI.isShuffleMaskLegal(NewMask, VT))
15517         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15518                                     NewMask);
15519     }
15520   }
15521 
15522   return SDValue();
15523 }
15524 
15525 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15526   EVT VT = N->getValueType(0);
15527   SDValue N0 = N->getOperand(0);
15528   SDValue N1 = N->getOperand(1);
15529   SDValue N2 = N->getOperand(2);
15530 
15531   // If inserting an UNDEF, just return the original vector.
15532   if (N1.isUndef())
15533     return N0;
15534 
15535   // If this is an insert of an extracted vector into an undef vector, we can
15536   // just use the input to the extract.
15537   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15538       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15539     return N1.getOperand(0);
15540 
15541   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15542   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15543   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15544   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15545       N0.getOperand(1).getValueType() == N1.getValueType() &&
15546       N0.getOperand(2) == N2)
15547     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15548                        N1, N2);
15549 
15550   if (!isa<ConstantSDNode>(N2))
15551     return SDValue();
15552 
15553   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15554 
15555   // Canonicalize insert_subvector dag nodes.
15556   // Example:
15557   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15558   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15559   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15560       N1.getValueType() == N0.getOperand(1).getValueType() &&
15561       isa<ConstantSDNode>(N0.getOperand(2))) {
15562     unsigned OtherIdx = N0.getConstantOperandVal(2);
15563     if (InsIdx < OtherIdx) {
15564       // Swap nodes.
15565       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15566                                   N0.getOperand(0), N1, N2);
15567       AddToWorklist(NewOp.getNode());
15568       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15569                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15570     }
15571   }
15572 
15573   // If the input vector is a concatenation, and the insert replaces
15574   // one of the pieces, we can optimize into a single concat_vectors.
15575   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15576       N0.getOperand(0).getValueType() == N1.getValueType()) {
15577     unsigned Factor = N1.getValueType().getVectorNumElements();
15578 
15579     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15580     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15581 
15582     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15583   }
15584 
15585   return SDValue();
15586 }
15587 
15588 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15589   SDValue N0 = N->getOperand(0);
15590 
15591   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15592   if (N0->getOpcode() == ISD::FP16_TO_FP)
15593     return N0->getOperand(0);
15594 
15595   return SDValue();
15596 }
15597 
15598 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15599   SDValue N0 = N->getOperand(0);
15600 
15601   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15602   if (N0->getOpcode() == ISD::AND) {
15603     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15604     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15605       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15606                          N0.getOperand(0));
15607     }
15608   }
15609 
15610   return SDValue();
15611 }
15612 
15613 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15614 /// with the destination vector and a zero vector.
15615 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15616 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
15617 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15618   EVT VT = N->getValueType(0);
15619   SDValue LHS = N->getOperand(0);
15620   SDValue RHS = N->getOperand(1);
15621   SDLoc DL(N);
15622 
15623   // Make sure we're not running after operation legalization where it
15624   // may have custom lowered the vector shuffles.
15625   if (LegalOperations)
15626     return SDValue();
15627 
15628   if (N->getOpcode() != ISD::AND)
15629     return SDValue();
15630 
15631   if (RHS.getOpcode() == ISD::BITCAST)
15632     RHS = RHS.getOperand(0);
15633 
15634   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15635     return SDValue();
15636 
15637   EVT RVT = RHS.getValueType();
15638   unsigned NumElts = RHS.getNumOperands();
15639 
15640   // Attempt to create a valid clear mask, splitting the mask into
15641   // sub elements and checking to see if each is
15642   // all zeros or all ones - suitable for shuffle masking.
15643   auto BuildClearMask = [&](int Split) {
15644     int NumSubElts = NumElts * Split;
15645     int NumSubBits = RVT.getScalarSizeInBits() / Split;
15646 
15647     SmallVector<int, 8> Indices;
15648     for (int i = 0; i != NumSubElts; ++i) {
15649       int EltIdx = i / Split;
15650       int SubIdx = i % Split;
15651       SDValue Elt = RHS.getOperand(EltIdx);
15652       if (Elt.isUndef()) {
15653         Indices.push_back(-1);
15654         continue;
15655       }
15656 
15657       APInt Bits;
15658       if (isa<ConstantSDNode>(Elt))
15659         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15660       else if (isa<ConstantFPSDNode>(Elt))
15661         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15662       else
15663         return SDValue();
15664 
15665       // Extract the sub element from the constant bit mask.
15666       if (DAG.getDataLayout().isBigEndian()) {
15667         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15668       } else {
15669         Bits.lshrInPlace(SubIdx * NumSubBits);
15670       }
15671 
15672       if (Split > 1)
15673         Bits = Bits.trunc(NumSubBits);
15674 
15675       if (Bits.isAllOnesValue())
15676         Indices.push_back(i);
15677       else if (Bits == 0)
15678         Indices.push_back(i + NumSubElts);
15679       else
15680         return SDValue();
15681     }
15682 
15683     // Let's see if the target supports this vector_shuffle.
15684     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15685     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15686     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15687       return SDValue();
15688 
15689     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15690     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15691                                                    DAG.getBitcast(ClearVT, LHS),
15692                                                    Zero, Indices));
15693   };
15694 
15695   // Determine maximum split level (byte level masking).
15696   int MaxSplit = 1;
15697   if (RVT.getScalarSizeInBits() % 8 == 0)
15698     MaxSplit = RVT.getScalarSizeInBits() / 8;
15699 
15700   for (int Split = 1; Split <= MaxSplit; ++Split)
15701     if (RVT.getScalarSizeInBits() % Split == 0)
15702       if (SDValue S = BuildClearMask(Split))
15703         return S;
15704 
15705   return SDValue();
15706 }
15707 
15708 /// Visit a binary vector operation, like ADD.
15709 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15710   assert(N->getValueType(0).isVector() &&
15711          "SimplifyVBinOp only works on vectors!");
15712 
15713   SDValue LHS = N->getOperand(0);
15714   SDValue RHS = N->getOperand(1);
15715   SDValue Ops[] = {LHS, RHS};
15716 
15717   // See if we can constant fold the vector operation.
15718   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15719           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15720     return Fold;
15721 
15722   // Try to convert a constant mask AND into a shuffle clear mask.
15723   if (SDValue Shuffle = XformToShuffleWithZero(N))
15724     return Shuffle;
15725 
15726   // Type legalization might introduce new shuffles in the DAG.
15727   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15728   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
15729   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15730       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15731       LHS.getOperand(1).isUndef() &&
15732       RHS.getOperand(1).isUndef()) {
15733     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15734     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15735 
15736     if (SVN0->getMask().equals(SVN1->getMask())) {
15737       EVT VT = N->getValueType(0);
15738       SDValue UndefVector = LHS.getOperand(1);
15739       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15740                                      LHS.getOperand(0), RHS.getOperand(0),
15741                                      N->getFlags());
15742       AddUsersToWorklist(N);
15743       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15744                                   SVN0->getMask());
15745     }
15746   }
15747 
15748   return SDValue();
15749 }
15750 
15751 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15752                                     SDValue N2) {
15753   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15754 
15755   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15756                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
15757 
15758   // If we got a simplified select_cc node back from SimplifySelectCC, then
15759   // break it down into a new SETCC node, and a new SELECT node, and then return
15760   // the SELECT node, since we were called with a SELECT node.
15761   if (SCC.getNode()) {
15762     // Check to see if we got a select_cc back (to turn into setcc/select).
15763     // Otherwise, just return whatever node we got back, like fabs.
15764     if (SCC.getOpcode() == ISD::SELECT_CC) {
15765       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15766                                   N0.getValueType(),
15767                                   SCC.getOperand(0), SCC.getOperand(1),
15768                                   SCC.getOperand(4));
15769       AddToWorklist(SETCC.getNode());
15770       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15771                            SCC.getOperand(2), SCC.getOperand(3));
15772     }
15773 
15774     return SCC;
15775   }
15776   return SDValue();
15777 }
15778 
15779 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15780 /// being selected between, see if we can simplify the select.  Callers of this
15781 /// should assume that TheSelect is deleted if this returns true.  As such, they
15782 /// should return the appropriate thing (e.g. the node) back to the top-level of
15783 /// the DAG combiner loop to avoid it being looked at.
15784 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15785                                     SDValue RHS) {
15786 
15787   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15788   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15789   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15790     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15791       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15792       SDValue Sqrt = RHS;
15793       ISD::CondCode CC;
15794       SDValue CmpLHS;
15795       const ConstantFPSDNode *Zero = nullptr;
15796 
15797       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15798         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15799         CmpLHS = TheSelect->getOperand(0);
15800         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15801       } else {
15802         // SELECT or VSELECT
15803         SDValue Cmp = TheSelect->getOperand(0);
15804         if (Cmp.getOpcode() == ISD::SETCC) {
15805           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15806           CmpLHS = Cmp.getOperand(0);
15807           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15808         }
15809       }
15810       if (Zero && Zero->isZero() &&
15811           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15812           CC == ISD::SETULT || CC == ISD::SETLT)) {
15813         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15814         CombineTo(TheSelect, Sqrt);
15815         return true;
15816       }
15817     }
15818   }
15819   // Cannot simplify select with vector condition
15820   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15821 
15822   // If this is a select from two identical things, try to pull the operation
15823   // through the select.
15824   if (LHS.getOpcode() != RHS.getOpcode() ||
15825       !LHS.hasOneUse() || !RHS.hasOneUse())
15826     return false;
15827 
15828   // If this is a load and the token chain is identical, replace the select
15829   // of two loads with a load through a select of the address to load from.
15830   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15831   // constants have been dropped into the constant pool.
15832   if (LHS.getOpcode() == ISD::LOAD) {
15833     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15834     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15835 
15836     // Token chains must be identical.
15837     if (LHS.getOperand(0) != RHS.getOperand(0) ||
15838         // Do not let this transformation reduce the number of volatile loads.
15839         LLD->isVolatile() || RLD->isVolatile() ||
15840         // FIXME: If either is a pre/post inc/dec load,
15841         // we'd need to split out the address adjustment.
15842         LLD->isIndexed() || RLD->isIndexed() ||
15843         // If this is an EXTLOAD, the VT's must match.
15844         LLD->getMemoryVT() != RLD->getMemoryVT() ||
15845         // If this is an EXTLOAD, the kind of extension must match.
15846         (LLD->getExtensionType() != RLD->getExtensionType() &&
15847          // The only exception is if one of the extensions is anyext.
15848          LLD->getExtensionType() != ISD::EXTLOAD &&
15849          RLD->getExtensionType() != ISD::EXTLOAD) ||
15850         // FIXME: this discards src value information.  This is
15851         // over-conservative. It would be beneficial to be able to remember
15852         // both potential memory locations.  Since we are discarding
15853         // src value info, don't do the transformation if the memory
15854         // locations are not in the default address space.
15855         LLD->getPointerInfo().getAddrSpace() != 0 ||
15856         RLD->getPointerInfo().getAddrSpace() != 0 ||
15857         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15858                                       LLD->getBasePtr().getValueType()))
15859       return false;
15860 
15861     // Check that the select condition doesn't reach either load.  If so,
15862     // folding this will induce a cycle into the DAG.  If not, this is safe to
15863     // xform, so create a select of the addresses.
15864     SDValue Addr;
15865     if (TheSelect->getOpcode() == ISD::SELECT) {
15866       SDNode *CondNode = TheSelect->getOperand(0).getNode();
15867       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15868           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15869         return false;
15870       // The loads must not depend on one another.
15871       if (LLD->isPredecessorOf(RLD) ||
15872           RLD->isPredecessorOf(LLD))
15873         return false;
15874       Addr = DAG.getSelect(SDLoc(TheSelect),
15875                            LLD->getBasePtr().getValueType(),
15876                            TheSelect->getOperand(0), LLD->getBasePtr(),
15877                            RLD->getBasePtr());
15878     } else {  // Otherwise SELECT_CC
15879       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15880       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15881 
15882       if ((LLD->hasAnyUseOfValue(1) &&
15883            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15884           (RLD->hasAnyUseOfValue(1) &&
15885            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15886         return false;
15887 
15888       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15889                          LLD->getBasePtr().getValueType(),
15890                          TheSelect->getOperand(0),
15891                          TheSelect->getOperand(1),
15892                          LLD->getBasePtr(), RLD->getBasePtr(),
15893                          TheSelect->getOperand(4));
15894     }
15895 
15896     SDValue Load;
15897     // It is safe to replace the two loads if they have different alignments,
15898     // but the new load must be the minimum (most restrictive) alignment of the
15899     // inputs.
15900     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15901     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15902     if (!RLD->isInvariant())
15903       MMOFlags &= ~MachineMemOperand::MOInvariant;
15904     if (!RLD->isDereferenceable())
15905       MMOFlags &= ~MachineMemOperand::MODereferenceable;
15906     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15907       // FIXME: Discards pointer and AA info.
15908       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15909                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15910                          MMOFlags);
15911     } else {
15912       // FIXME: Discards pointer and AA info.
15913       Load = DAG.getExtLoad(
15914           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15915                                                   : LLD->getExtensionType(),
15916           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15917           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15918     }
15919 
15920     // Users of the select now use the result of the load.
15921     CombineTo(TheSelect, Load);
15922 
15923     // Users of the old loads now use the new load's chain.  We know the
15924     // old-load value is dead now.
15925     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15926     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15927     return true;
15928   }
15929 
15930   return false;
15931 }
15932 
15933 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15934 /// bitwise 'and'.
15935 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15936                                             SDValue N1, SDValue N2, SDValue N3,
15937                                             ISD::CondCode CC) {
15938   // If this is a select where the false operand is zero and the compare is a
15939   // check of the sign bit, see if we can perform the "gzip trick":
15940   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15941   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15942   EVT XType = N0.getValueType();
15943   EVT AType = N2.getValueType();
15944   if (!isNullConstant(N3) || !XType.bitsGE(AType))
15945     return SDValue();
15946 
15947   // If the comparison is testing for a positive value, we have to invert
15948   // the sign bit mask, so only do that transform if the target has a bitwise
15949   // 'and not' instruction (the invert is free).
15950   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15951     // (X > -1) ? A : 0
15952     // (X >  0) ? X : 0 <-- This is canonical signed max.
15953     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15954       return SDValue();
15955   } else if (CC == ISD::SETLT) {
15956     // (X <  0) ? A : 0
15957     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
15958     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15959       return SDValue();
15960   } else {
15961     return SDValue();
15962   }
15963 
15964   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15965   // constant.
15966   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15967   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15968   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15969     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15970     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15971     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15972     AddToWorklist(Shift.getNode());
15973 
15974     if (XType.bitsGT(AType)) {
15975       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15976       AddToWorklist(Shift.getNode());
15977     }
15978 
15979     if (CC == ISD::SETGT)
15980       Shift = DAG.getNOT(DL, Shift, AType);
15981 
15982     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15983   }
15984 
15985   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15986   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15987   AddToWorklist(Shift.getNode());
15988 
15989   if (XType.bitsGT(AType)) {
15990     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15991     AddToWorklist(Shift.getNode());
15992   }
15993 
15994   if (CC == ISD::SETGT)
15995     Shift = DAG.getNOT(DL, Shift, AType);
15996 
15997   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15998 }
15999 
16000 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16001 /// where 'cond' is the comparison specified by CC.
16002 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16003                                       SDValue N2, SDValue N3, ISD::CondCode CC,
16004                                       bool NotExtCompare) {
16005   // (x ? y : y) -> y.
16006   if (N2 == N3) return N2;
16007 
16008   EVT VT = N2.getValueType();
16009   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16010   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16011 
16012   // Determine if the condition we're dealing with is constant
16013   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16014                               N0, N1, CC, DL, false);
16015   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16016 
16017   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16018     // fold select_cc true, x, y -> x
16019     // fold select_cc false, x, y -> y
16020     return !SCCC->isNullValue() ? N2 : N3;
16021   }
16022 
16023   // Check to see if we can simplify the select into an fabs node
16024   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16025     // Allow either -0.0 or 0.0
16026     if (CFP->isZero()) {
16027       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16028       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16029           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16030           N2 == N3.getOperand(0))
16031         return DAG.getNode(ISD::FABS, DL, VT, N0);
16032 
16033       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16034       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16035           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16036           N2.getOperand(0) == N3)
16037         return DAG.getNode(ISD::FABS, DL, VT, N3);
16038     }
16039   }
16040 
16041   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16042   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16043   // in it.  This is a win when the constant is not otherwise available because
16044   // it replaces two constant pool loads with one.  We only do this if the FP
16045   // type is known to be legal, because if it isn't, then we are before legalize
16046   // types an we want the other legalization to happen first (e.g. to avoid
16047   // messing with soft float) and if the ConstantFP is not legal, because if
16048   // it is legal, we may not need to store the FP constant in a constant pool.
16049   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16050     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16051       if (TLI.isTypeLegal(N2.getValueType()) &&
16052           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16053                TargetLowering::Legal &&
16054            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16055            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16056           // If both constants have multiple uses, then we won't need to do an
16057           // extra load, they are likely around in registers for other users.
16058           (TV->hasOneUse() || FV->hasOneUse())) {
16059         Constant *Elts[] = {
16060           const_cast<ConstantFP*>(FV->getConstantFPValue()),
16061           const_cast<ConstantFP*>(TV->getConstantFPValue())
16062         };
16063         Type *FPTy = Elts[0]->getType();
16064         const DataLayout &TD = DAG.getDataLayout();
16065 
16066         // Create a ConstantArray of the two constants.
16067         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16068         SDValue CPIdx =
16069             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16070                                 TD.getPrefTypeAlignment(FPTy));
16071         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16072 
16073         // Get the offsets to the 0 and 1 element of the array so that we can
16074         // select between them.
16075         SDValue Zero = DAG.getIntPtrConstant(0, DL);
16076         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16077         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16078 
16079         SDValue Cond = DAG.getSetCC(DL,
16080                                     getSetCCResultType(N0.getValueType()),
16081                                     N0, N1, CC);
16082         AddToWorklist(Cond.getNode());
16083         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16084                                           Cond, One, Zero);
16085         AddToWorklist(CstOffset.getNode());
16086         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16087                             CstOffset);
16088         AddToWorklist(CPIdx.getNode());
16089         return DAG.getLoad(
16090             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16091             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16092             Alignment);
16093       }
16094     }
16095 
16096   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16097     return V;
16098 
16099   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16100   // where y is has a single bit set.
16101   // A plaintext description would be, we can turn the SELECT_CC into an AND
16102   // when the condition can be materialized as an all-ones register.  Any
16103   // single bit-test can be materialized as an all-ones register with
16104   // shift-left and shift-right-arith.
16105   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16106       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16107     SDValue AndLHS = N0->getOperand(0);
16108     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16109     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16110       // Shift the tested bit over the sign bit.
16111       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16112       SDValue ShlAmt =
16113         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16114                         getShiftAmountTy(AndLHS.getValueType()));
16115       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16116 
16117       // Now arithmetic right shift it all the way over, so the result is either
16118       // all-ones, or zero.
16119       SDValue ShrAmt =
16120         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16121                         getShiftAmountTy(Shl.getValueType()));
16122       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16123 
16124       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16125     }
16126   }
16127 
16128   // fold select C, 16, 0 -> shl C, 4
16129   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16130       TLI.getBooleanContents(N0.getValueType()) ==
16131           TargetLowering::ZeroOrOneBooleanContent) {
16132 
16133     // If the caller doesn't want us to simplify this into a zext of a compare,
16134     // don't do it.
16135     if (NotExtCompare && N2C->isOne())
16136       return SDValue();
16137 
16138     // Get a SetCC of the condition
16139     // NOTE: Don't create a SETCC if it's not legal on this target.
16140     if (!LegalOperations ||
16141         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16142       SDValue Temp, SCC;
16143       // cast from setcc result type to select result type
16144       if (LegalTypes) {
16145         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16146                             N0, N1, CC);
16147         if (N2.getValueType().bitsLT(SCC.getValueType()))
16148           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16149                                         N2.getValueType());
16150         else
16151           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16152                              N2.getValueType(), SCC);
16153       } else {
16154         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16155         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16156                            N2.getValueType(), SCC);
16157       }
16158 
16159       AddToWorklist(SCC.getNode());
16160       AddToWorklist(Temp.getNode());
16161 
16162       if (N2C->isOne())
16163         return Temp;
16164 
16165       // shl setcc result by log2 n2c
16166       return DAG.getNode(
16167           ISD::SHL, DL, N2.getValueType(), Temp,
16168           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16169                           getShiftAmountTy(Temp.getValueType())));
16170     }
16171   }
16172 
16173   // Check to see if this is an integer abs.
16174   // select_cc setg[te] X,  0,  X, -X ->
16175   // select_cc setgt    X, -1,  X, -X ->
16176   // select_cc setl[te] X,  0, -X,  X ->
16177   // select_cc setlt    X,  1, -X,  X ->
16178   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16179   if (N1C) {
16180     ConstantSDNode *SubC = nullptr;
16181     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16182          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16183         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16184       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16185     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16186               (N1C->isOne() && CC == ISD::SETLT)) &&
16187              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16188       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16189 
16190     EVT XType = N0.getValueType();
16191     if (SubC && SubC->isNullValue() && XType.isInteger()) {
16192       SDLoc DL(N0);
16193       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16194                                   N0,
16195                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
16196                                          getShiftAmountTy(N0.getValueType())));
16197       SDValue Add = DAG.getNode(ISD::ADD, DL,
16198                                 XType, N0, Shift);
16199       AddToWorklist(Shift.getNode());
16200       AddToWorklist(Add.getNode());
16201       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16202     }
16203   }
16204 
16205   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16206   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16207   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16208   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16209   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16210   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16211   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16212   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16213   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16214     SDValue ValueOnZero = N2;
16215     SDValue Count = N3;
16216     // If the condition is NE instead of E, swap the operands.
16217     if (CC == ISD::SETNE)
16218       std::swap(ValueOnZero, Count);
16219     // Check if the value on zero is a constant equal to the bits in the type.
16220     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16221       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16222         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16223         // legal, combine to just cttz.
16224         if ((Count.getOpcode() == ISD::CTTZ ||
16225              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16226             N0 == Count.getOperand(0) &&
16227             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16228           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16229         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16230         // legal, combine to just ctlz.
16231         if ((Count.getOpcode() == ISD::CTLZ ||
16232              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16233             N0 == Count.getOperand(0) &&
16234             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16235           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16236       }
16237     }
16238   }
16239 
16240   return SDValue();
16241 }
16242 
16243 /// This is a stub for TargetLowering::SimplifySetCC.
16244 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16245                                    ISD::CondCode Cond, const SDLoc &DL,
16246                                    bool foldBooleans) {
16247   TargetLowering::DAGCombinerInfo
16248     DagCombineInfo(DAG, Level, false, this);
16249   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16250 }
16251 
16252 /// Given an ISD::SDIV node expressing a divide by constant, return
16253 /// a DAG expression to select that will generate the same value by multiplying
16254 /// by a magic number.
16255 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16256 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16257   // when optimising for minimum size, we don't want to expand a div to a mul
16258   // and a shift.
16259   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16260     return SDValue();
16261 
16262   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16263   if (!C)
16264     return SDValue();
16265 
16266   // Avoid division by zero.
16267   if (C->isNullValue())
16268     return SDValue();
16269 
16270   std::vector<SDNode*> Built;
16271   SDValue S =
16272       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16273 
16274   for (SDNode *N : Built)
16275     AddToWorklist(N);
16276   return S;
16277 }
16278 
16279 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16280 /// DAG expression that will generate the same value by right shifting.
16281 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
16282   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16283   if (!C)
16284     return SDValue();
16285 
16286   // Avoid division by zero.
16287   if (C->isNullValue())
16288     return SDValue();
16289 
16290   std::vector<SDNode *> Built;
16291   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16292 
16293   for (SDNode *N : Built)
16294     AddToWorklist(N);
16295   return S;
16296 }
16297 
16298 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16299 /// expression that will generate the same value by multiplying by a magic
16300 /// number.
16301 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16302 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16303   // when optimising for minimum size, we don't want to expand a div to a mul
16304   // and a shift.
16305   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16306     return SDValue();
16307 
16308   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16309   if (!C)
16310     return SDValue();
16311 
16312   // Avoid division by zero.
16313   if (C->isNullValue())
16314     return SDValue();
16315 
16316   std::vector<SDNode*> Built;
16317   SDValue S =
16318       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16319 
16320   for (SDNode *N : Built)
16321     AddToWorklist(N);
16322   return S;
16323 }
16324 
16325 /// Determines the LogBase2 value for a non-null input value using the
16326 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16327 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16328   EVT VT = V.getValueType();
16329   unsigned EltBits = VT.getScalarSizeInBits();
16330   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16331   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16332   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16333   return LogBase2;
16334 }
16335 
16336 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16337 /// For the reciprocal, we need to find the zero of the function:
16338 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16339 ///     =>
16340 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16341 ///     does not require additional intermediate precision]
16342 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16343   if (Level >= AfterLegalizeDAG)
16344     return SDValue();
16345 
16346   // TODO: Handle half and/or extended types?
16347   EVT VT = Op.getValueType();
16348   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16349     return SDValue();
16350 
16351   // If estimates are explicitly disabled for this function, we're done.
16352   MachineFunction &MF = DAG.getMachineFunction();
16353   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16354   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16355     return SDValue();
16356 
16357   // Estimates may be explicitly enabled for this type with a custom number of
16358   // refinement steps.
16359   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16360   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16361     AddToWorklist(Est.getNode());
16362 
16363     if (Iterations) {
16364       EVT VT = Op.getValueType();
16365       SDLoc DL(Op);
16366       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16367 
16368       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16369       for (int i = 0; i < Iterations; ++i) {
16370         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16371         AddToWorklist(NewEst.getNode());
16372 
16373         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16374         AddToWorklist(NewEst.getNode());
16375 
16376         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16377         AddToWorklist(NewEst.getNode());
16378 
16379         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16380         AddToWorklist(Est.getNode());
16381       }
16382     }
16383     return Est;
16384   }
16385 
16386   return SDValue();
16387 }
16388 
16389 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16390 /// For the reciprocal sqrt, we need to find the zero of the function:
16391 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16392 ///     =>
16393 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16394 /// As a result, we precompute A/2 prior to the iteration loop.
16395 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16396                                          unsigned Iterations,
16397                                          SDNodeFlags Flags, bool Reciprocal) {
16398   EVT VT = Arg.getValueType();
16399   SDLoc DL(Arg);
16400   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16401 
16402   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16403   // this entire sequence requires only one FP constant.
16404   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16405   AddToWorklist(HalfArg.getNode());
16406 
16407   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16408   AddToWorklist(HalfArg.getNode());
16409 
16410   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16411   for (unsigned i = 0; i < Iterations; ++i) {
16412     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16413     AddToWorklist(NewEst.getNode());
16414 
16415     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16416     AddToWorklist(NewEst.getNode());
16417 
16418     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16419     AddToWorklist(NewEst.getNode());
16420 
16421     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16422     AddToWorklist(Est.getNode());
16423   }
16424 
16425   // If non-reciprocal square root is requested, multiply the result by Arg.
16426   if (!Reciprocal) {
16427     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16428     AddToWorklist(Est.getNode());
16429   }
16430 
16431   return Est;
16432 }
16433 
16434 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16435 /// For the reciprocal sqrt, we need to find the zero of the function:
16436 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16437 ///     =>
16438 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16439 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16440                                          unsigned Iterations,
16441                                          SDNodeFlags Flags, bool Reciprocal) {
16442   EVT VT = Arg.getValueType();
16443   SDLoc DL(Arg);
16444   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16445   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16446 
16447   // This routine must enter the loop below to work correctly
16448   // when (Reciprocal == false).
16449   assert(Iterations > 0);
16450 
16451   // Newton iterations for reciprocal square root:
16452   // E = (E * -0.5) * ((A * E) * E + -3.0)
16453   for (unsigned i = 0; i < Iterations; ++i) {
16454     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16455     AddToWorklist(AE.getNode());
16456 
16457     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16458     AddToWorklist(AEE.getNode());
16459 
16460     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16461     AddToWorklist(RHS.getNode());
16462 
16463     // When calculating a square root at the last iteration build:
16464     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16465     // (notice a common subexpression)
16466     SDValue LHS;
16467     if (Reciprocal || (i + 1) < Iterations) {
16468       // RSQRT: LHS = (E * -0.5)
16469       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16470     } else {
16471       // SQRT: LHS = (A * E) * -0.5
16472       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16473     }
16474     AddToWorklist(LHS.getNode());
16475 
16476     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16477     AddToWorklist(Est.getNode());
16478   }
16479 
16480   return Est;
16481 }
16482 
16483 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16484 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16485 /// Op can be zero.
16486 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16487                                            bool Reciprocal) {
16488   if (Level >= AfterLegalizeDAG)
16489     return SDValue();
16490 
16491   // TODO: Handle half and/or extended types?
16492   EVT VT = Op.getValueType();
16493   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16494     return SDValue();
16495 
16496   // If estimates are explicitly disabled for this function, we're done.
16497   MachineFunction &MF = DAG.getMachineFunction();
16498   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16499   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16500     return SDValue();
16501 
16502   // Estimates may be explicitly enabled for this type with a custom number of
16503   // refinement steps.
16504   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16505 
16506   bool UseOneConstNR = false;
16507   if (SDValue Est =
16508       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16509                           Reciprocal)) {
16510     AddToWorklist(Est.getNode());
16511 
16512     if (Iterations) {
16513       Est = UseOneConstNR
16514             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16515             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16516 
16517       if (!Reciprocal) {
16518         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16519         // Select out this case and force the answer to 0.0.
16520         EVT VT = Op.getValueType();
16521         SDLoc DL(Op);
16522 
16523         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16524         EVT CCVT = getSetCCResultType(VT);
16525         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16526         AddToWorklist(ZeroCmp.getNode());
16527 
16528         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16529                           ZeroCmp, FPZero, Est);
16530         AddToWorklist(Est.getNode());
16531       }
16532     }
16533     return Est;
16534   }
16535 
16536   return SDValue();
16537 }
16538 
16539 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16540   return buildSqrtEstimateImpl(Op, Flags, true);
16541 }
16542 
16543 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16544   return buildSqrtEstimateImpl(Op, Flags, false);
16545 }
16546 
16547 /// Return true if base is a frame index, which is known not to alias with
16548 /// anything but itself.  Provides base object and offset as results.
16549 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16550                            const GlobalValue *&GV, const void *&CV) {
16551   // Assume it is a primitive operation.
16552   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16553 
16554   // If it's an adding a simple constant then integrate the offset.
16555   if (Base.getOpcode() == ISD::ADD) {
16556     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16557       Base = Base.getOperand(0);
16558       Offset += C->getSExtValue();
16559     }
16560   }
16561 
16562   // Return the underlying GlobalValue, and update the Offset.  Return false
16563   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16564   // by multiple nodes with different offsets.
16565   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16566     GV = G->getGlobal();
16567     Offset += G->getOffset();
16568     return false;
16569   }
16570 
16571   // Return the underlying Constant value, and update the Offset.  Return false
16572   // for ConstantSDNodes since the same constant pool entry may be represented
16573   // by multiple nodes with different offsets.
16574   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16575     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16576                                          : (const void *)C->getConstVal();
16577     Offset += C->getOffset();
16578     return false;
16579   }
16580   // If it's any of the following then it can't alias with anything but itself.
16581   return isa<FrameIndexSDNode>(Base);
16582 }
16583 
16584 /// Return true if there is any possibility that the two addresses overlap.
16585 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16586   // If they are the same then they must be aliases.
16587   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16588 
16589   // If they are both volatile then they cannot be reordered.
16590   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16591 
16592   // If one operation reads from invariant memory, and the other may store, they
16593   // cannot alias. These should really be checking the equivalent of mayWrite,
16594   // but it only matters for memory nodes other than load /store.
16595   if (Op0->isInvariant() && Op1->writeMem())
16596     return false;
16597 
16598   if (Op1->isInvariant() && Op0->writeMem())
16599     return false;
16600 
16601   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16602   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16603 
16604   // Check for BaseIndexOffset matching.
16605   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16606   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16607   int64_t PtrDiff;
16608   if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
16609     return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
16610 
16611   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16612   // modified to use BaseIndexOffset.
16613 
16614   // Gather base node and offset information.
16615   SDValue Base0, Base1;
16616   int64_t Offset0, Offset1;
16617   const GlobalValue *GV0, *GV1;
16618   const void *CV0, *CV1;
16619   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16620                                       Base0, Offset0, GV0, CV0);
16621   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16622                                       Base1, Offset1, GV1, CV1);
16623 
16624   // If they have the same base address, then check to see if they overlap.
16625   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16626     return !((Offset0 + NumBytes0) <= Offset1 ||
16627              (Offset1 + NumBytes1) <= Offset0);
16628 
16629   // It is possible for different frame indices to alias each other, mostly
16630   // when tail call optimization reuses return address slots for arguments.
16631   // To catch this case, look up the actual index of frame indices to compute
16632   // the real alias relationship.
16633   if (IsFrameIndex0 && IsFrameIndex1) {
16634     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16635     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16636     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16637     return !((Offset0 + NumBytes0) <= Offset1 ||
16638              (Offset1 + NumBytes1) <= Offset0);
16639   }
16640 
16641   // Otherwise, if we know what the bases are, and they aren't identical, then
16642   // we know they cannot alias.
16643   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16644     return false;
16645 
16646   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16647   // compared to the size and offset of the access, we may be able to prove they
16648   // do not alias. This check is conservative for now to catch cases created by
16649   // splitting vector types.
16650   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16651   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16652   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16653   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16654   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16655       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16656     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16657     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16658 
16659     // There is no overlap between these relatively aligned accesses of similar
16660     // size. Return no alias.
16661     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16662         (OffAlign1 + NumBytes1) <= OffAlign0)
16663       return false;
16664   }
16665 
16666   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16667                    ? CombinerGlobalAA
16668                    : DAG.getSubtarget().useAA();
16669 #ifndef NDEBUG
16670   if (CombinerAAOnlyFunc.getNumOccurrences() &&
16671       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16672     UseAA = false;
16673 #endif
16674 
16675   if (UseAA && AA &&
16676       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16677     // Use alias analysis information.
16678     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16679     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16680     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16681     AliasResult AAResult =
16682         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16683                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16684                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16685                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
16686     if (AAResult == NoAlias)
16687       return false;
16688   }
16689 
16690   // Otherwise we have to assume they alias.
16691   return true;
16692 }
16693 
16694 /// Walk up chain skipping non-aliasing memory nodes,
16695 /// looking for aliasing nodes and adding them to the Aliases vector.
16696 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16697                                    SmallVectorImpl<SDValue> &Aliases) {
16698   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
16699   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
16700 
16701   // Get alias information for node.
16702   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16703 
16704   // Starting off.
16705   Chains.push_back(OriginalChain);
16706   unsigned Depth = 0;
16707 
16708   // Look at each chain and determine if it is an alias.  If so, add it to the
16709   // aliases list.  If not, then continue up the chain looking for the next
16710   // candidate.
16711   while (!Chains.empty()) {
16712     SDValue Chain = Chains.pop_back_val();
16713 
16714     // For TokenFactor nodes, look at each operand and only continue up the
16715     // chain until we reach the depth limit.
16716     //
16717     // FIXME: The depth check could be made to return the last non-aliasing
16718     // chain we found before we hit a tokenfactor rather than the original
16719     // chain.
16720     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16721       Aliases.clear();
16722       Aliases.push_back(OriginalChain);
16723       return;
16724     }
16725 
16726     // Don't bother if we've been before.
16727     if (!Visited.insert(Chain.getNode()).second)
16728       continue;
16729 
16730     switch (Chain.getOpcode()) {
16731     case ISD::EntryToken:
16732       // Entry token is ideal chain operand, but handled in FindBetterChain.
16733       break;
16734 
16735     case ISD::LOAD:
16736     case ISD::STORE: {
16737       // Get alias information for Chain.
16738       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16739           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16740 
16741       // If chain is alias then stop here.
16742       if (!(IsLoad && IsOpLoad) &&
16743           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16744         Aliases.push_back(Chain);
16745       } else {
16746         // Look further up the chain.
16747         Chains.push_back(Chain.getOperand(0));
16748         ++Depth;
16749       }
16750       break;
16751     }
16752 
16753     case ISD::TokenFactor:
16754       // We have to check each of the operands of the token factor for "small"
16755       // token factors, so we queue them up.  Adding the operands to the queue
16756       // (stack) in reverse order maintains the original order and increases the
16757       // likelihood that getNode will find a matching token factor (CSE.)
16758       if (Chain.getNumOperands() > 16) {
16759         Aliases.push_back(Chain);
16760         break;
16761       }
16762       for (unsigned n = Chain.getNumOperands(); n;)
16763         Chains.push_back(Chain.getOperand(--n));
16764       ++Depth;
16765       break;
16766 
16767     case ISD::CopyFromReg:
16768       // Forward past CopyFromReg.
16769       Chains.push_back(Chain.getOperand(0));
16770       ++Depth;
16771       break;
16772 
16773     default:
16774       // For all other instructions we will just have to take what we can get.
16775       Aliases.push_back(Chain);
16776       break;
16777     }
16778   }
16779 }
16780 
16781 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16782 /// (aliasing node.)
16783 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16784   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
16785 
16786   // Accumulate all the aliases to this node.
16787   GatherAllAliases(N, OldChain, Aliases);
16788 
16789   // If no operands then chain to entry token.
16790   if (Aliases.size() == 0)
16791     return DAG.getEntryNode();
16792 
16793   // If a single operand then chain to it.  We don't need to revisit it.
16794   if (Aliases.size() == 1)
16795     return Aliases[0];
16796 
16797   // Construct a custom tailored token factor.
16798   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16799 }
16800 
16801 // This function tries to collect a bunch of potentially interesting
16802 // nodes to improve the chains of, all at once. This might seem
16803 // redundant, as this function gets called when visiting every store
16804 // node, so why not let the work be done on each store as it's visited?
16805 //
16806 // I believe this is mainly important because MergeConsecutiveStores
16807 // is unable to deal with merging stores of different sizes, so unless
16808 // we improve the chains of all the potential candidates up-front
16809 // before running MergeConsecutiveStores, it might only see some of
16810 // the nodes that will eventually be candidates, and then not be able
16811 // to go from a partially-merged state to the desired final
16812 // fully-merged state.
16813 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16814   // This holds the base pointer, index, and the offset in bytes from the base
16815   // pointer.
16816   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16817 
16818   // We must have a base and an offset.
16819   if (!BasePtr.getBase().getNode())
16820     return false;
16821 
16822   // Do not handle stores to undef base pointers.
16823   if (BasePtr.getBase().isUndef())
16824     return false;
16825 
16826   SmallVector<StoreSDNode *, 8> ChainedStores;
16827   ChainedStores.push_back(St);
16828 
16829   // Walk up the chain and look for nodes with offsets from the same
16830   // base pointer. Stop when reaching an instruction with a different kind
16831   // or instruction which has a different base pointer.
16832   StoreSDNode *Index = St;
16833   while (Index) {
16834     // If the chain has more than one use, then we can't reorder the mem ops.
16835     if (Index != St && !SDValue(Index, 0)->hasOneUse())
16836       break;
16837 
16838     if (Index->isVolatile() || Index->isIndexed())
16839       break;
16840 
16841     // Find the base pointer and offset for this memory node.
16842     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16843 
16844     // Check that the base pointer is the same as the original one.
16845     if (!BasePtr.equalBaseIndex(Ptr, DAG))
16846       break;
16847 
16848     // Walk up the chain to find the next store node, ignoring any
16849     // intermediate loads. Any other kind of node will halt the loop.
16850     SDNode *NextInChain = Index->getChain().getNode();
16851     while (true) {
16852       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16853         // We found a store node. Use it for the next iteration.
16854         if (STn->isVolatile() || STn->isIndexed()) {
16855           Index = nullptr;
16856           break;
16857         }
16858         ChainedStores.push_back(STn);
16859         Index = STn;
16860         break;
16861       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16862         NextInChain = Ldn->getChain().getNode();
16863         continue;
16864       } else {
16865         Index = nullptr;
16866         break;
16867       }
16868     } // end while
16869   }
16870 
16871   // At this point, ChainedStores lists all of the Store nodes
16872   // reachable by iterating up through chain nodes matching the above
16873   // conditions.  For each such store identified, try to find an
16874   // earlier chain to attach the store to which won't violate the
16875   // required ordering.
16876   bool MadeChangeToSt = false;
16877   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16878 
16879   for (StoreSDNode *ChainedStore : ChainedStores) {
16880     SDValue Chain = ChainedStore->getChain();
16881     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16882 
16883     if (Chain != BetterChain) {
16884       if (ChainedStore == St)
16885         MadeChangeToSt = true;
16886       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16887     }
16888   }
16889 
16890   // Do all replacements after finding the replacements to make to avoid making
16891   // the chains more complicated by introducing new TokenFactors.
16892   for (auto Replacement : BetterChains)
16893     replaceStoreChain(Replacement.first, Replacement.second);
16894 
16895   return MadeChangeToSt;
16896 }
16897 
16898 /// This is the entry point for the file.
16899 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
16900                            CodeGenOpt::Level OptLevel) {
16901   /// This is the main entry point to this class.
16902   DAGCombiner(*this, AA, OptLevel).Run(Level);
16903 }
16904