1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "dagcombine"
45 
46 STATISTIC(NodesCombined   , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
52 
53 namespace {
54   static cl::opt<bool>
55     CombinerAA("combiner-alias-analysis", cl::Hidden,
56                cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 
58   static cl::opt<bool>
59     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60                cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 
62   static cl::opt<bool>
63     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64                cl::desc("Enable DAG combiner's use of TBAA"));
65 
66 #ifndef NDEBUG
67   static cl::opt<std::string>
68     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69                cl::desc("Only use DAG-combiner alias analysis in this"
70                         " function"));
71 #endif
72 
73   /// Hidden option to stress test load slicing, i.e., when this option
74   /// is enabled, load slicing bypasses most of its profitability guards.
75   static cl::opt<bool>
76   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77                     cl::desc("Bypass the profitability model of load "
78                              "slicing"),
79                     cl::init(false));
80 
81   static cl::opt<bool>
82     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83                       cl::desc("DAG combiner may split indexing from loads"));
84 
85 //------------------------------ DAGCombiner ---------------------------------//
86 
87   class DAGCombiner {
88     SelectionDAG &DAG;
89     const TargetLowering &TLI;
90     CombineLevel Level;
91     CodeGenOpt::Level OptLevel;
92     bool LegalOperations;
93     bool LegalTypes;
94     bool ForCodeSize;
95 
96     /// \brief Worklist of all of the nodes that need to be simplified.
97     ///
98     /// This must behave as a stack -- new nodes to process are pushed onto the
99     /// back and when processing we pop off of the back.
100     ///
101     /// The worklist will not contain duplicates but may contain null entries
102     /// due to nodes being deleted from the underlying DAG.
103     SmallVector<SDNode *, 64> Worklist;
104 
105     /// \brief Mapping from an SDNode to its position on the worklist.
106     ///
107     /// This is used to find and remove nodes from the worklist (by nulling
108     /// them) when they are deleted from the underlying DAG. It relies on
109     /// stable indices of nodes within the worklist.
110     DenseMap<SDNode *, unsigned> WorklistMap;
111 
112     /// \brief Set of nodes which have been combined (at least once).
113     ///
114     /// This is used to allow us to reliably add any operands of a DAG node
115     /// which have not yet been combined to the worklist.
116     SmallPtrSet<SDNode *, 32> CombinedNodes;
117 
118     // AA - Used for DAG load/store alias analysis.
119     AliasAnalysis &AA;
120 
121     /// When an instruction is simplified, add all users of the instruction to
122     /// the work lists because they might get more simplified now.
123     void AddUsersToWorklist(SDNode *N) {
124       for (SDNode *Node : N->uses())
125         AddToWorklist(Node);
126     }
127 
128     /// Call the node-specific routine that folds each particular type of node.
129     SDValue visit(SDNode *N);
130 
131   public:
132     /// Add to the worklist making sure its instance is at the back (next to be
133     /// processed.)
134     void AddToWorklist(SDNode *N) {
135       // Skip handle nodes as they can't usefully be combined and confuse the
136       // zero-use deletion strategy.
137       if (N->getOpcode() == ISD::HANDLENODE)
138         return;
139 
140       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141         Worklist.push_back(N);
142     }
143 
144     /// Remove all instances of N from the worklist.
145     void removeFromWorklist(SDNode *N) {
146       CombinedNodes.erase(N);
147 
148       auto It = WorklistMap.find(N);
149       if (It == WorklistMap.end())
150         return; // Not in the worklist.
151 
152       // Null out the entry rather than erasing it to avoid a linear operation.
153       Worklist[It->second] = nullptr;
154       WorklistMap.erase(It);
155     }
156 
157     void deleteAndRecombine(SDNode *N);
158     bool recursivelyDeleteUnusedNodes(SDNode *N);
159 
160     /// Replaces all uses of the results of one DAG node with new values.
161     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162                       bool AddTo = true);
163 
164     /// Replaces all uses of the results of one DAG node with new values.
165     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166       return CombineTo(N, &Res, 1, AddTo);
167     }
168 
169     /// Replaces all uses of the results of one DAG node with new values.
170     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171                       bool AddTo = true) {
172       SDValue To[] = { Res0, Res1 };
173       return CombineTo(N, To, 2, AddTo);
174     }
175 
176     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177 
178   private:
179 
180     /// Check the specified integer node value to see if it can be simplified or
181     /// if things it uses can be simplified by bit propagation.
182     /// If so, return true.
183     bool SimplifyDemandedBits(SDValue Op) {
184       unsigned BitWidth = Op.getScalarValueSizeInBits();
185       APInt Demanded = APInt::getAllOnesValue(BitWidth);
186       return SimplifyDemandedBits(Op, Demanded);
187     }
188 
189     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 
191     bool CombineToPreIndexedLoadStore(SDNode *N);
192     bool CombineToPostIndexedLoadStore(SDNode *N);
193     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
194     bool SliceUpLoad(SDNode *N);
195 
196     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
197     ///   load.
198     ///
199     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
200     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
201     /// \param EltNo index of the vector element to load.
202     /// \param OriginalLoad load that EVE came from to be replaced.
203     /// \returns EVE on success SDValue() on failure.
204     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
205         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
206     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
207     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
208     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue PromoteIntBinOp(SDValue Op);
211     SDValue PromoteIntShiftOp(SDValue Op);
212     SDValue PromoteExtend(SDValue Op);
213     bool PromoteLoad(SDValue Op);
214 
215     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
216                          SDValue ExtLoad, const SDLoc &DL,
217                          ISD::NodeType ExtType);
218 
219     /// Call the node-specific routine that knows how to fold each
220     /// particular type of node. If that doesn't do anything, try the
221     /// target-specific DAG combines.
222     SDValue combine(SDNode *N);
223 
224     // Visitation implementation - Implement dag node combining for different
225     // node types.  The semantics are as follows:
226     // Return Value:
227     //   SDValue.getNode() == 0 - No change was made
228     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
229     //   otherwise              - N should be replaced by the returned Operand.
230     //
231     SDValue visitTokenFactor(SDNode *N);
232     SDValue visitMERGE_VALUES(SDNode *N);
233     SDValue visitADD(SDNode *N);
234     SDValue visitSUB(SDNode *N);
235     SDValue visitADDC(SDNode *N);
236     SDValue visitSUBC(SDNode *N);
237     SDValue visitADDE(SDNode *N);
238     SDValue visitSUBE(SDNode *N);
239     SDValue visitMUL(SDNode *N);
240     SDValue useDivRem(SDNode *N);
241     SDValue visitSDIV(SDNode *N);
242     SDValue visitUDIV(SDNode *N);
243     SDValue visitREM(SDNode *N);
244     SDValue visitMULHU(SDNode *N);
245     SDValue visitMULHS(SDNode *N);
246     SDValue visitSMUL_LOHI(SDNode *N);
247     SDValue visitUMUL_LOHI(SDNode *N);
248     SDValue visitSMULO(SDNode *N);
249     SDValue visitUMULO(SDNode *N);
250     SDValue visitIMINMAX(SDNode *N);
251     SDValue visitAND(SDNode *N);
252     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitOR(SDNode *N);
254     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitXOR(SDNode *N);
256     SDValue SimplifyVBinOp(SDNode *N);
257     SDValue visitSHL(SDNode *N);
258     SDValue visitSRA(SDNode *N);
259     SDValue visitSRL(SDNode *N);
260     SDValue visitRotate(SDNode *N);
261     SDValue visitBSWAP(SDNode *N);
262     SDValue visitBITREVERSE(SDNode *N);
263     SDValue visitCTLZ(SDNode *N);
264     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTTZ(SDNode *N);
266     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
267     SDValue visitCTPOP(SDNode *N);
268     SDValue visitSELECT(SDNode *N);
269     SDValue visitVSELECT(SDNode *N);
270     SDValue visitSELECT_CC(SDNode *N);
271     SDValue visitSETCC(SDNode *N);
272     SDValue visitSETCCE(SDNode *N);
273     SDValue visitSIGN_EXTEND(SDNode *N);
274     SDValue visitZERO_EXTEND(SDNode *N);
275     SDValue visitANY_EXTEND(SDNode *N);
276     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
277     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
278     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
279     SDValue visitTRUNCATE(SDNode *N);
280     SDValue visitBITCAST(SDNode *N);
281     SDValue visitBUILD_PAIR(SDNode *N);
282     SDValue visitFADD(SDNode *N);
283     SDValue visitFSUB(SDNode *N);
284     SDValue visitFMUL(SDNode *N);
285     SDValue visitFMA(SDNode *N);
286     SDValue visitFDIV(SDNode *N);
287     SDValue visitFREM(SDNode *N);
288     SDValue visitFSQRT(SDNode *N);
289     SDValue visitFCOPYSIGN(SDNode *N);
290     SDValue visitSINT_TO_FP(SDNode *N);
291     SDValue visitUINT_TO_FP(SDNode *N);
292     SDValue visitFP_TO_SINT(SDNode *N);
293     SDValue visitFP_TO_UINT(SDNode *N);
294     SDValue visitFP_ROUND(SDNode *N);
295     SDValue visitFP_ROUND_INREG(SDNode *N);
296     SDValue visitFP_EXTEND(SDNode *N);
297     SDValue visitFNEG(SDNode *N);
298     SDValue visitFABS(SDNode *N);
299     SDValue visitFCEIL(SDNode *N);
300     SDValue visitFTRUNC(SDNode *N);
301     SDValue visitFFLOOR(SDNode *N);
302     SDValue visitFMINNUM(SDNode *N);
303     SDValue visitFMAXNUM(SDNode *N);
304     SDValue visitBRCOND(SDNode *N);
305     SDValue visitBR_CC(SDNode *N);
306     SDValue visitLOAD(SDNode *N);
307 
308     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
309     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
310 
311     SDValue visitSTORE(SDNode *N);
312     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
313     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
314     SDValue visitBUILD_VECTOR(SDNode *N);
315     SDValue visitCONCAT_VECTORS(SDNode *N);
316     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
317     SDValue visitVECTOR_SHUFFLE(SDNode *N);
318     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
319     SDValue visitINSERT_SUBVECTOR(SDNode *N);
320     SDValue visitMLOAD(SDNode *N);
321     SDValue visitMSTORE(SDNode *N);
322     SDValue visitMGATHER(SDNode *N);
323     SDValue visitMSCATTER(SDNode *N);
324     SDValue visitFP_TO_FP16(SDNode *N);
325     SDValue visitFP16_TO_FP(SDNode *N);
326 
327     SDValue visitFADDForFMACombine(SDNode *N);
328     SDValue visitFSUBForFMACombine(SDNode *N);
329     SDValue visitFMULForFMACombine(SDNode *N);
330 
331     SDValue XformToShuffleWithZero(SDNode *N);
332     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
333                            SDValue RHS);
334 
335     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
336 
337     SDValue foldSelectOfConstants(SDNode *N);
338     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
339     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
340     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
341     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
342                              SDValue N2, SDValue N3, ISD::CondCode CC,
343                              bool NotExtCompare = false);
344     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
345                           const SDLoc &DL, bool foldBooleans = true);
346 
347     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
348                            SDValue &CC) const;
349     bool isOneUseSetCC(SDValue N) const;
350 
351     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
352                                          unsigned HiOp);
353     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
354     SDValue CombineExtLoad(SDNode *N);
355     SDValue combineRepeatedFPDivisors(SDNode *N);
356     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
357     SDValue BuildSDIV(SDNode *N);
358     SDValue BuildSDIVPow2(SDNode *N);
359     SDValue BuildUDIV(SDNode *N);
360     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
361     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
362     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
363     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
364     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
365                                 SDNodeFlags *Flags, bool Reciprocal);
366     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
367                                 SDNodeFlags *Flags, bool Reciprocal);
368     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
369                                bool DemandHighBits = true);
370     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
371     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
372                               SDValue InnerPos, SDValue InnerNeg,
373                               unsigned PosOpcode, unsigned NegOpcode,
374                               const SDLoc &DL);
375     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
376     SDValue ReduceLoadWidth(SDNode *N);
377     SDValue ReduceLoadOpStoreWidth(SDNode *N);
378     SDValue splitMergedValStore(StoreSDNode *ST);
379     SDValue TransformFPLoadStorePair(SDNode *N);
380     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
381     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
382     SDValue reduceBuildVecToShuffle(SDNode *N);
383     SDValue createBuildVecShuffle(SDLoc DL, SDNode *N, ArrayRef<int> VectorMask,
384                                   SDValue VecIn1, SDValue VecIn2,
385                                   unsigned LeftIdx);
386 
387     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
388 
389     /// Walk up chain skipping non-aliasing memory nodes,
390     /// looking for aliasing nodes and adding them to the Aliases vector.
391     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
392                           SmallVectorImpl<SDValue> &Aliases);
393 
394     /// Return true if there is any possibility that the two addresses overlap.
395     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
396 
397     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
398     /// chain (aliasing node.)
399     SDValue FindBetterChain(SDNode *N, SDValue Chain);
400 
401     /// Try to replace a store and any possibly adjacent stores on
402     /// consecutive chains with better chains. Return true only if St is
403     /// replaced.
404     ///
405     /// Notice that other chains may still be replaced even if the function
406     /// returns false.
407     bool findBetterNeighborChains(StoreSDNode *St);
408 
409     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
410     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
411 
412     /// Holds a pointer to an LSBaseSDNode as well as information on where it
413     /// is located in a sequence of memory operations connected by a chain.
414     struct MemOpLink {
415       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
416       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
417       // Ptr to the mem node.
418       LSBaseSDNode *MemNode;
419       // Offset from the base ptr.
420       int64_t OffsetFromBase;
421       // What is the sequence number of this mem node.
422       // Lowest mem operand in the DAG starts at zero.
423       unsigned SequenceNum;
424     };
425 
426     /// This is a helper function for visitMUL to check the profitability
427     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
428     /// MulNode is the original multiply, AddNode is (add x, c1),
429     /// and ConstNode is c2.
430     bool isMulAddWithConstProfitable(SDNode *MulNode,
431                                      SDValue &AddNode,
432                                      SDValue &ConstNode);
433 
434     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
435     /// constant build_vector of the stored constant values in Stores.
436     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
437                                          ArrayRef<MemOpLink> Stores,
438                                          SmallVectorImpl<SDValue> &Chains,
439                                          EVT Ty) const;
440 
441     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
442     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
443     /// the type of the loaded value to be extended.  LoadedVT returns the type
444     /// of the original loaded value.  NarrowLoad returns whether the load would
445     /// need to be narrowed in order to match.
446     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
447                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
448                           bool &NarrowLoad);
449 
450     /// This is a helper function for MergeConsecutiveStores. When the source
451     /// elements of the consecutive stores are all constants or all extracted
452     /// vector elements, try to merge them into one larger store.
453     /// \return True if a merged store was created.
454     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
455                                          EVT MemVT, unsigned NumStores,
456                                          bool IsConstantSrc, bool UseVector);
457 
458     /// This is a helper function for MergeConsecutiveStores.
459     /// Stores that may be merged are placed in StoreNodes.
460     /// Loads that may alias with those stores are placed in AliasLoadNodes.
461     void getStoreMergeAndAliasCandidates(
462         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
463         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
464 
465     /// Helper function for MergeConsecutiveStores. Checks if
466     /// Candidate stores have indirect dependency through their
467     /// operands. \return True if safe to merge
468     bool checkMergeStoreCandidatesForDependencies(
469         SmallVectorImpl<MemOpLink> &StoreNodes);
470 
471     /// Merge consecutive store operations into a wide store.
472     /// This optimization uses wide integers or vectors when possible.
473     /// \return True if some memory operations were changed.
474     bool MergeConsecutiveStores(StoreSDNode *N);
475 
476     /// \brief Try to transform a truncation where C is a constant:
477     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
478     ///
479     /// \p N needs to be a truncation and its first operand an AND. Other
480     /// requirements are checked by the function (e.g. that trunc is
481     /// single-use) and if missed an empty SDValue is returned.
482     SDValue distributeTruncateThroughAnd(SDNode *N);
483 
484   public:
485     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
486         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
487           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
488       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
489     }
490 
491     /// Runs the dag combiner on all nodes in the work list
492     void Run(CombineLevel AtLevel);
493 
494     SelectionDAG &getDAG() const { return DAG; }
495 
496     /// Returns a type large enough to hold any valid shift amount - before type
497     /// legalization these can be huge.
498     EVT getShiftAmountTy(EVT LHSTy) {
499       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
500       if (LHSTy.isVector())
501         return LHSTy;
502       auto &DL = DAG.getDataLayout();
503       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
504                         : TLI.getPointerTy(DL);
505     }
506 
507     /// This method returns true if we are running before type legalization or
508     /// if the specified VT is legal.
509     bool isTypeLegal(const EVT &VT) {
510       if (!LegalTypes) return true;
511       return TLI.isTypeLegal(VT);
512     }
513 
514     /// Convenience wrapper around TargetLowering::getSetCCResultType
515     EVT getSetCCResultType(EVT VT) const {
516       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
517     }
518   };
519 }
520 
521 
522 namespace {
523 /// This class is a DAGUpdateListener that removes any deleted
524 /// nodes from the worklist.
525 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
526   DAGCombiner &DC;
527 public:
528   explicit WorklistRemover(DAGCombiner &dc)
529     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
530 
531   void NodeDeleted(SDNode *N, SDNode *E) override {
532     DC.removeFromWorklist(N);
533   }
534 };
535 }
536 
537 //===----------------------------------------------------------------------===//
538 //  TargetLowering::DAGCombinerInfo implementation
539 //===----------------------------------------------------------------------===//
540 
541 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
542   ((DAGCombiner*)DC)->AddToWorklist(N);
543 }
544 
545 SDValue TargetLowering::DAGCombinerInfo::
546 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
547   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
548 }
549 
550 SDValue TargetLowering::DAGCombinerInfo::
551 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
552   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
553 }
554 
555 
556 SDValue TargetLowering::DAGCombinerInfo::
557 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
558   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
559 }
560 
561 void TargetLowering::DAGCombinerInfo::
562 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
563   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
564 }
565 
566 //===----------------------------------------------------------------------===//
567 // Helper Functions
568 //===----------------------------------------------------------------------===//
569 
570 void DAGCombiner::deleteAndRecombine(SDNode *N) {
571   removeFromWorklist(N);
572 
573   // If the operands of this node are only used by the node, they will now be
574   // dead. Make sure to re-visit them and recursively delete dead nodes.
575   for (const SDValue &Op : N->ops())
576     // For an operand generating multiple values, one of the values may
577     // become dead allowing further simplification (e.g. split index
578     // arithmetic from an indexed load).
579     if (Op->hasOneUse() || Op->getNumValues() > 1)
580       AddToWorklist(Op.getNode());
581 
582   DAG.DeleteNode(N);
583 }
584 
585 /// Return 1 if we can compute the negated form of the specified expression for
586 /// the same cost as the expression itself, or 2 if we can compute the negated
587 /// form more cheaply than the expression itself.
588 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
589                                const TargetLowering &TLI,
590                                const TargetOptions *Options,
591                                unsigned Depth = 0) {
592   // fneg is removable even if it has multiple uses.
593   if (Op.getOpcode() == ISD::FNEG) return 2;
594 
595   // Don't allow anything with multiple uses.
596   if (!Op.hasOneUse()) return 0;
597 
598   // Don't recurse exponentially.
599   if (Depth > 6) return 0;
600 
601   switch (Op.getOpcode()) {
602   default: return false;
603   case ISD::ConstantFP:
604     // Don't invert constant FP values after legalize.  The negated constant
605     // isn't necessarily legal.
606     return LegalOperations ? 0 : 1;
607   case ISD::FADD:
608     // FIXME: determine better conditions for this xform.
609     if (!Options->UnsafeFPMath) return 0;
610 
611     // After operation legalization, it might not be legal to create new FSUBs.
612     if (LegalOperations &&
613         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
614       return 0;
615 
616     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
617     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
618                                     Options, Depth + 1))
619       return V;
620     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
621     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
622                               Depth + 1);
623   case ISD::FSUB:
624     // We can't turn -(A-B) into B-A when we honor signed zeros.
625     if (!Options->UnsafeFPMath && !Op.getNode()->getFlags()->hasNoSignedZeros())
626       return 0;
627 
628     // fold (fneg (fsub A, B)) -> (fsub B, A)
629     return 1;
630 
631   case ISD::FMUL:
632   case ISD::FDIV:
633     if (Options->HonorSignDependentRoundingFPMath()) return 0;
634 
635     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
636     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
637                                     Options, Depth + 1))
638       return V;
639 
640     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
641                               Depth + 1);
642 
643   case ISD::FP_EXTEND:
644   case ISD::FP_ROUND:
645   case ISD::FSIN:
646     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
647                               Depth + 1);
648   }
649 }
650 
651 /// If isNegatibleForFree returns true, return the newly negated expression.
652 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
653                                     bool LegalOperations, unsigned Depth = 0) {
654   const TargetOptions &Options = DAG.getTarget().Options;
655   // fneg is removable even if it has multiple uses.
656   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
657 
658   // Don't allow anything with multiple uses.
659   assert(Op.hasOneUse() && "Unknown reuse!");
660 
661   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
662 
663   const SDNodeFlags *Flags = Op.getNode()->getFlags();
664 
665   switch (Op.getOpcode()) {
666   default: llvm_unreachable("Unknown code");
667   case ISD::ConstantFP: {
668     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
669     V.changeSign();
670     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
671   }
672   case ISD::FADD:
673     // FIXME: determine better conditions for this xform.
674     assert(Options.UnsafeFPMath);
675 
676     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
677     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
678                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
679       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
680                          GetNegatedExpression(Op.getOperand(0), DAG,
681                                               LegalOperations, Depth+1),
682                          Op.getOperand(1), Flags);
683     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
684     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
685                        GetNegatedExpression(Op.getOperand(1), DAG,
686                                             LegalOperations, Depth+1),
687                        Op.getOperand(0), Flags);
688   case ISD::FSUB:
689     // fold (fneg (fsub 0, B)) -> B
690     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
691       if (N0CFP->isZero())
692         return Op.getOperand(1);
693 
694     // fold (fneg (fsub A, B)) -> (fsub B, A)
695     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
696                        Op.getOperand(1), Op.getOperand(0), Flags);
697 
698   case ISD::FMUL:
699   case ISD::FDIV:
700     assert(!Options.HonorSignDependentRoundingFPMath());
701 
702     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
703     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
704                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
705       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
706                          GetNegatedExpression(Op.getOperand(0), DAG,
707                                               LegalOperations, Depth+1),
708                          Op.getOperand(1), Flags);
709 
710     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
711     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
712                        Op.getOperand(0),
713                        GetNegatedExpression(Op.getOperand(1), DAG,
714                                             LegalOperations, Depth+1), Flags);
715 
716   case ISD::FP_EXTEND:
717   case ISD::FSIN:
718     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
719                        GetNegatedExpression(Op.getOperand(0), DAG,
720                                             LegalOperations, Depth+1));
721   case ISD::FP_ROUND:
722       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
723                          GetNegatedExpression(Op.getOperand(0), DAG,
724                                               LegalOperations, Depth+1),
725                          Op.getOperand(1));
726   }
727 }
728 
729 // APInts must be the same size for most operations, this helper
730 // function zero extends the shorter of the pair so that they match.
731 // We provide an Offset so that we can create bitwidths that won't overflow.
732 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
733   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
734   LHS = LHS.zextOrSelf(Bits);
735   RHS = RHS.zextOrSelf(Bits);
736 }
737 
738 // Return true if this node is a setcc, or is a select_cc
739 // that selects between the target values used for true and false, making it
740 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
741 // the appropriate nodes based on the type of node we are checking. This
742 // simplifies life a bit for the callers.
743 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
744                                     SDValue &CC) const {
745   if (N.getOpcode() == ISD::SETCC) {
746     LHS = N.getOperand(0);
747     RHS = N.getOperand(1);
748     CC  = N.getOperand(2);
749     return true;
750   }
751 
752   if (N.getOpcode() != ISD::SELECT_CC ||
753       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
754       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
755     return false;
756 
757   if (TLI.getBooleanContents(N.getValueType()) ==
758       TargetLowering::UndefinedBooleanContent)
759     return false;
760 
761   LHS = N.getOperand(0);
762   RHS = N.getOperand(1);
763   CC  = N.getOperand(4);
764   return true;
765 }
766 
767 /// Return true if this is a SetCC-equivalent operation with only one use.
768 /// If this is true, it allows the users to invert the operation for free when
769 /// it is profitable to do so.
770 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
771   SDValue N0, N1, N2;
772   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
773     return true;
774   return false;
775 }
776 
777 // \brief Returns the SDNode if it is a constant float BuildVector
778 // or constant float.
779 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
780   if (isa<ConstantFPSDNode>(N))
781     return N.getNode();
782   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
783     return N.getNode();
784   return nullptr;
785 }
786 
787 // Determines if it is a constant integer or a build vector of constant
788 // integers (and undefs).
789 // Do not permit build vector implicit truncation.
790 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
791   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
792     return !(Const->isOpaque() && NoOpaques);
793   if (N.getOpcode() != ISD::BUILD_VECTOR)
794     return false;
795   unsigned BitWidth = N.getScalarValueSizeInBits();
796   for (const SDValue &Op : N->op_values()) {
797     if (Op.isUndef())
798       continue;
799     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
800     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
801         (Const->isOpaque() && NoOpaques))
802       return false;
803   }
804   return true;
805 }
806 
807 // Determines if it is a constant null integer or a splatted vector of a
808 // constant null integer (with no undefs).
809 // Build vector implicit truncation is not an issue for null values.
810 static bool isNullConstantOrNullSplatConstant(SDValue N) {
811   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
812     return Splat->isNullValue();
813   return false;
814 }
815 
816 // Determines if it is a constant integer of one or a splatted vector of a
817 // constant integer of one (with no undefs).
818 // Do not permit build vector implicit truncation.
819 static bool isOneConstantOrOneSplatConstant(SDValue N) {
820   unsigned BitWidth = N.getScalarValueSizeInBits();
821   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
822     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
823   return false;
824 }
825 
826 // Determines if it is a constant integer of all ones or a splatted vector of a
827 // constant integer of all ones (with no undefs).
828 // Do not permit build vector implicit truncation.
829 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
830   unsigned BitWidth = N.getScalarValueSizeInBits();
831   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
832     return Splat->isAllOnesValue() &&
833            Splat->getAPIntValue().getBitWidth() == BitWidth;
834   return false;
835 }
836 
837 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
838                                     SDValue N1) {
839   EVT VT = N0.getValueType();
840   if (N0.getOpcode() == Opc) {
841     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
842       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
843         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
844         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
845           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
846         return SDValue();
847       }
848       if (N0.hasOneUse()) {
849         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
850         // use
851         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
852         if (!OpNode.getNode())
853           return SDValue();
854         AddToWorklist(OpNode.getNode());
855         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
856       }
857     }
858   }
859 
860   if (N1.getOpcode() == Opc) {
861     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
862       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
863         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
864         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
865           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
866         return SDValue();
867       }
868       if (N1.hasOneUse()) {
869         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
870         // use
871         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
872         if (!OpNode.getNode())
873           return SDValue();
874         AddToWorklist(OpNode.getNode());
875         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
876       }
877     }
878   }
879 
880   return SDValue();
881 }
882 
883 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
884                                bool AddTo) {
885   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
886   ++NodesCombined;
887   DEBUG(dbgs() << "\nReplacing.1 ";
888         N->dump(&DAG);
889         dbgs() << "\nWith: ";
890         To[0].getNode()->dump(&DAG);
891         dbgs() << " and " << NumTo-1 << " other values\n");
892   for (unsigned i = 0, e = NumTo; i != e; ++i)
893     assert((!To[i].getNode() ||
894             N->getValueType(i) == To[i].getValueType()) &&
895            "Cannot combine value to value of different type!");
896 
897   WorklistRemover DeadNodes(*this);
898   DAG.ReplaceAllUsesWith(N, To);
899   if (AddTo) {
900     // Push the new nodes and any users onto the worklist
901     for (unsigned i = 0, e = NumTo; i != e; ++i) {
902       if (To[i].getNode()) {
903         AddToWorklist(To[i].getNode());
904         AddUsersToWorklist(To[i].getNode());
905       }
906     }
907   }
908 
909   // Finally, if the node is now dead, remove it from the graph.  The node
910   // may not be dead if the replacement process recursively simplified to
911   // something else needing this node.
912   if (N->use_empty())
913     deleteAndRecombine(N);
914   return SDValue(N, 0);
915 }
916 
917 void DAGCombiner::
918 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
919   // Replace all uses.  If any nodes become isomorphic to other nodes and
920   // are deleted, make sure to remove them from our worklist.
921   WorklistRemover DeadNodes(*this);
922   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
923 
924   // Push the new node and any (possibly new) users onto the worklist.
925   AddToWorklist(TLO.New.getNode());
926   AddUsersToWorklist(TLO.New.getNode());
927 
928   // Finally, if the node is now dead, remove it from the graph.  The node
929   // may not be dead if the replacement process recursively simplified to
930   // something else needing this node.
931   if (TLO.Old.getNode()->use_empty())
932     deleteAndRecombine(TLO.Old.getNode());
933 }
934 
935 /// Check the specified integer node value to see if it can be simplified or if
936 /// things it uses can be simplified by bit propagation. If so, return true.
937 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
938   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
939   APInt KnownZero, KnownOne;
940   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
941     return false;
942 
943   // Revisit the node.
944   AddToWorklist(Op.getNode());
945 
946   // Replace the old value with the new one.
947   ++NodesCombined;
948   DEBUG(dbgs() << "\nReplacing.2 ";
949         TLO.Old.getNode()->dump(&DAG);
950         dbgs() << "\nWith: ";
951         TLO.New.getNode()->dump(&DAG);
952         dbgs() << '\n');
953 
954   CommitTargetLoweringOpt(TLO);
955   return true;
956 }
957 
958 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
959   SDLoc DL(Load);
960   EVT VT = Load->getValueType(0);
961   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
962 
963   DEBUG(dbgs() << "\nReplacing.9 ";
964         Load->dump(&DAG);
965         dbgs() << "\nWith: ";
966         Trunc.getNode()->dump(&DAG);
967         dbgs() << '\n');
968   WorklistRemover DeadNodes(*this);
969   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
970   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
971   deleteAndRecombine(Load);
972   AddToWorklist(Trunc.getNode());
973 }
974 
975 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
976   Replace = false;
977   SDLoc DL(Op);
978   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
979     LoadSDNode *LD = cast<LoadSDNode>(Op);
980     EVT MemVT = LD->getMemoryVT();
981     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
982       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
983                                                        : ISD::EXTLOAD)
984       : LD->getExtensionType();
985     Replace = true;
986     return DAG.getExtLoad(ExtType, DL, PVT,
987                           LD->getChain(), LD->getBasePtr(),
988                           MemVT, LD->getMemOperand());
989   }
990 
991   unsigned Opc = Op.getOpcode();
992   switch (Opc) {
993   default: break;
994   case ISD::AssertSext:
995     return DAG.getNode(ISD::AssertSext, DL, PVT,
996                        SExtPromoteOperand(Op.getOperand(0), PVT),
997                        Op.getOperand(1));
998   case ISD::AssertZext:
999     return DAG.getNode(ISD::AssertZext, DL, PVT,
1000                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1001                        Op.getOperand(1));
1002   case ISD::Constant: {
1003     unsigned ExtOpc =
1004       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1005     return DAG.getNode(ExtOpc, DL, PVT, Op);
1006   }
1007   }
1008 
1009   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1010     return SDValue();
1011   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1012 }
1013 
1014 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1015   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1016     return SDValue();
1017   EVT OldVT = Op.getValueType();
1018   SDLoc DL(Op);
1019   bool Replace = false;
1020   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1021   if (!NewOp.getNode())
1022     return SDValue();
1023   AddToWorklist(NewOp.getNode());
1024 
1025   if (Replace)
1026     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1027   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1028                      DAG.getValueType(OldVT));
1029 }
1030 
1031 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1032   EVT OldVT = Op.getValueType();
1033   SDLoc DL(Op);
1034   bool Replace = false;
1035   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1036   if (!NewOp.getNode())
1037     return SDValue();
1038   AddToWorklist(NewOp.getNode());
1039 
1040   if (Replace)
1041     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1042   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1043 }
1044 
1045 /// Promote the specified integer binary operation if the target indicates it is
1046 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1047 /// i32 since i16 instructions are longer.
1048 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1049   if (!LegalOperations)
1050     return SDValue();
1051 
1052   EVT VT = Op.getValueType();
1053   if (VT.isVector() || !VT.isInteger())
1054     return SDValue();
1055 
1056   // If operation type is 'undesirable', e.g. i16 on x86, consider
1057   // promoting it.
1058   unsigned Opc = Op.getOpcode();
1059   if (TLI.isTypeDesirableForOp(Opc, VT))
1060     return SDValue();
1061 
1062   EVT PVT = VT;
1063   // Consult target whether it is a good idea to promote this operation and
1064   // what's the right type to promote it to.
1065   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1066     assert(PVT != VT && "Don't know what type to promote to!");
1067 
1068     bool Replace0 = false;
1069     SDValue N0 = Op.getOperand(0);
1070     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1071     if (!NN0.getNode())
1072       return SDValue();
1073 
1074     bool Replace1 = false;
1075     SDValue N1 = Op.getOperand(1);
1076     SDValue NN1;
1077     if (N0 == N1)
1078       NN1 = NN0;
1079     else {
1080       NN1 = PromoteOperand(N1, PVT, Replace1);
1081       if (!NN1.getNode())
1082         return SDValue();
1083     }
1084 
1085     AddToWorklist(NN0.getNode());
1086     if (NN1.getNode())
1087       AddToWorklist(NN1.getNode());
1088 
1089     if (Replace0)
1090       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1091     if (Replace1)
1092       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1093 
1094     DEBUG(dbgs() << "\nPromoting ";
1095           Op.getNode()->dump(&DAG));
1096     SDLoc DL(Op);
1097     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1098                        DAG.getNode(Opc, DL, PVT, NN0, NN1));
1099   }
1100   return SDValue();
1101 }
1102 
1103 /// Promote the specified integer shift operation if the target indicates it is
1104 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1105 /// i32 since i16 instructions are longer.
1106 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1107   if (!LegalOperations)
1108     return SDValue();
1109 
1110   EVT VT = Op.getValueType();
1111   if (VT.isVector() || !VT.isInteger())
1112     return SDValue();
1113 
1114   // If operation type is 'undesirable', e.g. i16 on x86, consider
1115   // promoting it.
1116   unsigned Opc = Op.getOpcode();
1117   if (TLI.isTypeDesirableForOp(Opc, VT))
1118     return SDValue();
1119 
1120   EVT PVT = VT;
1121   // Consult target whether it is a good idea to promote this operation and
1122   // what's the right type to promote it to.
1123   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1124     assert(PVT != VT && "Don't know what type to promote to!");
1125 
1126     bool Replace = false;
1127     SDValue N0 = Op.getOperand(0);
1128     if (Opc == ISD::SRA)
1129       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1130     else if (Opc == ISD::SRL)
1131       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1132     else
1133       N0 = PromoteOperand(N0, PVT, Replace);
1134     if (!N0.getNode())
1135       return SDValue();
1136 
1137     AddToWorklist(N0.getNode());
1138     if (Replace)
1139       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1140 
1141     DEBUG(dbgs() << "\nPromoting ";
1142           Op.getNode()->dump(&DAG));
1143     SDLoc DL(Op);
1144     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1145                        DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1146   }
1147   return SDValue();
1148 }
1149 
1150 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1151   if (!LegalOperations)
1152     return SDValue();
1153 
1154   EVT VT = Op.getValueType();
1155   if (VT.isVector() || !VT.isInteger())
1156     return SDValue();
1157 
1158   // If operation type is 'undesirable', e.g. i16 on x86, consider
1159   // promoting it.
1160   unsigned Opc = Op.getOpcode();
1161   if (TLI.isTypeDesirableForOp(Opc, VT))
1162     return SDValue();
1163 
1164   EVT PVT = VT;
1165   // Consult target whether it is a good idea to promote this operation and
1166   // what's the right type to promote it to.
1167   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1168     assert(PVT != VT && "Don't know what type to promote to!");
1169     // fold (aext (aext x)) -> (aext x)
1170     // fold (aext (zext x)) -> (zext x)
1171     // fold (aext (sext x)) -> (sext x)
1172     DEBUG(dbgs() << "\nPromoting ";
1173           Op.getNode()->dump(&DAG));
1174     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1175   }
1176   return SDValue();
1177 }
1178 
1179 bool DAGCombiner::PromoteLoad(SDValue Op) {
1180   if (!LegalOperations)
1181     return false;
1182 
1183   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1184     return false;
1185 
1186   EVT VT = Op.getValueType();
1187   if (VT.isVector() || !VT.isInteger())
1188     return false;
1189 
1190   // If operation type is 'undesirable', e.g. i16 on x86, consider
1191   // promoting it.
1192   unsigned Opc = Op.getOpcode();
1193   if (TLI.isTypeDesirableForOp(Opc, VT))
1194     return false;
1195 
1196   EVT PVT = VT;
1197   // Consult target whether it is a good idea to promote this operation and
1198   // what's the right type to promote it to.
1199   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1200     assert(PVT != VT && "Don't know what type to promote to!");
1201 
1202     SDLoc DL(Op);
1203     SDNode *N = Op.getNode();
1204     LoadSDNode *LD = cast<LoadSDNode>(N);
1205     EVT MemVT = LD->getMemoryVT();
1206     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1207       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1208                                                        : ISD::EXTLOAD)
1209       : LD->getExtensionType();
1210     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1211                                    LD->getChain(), LD->getBasePtr(),
1212                                    MemVT, LD->getMemOperand());
1213     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1214 
1215     DEBUG(dbgs() << "\nPromoting ";
1216           N->dump(&DAG);
1217           dbgs() << "\nTo: ";
1218           Result.getNode()->dump(&DAG);
1219           dbgs() << '\n');
1220     WorklistRemover DeadNodes(*this);
1221     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1222     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1223     deleteAndRecombine(N);
1224     AddToWorklist(Result.getNode());
1225     return true;
1226   }
1227   return false;
1228 }
1229 
1230 /// \brief Recursively delete a node which has no uses and any operands for
1231 /// which it is the only use.
1232 ///
1233 /// Note that this both deletes the nodes and removes them from the worklist.
1234 /// It also adds any nodes who have had a user deleted to the worklist as they
1235 /// may now have only one use and subject to other combines.
1236 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1237   if (!N->use_empty())
1238     return false;
1239 
1240   SmallSetVector<SDNode *, 16> Nodes;
1241   Nodes.insert(N);
1242   do {
1243     N = Nodes.pop_back_val();
1244     if (!N)
1245       continue;
1246 
1247     if (N->use_empty()) {
1248       for (const SDValue &ChildN : N->op_values())
1249         Nodes.insert(ChildN.getNode());
1250 
1251       removeFromWorklist(N);
1252       DAG.DeleteNode(N);
1253     } else {
1254       AddToWorklist(N);
1255     }
1256   } while (!Nodes.empty());
1257   return true;
1258 }
1259 
1260 //===----------------------------------------------------------------------===//
1261 //  Main DAG Combiner implementation
1262 //===----------------------------------------------------------------------===//
1263 
1264 void DAGCombiner::Run(CombineLevel AtLevel) {
1265   // set the instance variables, so that the various visit routines may use it.
1266   Level = AtLevel;
1267   LegalOperations = Level >= AfterLegalizeVectorOps;
1268   LegalTypes = Level >= AfterLegalizeTypes;
1269 
1270   // Add all the dag nodes to the worklist.
1271   for (SDNode &Node : DAG.allnodes())
1272     AddToWorklist(&Node);
1273 
1274   // Create a dummy node (which is not added to allnodes), that adds a reference
1275   // to the root node, preventing it from being deleted, and tracking any
1276   // changes of the root.
1277   HandleSDNode Dummy(DAG.getRoot());
1278 
1279   // While the worklist isn't empty, find a node and try to combine it.
1280   while (!WorklistMap.empty()) {
1281     SDNode *N;
1282     // The Worklist holds the SDNodes in order, but it may contain null entries.
1283     do {
1284       N = Worklist.pop_back_val();
1285     } while (!N);
1286 
1287     bool GoodWorklistEntry = WorklistMap.erase(N);
1288     (void)GoodWorklistEntry;
1289     assert(GoodWorklistEntry &&
1290            "Found a worklist entry without a corresponding map entry!");
1291 
1292     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1293     // N is deleted from the DAG, since they too may now be dead or may have a
1294     // reduced number of uses, allowing other xforms.
1295     if (recursivelyDeleteUnusedNodes(N))
1296       continue;
1297 
1298     WorklistRemover DeadNodes(*this);
1299 
1300     // If this combine is running after legalizing the DAG, re-legalize any
1301     // nodes pulled off the worklist.
1302     if (Level == AfterLegalizeDAG) {
1303       SmallSetVector<SDNode *, 16> UpdatedNodes;
1304       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1305 
1306       for (SDNode *LN : UpdatedNodes) {
1307         AddToWorklist(LN);
1308         AddUsersToWorklist(LN);
1309       }
1310       if (!NIsValid)
1311         continue;
1312     }
1313 
1314     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1315 
1316     // Add any operands of the new node which have not yet been combined to the
1317     // worklist as well. Because the worklist uniques things already, this
1318     // won't repeatedly process the same operand.
1319     CombinedNodes.insert(N);
1320     for (const SDValue &ChildN : N->op_values())
1321       if (!CombinedNodes.count(ChildN.getNode()))
1322         AddToWorklist(ChildN.getNode());
1323 
1324     SDValue RV = combine(N);
1325 
1326     if (!RV.getNode())
1327       continue;
1328 
1329     ++NodesCombined;
1330 
1331     // If we get back the same node we passed in, rather than a new node or
1332     // zero, we know that the node must have defined multiple values and
1333     // CombineTo was used.  Since CombineTo takes care of the worklist
1334     // mechanics for us, we have no work to do in this case.
1335     if (RV.getNode() == N)
1336       continue;
1337 
1338     assert(N->getOpcode() != ISD::DELETED_NODE &&
1339            RV.getOpcode() != ISD::DELETED_NODE &&
1340            "Node was deleted but visit returned new node!");
1341 
1342     DEBUG(dbgs() << " ... into: ";
1343           RV.getNode()->dump(&DAG));
1344 
1345     if (N->getNumValues() == RV.getNode()->getNumValues())
1346       DAG.ReplaceAllUsesWith(N, RV.getNode());
1347     else {
1348       assert(N->getValueType(0) == RV.getValueType() &&
1349              N->getNumValues() == 1 && "Type mismatch");
1350       SDValue OpV = RV;
1351       DAG.ReplaceAllUsesWith(N, &OpV);
1352     }
1353 
1354     // Push the new node and any users onto the worklist
1355     AddToWorklist(RV.getNode());
1356     AddUsersToWorklist(RV.getNode());
1357 
1358     // Finally, if the node is now dead, remove it from the graph.  The node
1359     // may not be dead if the replacement process recursively simplified to
1360     // something else needing this node. This will also take care of adding any
1361     // operands which have lost a user to the worklist.
1362     recursivelyDeleteUnusedNodes(N);
1363   }
1364 
1365   // If the root changed (e.g. it was a dead load, update the root).
1366   DAG.setRoot(Dummy.getValue());
1367   DAG.RemoveDeadNodes();
1368 }
1369 
1370 SDValue DAGCombiner::visit(SDNode *N) {
1371   switch (N->getOpcode()) {
1372   default: break;
1373   case ISD::TokenFactor:        return visitTokenFactor(N);
1374   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1375   case ISD::ADD:                return visitADD(N);
1376   case ISD::SUB:                return visitSUB(N);
1377   case ISD::ADDC:               return visitADDC(N);
1378   case ISD::SUBC:               return visitSUBC(N);
1379   case ISD::ADDE:               return visitADDE(N);
1380   case ISD::SUBE:               return visitSUBE(N);
1381   case ISD::MUL:                return visitMUL(N);
1382   case ISD::SDIV:               return visitSDIV(N);
1383   case ISD::UDIV:               return visitUDIV(N);
1384   case ISD::SREM:
1385   case ISD::UREM:               return visitREM(N);
1386   case ISD::MULHU:              return visitMULHU(N);
1387   case ISD::MULHS:              return visitMULHS(N);
1388   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1389   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1390   case ISD::SMULO:              return visitSMULO(N);
1391   case ISD::UMULO:              return visitUMULO(N);
1392   case ISD::SMIN:
1393   case ISD::SMAX:
1394   case ISD::UMIN:
1395   case ISD::UMAX:               return visitIMINMAX(N);
1396   case ISD::AND:                return visitAND(N);
1397   case ISD::OR:                 return visitOR(N);
1398   case ISD::XOR:                return visitXOR(N);
1399   case ISD::SHL:                return visitSHL(N);
1400   case ISD::SRA:                return visitSRA(N);
1401   case ISD::SRL:                return visitSRL(N);
1402   case ISD::ROTR:
1403   case ISD::ROTL:               return visitRotate(N);
1404   case ISD::BSWAP:              return visitBSWAP(N);
1405   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1406   case ISD::CTLZ:               return visitCTLZ(N);
1407   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1408   case ISD::CTTZ:               return visitCTTZ(N);
1409   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1410   case ISD::CTPOP:              return visitCTPOP(N);
1411   case ISD::SELECT:             return visitSELECT(N);
1412   case ISD::VSELECT:            return visitVSELECT(N);
1413   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1414   case ISD::SETCC:              return visitSETCC(N);
1415   case ISD::SETCCE:             return visitSETCCE(N);
1416   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1417   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1418   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1419   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1420   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1421   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1422   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1423   case ISD::BITCAST:            return visitBITCAST(N);
1424   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1425   case ISD::FADD:               return visitFADD(N);
1426   case ISD::FSUB:               return visitFSUB(N);
1427   case ISD::FMUL:               return visitFMUL(N);
1428   case ISD::FMA:                return visitFMA(N);
1429   case ISD::FDIV:               return visitFDIV(N);
1430   case ISD::FREM:               return visitFREM(N);
1431   case ISD::FSQRT:              return visitFSQRT(N);
1432   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1433   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1434   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1435   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1436   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1437   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1438   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1439   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1440   case ISD::FNEG:               return visitFNEG(N);
1441   case ISD::FABS:               return visitFABS(N);
1442   case ISD::FFLOOR:             return visitFFLOOR(N);
1443   case ISD::FMINNUM:            return visitFMINNUM(N);
1444   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1445   case ISD::FCEIL:              return visitFCEIL(N);
1446   case ISD::FTRUNC:             return visitFTRUNC(N);
1447   case ISD::BRCOND:             return visitBRCOND(N);
1448   case ISD::BR_CC:              return visitBR_CC(N);
1449   case ISD::LOAD:               return visitLOAD(N);
1450   case ISD::STORE:              return visitSTORE(N);
1451   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1452   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1453   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1454   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1455   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1456   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1457   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1458   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1459   case ISD::MGATHER:            return visitMGATHER(N);
1460   case ISD::MLOAD:              return visitMLOAD(N);
1461   case ISD::MSCATTER:           return visitMSCATTER(N);
1462   case ISD::MSTORE:             return visitMSTORE(N);
1463   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1464   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1465   }
1466   return SDValue();
1467 }
1468 
1469 SDValue DAGCombiner::combine(SDNode *N) {
1470   SDValue RV = visit(N);
1471 
1472   // If nothing happened, try a target-specific DAG combine.
1473   if (!RV.getNode()) {
1474     assert(N->getOpcode() != ISD::DELETED_NODE &&
1475            "Node was deleted but visit returned NULL!");
1476 
1477     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1478         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1479 
1480       // Expose the DAG combiner to the target combiner impls.
1481       TargetLowering::DAGCombinerInfo
1482         DagCombineInfo(DAG, Level, false, this);
1483 
1484       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1485     }
1486   }
1487 
1488   // If nothing happened still, try promoting the operation.
1489   if (!RV.getNode()) {
1490     switch (N->getOpcode()) {
1491     default: break;
1492     case ISD::ADD:
1493     case ISD::SUB:
1494     case ISD::MUL:
1495     case ISD::AND:
1496     case ISD::OR:
1497     case ISD::XOR:
1498       RV = PromoteIntBinOp(SDValue(N, 0));
1499       break;
1500     case ISD::SHL:
1501     case ISD::SRA:
1502     case ISD::SRL:
1503       RV = PromoteIntShiftOp(SDValue(N, 0));
1504       break;
1505     case ISD::SIGN_EXTEND:
1506     case ISD::ZERO_EXTEND:
1507     case ISD::ANY_EXTEND:
1508       RV = PromoteExtend(SDValue(N, 0));
1509       break;
1510     case ISD::LOAD:
1511       if (PromoteLoad(SDValue(N, 0)))
1512         RV = SDValue(N, 0);
1513       break;
1514     }
1515   }
1516 
1517   // If N is a commutative binary node, try commuting it to enable more
1518   // sdisel CSE.
1519   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1520       N->getNumValues() == 1) {
1521     SDValue N0 = N->getOperand(0);
1522     SDValue N1 = N->getOperand(1);
1523 
1524     // Constant operands are canonicalized to RHS.
1525     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1526       SDValue Ops[] = {N1, N0};
1527       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1528                                             N->getFlags());
1529       if (CSENode)
1530         return SDValue(CSENode, 0);
1531     }
1532   }
1533 
1534   return RV;
1535 }
1536 
1537 /// Given a node, return its input chain if it has one, otherwise return a null
1538 /// sd operand.
1539 static SDValue getInputChainForNode(SDNode *N) {
1540   if (unsigned NumOps = N->getNumOperands()) {
1541     if (N->getOperand(0).getValueType() == MVT::Other)
1542       return N->getOperand(0);
1543     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1544       return N->getOperand(NumOps-1);
1545     for (unsigned i = 1; i < NumOps-1; ++i)
1546       if (N->getOperand(i).getValueType() == MVT::Other)
1547         return N->getOperand(i);
1548   }
1549   return SDValue();
1550 }
1551 
1552 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1553   // If N has two operands, where one has an input chain equal to the other,
1554   // the 'other' chain is redundant.
1555   if (N->getNumOperands() == 2) {
1556     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1557       return N->getOperand(0);
1558     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1559       return N->getOperand(1);
1560   }
1561 
1562   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1563   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1564   SmallPtrSet<SDNode*, 16> SeenOps;
1565   bool Changed = false;             // If we should replace this token factor.
1566 
1567   // Start out with this token factor.
1568   TFs.push_back(N);
1569 
1570   // Iterate through token factors.  The TFs grows when new token factors are
1571   // encountered.
1572   for (unsigned i = 0; i < TFs.size(); ++i) {
1573     SDNode *TF = TFs[i];
1574 
1575     // Check each of the operands.
1576     for (const SDValue &Op : TF->op_values()) {
1577 
1578       switch (Op.getOpcode()) {
1579       case ISD::EntryToken:
1580         // Entry tokens don't need to be added to the list. They are
1581         // redundant.
1582         Changed = true;
1583         break;
1584 
1585       case ISD::TokenFactor:
1586         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1587           // Queue up for processing.
1588           TFs.push_back(Op.getNode());
1589           // Clean up in case the token factor is removed.
1590           AddToWorklist(Op.getNode());
1591           Changed = true;
1592           break;
1593         }
1594         LLVM_FALLTHROUGH;
1595 
1596       default:
1597         // Only add if it isn't already in the list.
1598         if (SeenOps.insert(Op.getNode()).second)
1599           Ops.push_back(Op);
1600         else
1601           Changed = true;
1602         break;
1603       }
1604     }
1605   }
1606 
1607   SDValue Result;
1608 
1609   // If we've changed things around then replace token factor.
1610   if (Changed) {
1611     if (Ops.empty()) {
1612       // The entry token is the only possible outcome.
1613       Result = DAG.getEntryNode();
1614     } else {
1615       // New and improved token factor.
1616       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1617     }
1618 
1619     // Add users to worklist if AA is enabled, since it may introduce
1620     // a lot of new chained token factors while removing memory deps.
1621     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1622       : DAG.getSubtarget().useAA();
1623     return CombineTo(N, Result, UseAA /*add to worklist*/);
1624   }
1625 
1626   return Result;
1627 }
1628 
1629 /// MERGE_VALUES can always be eliminated.
1630 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1631   WorklistRemover DeadNodes(*this);
1632   // Replacing results may cause a different MERGE_VALUES to suddenly
1633   // be CSE'd with N, and carry its uses with it. Iterate until no
1634   // uses remain, to ensure that the node can be safely deleted.
1635   // First add the users of this node to the work list so that they
1636   // can be tried again once they have new operands.
1637   AddUsersToWorklist(N);
1638   do {
1639     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1640       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1641   } while (!N->use_empty());
1642   deleteAndRecombine(N);
1643   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1644 }
1645 
1646 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1647 /// ConstantSDNode pointer else nullptr.
1648 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1649   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1650   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1651 }
1652 
1653 SDValue DAGCombiner::visitADD(SDNode *N) {
1654   SDValue N0 = N->getOperand(0);
1655   SDValue N1 = N->getOperand(1);
1656   EVT VT = N0.getValueType();
1657   SDLoc DL(N);
1658 
1659   // fold vector ops
1660   if (VT.isVector()) {
1661     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1662       return FoldedVOp;
1663 
1664     // fold (add x, 0) -> x, vector edition
1665     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1666       return N0;
1667     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1668       return N1;
1669   }
1670 
1671   // fold (add x, undef) -> undef
1672   if (N0.isUndef())
1673     return N0;
1674 
1675   if (N1.isUndef())
1676     return N1;
1677 
1678   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1679     // canonicalize constant to RHS
1680     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1681       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1682     // fold (add c1, c2) -> c1+c2
1683     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1684                                       N1.getNode());
1685   }
1686 
1687   // fold (add x, 0) -> x
1688   if (isNullConstant(N1))
1689     return N0;
1690 
1691   // fold ((c1-A)+c2) -> (c1+c2)-A
1692   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1693     if (N0.getOpcode() == ISD::SUB)
1694       if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1695         return DAG.getNode(ISD::SUB, DL, VT,
1696                            DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1697                            N0.getOperand(1));
1698       }
1699   }
1700 
1701   // reassociate add
1702   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1703     return RADD;
1704 
1705   // fold ((0-A) + B) -> B-A
1706   if (N0.getOpcode() == ISD::SUB &&
1707       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1708     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1709 
1710   // fold (A + (0-B)) -> A-B
1711   if (N1.getOpcode() == ISD::SUB &&
1712       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1713     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1714 
1715   // fold (A+(B-A)) -> B
1716   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1717     return N1.getOperand(0);
1718 
1719   // fold ((B-A)+A) -> B
1720   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1721     return N0.getOperand(0);
1722 
1723   // fold (A+(B-(A+C))) to (B-C)
1724   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1725       N0 == N1.getOperand(1).getOperand(0))
1726     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1727                        N1.getOperand(1).getOperand(1));
1728 
1729   // fold (A+(B-(C+A))) to (B-C)
1730   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1731       N0 == N1.getOperand(1).getOperand(1))
1732     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1733                        N1.getOperand(1).getOperand(0));
1734 
1735   // fold (A+((B-A)+or-C)) to (B+or-C)
1736   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1737       N1.getOperand(0).getOpcode() == ISD::SUB &&
1738       N0 == N1.getOperand(0).getOperand(1))
1739     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1740                        N1.getOperand(1));
1741 
1742   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1743   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1744     SDValue N00 = N0.getOperand(0);
1745     SDValue N01 = N0.getOperand(1);
1746     SDValue N10 = N1.getOperand(0);
1747     SDValue N11 = N1.getOperand(1);
1748 
1749     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1750       return DAG.getNode(ISD::SUB, DL, VT,
1751                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1752                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1753   }
1754 
1755   if (SimplifyDemandedBits(SDValue(N, 0)))
1756     return SDValue(N, 0);
1757 
1758   // fold (a+b) -> (a|b) iff a and b share no bits.
1759   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1760       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1761     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1762 
1763   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1764   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1765       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1766     return DAG.getNode(ISD::SUB, DL, VT, N0,
1767                        DAG.getNode(ISD::SHL, DL, VT,
1768                                    N1.getOperand(0).getOperand(1),
1769                                    N1.getOperand(1)));
1770   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1771       isNullConstantOrNullSplatConstant(N0.getOperand(0).getOperand(0)))
1772     return DAG.getNode(ISD::SUB, DL, VT, N1,
1773                        DAG.getNode(ISD::SHL, DL, VT,
1774                                    N0.getOperand(0).getOperand(1),
1775                                    N0.getOperand(1)));
1776 
1777   if (N1.getOpcode() == ISD::AND) {
1778     SDValue AndOp0 = N1.getOperand(0);
1779     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1780     unsigned DestBits = VT.getScalarSizeInBits();
1781 
1782     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1783     // and similar xforms where the inner op is either ~0 or 0.
1784     if (NumSignBits == DestBits &&
1785         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1786       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1787   }
1788 
1789   // add (sext i1), X -> sub X, (zext i1)
1790   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1791       N0.getOperand(0).getValueType() == MVT::i1 &&
1792       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1793     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1794     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1795   }
1796 
1797   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1798   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1799     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1800     if (TN->getVT() == MVT::i1) {
1801       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1802                                  DAG.getConstant(1, DL, VT));
1803       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1804     }
1805   }
1806 
1807   return SDValue();
1808 }
1809 
1810 SDValue DAGCombiner::visitADDC(SDNode *N) {
1811   SDValue N0 = N->getOperand(0);
1812   SDValue N1 = N->getOperand(1);
1813   EVT VT = N0.getValueType();
1814 
1815   // If the flag result is dead, turn this into an ADD.
1816   if (!N->hasAnyUseOfValue(1))
1817     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1818                      DAG.getNode(ISD::CARRY_FALSE,
1819                                  SDLoc(N), MVT::Glue));
1820 
1821   // canonicalize constant to RHS.
1822   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1823   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1824   if (N0C && !N1C)
1825     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1826 
1827   // fold (addc x, 0) -> x + no carry out
1828   if (isNullConstant(N1))
1829     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1830                                         SDLoc(N), MVT::Glue));
1831 
1832   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1833   APInt LHSZero, LHSOne;
1834   APInt RHSZero, RHSOne;
1835   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1836 
1837   if (LHSZero.getBoolValue()) {
1838     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1839 
1840     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1841     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1842     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1843       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1844                        DAG.getNode(ISD::CARRY_FALSE,
1845                                    SDLoc(N), MVT::Glue));
1846   }
1847 
1848   return SDValue();
1849 }
1850 
1851 SDValue DAGCombiner::visitADDE(SDNode *N) {
1852   SDValue N0 = N->getOperand(0);
1853   SDValue N1 = N->getOperand(1);
1854   SDValue CarryIn = N->getOperand(2);
1855 
1856   // canonicalize constant to RHS
1857   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1858   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1859   if (N0C && !N1C)
1860     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1861                        N1, N0, CarryIn);
1862 
1863   // fold (adde x, y, false) -> (addc x, y)
1864   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1865     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1866 
1867   return SDValue();
1868 }
1869 
1870 // Since it may not be valid to emit a fold to zero for vector initializers
1871 // check if we can before folding.
1872 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1873                              SelectionDAG &DAG, bool LegalOperations,
1874                              bool LegalTypes) {
1875   if (!VT.isVector())
1876     return DAG.getConstant(0, DL, VT);
1877   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1878     return DAG.getConstant(0, DL, VT);
1879   return SDValue();
1880 }
1881 
1882 SDValue DAGCombiner::visitSUB(SDNode *N) {
1883   SDValue N0 = N->getOperand(0);
1884   SDValue N1 = N->getOperand(1);
1885   EVT VT = N0.getValueType();
1886   SDLoc DL(N);
1887 
1888   // fold vector ops
1889   if (VT.isVector()) {
1890     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1891       return FoldedVOp;
1892 
1893     // fold (sub x, 0) -> x, vector edition
1894     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1895       return N0;
1896   }
1897 
1898   // fold (sub x, x) -> 0
1899   // FIXME: Refactor this and xor and other similar operations together.
1900   if (N0 == N1)
1901     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1902   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1903       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1904     // fold (sub c1, c2) -> c1-c2
1905     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1906                                       N1.getNode());
1907   }
1908 
1909   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1910 
1911   // fold (sub x, c) -> (add x, -c)
1912   if (N1C) {
1913     return DAG.getNode(ISD::ADD, DL, VT, N0,
1914                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1915   }
1916 
1917   if (isNullConstantOrNullSplatConstant(N0)) {
1918     unsigned BitWidth = VT.getScalarSizeInBits();
1919     // Right-shifting everything out but the sign bit followed by negation is
1920     // the same as flipping arithmetic/logical shift type without the negation:
1921     // -(X >>u 31) -> (X >>s 31)
1922     // -(X >>s 31) -> (X >>u 31)
1923     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
1924       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
1925       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
1926         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
1927         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
1928           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
1929       }
1930     }
1931 
1932     // 0 - X --> 0 if the sub is NUW.
1933     if (N->getFlags()->hasNoUnsignedWrap())
1934       return N0;
1935 
1936     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) {
1937       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
1938       // N1 must be 0 because negating the minimum signed value is undefined.
1939       if (N->getFlags()->hasNoSignedWrap())
1940         return N0;
1941 
1942       // 0 - X --> X if X is 0 or the minimum signed value.
1943       return N1;
1944     }
1945   }
1946 
1947   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1948   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
1949     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1950 
1951   // fold A-(A-B) -> B
1952   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1953     return N1.getOperand(1);
1954 
1955   // fold (A+B)-A -> B
1956   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1957     return N0.getOperand(1);
1958 
1959   // fold (A+B)-B -> A
1960   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1961     return N0.getOperand(0);
1962 
1963   // fold C2-(A+C1) -> (C2-C1)-A
1964   if (N1.getOpcode() == ISD::ADD) {
1965     SDValue N11 = N1.getOperand(1);
1966     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
1967         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
1968       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
1969       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
1970     }
1971   }
1972 
1973   // fold ((A+(B+or-C))-B) -> A+or-C
1974   if (N0.getOpcode() == ISD::ADD &&
1975       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1976        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1977       N0.getOperand(1).getOperand(0) == N1)
1978     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
1979                        N0.getOperand(1).getOperand(1));
1980 
1981   // fold ((A+(C+B))-B) -> A+C
1982   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
1983       N0.getOperand(1).getOperand(1) == N1)
1984     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
1985                        N0.getOperand(1).getOperand(0));
1986 
1987   // fold ((A-(B-C))-C) -> A-B
1988   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
1989       N0.getOperand(1).getOperand(1) == N1)
1990     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
1991                        N0.getOperand(1).getOperand(0));
1992 
1993   // If either operand of a sub is undef, the result is undef
1994   if (N0.isUndef())
1995     return N0;
1996   if (N1.isUndef())
1997     return N1;
1998 
1999   // If the relocation model supports it, consider symbol offsets.
2000   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2001     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2002       // fold (sub Sym, c) -> Sym-c
2003       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2004         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2005                                     GA->getOffset() -
2006                                         (uint64_t)N1C->getSExtValue());
2007       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2008       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2009         if (GA->getGlobal() == GB->getGlobal())
2010           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2011                                  DL, VT);
2012     }
2013 
2014   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2015   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2016     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2017     if (TN->getVT() == MVT::i1) {
2018       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2019                                  DAG.getConstant(1, DL, VT));
2020       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2021     }
2022   }
2023 
2024   return SDValue();
2025 }
2026 
2027 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2028   SDValue N0 = N->getOperand(0);
2029   SDValue N1 = N->getOperand(1);
2030   EVT VT = N0.getValueType();
2031   SDLoc DL(N);
2032 
2033   // If the flag result is dead, turn this into an SUB.
2034   if (!N->hasAnyUseOfValue(1))
2035     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2036                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2037 
2038   // fold (subc x, x) -> 0 + no borrow
2039   if (N0 == N1)
2040     return CombineTo(N, DAG.getConstant(0, DL, VT),
2041                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2042 
2043   // fold (subc x, 0) -> x + no borrow
2044   if (isNullConstant(N1))
2045     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2046 
2047   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2048   if (isAllOnesConstant(N0))
2049     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2050                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2051 
2052   return SDValue();
2053 }
2054 
2055 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2056   SDValue N0 = N->getOperand(0);
2057   SDValue N1 = N->getOperand(1);
2058   SDValue CarryIn = N->getOperand(2);
2059 
2060   // fold (sube x, y, false) -> (subc x, y)
2061   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2062     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2063 
2064   return SDValue();
2065 }
2066 
2067 SDValue DAGCombiner::visitMUL(SDNode *N) {
2068   SDValue N0 = N->getOperand(0);
2069   SDValue N1 = N->getOperand(1);
2070   EVT VT = N0.getValueType();
2071 
2072   // fold (mul x, undef) -> 0
2073   if (N0.isUndef() || N1.isUndef())
2074     return DAG.getConstant(0, SDLoc(N), VT);
2075 
2076   bool N0IsConst = false;
2077   bool N1IsConst = false;
2078   bool N1IsOpaqueConst = false;
2079   bool N0IsOpaqueConst = false;
2080   APInt ConstValue0, ConstValue1;
2081   // fold vector ops
2082   if (VT.isVector()) {
2083     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2084       return FoldedVOp;
2085 
2086     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2087     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2088   } else {
2089     N0IsConst = isa<ConstantSDNode>(N0);
2090     if (N0IsConst) {
2091       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2092       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2093     }
2094     N1IsConst = isa<ConstantSDNode>(N1);
2095     if (N1IsConst) {
2096       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2097       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2098     }
2099   }
2100 
2101   // fold (mul c1, c2) -> c1*c2
2102   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2103     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2104                                       N0.getNode(), N1.getNode());
2105 
2106   // canonicalize constant to RHS (vector doesn't have to splat)
2107   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2108      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2109     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2110   // fold (mul x, 0) -> 0
2111   if (N1IsConst && ConstValue1 == 0)
2112     return N1;
2113   // We require a splat of the entire scalar bit width for non-contiguous
2114   // bit patterns.
2115   bool IsFullSplat =
2116     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2117   // fold (mul x, 1) -> x
2118   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2119     return N0;
2120   // fold (mul x, -1) -> 0-x
2121   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2122     SDLoc DL(N);
2123     return DAG.getNode(ISD::SUB, DL, VT,
2124                        DAG.getConstant(0, DL, VT), N0);
2125   }
2126   // fold (mul x, (1 << c)) -> x << c
2127   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2128       IsFullSplat) {
2129     SDLoc DL(N);
2130     return DAG.getNode(ISD::SHL, DL, VT, N0,
2131                        DAG.getConstant(ConstValue1.logBase2(), DL,
2132                                        getShiftAmountTy(N0.getValueType())));
2133   }
2134   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2135   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2136       IsFullSplat) {
2137     unsigned Log2Val = (-ConstValue1).logBase2();
2138     SDLoc DL(N);
2139     // FIXME: If the input is something that is easily negated (e.g. a
2140     // single-use add), we should put the negate there.
2141     return DAG.getNode(ISD::SUB, DL, VT,
2142                        DAG.getConstant(0, DL, VT),
2143                        DAG.getNode(ISD::SHL, DL, VT, N0,
2144                             DAG.getConstant(Log2Val, DL,
2145                                       getShiftAmountTy(N0.getValueType()))));
2146   }
2147 
2148   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2149   if (N0.getOpcode() == ISD::SHL &&
2150       isConstantOrConstantVector(N1) &&
2151       isConstantOrConstantVector(N0.getOperand(1))) {
2152     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2153     AddToWorklist(C3.getNode());
2154     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2155   }
2156 
2157   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2158   // use.
2159   {
2160     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2161 
2162     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2163     if (N0.getOpcode() == ISD::SHL &&
2164         isConstantOrConstantVector(N0.getOperand(1)) &&
2165         N0.getNode()->hasOneUse()) {
2166       Sh = N0; Y = N1;
2167     } else if (N1.getOpcode() == ISD::SHL &&
2168                isConstantOrConstantVector(N1.getOperand(1)) &&
2169                N1.getNode()->hasOneUse()) {
2170       Sh = N1; Y = N0;
2171     }
2172 
2173     if (Sh.getNode()) {
2174       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2175       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2176     }
2177   }
2178 
2179   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2180   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2181       N0.getOpcode() == ISD::ADD &&
2182       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2183       isMulAddWithConstProfitable(N, N0, N1))
2184       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2185                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2186                                      N0.getOperand(0), N1),
2187                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2188                                      N0.getOperand(1), N1));
2189 
2190   // reassociate mul
2191   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2192     return RMUL;
2193 
2194   return SDValue();
2195 }
2196 
2197 /// Return true if divmod libcall is available.
2198 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2199                                      const TargetLowering &TLI) {
2200   RTLIB::Libcall LC;
2201   EVT NodeType = Node->getValueType(0);
2202   if (!NodeType.isSimple())
2203     return false;
2204   switch (NodeType.getSimpleVT().SimpleTy) {
2205   default: return false; // No libcall for vector types.
2206   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2207   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2208   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2209   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2210   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2211   }
2212 
2213   return TLI.getLibcallName(LC) != nullptr;
2214 }
2215 
2216 /// Issue divrem if both quotient and remainder are needed.
2217 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2218   if (Node->use_empty())
2219     return SDValue(); // This is a dead node, leave it alone.
2220 
2221   unsigned Opcode = Node->getOpcode();
2222   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2223   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2224 
2225   // DivMod lib calls can still work on non-legal types if using lib-calls.
2226   EVT VT = Node->getValueType(0);
2227   if (VT.isVector() || !VT.isInteger())
2228     return SDValue();
2229 
2230   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2231     return SDValue();
2232 
2233   // If DIVREM is going to get expanded into a libcall,
2234   // but there is no libcall available, then don't combine.
2235   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2236       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2237     return SDValue();
2238 
2239   // If div is legal, it's better to do the normal expansion
2240   unsigned OtherOpcode = 0;
2241   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2242     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2243     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2244       return SDValue();
2245   } else {
2246     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2247     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2248       return SDValue();
2249   }
2250 
2251   SDValue Op0 = Node->getOperand(0);
2252   SDValue Op1 = Node->getOperand(1);
2253   SDValue combined;
2254   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2255          UE = Op0.getNode()->use_end(); UI != UE;) {
2256     SDNode *User = *UI++;
2257     if (User == Node || User->use_empty())
2258       continue;
2259     // Convert the other matching node(s), too;
2260     // otherwise, the DIVREM may get target-legalized into something
2261     // target-specific that we won't be able to recognize.
2262     unsigned UserOpc = User->getOpcode();
2263     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2264         User->getOperand(0) == Op0 &&
2265         User->getOperand(1) == Op1) {
2266       if (!combined) {
2267         if (UserOpc == OtherOpcode) {
2268           SDVTList VTs = DAG.getVTList(VT, VT);
2269           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2270         } else if (UserOpc == DivRemOpc) {
2271           combined = SDValue(User, 0);
2272         } else {
2273           assert(UserOpc == Opcode);
2274           continue;
2275         }
2276       }
2277       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2278         CombineTo(User, combined);
2279       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2280         CombineTo(User, combined.getValue(1));
2281     }
2282   }
2283   return combined;
2284 }
2285 
2286 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2287   SDValue N0 = N->getOperand(0);
2288   SDValue N1 = N->getOperand(1);
2289   EVT VT = N->getValueType(0);
2290 
2291   // fold vector ops
2292   if (VT.isVector())
2293     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2294       return FoldedVOp;
2295 
2296   SDLoc DL(N);
2297 
2298   // fold (sdiv c1, c2) -> c1/c2
2299   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2300   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2301   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2302     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2303   // fold (sdiv X, 1) -> X
2304   if (N1C && N1C->isOne())
2305     return N0;
2306   // fold (sdiv X, -1) -> 0-X
2307   if (N1C && N1C->isAllOnesValue())
2308     return DAG.getNode(ISD::SUB, DL, VT,
2309                        DAG.getConstant(0, DL, VT), N0);
2310 
2311   // If we know the sign bits of both operands are zero, strength reduce to a
2312   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2313   if (!VT.isVector()) {
2314     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2315       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2316   }
2317 
2318   // fold (sdiv X, pow2) -> simple ops after legalize
2319   // FIXME: We check for the exact bit here because the generic lowering gives
2320   // better results in that case. The target-specific lowering should learn how
2321   // to handle exact sdivs efficiently.
2322   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2323       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2324       (N1C->getAPIntValue().isPowerOf2() ||
2325        (-N1C->getAPIntValue()).isPowerOf2())) {
2326     // Target-specific implementation of sdiv x, pow2.
2327     if (SDValue Res = BuildSDIVPow2(N))
2328       return Res;
2329 
2330     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2331 
2332     // Splat the sign bit into the register
2333     SDValue SGN =
2334         DAG.getNode(ISD::SRA, DL, VT, N0,
2335                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2336                                     getShiftAmountTy(N0.getValueType())));
2337     AddToWorklist(SGN.getNode());
2338 
2339     // Add (N0 < 0) ? abs2 - 1 : 0;
2340     SDValue SRL =
2341         DAG.getNode(ISD::SRL, DL, VT, SGN,
2342                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2343                                     getShiftAmountTy(SGN.getValueType())));
2344     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2345     AddToWorklist(SRL.getNode());
2346     AddToWorklist(ADD.getNode());    // Divide by pow2
2347     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2348                   DAG.getConstant(lg2, DL,
2349                                   getShiftAmountTy(ADD.getValueType())));
2350 
2351     // If we're dividing by a positive value, we're done.  Otherwise, we must
2352     // negate the result.
2353     if (N1C->getAPIntValue().isNonNegative())
2354       return SRA;
2355 
2356     AddToWorklist(SRA.getNode());
2357     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2358   }
2359 
2360   // If integer divide is expensive and we satisfy the requirements, emit an
2361   // alternate sequence.  Targets may check function attributes for size/speed
2362   // trade-offs.
2363   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2364   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2365     if (SDValue Op = BuildSDIV(N))
2366       return Op;
2367 
2368   // sdiv, srem -> sdivrem
2369   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2370   // Otherwise, we break the simplification logic in visitREM().
2371   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2372     if (SDValue DivRem = useDivRem(N))
2373         return DivRem;
2374 
2375   // undef / X -> 0
2376   if (N0.isUndef())
2377     return DAG.getConstant(0, DL, VT);
2378   // X / undef -> undef
2379   if (N1.isUndef())
2380     return N1;
2381 
2382   return SDValue();
2383 }
2384 
2385 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2386   SDValue N0 = N->getOperand(0);
2387   SDValue N1 = N->getOperand(1);
2388   EVT VT = N->getValueType(0);
2389 
2390   // fold vector ops
2391   if (VT.isVector())
2392     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2393       return FoldedVOp;
2394 
2395   SDLoc DL(N);
2396 
2397   // fold (udiv c1, c2) -> c1/c2
2398   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2399   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2400   if (N0C && N1C)
2401     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2402                                                     N0C, N1C))
2403       return Folded;
2404 
2405   // fold (udiv x, (1 << c)) -> x >>u c
2406   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2407     return DAG.getNode(ISD::SRL, DL, VT, N0,
2408                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2409                                        getShiftAmountTy(N0.getValueType())));
2410 
2411   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2412   if (N1.getOpcode() == ISD::SHL) {
2413     if (ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0))) {
2414       if (!SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) {
2415         EVT ADDVT = N1.getOperand(1).getValueType();
2416         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2417                                   N1.getOperand(1),
2418                                   DAG.getConstant(SHC->getAPIntValue()
2419                                                                   .logBase2(),
2420                                                   DL, ADDVT));
2421         AddToWorklist(Add.getNode());
2422         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2423       }
2424     }
2425   }
2426 
2427   // fold (udiv x, c) -> alternate
2428   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2429   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2430     if (SDValue Op = BuildUDIV(N))
2431       return Op;
2432 
2433   // sdiv, srem -> sdivrem
2434   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2435   // Otherwise, we break the simplification logic in visitREM().
2436   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2437     if (SDValue DivRem = useDivRem(N))
2438         return DivRem;
2439 
2440   // undef / X -> 0
2441   if (N0.isUndef())
2442     return DAG.getConstant(0, DL, VT);
2443   // X / undef -> undef
2444   if (N1.isUndef())
2445     return N1;
2446 
2447   return SDValue();
2448 }
2449 
2450 // handles ISD::SREM and ISD::UREM
2451 SDValue DAGCombiner::visitREM(SDNode *N) {
2452   unsigned Opcode = N->getOpcode();
2453   SDValue N0 = N->getOperand(0);
2454   SDValue N1 = N->getOperand(1);
2455   EVT VT = N->getValueType(0);
2456   bool isSigned = (Opcode == ISD::SREM);
2457   SDLoc DL(N);
2458 
2459   // fold (rem c1, c2) -> c1%c2
2460   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2461   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2462   if (N0C && N1C)
2463     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2464       return Folded;
2465 
2466   if (isSigned) {
2467     // If we know the sign bits of both operands are zero, strength reduce to a
2468     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2469     if (!VT.isVector()) {
2470       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2471         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2472     }
2473   } else {
2474     // fold (urem x, pow2) -> (and x, pow2-1)
2475     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2476         N1C->getAPIntValue().isPowerOf2()) {
2477       return DAG.getNode(ISD::AND, DL, VT, N0,
2478                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2479     }
2480     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2481     if (N1.getOpcode() == ISD::SHL) {
2482       ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0));
2483       if (SHC && SHC->getAPIntValue().isPowerOf2()) {
2484         APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits());
2485         SDValue Add =
2486             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2487         AddToWorklist(Add.getNode());
2488         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2489       }
2490     }
2491   }
2492 
2493   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2494 
2495   // If X/C can be simplified by the division-by-constant logic, lower
2496   // X%C to the equivalent of X-X/C*C.
2497   // To avoid mangling nodes, this simplification requires that the combine()
2498   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2499   // against this by skipping the simplification if isIntDivCheap().  When
2500   // div is not cheap, combine will not return a DIVREM.  Regardless,
2501   // checking cheapness here makes sense since the simplification results in
2502   // fatter code.
2503   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2504     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2505     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2506     AddToWorklist(Div.getNode());
2507     SDValue OptimizedDiv = combine(Div.getNode());
2508     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2509       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2510              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2511       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2512       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2513       AddToWorklist(Mul.getNode());
2514       return Sub;
2515     }
2516   }
2517 
2518   // sdiv, srem -> sdivrem
2519   if (SDValue DivRem = useDivRem(N))
2520     return DivRem.getValue(1);
2521 
2522   // undef % X -> 0
2523   if (N0.isUndef())
2524     return DAG.getConstant(0, DL, VT);
2525   // X % undef -> undef
2526   if (N1.isUndef())
2527     return N1;
2528 
2529   return SDValue();
2530 }
2531 
2532 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2533   SDValue N0 = N->getOperand(0);
2534   SDValue N1 = N->getOperand(1);
2535   EVT VT = N->getValueType(0);
2536   SDLoc DL(N);
2537 
2538   // fold (mulhs x, 0) -> 0
2539   if (isNullConstant(N1))
2540     return N1;
2541   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2542   if (isOneConstant(N1)) {
2543     SDLoc DL(N);
2544     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2545                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2546                                        getShiftAmountTy(N0.getValueType())));
2547   }
2548   // fold (mulhs x, undef) -> 0
2549   if (N0.isUndef() || N1.isUndef())
2550     return DAG.getConstant(0, SDLoc(N), VT);
2551 
2552   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2553   // plus a shift.
2554   if (VT.isSimple() && !VT.isVector()) {
2555     MVT Simple = VT.getSimpleVT();
2556     unsigned SimpleSize = Simple.getSizeInBits();
2557     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2558     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2559       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2560       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2561       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2562       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2563             DAG.getConstant(SimpleSize, DL,
2564                             getShiftAmountTy(N1.getValueType())));
2565       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2566     }
2567   }
2568 
2569   return SDValue();
2570 }
2571 
2572 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2573   SDValue N0 = N->getOperand(0);
2574   SDValue N1 = N->getOperand(1);
2575   EVT VT = N->getValueType(0);
2576   SDLoc DL(N);
2577 
2578   // fold (mulhu x, 0) -> 0
2579   if (isNullConstant(N1))
2580     return N1;
2581   // fold (mulhu x, 1) -> 0
2582   if (isOneConstant(N1))
2583     return DAG.getConstant(0, DL, N0.getValueType());
2584   // fold (mulhu x, undef) -> 0
2585   if (N0.isUndef() || N1.isUndef())
2586     return DAG.getConstant(0, DL, VT);
2587 
2588   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2589   // plus a shift.
2590   if (VT.isSimple() && !VT.isVector()) {
2591     MVT Simple = VT.getSimpleVT();
2592     unsigned SimpleSize = Simple.getSizeInBits();
2593     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2594     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2595       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2596       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2597       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2598       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2599             DAG.getConstant(SimpleSize, DL,
2600                             getShiftAmountTy(N1.getValueType())));
2601       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2602     }
2603   }
2604 
2605   return SDValue();
2606 }
2607 
2608 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2609 /// give the opcodes for the two computations that are being performed. Return
2610 /// true if a simplification was made.
2611 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2612                                                 unsigned HiOp) {
2613   // If the high half is not needed, just compute the low half.
2614   bool HiExists = N->hasAnyUseOfValue(1);
2615   if (!HiExists &&
2616       (!LegalOperations ||
2617        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2618     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2619     return CombineTo(N, Res, Res);
2620   }
2621 
2622   // If the low half is not needed, just compute the high half.
2623   bool LoExists = N->hasAnyUseOfValue(0);
2624   if (!LoExists &&
2625       (!LegalOperations ||
2626        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2627     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2628     return CombineTo(N, Res, Res);
2629   }
2630 
2631   // If both halves are used, return as it is.
2632   if (LoExists && HiExists)
2633     return SDValue();
2634 
2635   // If the two computed results can be simplified separately, separate them.
2636   if (LoExists) {
2637     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2638     AddToWorklist(Lo.getNode());
2639     SDValue LoOpt = combine(Lo.getNode());
2640     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2641         (!LegalOperations ||
2642          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2643       return CombineTo(N, LoOpt, LoOpt);
2644   }
2645 
2646   if (HiExists) {
2647     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2648     AddToWorklist(Hi.getNode());
2649     SDValue HiOpt = combine(Hi.getNode());
2650     if (HiOpt.getNode() && HiOpt != Hi &&
2651         (!LegalOperations ||
2652          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2653       return CombineTo(N, HiOpt, HiOpt);
2654   }
2655 
2656   return SDValue();
2657 }
2658 
2659 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2660   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2661     return Res;
2662 
2663   EVT VT = N->getValueType(0);
2664   SDLoc DL(N);
2665 
2666   // If the type is twice as wide is legal, transform the mulhu to a wider
2667   // multiply plus a shift.
2668   if (VT.isSimple() && !VT.isVector()) {
2669     MVT Simple = VT.getSimpleVT();
2670     unsigned SimpleSize = Simple.getSizeInBits();
2671     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2672     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2673       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2674       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2675       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2676       // Compute the high part as N1.
2677       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2678             DAG.getConstant(SimpleSize, DL,
2679                             getShiftAmountTy(Lo.getValueType())));
2680       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2681       // Compute the low part as N0.
2682       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2683       return CombineTo(N, Lo, Hi);
2684     }
2685   }
2686 
2687   return SDValue();
2688 }
2689 
2690 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2691   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2692     return Res;
2693 
2694   EVT VT = N->getValueType(0);
2695   SDLoc DL(N);
2696 
2697   // If the type is twice as wide is legal, transform the mulhu to a wider
2698   // multiply plus a shift.
2699   if (VT.isSimple() && !VT.isVector()) {
2700     MVT Simple = VT.getSimpleVT();
2701     unsigned SimpleSize = Simple.getSizeInBits();
2702     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2703     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2704       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2705       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2706       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2707       // Compute the high part as N1.
2708       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2709             DAG.getConstant(SimpleSize, DL,
2710                             getShiftAmountTy(Lo.getValueType())));
2711       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2712       // Compute the low part as N0.
2713       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2714       return CombineTo(N, Lo, Hi);
2715     }
2716   }
2717 
2718   return SDValue();
2719 }
2720 
2721 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2722   // (smulo x, 2) -> (saddo x, x)
2723   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2724     if (C2->getAPIntValue() == 2)
2725       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2726                          N->getOperand(0), N->getOperand(0));
2727 
2728   return SDValue();
2729 }
2730 
2731 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2732   // (umulo x, 2) -> (uaddo x, x)
2733   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2734     if (C2->getAPIntValue() == 2)
2735       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2736                          N->getOperand(0), N->getOperand(0));
2737 
2738   return SDValue();
2739 }
2740 
2741 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2742   SDValue N0 = N->getOperand(0);
2743   SDValue N1 = N->getOperand(1);
2744   EVT VT = N0.getValueType();
2745 
2746   // fold vector ops
2747   if (VT.isVector())
2748     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2749       return FoldedVOp;
2750 
2751   // fold (add c1, c2) -> c1+c2
2752   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2753   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2754   if (N0C && N1C)
2755     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2756 
2757   // canonicalize constant to RHS
2758   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2759      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2760     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2761 
2762   return SDValue();
2763 }
2764 
2765 /// If this is a binary operator with two operands of the same opcode, try to
2766 /// simplify it.
2767 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2768   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2769   EVT VT = N0.getValueType();
2770   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2771 
2772   // Bail early if none of these transforms apply.
2773   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2774 
2775   // For each of OP in AND/OR/XOR:
2776   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2777   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2778   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2779   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2780   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2781   //
2782   // do not sink logical op inside of a vector extend, since it may combine
2783   // into a vsetcc.
2784   EVT Op0VT = N0.getOperand(0).getValueType();
2785   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2786        N0.getOpcode() == ISD::SIGN_EXTEND ||
2787        N0.getOpcode() == ISD::BSWAP ||
2788        // Avoid infinite looping with PromoteIntBinOp.
2789        (N0.getOpcode() == ISD::ANY_EXTEND &&
2790         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2791        (N0.getOpcode() == ISD::TRUNCATE &&
2792         (!TLI.isZExtFree(VT, Op0VT) ||
2793          !TLI.isTruncateFree(Op0VT, VT)) &&
2794         TLI.isTypeLegal(Op0VT))) &&
2795       !VT.isVector() &&
2796       Op0VT == N1.getOperand(0).getValueType() &&
2797       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2798     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2799                                  N0.getOperand(0).getValueType(),
2800                                  N0.getOperand(0), N1.getOperand(0));
2801     AddToWorklist(ORNode.getNode());
2802     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2803   }
2804 
2805   // For each of OP in SHL/SRL/SRA/AND...
2806   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2807   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2808   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2809   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2810        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2811       N0.getOperand(1) == N1.getOperand(1)) {
2812     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2813                                  N0.getOperand(0).getValueType(),
2814                                  N0.getOperand(0), N1.getOperand(0));
2815     AddToWorklist(ORNode.getNode());
2816     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2817                        ORNode, N0.getOperand(1));
2818   }
2819 
2820   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2821   // Only perform this optimization up until type legalization, before
2822   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2823   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2824   // we don't want to undo this promotion.
2825   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2826   // on scalars.
2827   if ((N0.getOpcode() == ISD::BITCAST ||
2828        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2829        Level <= AfterLegalizeTypes) {
2830     SDValue In0 = N0.getOperand(0);
2831     SDValue In1 = N1.getOperand(0);
2832     EVT In0Ty = In0.getValueType();
2833     EVT In1Ty = In1.getValueType();
2834     SDLoc DL(N);
2835     // If both incoming values are integers, and the original types are the
2836     // same.
2837     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2838       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2839       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2840       AddToWorklist(Op.getNode());
2841       return BC;
2842     }
2843   }
2844 
2845   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2846   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2847   // If both shuffles use the same mask, and both shuffle within a single
2848   // vector, then it is worthwhile to move the swizzle after the operation.
2849   // The type-legalizer generates this pattern when loading illegal
2850   // vector types from memory. In many cases this allows additional shuffle
2851   // optimizations.
2852   // There are other cases where moving the shuffle after the xor/and/or
2853   // is profitable even if shuffles don't perform a swizzle.
2854   // If both shuffles use the same mask, and both shuffles have the same first
2855   // or second operand, then it might still be profitable to move the shuffle
2856   // after the xor/and/or operation.
2857   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2858     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2859     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2860 
2861     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2862            "Inputs to shuffles are not the same type");
2863 
2864     // Check that both shuffles use the same mask. The masks are known to be of
2865     // the same length because the result vector type is the same.
2866     // Check also that shuffles have only one use to avoid introducing extra
2867     // instructions.
2868     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2869         SVN0->getMask().equals(SVN1->getMask())) {
2870       SDValue ShOp = N0->getOperand(1);
2871 
2872       // Don't try to fold this node if it requires introducing a
2873       // build vector of all zeros that might be illegal at this stage.
2874       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2875         if (!LegalTypes)
2876           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2877         else
2878           ShOp = SDValue();
2879       }
2880 
2881       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2882       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2883       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2884       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2885         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2886                                       N0->getOperand(0), N1->getOperand(0));
2887         AddToWorklist(NewNode.getNode());
2888         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2889                                     SVN0->getMask());
2890       }
2891 
2892       // Don't try to fold this node if it requires introducing a
2893       // build vector of all zeros that might be illegal at this stage.
2894       ShOp = N0->getOperand(0);
2895       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2896         if (!LegalTypes)
2897           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2898         else
2899           ShOp = SDValue();
2900       }
2901 
2902       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2903       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2904       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2905       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2906         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2907                                       N0->getOperand(1), N1->getOperand(1));
2908         AddToWorklist(NewNode.getNode());
2909         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2910                                     SVN0->getMask());
2911       }
2912     }
2913   }
2914 
2915   return SDValue();
2916 }
2917 
2918 /// This contains all DAGCombine rules which reduce two values combined by
2919 /// an And operation to a single value. This makes them reusable in the context
2920 /// of visitSELECT(). Rules involving constants are not included as
2921 /// visitSELECT() already handles those cases.
2922 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2923                                   SDNode *LocReference) {
2924   EVT VT = N1.getValueType();
2925 
2926   // fold (and x, undef) -> 0
2927   if (N0.isUndef() || N1.isUndef())
2928     return DAG.getConstant(0, SDLoc(LocReference), VT);
2929   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2930   SDValue LL, LR, RL, RR, CC0, CC1;
2931   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2932     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2933     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2934 
2935     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2936         LL.getValueType().isInteger()) {
2937       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2938       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2939         EVT CCVT = getSetCCResultType(LR.getValueType());
2940         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2941           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2942                                        LR.getValueType(), LL, RL);
2943           AddToWorklist(ORNode.getNode());
2944           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2945         }
2946       }
2947       if (isAllOnesConstant(LR)) {
2948         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2949         if (Op1 == ISD::SETEQ) {
2950           EVT CCVT = getSetCCResultType(LR.getValueType());
2951           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2952             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2953                                           LR.getValueType(), LL, RL);
2954             AddToWorklist(ANDNode.getNode());
2955             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2956           }
2957         }
2958         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2959         if (Op1 == ISD::SETGT) {
2960           EVT CCVT = getSetCCResultType(LR.getValueType());
2961           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2962             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2963                                          LR.getValueType(), LL, RL);
2964             AddToWorklist(ORNode.getNode());
2965             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2966           }
2967         }
2968       }
2969     }
2970     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2971     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2972         Op0 == Op1 && LL.getValueType().isInteger() &&
2973       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2974                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2975       EVT CCVT = getSetCCResultType(LL.getValueType());
2976       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2977         SDLoc DL(N0);
2978         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2979                                       LL, DAG.getConstant(1, DL,
2980                                                           LL.getValueType()));
2981         AddToWorklist(ADDNode.getNode());
2982         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2983                             DAG.getConstant(2, DL, LL.getValueType()),
2984                             ISD::SETUGE);
2985       }
2986     }
2987     // canonicalize equivalent to ll == rl
2988     if (LL == RR && LR == RL) {
2989       Op1 = ISD::getSetCCSwappedOperands(Op1);
2990       std::swap(RL, RR);
2991     }
2992     if (LL == RL && LR == RR) {
2993       bool isInteger = LL.getValueType().isInteger();
2994       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2995       if (Result != ISD::SETCC_INVALID &&
2996           (!LegalOperations ||
2997            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2998             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2999         EVT CCVT = getSetCCResultType(LL.getValueType());
3000         if (N0.getValueType() == CCVT ||
3001             (!LegalOperations && N0.getValueType() == MVT::i1))
3002           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3003                               LL, LR, Result);
3004       }
3005     }
3006   }
3007 
3008   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3009       VT.getSizeInBits() <= 64) {
3010     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3011       APInt ADDC = ADDI->getAPIntValue();
3012       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3013         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3014         // immediate for an add, but it is legal if its top c2 bits are set,
3015         // transform the ADD so the immediate doesn't need to be materialized
3016         // in a register.
3017         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3018           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3019                                              SRLI->getZExtValue());
3020           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3021             ADDC |= Mask;
3022             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3023               SDLoc DL(N0);
3024               SDValue NewAdd =
3025                 DAG.getNode(ISD::ADD, DL, VT,
3026                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3027               CombineTo(N0.getNode(), NewAdd);
3028               // Return N so it doesn't get rechecked!
3029               return SDValue(LocReference, 0);
3030             }
3031           }
3032         }
3033       }
3034     }
3035   }
3036 
3037   // Reduce bit extract of low half of an integer to the narrower type.
3038   // (and (srl i64:x, K), KMask) ->
3039   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3040   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3041     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3042       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3043         unsigned Size = VT.getSizeInBits();
3044         const APInt &AndMask = CAnd->getAPIntValue();
3045         unsigned ShiftBits = CShift->getZExtValue();
3046         unsigned MaskBits = AndMask.countTrailingOnes();
3047         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3048 
3049         if (APIntOps::isMask(AndMask) &&
3050             // Required bits must not span the two halves of the integer and
3051             // must fit in the half size type.
3052             (ShiftBits + MaskBits <= Size / 2) &&
3053             TLI.isNarrowingProfitable(VT, HalfVT) &&
3054             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3055             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3056             TLI.isTruncateFree(VT, HalfVT) &&
3057             TLI.isZExtFree(HalfVT, VT)) {
3058           // The isNarrowingProfitable is to avoid regressions on PPC and
3059           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3060           // on downstream users of this. Those patterns could probably be
3061           // extended to handle extensions mixed in.
3062 
3063           SDValue SL(N0);
3064           assert(ShiftBits != 0 && MaskBits <= Size);
3065 
3066           // Extracting the highest bit of the low half.
3067           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3068           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3069                                       N0.getOperand(0));
3070 
3071           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3072           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3073           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3074           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3075           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3076         }
3077       }
3078     }
3079   }
3080 
3081   return SDValue();
3082 }
3083 
3084 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3085                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3086                                    bool &NarrowLoad) {
3087   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3088 
3089   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3090     return false;
3091 
3092   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3093   LoadedVT = LoadN->getMemoryVT();
3094 
3095   if (ExtVT == LoadedVT &&
3096       (!LegalOperations ||
3097        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3098     // ZEXTLOAD will match without needing to change the size of the value being
3099     // loaded.
3100     NarrowLoad = false;
3101     return true;
3102   }
3103 
3104   // Do not change the width of a volatile load.
3105   if (LoadN->isVolatile())
3106     return false;
3107 
3108   // Do not generate loads of non-round integer types since these can
3109   // be expensive (and would be wrong if the type is not byte sized).
3110   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3111     return false;
3112 
3113   if (LegalOperations &&
3114       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3115     return false;
3116 
3117   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3118     return false;
3119 
3120   NarrowLoad = true;
3121   return true;
3122 }
3123 
3124 SDValue DAGCombiner::visitAND(SDNode *N) {
3125   SDValue N0 = N->getOperand(0);
3126   SDValue N1 = N->getOperand(1);
3127   EVT VT = N1.getValueType();
3128 
3129   // fold vector ops
3130   if (VT.isVector()) {
3131     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3132       return FoldedVOp;
3133 
3134     // fold (and x, 0) -> 0, vector edition
3135     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3136       // do not return N0, because undef node may exist in N0
3137       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3138                              SDLoc(N), N0.getValueType());
3139     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3140       // do not return N1, because undef node may exist in N1
3141       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3142                              SDLoc(N), N1.getValueType());
3143 
3144     // fold (and x, -1) -> x, vector edition
3145     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3146       return N1;
3147     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3148       return N0;
3149   }
3150 
3151   // fold (and c1, c2) -> c1&c2
3152   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3153   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3154   if (N0C && N1C && !N1C->isOpaque())
3155     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3156   // canonicalize constant to RHS
3157   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3158      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3159     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3160   // fold (and x, -1) -> x
3161   if (isAllOnesConstant(N1))
3162     return N0;
3163   // if (and x, c) is known to be zero, return 0
3164   unsigned BitWidth = VT.getScalarSizeInBits();
3165   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3166                                    APInt::getAllOnesValue(BitWidth)))
3167     return DAG.getConstant(0, SDLoc(N), VT);
3168   // reassociate and
3169   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3170     return RAND;
3171   // fold (and (or x, C), D) -> D if (C & D) == D
3172   if (N1C && N0.getOpcode() == ISD::OR)
3173     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3174       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3175         return N1;
3176   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3177   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3178     SDValue N0Op0 = N0.getOperand(0);
3179     APInt Mask = ~N1C->getAPIntValue();
3180     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3181     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3182       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3183                                  N0.getValueType(), N0Op0);
3184 
3185       // Replace uses of the AND with uses of the Zero extend node.
3186       CombineTo(N, Zext);
3187 
3188       // We actually want to replace all uses of the any_extend with the
3189       // zero_extend, to avoid duplicating things.  This will later cause this
3190       // AND to be folded.
3191       CombineTo(N0.getNode(), Zext);
3192       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3193     }
3194   }
3195   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3196   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3197   // already be zero by virtue of the width of the base type of the load.
3198   //
3199   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3200   // more cases.
3201   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3202        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3203        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3204        N0.getOperand(0).getResNo() == 0) ||
3205       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3206     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3207                                          N0 : N0.getOperand(0) );
3208 
3209     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3210     // This can be a pure constant or a vector splat, in which case we treat the
3211     // vector as a scalar and use the splat value.
3212     APInt Constant = APInt::getNullValue(1);
3213     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3214       Constant = C->getAPIntValue();
3215     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3216       APInt SplatValue, SplatUndef;
3217       unsigned SplatBitSize;
3218       bool HasAnyUndefs;
3219       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3220                                              SplatBitSize, HasAnyUndefs);
3221       if (IsSplat) {
3222         // Undef bits can contribute to a possible optimisation if set, so
3223         // set them.
3224         SplatValue |= SplatUndef;
3225 
3226         // The splat value may be something like "0x00FFFFFF", which means 0 for
3227         // the first vector value and FF for the rest, repeating. We need a mask
3228         // that will apply equally to all members of the vector, so AND all the
3229         // lanes of the constant together.
3230         EVT VT = Vector->getValueType(0);
3231         unsigned BitWidth = VT.getScalarSizeInBits();
3232 
3233         // If the splat value has been compressed to a bitlength lower
3234         // than the size of the vector lane, we need to re-expand it to
3235         // the lane size.
3236         if (BitWidth > SplatBitSize)
3237           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3238                SplatBitSize < BitWidth;
3239                SplatBitSize = SplatBitSize * 2)
3240             SplatValue |= SplatValue.shl(SplatBitSize);
3241 
3242         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3243         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3244         if (SplatBitSize % BitWidth == 0) {
3245           Constant = APInt::getAllOnesValue(BitWidth);
3246           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3247             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3248         }
3249       }
3250     }
3251 
3252     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3253     // actually legal and isn't going to get expanded, else this is a false
3254     // optimisation.
3255     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3256                                                     Load->getValueType(0),
3257                                                     Load->getMemoryVT());
3258 
3259     // Resize the constant to the same size as the original memory access before
3260     // extension. If it is still the AllOnesValue then this AND is completely
3261     // unneeded.
3262     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3263 
3264     bool B;
3265     switch (Load->getExtensionType()) {
3266     default: B = false; break;
3267     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3268     case ISD::ZEXTLOAD:
3269     case ISD::NON_EXTLOAD: B = true; break;
3270     }
3271 
3272     if (B && Constant.isAllOnesValue()) {
3273       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3274       // preserve semantics once we get rid of the AND.
3275       SDValue NewLoad(Load, 0);
3276       if (Load->getExtensionType() == ISD::EXTLOAD) {
3277         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3278                               Load->getValueType(0), SDLoc(Load),
3279                               Load->getChain(), Load->getBasePtr(),
3280                               Load->getOffset(), Load->getMemoryVT(),
3281                               Load->getMemOperand());
3282         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3283         if (Load->getNumValues() == 3) {
3284           // PRE/POST_INC loads have 3 values.
3285           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3286                            NewLoad.getValue(2) };
3287           CombineTo(Load, To, 3, true);
3288         } else {
3289           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3290         }
3291       }
3292 
3293       // Fold the AND away, taking care not to fold to the old load node if we
3294       // replaced it.
3295       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3296 
3297       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3298     }
3299   }
3300 
3301   // fold (and (load x), 255) -> (zextload x, i8)
3302   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3303   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3304   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3305                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3306                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3307     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3308     LoadSDNode *LN0 = HasAnyExt
3309       ? cast<LoadSDNode>(N0.getOperand(0))
3310       : cast<LoadSDNode>(N0);
3311     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3312         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3313       auto NarrowLoad = false;
3314       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3315       EVT ExtVT, LoadedVT;
3316       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3317                            NarrowLoad)) {
3318         if (!NarrowLoad) {
3319           SDValue NewLoad =
3320             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3321                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3322                            LN0->getMemOperand());
3323           AddToWorklist(N);
3324           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3325           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3326         } else {
3327           EVT PtrType = LN0->getOperand(1).getValueType();
3328 
3329           unsigned Alignment = LN0->getAlignment();
3330           SDValue NewPtr = LN0->getBasePtr();
3331 
3332           // For big endian targets, we need to add an offset to the pointer
3333           // to load the correct bytes.  For little endian systems, we merely
3334           // need to read fewer bytes from the same pointer.
3335           if (DAG.getDataLayout().isBigEndian()) {
3336             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3337             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3338             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3339             SDLoc DL(LN0);
3340             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3341                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3342             Alignment = MinAlign(Alignment, PtrOff);
3343           }
3344 
3345           AddToWorklist(NewPtr.getNode());
3346 
3347           SDValue Load = DAG.getExtLoad(
3348               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3349               LN0->getPointerInfo(), ExtVT, Alignment,
3350               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3351           AddToWorklist(N);
3352           CombineTo(LN0, Load, Load.getValue(1));
3353           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3354         }
3355       }
3356     }
3357   }
3358 
3359   if (SDValue Combined = visitANDLike(N0, N1, N))
3360     return Combined;
3361 
3362   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3363   if (N0.getOpcode() == N1.getOpcode())
3364     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3365       return Tmp;
3366 
3367   // Masking the negated extension of a boolean is just the zero-extended
3368   // boolean:
3369   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3370   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3371   //
3372   // Note: the SimplifyDemandedBits fold below can make an information-losing
3373   // transform, and then we have no way to find this better fold.
3374   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3375     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3376     SDValue SubRHS = N0.getOperand(1);
3377     if (SubLHS && SubLHS->isNullValue()) {
3378       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3379           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3380         return SubRHS;
3381       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3382           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3383         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3384     }
3385   }
3386 
3387   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3388   // fold (and (sra)) -> (and (srl)) when possible.
3389   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
3390     return SDValue(N, 0);
3391 
3392   // fold (zext_inreg (extload x)) -> (zextload x)
3393   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3394     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3395     EVT MemVT = LN0->getMemoryVT();
3396     // If we zero all the possible extended bits, then we can turn this into
3397     // a zextload if we are running before legalize or the operation is legal.
3398     unsigned BitWidth = N1.getScalarValueSizeInBits();
3399     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3400                            BitWidth - MemVT.getScalarSizeInBits())) &&
3401         ((!LegalOperations && !LN0->isVolatile()) ||
3402          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3403       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3404                                        LN0->getChain(), LN0->getBasePtr(),
3405                                        MemVT, LN0->getMemOperand());
3406       AddToWorklist(N);
3407       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3408       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3409     }
3410   }
3411   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3412   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3413       N0.hasOneUse()) {
3414     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3415     EVT MemVT = LN0->getMemoryVT();
3416     // If we zero all the possible extended bits, then we can turn this into
3417     // a zextload if we are running before legalize or the operation is legal.
3418     unsigned BitWidth = N1.getScalarValueSizeInBits();
3419     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3420                            BitWidth - MemVT.getScalarSizeInBits())) &&
3421         ((!LegalOperations && !LN0->isVolatile()) ||
3422          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3423       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3424                                        LN0->getChain(), LN0->getBasePtr(),
3425                                        MemVT, LN0->getMemOperand());
3426       AddToWorklist(N);
3427       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3428       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3429     }
3430   }
3431   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3432   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3433     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3434                                            N0.getOperand(1), false))
3435       return BSwap;
3436   }
3437 
3438   return SDValue();
3439 }
3440 
3441 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3442 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3443                                         bool DemandHighBits) {
3444   if (!LegalOperations)
3445     return SDValue();
3446 
3447   EVT VT = N->getValueType(0);
3448   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3449     return SDValue();
3450   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3451     return SDValue();
3452 
3453   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3454   bool LookPassAnd0 = false;
3455   bool LookPassAnd1 = false;
3456   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3457       std::swap(N0, N1);
3458   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3459       std::swap(N0, N1);
3460   if (N0.getOpcode() == ISD::AND) {
3461     if (!N0.getNode()->hasOneUse())
3462       return SDValue();
3463     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3464     if (!N01C || N01C->getZExtValue() != 0xFF00)
3465       return SDValue();
3466     N0 = N0.getOperand(0);
3467     LookPassAnd0 = true;
3468   }
3469 
3470   if (N1.getOpcode() == ISD::AND) {
3471     if (!N1.getNode()->hasOneUse())
3472       return SDValue();
3473     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3474     if (!N11C || N11C->getZExtValue() != 0xFF)
3475       return SDValue();
3476     N1 = N1.getOperand(0);
3477     LookPassAnd1 = true;
3478   }
3479 
3480   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3481     std::swap(N0, N1);
3482   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3483     return SDValue();
3484   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3485     return SDValue();
3486 
3487   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3488   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3489   if (!N01C || !N11C)
3490     return SDValue();
3491   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3492     return SDValue();
3493 
3494   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3495   SDValue N00 = N0->getOperand(0);
3496   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3497     if (!N00.getNode()->hasOneUse())
3498       return SDValue();
3499     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3500     if (!N001C || N001C->getZExtValue() != 0xFF)
3501       return SDValue();
3502     N00 = N00.getOperand(0);
3503     LookPassAnd0 = true;
3504   }
3505 
3506   SDValue N10 = N1->getOperand(0);
3507   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3508     if (!N10.getNode()->hasOneUse())
3509       return SDValue();
3510     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3511     if (!N101C || N101C->getZExtValue() != 0xFF00)
3512       return SDValue();
3513     N10 = N10.getOperand(0);
3514     LookPassAnd1 = true;
3515   }
3516 
3517   if (N00 != N10)
3518     return SDValue();
3519 
3520   // Make sure everything beyond the low halfword gets set to zero since the SRL
3521   // 16 will clear the top bits.
3522   unsigned OpSizeInBits = VT.getSizeInBits();
3523   if (DemandHighBits && OpSizeInBits > 16) {
3524     // If the left-shift isn't masked out then the only way this is a bswap is
3525     // if all bits beyond the low 8 are 0. In that case the entire pattern
3526     // reduces to a left shift anyway: leave it for other parts of the combiner.
3527     if (!LookPassAnd0)
3528       return SDValue();
3529 
3530     // However, if the right shift isn't masked out then it might be because
3531     // it's not needed. See if we can spot that too.
3532     if (!LookPassAnd1 &&
3533         !DAG.MaskedValueIsZero(
3534             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3535       return SDValue();
3536   }
3537 
3538   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3539   if (OpSizeInBits > 16) {
3540     SDLoc DL(N);
3541     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3542                       DAG.getConstant(OpSizeInBits - 16, DL,
3543                                       getShiftAmountTy(VT)));
3544   }
3545   return Res;
3546 }
3547 
3548 /// Return true if the specified node is an element that makes up a 32-bit
3549 /// packed halfword byteswap.
3550 /// ((x & 0x000000ff) << 8) |
3551 /// ((x & 0x0000ff00) >> 8) |
3552 /// ((x & 0x00ff0000) << 8) |
3553 /// ((x & 0xff000000) >> 8)
3554 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3555   if (!N.getNode()->hasOneUse())
3556     return false;
3557 
3558   unsigned Opc = N.getOpcode();
3559   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3560     return false;
3561 
3562   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3563   if (!N1C)
3564     return false;
3565 
3566   unsigned Num;
3567   switch (N1C->getZExtValue()) {
3568   default:
3569     return false;
3570   case 0xFF:       Num = 0; break;
3571   case 0xFF00:     Num = 1; break;
3572   case 0xFF0000:   Num = 2; break;
3573   case 0xFF000000: Num = 3; break;
3574   }
3575 
3576   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3577   SDValue N0 = N.getOperand(0);
3578   if (Opc == ISD::AND) {
3579     if (Num == 0 || Num == 2) {
3580       // (x >> 8) & 0xff
3581       // (x >> 8) & 0xff0000
3582       if (N0.getOpcode() != ISD::SRL)
3583         return false;
3584       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3585       if (!C || C->getZExtValue() != 8)
3586         return false;
3587     } else {
3588       // (x << 8) & 0xff00
3589       // (x << 8) & 0xff000000
3590       if (N0.getOpcode() != ISD::SHL)
3591         return false;
3592       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3593       if (!C || C->getZExtValue() != 8)
3594         return false;
3595     }
3596   } else if (Opc == ISD::SHL) {
3597     // (x & 0xff) << 8
3598     // (x & 0xff0000) << 8
3599     if (Num != 0 && Num != 2)
3600       return false;
3601     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3602     if (!C || C->getZExtValue() != 8)
3603       return false;
3604   } else { // Opc == ISD::SRL
3605     // (x & 0xff00) >> 8
3606     // (x & 0xff000000) >> 8
3607     if (Num != 1 && Num != 3)
3608       return false;
3609     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3610     if (!C || C->getZExtValue() != 8)
3611       return false;
3612   }
3613 
3614   if (Parts[Num])
3615     return false;
3616 
3617   Parts[Num] = N0.getOperand(0).getNode();
3618   return true;
3619 }
3620 
3621 /// Match a 32-bit packed halfword bswap. That is
3622 /// ((x & 0x000000ff) << 8) |
3623 /// ((x & 0x0000ff00) >> 8) |
3624 /// ((x & 0x00ff0000) << 8) |
3625 /// ((x & 0xff000000) >> 8)
3626 /// => (rotl (bswap x), 16)
3627 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3628   if (!LegalOperations)
3629     return SDValue();
3630 
3631   EVT VT = N->getValueType(0);
3632   if (VT != MVT::i32)
3633     return SDValue();
3634   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3635     return SDValue();
3636 
3637   // Look for either
3638   // (or (or (and), (and)), (or (and), (and)))
3639   // (or (or (or (and), (and)), (and)), (and))
3640   if (N0.getOpcode() != ISD::OR)
3641     return SDValue();
3642   SDValue N00 = N0.getOperand(0);
3643   SDValue N01 = N0.getOperand(1);
3644   SDNode *Parts[4] = {};
3645 
3646   if (N1.getOpcode() == ISD::OR &&
3647       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3648     // (or (or (and), (and)), (or (and), (and)))
3649     SDValue N000 = N00.getOperand(0);
3650     if (!isBSwapHWordElement(N000, Parts))
3651       return SDValue();
3652 
3653     SDValue N001 = N00.getOperand(1);
3654     if (!isBSwapHWordElement(N001, Parts))
3655       return SDValue();
3656     SDValue N010 = N01.getOperand(0);
3657     if (!isBSwapHWordElement(N010, Parts))
3658       return SDValue();
3659     SDValue N011 = N01.getOperand(1);
3660     if (!isBSwapHWordElement(N011, Parts))
3661       return SDValue();
3662   } else {
3663     // (or (or (or (and), (and)), (and)), (and))
3664     if (!isBSwapHWordElement(N1, Parts))
3665       return SDValue();
3666     if (!isBSwapHWordElement(N01, Parts))
3667       return SDValue();
3668     if (N00.getOpcode() != ISD::OR)
3669       return SDValue();
3670     SDValue N000 = N00.getOperand(0);
3671     if (!isBSwapHWordElement(N000, Parts))
3672       return SDValue();
3673     SDValue N001 = N00.getOperand(1);
3674     if (!isBSwapHWordElement(N001, Parts))
3675       return SDValue();
3676   }
3677 
3678   // Make sure the parts are all coming from the same node.
3679   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3680     return SDValue();
3681 
3682   SDLoc DL(N);
3683   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3684                               SDValue(Parts[0], 0));
3685 
3686   // Result of the bswap should be rotated by 16. If it's not legal, then
3687   // do  (x << 16) | (x >> 16).
3688   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3689   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3690     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3691   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3692     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3693   return DAG.getNode(ISD::OR, DL, VT,
3694                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3695                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3696 }
3697 
3698 /// This contains all DAGCombine rules which reduce two values combined by
3699 /// an Or operation to a single value \see visitANDLike().
3700 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3701   EVT VT = N1.getValueType();
3702   // fold (or x, undef) -> -1
3703   if (!LegalOperations &&
3704       (N0.isUndef() || N1.isUndef())) {
3705     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3706     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3707                            SDLoc(LocReference), VT);
3708   }
3709   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3710   SDValue LL, LR, RL, RR, CC0, CC1;
3711   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3712     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3713     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3714 
3715     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3716       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3717       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3718       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3719         EVT CCVT = getSetCCResultType(LR.getValueType());
3720         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3721           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3722                                        LR.getValueType(), LL, RL);
3723           AddToWorklist(ORNode.getNode());
3724           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3725         }
3726       }
3727       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3728       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3729       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3730         EVT CCVT = getSetCCResultType(LR.getValueType());
3731         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3732           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3733                                         LR.getValueType(), LL, RL);
3734           AddToWorklist(ANDNode.getNode());
3735           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3736         }
3737       }
3738     }
3739     // canonicalize equivalent to ll == rl
3740     if (LL == RR && LR == RL) {
3741       Op1 = ISD::getSetCCSwappedOperands(Op1);
3742       std::swap(RL, RR);
3743     }
3744     if (LL == RL && LR == RR) {
3745       bool isInteger = LL.getValueType().isInteger();
3746       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3747       if (Result != ISD::SETCC_INVALID &&
3748           (!LegalOperations ||
3749            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3750             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3751         EVT CCVT = getSetCCResultType(LL.getValueType());
3752         if (N0.getValueType() == CCVT ||
3753             (!LegalOperations && N0.getValueType() == MVT::i1))
3754           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3755                               LL, LR, Result);
3756       }
3757     }
3758   }
3759 
3760   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3761   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3762       // Don't increase # computations.
3763       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3764     // We can only do this xform if we know that bits from X that are set in C2
3765     // but not in C1 are already zero.  Likewise for Y.
3766     if (const ConstantSDNode *N0O1C =
3767         getAsNonOpaqueConstant(N0.getOperand(1))) {
3768       if (const ConstantSDNode *N1O1C =
3769           getAsNonOpaqueConstant(N1.getOperand(1))) {
3770         // We can only do this xform if we know that bits from X that are set in
3771         // C2 but not in C1 are already zero.  Likewise for Y.
3772         const APInt &LHSMask = N0O1C->getAPIntValue();
3773         const APInt &RHSMask = N1O1C->getAPIntValue();
3774 
3775         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3776             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3777           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3778                                   N0.getOperand(0), N1.getOperand(0));
3779           SDLoc DL(LocReference);
3780           return DAG.getNode(ISD::AND, DL, VT, X,
3781                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3782         }
3783       }
3784     }
3785   }
3786 
3787   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3788   if (N0.getOpcode() == ISD::AND &&
3789       N1.getOpcode() == ISD::AND &&
3790       N0.getOperand(0) == N1.getOperand(0) &&
3791       // Don't increase # computations.
3792       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3793     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3794                             N0.getOperand(1), N1.getOperand(1));
3795     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3796   }
3797 
3798   return SDValue();
3799 }
3800 
3801 SDValue DAGCombiner::visitOR(SDNode *N) {
3802   SDValue N0 = N->getOperand(0);
3803   SDValue N1 = N->getOperand(1);
3804   EVT VT = N1.getValueType();
3805 
3806   // fold vector ops
3807   if (VT.isVector()) {
3808     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3809       return FoldedVOp;
3810 
3811     // fold (or x, 0) -> x, vector edition
3812     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3813       return N1;
3814     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3815       return N0;
3816 
3817     // fold (or x, -1) -> -1, vector edition
3818     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3819       // do not return N0, because undef node may exist in N0
3820       return DAG.getConstant(
3821           APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3822           N0.getValueType());
3823     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3824       // do not return N1, because undef node may exist in N1
3825       return DAG.getConstant(
3826           APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3827           N1.getValueType());
3828 
3829     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3830     // Do this only if the resulting shuffle is legal.
3831     if (isa<ShuffleVectorSDNode>(N0) &&
3832         isa<ShuffleVectorSDNode>(N1) &&
3833         // Avoid folding a node with illegal type.
3834         TLI.isTypeLegal(VT)) {
3835       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3836       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3837       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3838       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3839       // Ensure both shuffles have a zero input.
3840       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3841         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3842         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3843         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3844         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3845         bool CanFold = true;
3846         int NumElts = VT.getVectorNumElements();
3847         SmallVector<int, 4> Mask(NumElts);
3848 
3849         for (int i = 0; i != NumElts; ++i) {
3850           int M0 = SV0->getMaskElt(i);
3851           int M1 = SV1->getMaskElt(i);
3852 
3853           // Determine if either index is pointing to a zero vector.
3854           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3855           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3856 
3857           // If one element is zero and the otherside is undef, keep undef.
3858           // This also handles the case that both are undef.
3859           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3860             Mask[i] = -1;
3861             continue;
3862           }
3863 
3864           // Make sure only one of the elements is zero.
3865           if (M0Zero == M1Zero) {
3866             CanFold = false;
3867             break;
3868           }
3869 
3870           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3871 
3872           // We have a zero and non-zero element. If the non-zero came from
3873           // SV0 make the index a LHS index. If it came from SV1, make it
3874           // a RHS index. We need to mod by NumElts because we don't care
3875           // which operand it came from in the original shuffles.
3876           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3877         }
3878 
3879         if (CanFold) {
3880           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3881           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3882 
3883           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3884           if (!LegalMask) {
3885             std::swap(NewLHS, NewRHS);
3886             ShuffleVectorSDNode::commuteMask(Mask);
3887             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3888           }
3889 
3890           if (LegalMask)
3891             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3892         }
3893       }
3894     }
3895   }
3896 
3897   // fold (or c1, c2) -> c1|c2
3898   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3899   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3900   if (N0C && N1C && !N1C->isOpaque())
3901     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3902   // canonicalize constant to RHS
3903   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3904      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3905     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3906   // fold (or x, 0) -> x
3907   if (isNullConstant(N1))
3908     return N0;
3909   // fold (or x, -1) -> -1
3910   if (isAllOnesConstant(N1))
3911     return N1;
3912   // fold (or x, c) -> c iff (x & ~c) == 0
3913   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3914     return N1;
3915 
3916   if (SDValue Combined = visitORLike(N0, N1, N))
3917     return Combined;
3918 
3919   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3920   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3921     return BSwap;
3922   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3923     return BSwap;
3924 
3925   // reassociate or
3926   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3927     return ROR;
3928   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3929   // iff (c1 & c2) == 0.
3930   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3931              isa<ConstantSDNode>(N0.getOperand(1))) {
3932     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3933     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3934       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3935                                                    N1C, C1))
3936         return DAG.getNode(
3937             ISD::AND, SDLoc(N), VT,
3938             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3939       return SDValue();
3940     }
3941   }
3942   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3943   if (N0.getOpcode() == N1.getOpcode())
3944     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3945       return Tmp;
3946 
3947   // See if this is some rotate idiom.
3948   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3949     return SDValue(Rot, 0);
3950 
3951   // Simplify the operands using demanded-bits information.
3952   if (!VT.isVector() &&
3953       SimplifyDemandedBits(SDValue(N, 0)))
3954     return SDValue(N, 0);
3955 
3956   return SDValue();
3957 }
3958 
3959 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3960 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3961   if (Op.getOpcode() == ISD::AND) {
3962     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3963       Mask = Op.getOperand(1);
3964       Op = Op.getOperand(0);
3965     } else {
3966       return false;
3967     }
3968   }
3969 
3970   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3971     Shift = Op;
3972     return true;
3973   }
3974 
3975   return false;
3976 }
3977 
3978 // Return true if we can prove that, whenever Neg and Pos are both in the
3979 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3980 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3981 //
3982 //     (or (shift1 X, Neg), (shift2 X, Pos))
3983 //
3984 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3985 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3986 // to consider shift amounts with defined behavior.
3987 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3988   // If EltSize is a power of 2 then:
3989   //
3990   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3991   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3992   //
3993   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3994   // for the stronger condition:
3995   //
3996   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3997   //
3998   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3999   // we can just replace Neg with Neg' for the rest of the function.
4000   //
4001   // In other cases we check for the even stronger condition:
4002   //
4003   //     Neg == EltSize - Pos                                    [B]
4004   //
4005   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4006   // behavior if Pos == 0 (and consequently Neg == EltSize).
4007   //
4008   // We could actually use [A] whenever EltSize is a power of 2, but the
4009   // only extra cases that it would match are those uninteresting ones
4010   // where Neg and Pos are never in range at the same time.  E.g. for
4011   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4012   // as well as (sub 32, Pos), but:
4013   //
4014   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4015   //
4016   // always invokes undefined behavior for 32-bit X.
4017   //
4018   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4019   unsigned MaskLoBits = 0;
4020   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4021     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4022       if (NegC->getAPIntValue() == EltSize - 1) {
4023         Neg = Neg.getOperand(0);
4024         MaskLoBits = Log2_64(EltSize);
4025       }
4026     }
4027   }
4028 
4029   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4030   if (Neg.getOpcode() != ISD::SUB)
4031     return false;
4032   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4033   if (!NegC)
4034     return false;
4035   SDValue NegOp1 = Neg.getOperand(1);
4036 
4037   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4038   // Pos'.  The truncation is redundant for the purpose of the equality.
4039   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4040     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4041       if (PosC->getAPIntValue() == EltSize - 1)
4042         Pos = Pos.getOperand(0);
4043 
4044   // The condition we need is now:
4045   //
4046   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4047   //
4048   // If NegOp1 == Pos then we need:
4049   //
4050   //              EltSize & Mask == NegC & Mask
4051   //
4052   // (because "x & Mask" is a truncation and distributes through subtraction).
4053   APInt Width;
4054   if (Pos == NegOp1)
4055     Width = NegC->getAPIntValue();
4056 
4057   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4058   // Then the condition we want to prove becomes:
4059   //
4060   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4061   //
4062   // which, again because "x & Mask" is a truncation, becomes:
4063   //
4064   //                NegC & Mask == (EltSize - PosC) & Mask
4065   //             EltSize & Mask == (NegC + PosC) & Mask
4066   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4067     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4068       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4069     else
4070       return false;
4071   } else
4072     return false;
4073 
4074   // Now we just need to check that EltSize & Mask == Width & Mask.
4075   if (MaskLoBits)
4076     // EltSize & Mask is 0 since Mask is EltSize - 1.
4077     return Width.getLoBits(MaskLoBits) == 0;
4078   return Width == EltSize;
4079 }
4080 
4081 // A subroutine of MatchRotate used once we have found an OR of two opposite
4082 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4083 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4084 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4085 // Neg with outer conversions stripped away.
4086 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4087                                        SDValue Neg, SDValue InnerPos,
4088                                        SDValue InnerNeg, unsigned PosOpcode,
4089                                        unsigned NegOpcode, const SDLoc &DL) {
4090   // fold (or (shl x, (*ext y)),
4091   //          (srl x, (*ext (sub 32, y)))) ->
4092   //   (rotl x, y) or (rotr x, (sub 32, y))
4093   //
4094   // fold (or (shl x, (*ext (sub 32, y))),
4095   //          (srl x, (*ext y))) ->
4096   //   (rotr x, y) or (rotl x, (sub 32, y))
4097   EVT VT = Shifted.getValueType();
4098   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4099     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4100     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4101                        HasPos ? Pos : Neg).getNode();
4102   }
4103 
4104   return nullptr;
4105 }
4106 
4107 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4108 // idioms for rotate, and if the target supports rotation instructions, generate
4109 // a rot[lr].
4110 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4111   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4112   EVT VT = LHS.getValueType();
4113   if (!TLI.isTypeLegal(VT)) return nullptr;
4114 
4115   // The target must have at least one rotate flavor.
4116   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4117   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4118   if (!HasROTL && !HasROTR) return nullptr;
4119 
4120   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4121   SDValue LHSShift;   // The shift.
4122   SDValue LHSMask;    // AND value if any.
4123   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4124     return nullptr; // Not part of a rotate.
4125 
4126   SDValue RHSShift;   // The shift.
4127   SDValue RHSMask;    // AND value if any.
4128   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4129     return nullptr; // Not part of a rotate.
4130 
4131   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4132     return nullptr;   // Not shifting the same value.
4133 
4134   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4135     return nullptr;   // Shifts must disagree.
4136 
4137   // Canonicalize shl to left side in a shl/srl pair.
4138   if (RHSShift.getOpcode() == ISD::SHL) {
4139     std::swap(LHS, RHS);
4140     std::swap(LHSShift, RHSShift);
4141     std::swap(LHSMask, RHSMask);
4142   }
4143 
4144   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4145   SDValue LHSShiftArg = LHSShift.getOperand(0);
4146   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4147   SDValue RHSShiftArg = RHSShift.getOperand(0);
4148   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4149 
4150   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4151   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4152   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4153     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4154     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4155     if ((LShVal + RShVal) != EltSizeInBits)
4156       return nullptr;
4157 
4158     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4159                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4160 
4161     // If there is an AND of either shifted operand, apply it to the result.
4162     if (LHSMask.getNode() || RHSMask.getNode()) {
4163       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4164       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4165 
4166       if (LHSMask.getNode()) {
4167         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4168         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4169                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4170                                        DAG.getConstant(RHSBits, DL, VT)));
4171       }
4172       if (RHSMask.getNode()) {
4173         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4174         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4175                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4176                                        DAG.getConstant(LHSBits, DL, VT)));
4177       }
4178 
4179       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4180     }
4181 
4182     return Rot.getNode();
4183   }
4184 
4185   // If there is a mask here, and we have a variable shift, we can't be sure
4186   // that we're masking out the right stuff.
4187   if (LHSMask.getNode() || RHSMask.getNode())
4188     return nullptr;
4189 
4190   // If the shift amount is sign/zext/any-extended just peel it off.
4191   SDValue LExtOp0 = LHSShiftAmt;
4192   SDValue RExtOp0 = RHSShiftAmt;
4193   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4194        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4195        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4196        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4197       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4198        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4199        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4200        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4201     LExtOp0 = LHSShiftAmt.getOperand(0);
4202     RExtOp0 = RHSShiftAmt.getOperand(0);
4203   }
4204 
4205   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4206                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4207   if (TryL)
4208     return TryL;
4209 
4210   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4211                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4212   if (TryR)
4213     return TryR;
4214 
4215   return nullptr;
4216 }
4217 
4218 SDValue DAGCombiner::visitXOR(SDNode *N) {
4219   SDValue N0 = N->getOperand(0);
4220   SDValue N1 = N->getOperand(1);
4221   EVT VT = N0.getValueType();
4222 
4223   // fold vector ops
4224   if (VT.isVector()) {
4225     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4226       return FoldedVOp;
4227 
4228     // fold (xor x, 0) -> x, vector edition
4229     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4230       return N1;
4231     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4232       return N0;
4233   }
4234 
4235   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4236   if (N0.isUndef() && N1.isUndef())
4237     return DAG.getConstant(0, SDLoc(N), VT);
4238   // fold (xor x, undef) -> undef
4239   if (N0.isUndef())
4240     return N0;
4241   if (N1.isUndef())
4242     return N1;
4243   // fold (xor c1, c2) -> c1^c2
4244   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4245   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4246   if (N0C && N1C)
4247     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4248   // canonicalize constant to RHS
4249   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4250      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4251     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4252   // fold (xor x, 0) -> x
4253   if (isNullConstant(N1))
4254     return N0;
4255   // reassociate xor
4256   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4257     return RXOR;
4258 
4259   // fold !(x cc y) -> (x !cc y)
4260   SDValue LHS, RHS, CC;
4261   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4262     bool isInt = LHS.getValueType().isInteger();
4263     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4264                                                isInt);
4265 
4266     if (!LegalOperations ||
4267         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4268       switch (N0.getOpcode()) {
4269       default:
4270         llvm_unreachable("Unhandled SetCC Equivalent!");
4271       case ISD::SETCC:
4272         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4273       case ISD::SELECT_CC:
4274         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4275                                N0.getOperand(3), NotCC);
4276       }
4277     }
4278   }
4279 
4280   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4281   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4282       N0.getNode()->hasOneUse() &&
4283       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4284     SDValue V = N0.getOperand(0);
4285     SDLoc DL(N0);
4286     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4287                     DAG.getConstant(1, DL, V.getValueType()));
4288     AddToWorklist(V.getNode());
4289     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4290   }
4291 
4292   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4293   if (isOneConstant(N1) && VT == MVT::i1 &&
4294       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4295     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4296     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4297       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4298       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4299       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4300       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4301       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4302     }
4303   }
4304   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4305   if (isAllOnesConstant(N1) &&
4306       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4307     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4308     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4309       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4310       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4311       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4312       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4313       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4314     }
4315   }
4316   // fold (xor (and x, y), y) -> (and (not x), y)
4317   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4318       N0->getOperand(1) == N1) {
4319     SDValue X = N0->getOperand(0);
4320     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4321     AddToWorklist(NotX.getNode());
4322     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4323   }
4324   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4325   if (N1C && N0.getOpcode() == ISD::XOR) {
4326     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4327       SDLoc DL(N);
4328       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4329                          DAG.getConstant(N1C->getAPIntValue() ^
4330                                          N00C->getAPIntValue(), DL, VT));
4331     }
4332     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4333       SDLoc DL(N);
4334       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4335                          DAG.getConstant(N1C->getAPIntValue() ^
4336                                          N01C->getAPIntValue(), DL, VT));
4337     }
4338   }
4339   // fold (xor x, x) -> 0
4340   if (N0 == N1)
4341     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4342 
4343   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4344   // Here is a concrete example of this equivalence:
4345   // i16   x ==  14
4346   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4347   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4348   //
4349   // =>
4350   //
4351   // i16     ~1      == 0b1111111111111110
4352   // i16 rol(~1, 14) == 0b1011111111111111
4353   //
4354   // Some additional tips to help conceptualize this transform:
4355   // - Try to see the operation as placing a single zero in a value of all ones.
4356   // - There exists no value for x which would allow the result to contain zero.
4357   // - Values of x larger than the bitwidth are undefined and do not require a
4358   //   consistent result.
4359   // - Pushing the zero left requires shifting one bits in from the right.
4360   // A rotate left of ~1 is a nice way of achieving the desired result.
4361   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4362       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4363     SDLoc DL(N);
4364     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4365                        N0.getOperand(1));
4366   }
4367 
4368   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4369   if (N0.getOpcode() == N1.getOpcode())
4370     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4371       return Tmp;
4372 
4373   // Simplify the expression using non-local knowledge.
4374   if (!VT.isVector() &&
4375       SimplifyDemandedBits(SDValue(N, 0)))
4376     return SDValue(N, 0);
4377 
4378   return SDValue();
4379 }
4380 
4381 /// Handle transforms common to the three shifts, when the shift amount is a
4382 /// constant.
4383 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4384   SDNode *LHS = N->getOperand(0).getNode();
4385   if (!LHS->hasOneUse()) return SDValue();
4386 
4387   // We want to pull some binops through shifts, so that we have (and (shift))
4388   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4389   // thing happens with address calculations, so it's important to canonicalize
4390   // it.
4391   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4392 
4393   switch (LHS->getOpcode()) {
4394   default: return SDValue();
4395   case ISD::OR:
4396   case ISD::XOR:
4397     HighBitSet = false; // We can only transform sra if the high bit is clear.
4398     break;
4399   case ISD::AND:
4400     HighBitSet = true;  // We can only transform sra if the high bit is set.
4401     break;
4402   case ISD::ADD:
4403     if (N->getOpcode() != ISD::SHL)
4404       return SDValue(); // only shl(add) not sr[al](add).
4405     HighBitSet = false; // We can only transform sra if the high bit is clear.
4406     break;
4407   }
4408 
4409   // We require the RHS of the binop to be a constant and not opaque as well.
4410   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4411   if (!BinOpCst) return SDValue();
4412 
4413   // FIXME: disable this unless the input to the binop is a shift by a constant.
4414   // If it is not a shift, it pessimizes some common cases like:
4415   //
4416   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4417   //    int bar(int *X, int i) { return X[i & 255]; }
4418   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4419   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4420        BinOpLHSVal->getOpcode() != ISD::SRA &&
4421        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4422       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4423     return SDValue();
4424 
4425   EVT VT = N->getValueType(0);
4426 
4427   // If this is a signed shift right, and the high bit is modified by the
4428   // logical operation, do not perform the transformation. The highBitSet
4429   // boolean indicates the value of the high bit of the constant which would
4430   // cause it to be modified for this operation.
4431   if (N->getOpcode() == ISD::SRA) {
4432     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4433     if (BinOpRHSSignSet != HighBitSet)
4434       return SDValue();
4435   }
4436 
4437   if (!TLI.isDesirableToCommuteWithShift(LHS))
4438     return SDValue();
4439 
4440   // Fold the constants, shifting the binop RHS by the shift amount.
4441   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4442                                N->getValueType(0),
4443                                LHS->getOperand(1), N->getOperand(1));
4444   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4445 
4446   // Create the new shift.
4447   SDValue NewShift = DAG.getNode(N->getOpcode(),
4448                                  SDLoc(LHS->getOperand(0)),
4449                                  VT, LHS->getOperand(0), N->getOperand(1));
4450 
4451   // Create the new binop.
4452   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4453 }
4454 
4455 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4456   assert(N->getOpcode() == ISD::TRUNCATE);
4457   assert(N->getOperand(0).getOpcode() == ISD::AND);
4458 
4459   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4460   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4461     SDValue N01 = N->getOperand(0).getOperand(1);
4462     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
4463       SDLoc DL(N);
4464       EVT TruncVT = N->getValueType(0);
4465       SDValue N00 = N->getOperand(0).getOperand(0);
4466       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
4467       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
4468       AddToWorklist(Trunc00.getNode());
4469       AddToWorklist(Trunc01.getNode());
4470       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
4471     }
4472   }
4473 
4474   return SDValue();
4475 }
4476 
4477 SDValue DAGCombiner::visitRotate(SDNode *N) {
4478   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4479   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4480       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4481     if (SDValue NewOp1 =
4482             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4483       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4484                          N->getOperand(0), NewOp1);
4485   }
4486   return SDValue();
4487 }
4488 
4489 SDValue DAGCombiner::visitSHL(SDNode *N) {
4490   SDValue N0 = N->getOperand(0);
4491   SDValue N1 = N->getOperand(1);
4492   EVT VT = N0.getValueType();
4493   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4494 
4495   // fold vector ops
4496   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4497   if (VT.isVector()) {
4498     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4499       return FoldedVOp;
4500 
4501     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4502     // If setcc produces all-one true value then:
4503     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4504     if (N1CV && N1CV->isConstant()) {
4505       if (N0.getOpcode() == ISD::AND) {
4506         SDValue N00 = N0->getOperand(0);
4507         SDValue N01 = N0->getOperand(1);
4508         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4509 
4510         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4511             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4512                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4513           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4514                                                      N01CV, N1CV))
4515             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4516         }
4517       } else {
4518         N1C = isConstOrConstSplat(N1);
4519       }
4520     }
4521   }
4522 
4523   // fold (shl c1, c2) -> c1<<c2
4524   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4525   if (N0C && N1C && !N1C->isOpaque())
4526     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4527   // fold (shl 0, x) -> 0
4528   if (isNullConstant(N0))
4529     return N0;
4530   // fold (shl x, c >= size(x)) -> undef
4531   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4532     return DAG.getUNDEF(VT);
4533   // fold (shl x, 0) -> x
4534   if (N1C && N1C->isNullValue())
4535     return N0;
4536   // fold (shl undef, x) -> 0
4537   if (N0.isUndef())
4538     return DAG.getConstant(0, SDLoc(N), VT);
4539   // if (shl x, c) is known to be zero, return 0
4540   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4541                             APInt::getAllOnesValue(OpSizeInBits)))
4542     return DAG.getConstant(0, SDLoc(N), VT);
4543   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4544   if (N1.getOpcode() == ISD::TRUNCATE &&
4545       N1.getOperand(0).getOpcode() == ISD::AND) {
4546     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4547       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4548   }
4549 
4550   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4551     return SDValue(N, 0);
4552 
4553   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4554   if (N1C && N0.getOpcode() == ISD::SHL) {
4555     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4556       SDLoc DL(N);
4557       APInt c1 = N0C1->getAPIntValue();
4558       APInt c2 = N1C->getAPIntValue();
4559       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4560 
4561       APInt Sum = c1 + c2;
4562       if (Sum.uge(OpSizeInBits))
4563         return DAG.getConstant(0, DL, VT);
4564 
4565       return DAG.getNode(
4566           ISD::SHL, DL, VT, N0.getOperand(0),
4567           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4568     }
4569   }
4570 
4571   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4572   // For this to be valid, the second form must not preserve any of the bits
4573   // that are shifted out by the inner shift in the first form.  This means
4574   // the outer shift size must be >= the number of bits added by the ext.
4575   // As a corollary, we don't care what kind of ext it is.
4576   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4577               N0.getOpcode() == ISD::ANY_EXTEND ||
4578               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4579       N0.getOperand(0).getOpcode() == ISD::SHL) {
4580     SDValue N0Op0 = N0.getOperand(0);
4581     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4582       APInt c1 = N0Op0C1->getAPIntValue();
4583       APInt c2 = N1C->getAPIntValue();
4584       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4585 
4586       EVT InnerShiftVT = N0Op0.getValueType();
4587       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4588       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4589         SDLoc DL(N0);
4590         APInt Sum = c1 + c2;
4591         if (Sum.uge(OpSizeInBits))
4592           return DAG.getConstant(0, DL, VT);
4593 
4594         return DAG.getNode(
4595             ISD::SHL, DL, VT,
4596             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4597             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4598       }
4599     }
4600   }
4601 
4602   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4603   // Only fold this if the inner zext has no other uses to avoid increasing
4604   // the total number of instructions.
4605   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4606       N0.getOperand(0).getOpcode() == ISD::SRL) {
4607     SDValue N0Op0 = N0.getOperand(0);
4608     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4609       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4610         uint64_t c1 = N0Op0C1->getZExtValue();
4611         uint64_t c2 = N1C->getZExtValue();
4612         if (c1 == c2) {
4613           SDValue NewOp0 = N0.getOperand(0);
4614           EVT CountVT = NewOp0.getOperand(1).getValueType();
4615           SDLoc DL(N);
4616           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4617                                        NewOp0,
4618                                        DAG.getConstant(c2, DL, CountVT));
4619           AddToWorklist(NewSHL.getNode());
4620           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4621         }
4622       }
4623     }
4624   }
4625 
4626   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4627   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4628   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4629       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4630     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4631       uint64_t C1 = N0C1->getZExtValue();
4632       uint64_t C2 = N1C->getZExtValue();
4633       SDLoc DL(N);
4634       if (C1 <= C2)
4635         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4636                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4637       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4638                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4639     }
4640   }
4641 
4642   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4643   //                               (and (srl x, (sub c1, c2), MASK)
4644   // Only fold this if the inner shift has no other uses -- if it does, folding
4645   // this will increase the total number of instructions.
4646   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4647     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4648       uint64_t c1 = N0C1->getZExtValue();
4649       if (c1 < OpSizeInBits) {
4650         uint64_t c2 = N1C->getZExtValue();
4651         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4652         SDValue Shift;
4653         if (c2 > c1) {
4654           Mask = Mask.shl(c2 - c1);
4655           SDLoc DL(N);
4656           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4657                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4658         } else {
4659           Mask = Mask.lshr(c1 - c2);
4660           SDLoc DL(N);
4661           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4662                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4663         }
4664         SDLoc DL(N0);
4665         return DAG.getNode(ISD::AND, DL, VT, Shift,
4666                            DAG.getConstant(Mask, DL, VT));
4667       }
4668     }
4669   }
4670 
4671   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4672   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
4673       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
4674     unsigned BitSize = VT.getScalarSizeInBits();
4675     SDLoc DL(N);
4676     SDValue AllBits = DAG.getConstant(APInt::getAllOnesValue(BitSize), DL, VT);
4677     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
4678     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
4679   }
4680 
4681   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4682   // Variant of version done on multiply, except mul by a power of 2 is turned
4683   // into a shift.
4684   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4685       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4686       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4687     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4688     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4689     AddToWorklist(Shl0.getNode());
4690     AddToWorklist(Shl1.getNode());
4691     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4692   }
4693 
4694   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4695   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
4696       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4697       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4698     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4699     AddToWorklist(Shl.getNode());
4700     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
4701   }
4702 
4703   if (N1C && !N1C->isOpaque())
4704     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4705       return NewSHL;
4706 
4707   return SDValue();
4708 }
4709 
4710 SDValue DAGCombiner::visitSRA(SDNode *N) {
4711   SDValue N0 = N->getOperand(0);
4712   SDValue N1 = N->getOperand(1);
4713   EVT VT = N0.getValueType();
4714   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4715 
4716   // Arithmetic shifting an all-sign-bit value is a no-op.
4717   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
4718     return N0;
4719 
4720   // fold vector ops
4721   if (VT.isVector())
4722     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4723       return FoldedVOp;
4724 
4725   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4726 
4727   // fold (sra c1, c2) -> (sra c1, c2)
4728   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4729   if (N0C && N1C && !N1C->isOpaque())
4730     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4731   // fold (sra 0, x) -> 0
4732   if (isNullConstant(N0))
4733     return N0;
4734   // fold (sra -1, x) -> -1
4735   if (isAllOnesConstant(N0))
4736     return N0;
4737   // fold (sra x, c >= size(x)) -> undef
4738   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4739     return DAG.getUNDEF(VT);
4740   // fold (sra x, 0) -> x
4741   if (N1C && N1C->isNullValue())
4742     return N0;
4743   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4744   // sext_inreg.
4745   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4746     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4747     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4748     if (VT.isVector())
4749       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4750                                ExtVT, VT.getVectorNumElements());
4751     if ((!LegalOperations ||
4752          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4753       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4754                          N0.getOperand(0), DAG.getValueType(ExtVT));
4755   }
4756 
4757   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4758   if (N1C && N0.getOpcode() == ISD::SRA) {
4759     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4760       SDLoc DL(N);
4761       APInt c1 = N0C1->getAPIntValue();
4762       APInt c2 = N1C->getAPIntValue();
4763       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4764 
4765       APInt Sum = c1 + c2;
4766       if (Sum.uge(OpSizeInBits))
4767         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4768 
4769       return DAG.getNode(
4770           ISD::SRA, DL, VT, N0.getOperand(0),
4771           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4772     }
4773   }
4774 
4775   // fold (sra (shl X, m), (sub result_size, n))
4776   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4777   // result_size - n != m.
4778   // If truncate is free for the target sext(shl) is likely to result in better
4779   // code.
4780   if (N0.getOpcode() == ISD::SHL && N1C) {
4781     // Get the two constanst of the shifts, CN0 = m, CN = n.
4782     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4783     if (N01C) {
4784       LLVMContext &Ctx = *DAG.getContext();
4785       // Determine what the truncate's result bitsize and type would be.
4786       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4787 
4788       if (VT.isVector())
4789         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4790 
4791       // Determine the residual right-shift amount.
4792       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4793 
4794       // If the shift is not a no-op (in which case this should be just a sign
4795       // extend already), the truncated to type is legal, sign_extend is legal
4796       // on that type, and the truncate to that type is both legal and free,
4797       // perform the transform.
4798       if ((ShiftAmt > 0) &&
4799           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4800           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4801           TLI.isTruncateFree(VT, TruncVT)) {
4802 
4803         SDLoc DL(N);
4804         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4805             getShiftAmountTy(N0.getOperand(0).getValueType()));
4806         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4807                                     N0.getOperand(0), Amt);
4808         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4809                                     Shift);
4810         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4811                            N->getValueType(0), Trunc);
4812       }
4813     }
4814   }
4815 
4816   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4817   if (N1.getOpcode() == ISD::TRUNCATE &&
4818       N1.getOperand(0).getOpcode() == ISD::AND) {
4819     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4820       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4821   }
4822 
4823   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4824   //      if c1 is equal to the number of bits the trunc removes
4825   if (N0.getOpcode() == ISD::TRUNCATE &&
4826       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4827        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4828       N0.getOperand(0).hasOneUse() &&
4829       N0.getOperand(0).getOperand(1).hasOneUse() &&
4830       N1C) {
4831     SDValue N0Op0 = N0.getOperand(0);
4832     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4833       unsigned LargeShiftVal = LargeShift->getZExtValue();
4834       EVT LargeVT = N0Op0.getValueType();
4835 
4836       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4837         SDLoc DL(N);
4838         SDValue Amt =
4839           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4840                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4841         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4842                                   N0Op0.getOperand(0), Amt);
4843         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4844       }
4845     }
4846   }
4847 
4848   // Simplify, based on bits shifted out of the LHS.
4849   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4850     return SDValue(N, 0);
4851 
4852 
4853   // If the sign bit is known to be zero, switch this to a SRL.
4854   if (DAG.SignBitIsZero(N0))
4855     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4856 
4857   if (N1C && !N1C->isOpaque())
4858     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4859       return NewSRA;
4860 
4861   return SDValue();
4862 }
4863 
4864 SDValue DAGCombiner::visitSRL(SDNode *N) {
4865   SDValue N0 = N->getOperand(0);
4866   SDValue N1 = N->getOperand(1);
4867   EVT VT = N0.getValueType();
4868   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4869 
4870   // fold vector ops
4871   if (VT.isVector())
4872     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4873       return FoldedVOp;
4874 
4875   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4876 
4877   // fold (srl c1, c2) -> c1 >>u c2
4878   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4879   if (N0C && N1C && !N1C->isOpaque())
4880     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4881   // fold (srl 0, x) -> 0
4882   if (isNullConstant(N0))
4883     return N0;
4884   // fold (srl x, c >= size(x)) -> undef
4885   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4886     return DAG.getUNDEF(VT);
4887   // fold (srl x, 0) -> x
4888   if (N1C && N1C->isNullValue())
4889     return N0;
4890   // if (srl x, c) is known to be zero, return 0
4891   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4892                                    APInt::getAllOnesValue(OpSizeInBits)))
4893     return DAG.getConstant(0, SDLoc(N), VT);
4894 
4895   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4896   if (N1C && N0.getOpcode() == ISD::SRL) {
4897     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4898       SDLoc DL(N);
4899       APInt c1 = N0C1->getAPIntValue();
4900       APInt c2 = N1C->getAPIntValue();
4901       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4902 
4903       APInt Sum = c1 + c2;
4904       if (Sum.uge(OpSizeInBits))
4905         return DAG.getConstant(0, DL, VT);
4906 
4907       return DAG.getNode(
4908           ISD::SRL, DL, VT, N0.getOperand(0),
4909           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4910     }
4911   }
4912 
4913   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4914   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4915       N0.getOperand(0).getOpcode() == ISD::SRL &&
4916       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4917     uint64_t c1 =
4918       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4919     uint64_t c2 = N1C->getZExtValue();
4920     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4921     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4922     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4923     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4924     if (c1 + OpSizeInBits == InnerShiftSize) {
4925       SDLoc DL(N0);
4926       if (c1 + c2 >= InnerShiftSize)
4927         return DAG.getConstant(0, DL, VT);
4928       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4929                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4930                                      N0.getOperand(0)->getOperand(0),
4931                                      DAG.getConstant(c1 + c2, DL,
4932                                                      ShiftCountVT)));
4933     }
4934   }
4935 
4936   // fold (srl (shl x, c), c) -> (and x, cst2)
4937   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4938       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
4939     SDLoc DL(N);
4940     APInt AllBits = APInt::getAllOnesValue(N0.getScalarValueSizeInBits());
4941     SDValue Mask =
4942         DAG.getNode(ISD::SRL, DL, VT, DAG.getConstant(AllBits, DL, VT), N1);
4943     AddToWorklist(Mask.getNode());
4944     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
4945   }
4946 
4947   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4948   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4949     // Shifting in all undef bits?
4950     EVT SmallVT = N0.getOperand(0).getValueType();
4951     unsigned BitSize = SmallVT.getScalarSizeInBits();
4952     if (N1C->getZExtValue() >= BitSize)
4953       return DAG.getUNDEF(VT);
4954 
4955     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4956       uint64_t ShiftAmt = N1C->getZExtValue();
4957       SDLoc DL0(N0);
4958       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4959                                        N0.getOperand(0),
4960                           DAG.getConstant(ShiftAmt, DL0,
4961                                           getShiftAmountTy(SmallVT)));
4962       AddToWorklist(SmallShift.getNode());
4963       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4964       SDLoc DL(N);
4965       return DAG.getNode(ISD::AND, DL, VT,
4966                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4967                          DAG.getConstant(Mask, DL, VT));
4968     }
4969   }
4970 
4971   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4972   // bit, which is unmodified by sra.
4973   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4974     if (N0.getOpcode() == ISD::SRA)
4975       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4976   }
4977 
4978   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4979   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4980       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4981     APInt KnownZero, KnownOne;
4982     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4983 
4984     // If any of the input bits are KnownOne, then the input couldn't be all
4985     // zeros, thus the result of the srl will always be zero.
4986     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4987 
4988     // If all of the bits input the to ctlz node are known to be zero, then
4989     // the result of the ctlz is "32" and the result of the shift is one.
4990     APInt UnknownBits = ~KnownZero;
4991     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4992 
4993     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4994     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4995       // Okay, we know that only that the single bit specified by UnknownBits
4996       // could be set on input to the CTLZ node. If this bit is set, the SRL
4997       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4998       // to an SRL/XOR pair, which is likely to simplify more.
4999       unsigned ShAmt = UnknownBits.countTrailingZeros();
5000       SDValue Op = N0.getOperand(0);
5001 
5002       if (ShAmt) {
5003         SDLoc DL(N0);
5004         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5005                   DAG.getConstant(ShAmt, DL,
5006                                   getShiftAmountTy(Op.getValueType())));
5007         AddToWorklist(Op.getNode());
5008       }
5009 
5010       SDLoc DL(N);
5011       return DAG.getNode(ISD::XOR, DL, VT,
5012                          Op, DAG.getConstant(1, DL, VT));
5013     }
5014   }
5015 
5016   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5017   if (N1.getOpcode() == ISD::TRUNCATE &&
5018       N1.getOperand(0).getOpcode() == ISD::AND) {
5019     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5020       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5021   }
5022 
5023   // fold operands of srl based on knowledge that the low bits are not
5024   // demanded.
5025   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5026     return SDValue(N, 0);
5027 
5028   if (N1C && !N1C->isOpaque())
5029     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5030       return NewSRL;
5031 
5032   // Attempt to convert a srl of a load into a narrower zero-extending load.
5033   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5034     return NarrowLoad;
5035 
5036   // Here is a common situation. We want to optimize:
5037   //
5038   //   %a = ...
5039   //   %b = and i32 %a, 2
5040   //   %c = srl i32 %b, 1
5041   //   brcond i32 %c ...
5042   //
5043   // into
5044   //
5045   //   %a = ...
5046   //   %b = and %a, 2
5047   //   %c = setcc eq %b, 0
5048   //   brcond %c ...
5049   //
5050   // However when after the source operand of SRL is optimized into AND, the SRL
5051   // itself may not be optimized further. Look for it and add the BRCOND into
5052   // the worklist.
5053   if (N->hasOneUse()) {
5054     SDNode *Use = *N->use_begin();
5055     if (Use->getOpcode() == ISD::BRCOND)
5056       AddToWorklist(Use);
5057     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5058       // Also look pass the truncate.
5059       Use = *Use->use_begin();
5060       if (Use->getOpcode() == ISD::BRCOND)
5061         AddToWorklist(Use);
5062     }
5063   }
5064 
5065   return SDValue();
5066 }
5067 
5068 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5069   SDValue N0 = N->getOperand(0);
5070   EVT VT = N->getValueType(0);
5071 
5072   // fold (bswap c1) -> c2
5073   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5074     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5075   // fold (bswap (bswap x)) -> x
5076   if (N0.getOpcode() == ISD::BSWAP)
5077     return N0->getOperand(0);
5078   return SDValue();
5079 }
5080 
5081 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5082   SDValue N0 = N->getOperand(0);
5083 
5084   // fold (bitreverse (bitreverse x)) -> x
5085   if (N0.getOpcode() == ISD::BITREVERSE)
5086     return N0.getOperand(0);
5087   return SDValue();
5088 }
5089 
5090 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5091   SDValue N0 = N->getOperand(0);
5092   EVT VT = N->getValueType(0);
5093 
5094   // fold (ctlz c1) -> c2
5095   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5096     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5097   return SDValue();
5098 }
5099 
5100 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5101   SDValue N0 = N->getOperand(0);
5102   EVT VT = N->getValueType(0);
5103 
5104   // fold (ctlz_zero_undef c1) -> c2
5105   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5106     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5107   return SDValue();
5108 }
5109 
5110 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5111   SDValue N0 = N->getOperand(0);
5112   EVT VT = N->getValueType(0);
5113 
5114   // fold (cttz c1) -> c2
5115   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5116     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5117   return SDValue();
5118 }
5119 
5120 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5121   SDValue N0 = N->getOperand(0);
5122   EVT VT = N->getValueType(0);
5123 
5124   // fold (cttz_zero_undef c1) -> c2
5125   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5126     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5127   return SDValue();
5128 }
5129 
5130 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5131   SDValue N0 = N->getOperand(0);
5132   EVT VT = N->getValueType(0);
5133 
5134   // fold (ctpop c1) -> c2
5135   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5136     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5137   return SDValue();
5138 }
5139 
5140 
5141 /// \brief Generate Min/Max node
5142 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5143                                    SDValue RHS, SDValue True, SDValue False,
5144                                    ISD::CondCode CC, const TargetLowering &TLI,
5145                                    SelectionDAG &DAG) {
5146   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5147     return SDValue();
5148 
5149   switch (CC) {
5150   case ISD::SETOLT:
5151   case ISD::SETOLE:
5152   case ISD::SETLT:
5153   case ISD::SETLE:
5154   case ISD::SETULT:
5155   case ISD::SETULE: {
5156     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5157     if (TLI.isOperationLegal(Opcode, VT))
5158       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5159     return SDValue();
5160   }
5161   case ISD::SETOGT:
5162   case ISD::SETOGE:
5163   case ISD::SETGT:
5164   case ISD::SETGE:
5165   case ISD::SETUGT:
5166   case ISD::SETUGE: {
5167     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5168     if (TLI.isOperationLegal(Opcode, VT))
5169       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5170     return SDValue();
5171   }
5172   default:
5173     return SDValue();
5174   }
5175 }
5176 
5177 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5178 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5179   SDValue Cond = N->getOperand(0);
5180   SDValue N1 = N->getOperand(1);
5181   SDValue N2 = N->getOperand(2);
5182   EVT VT = N->getValueType(0);
5183   EVT CondVT = Cond.getValueType();
5184   SDLoc DL(N);
5185 
5186   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5187   // We can't do this reliably if integer based booleans have different contents
5188   // to floating point based booleans. This is because we can't tell whether we
5189   // have an integer-based boolean or a floating-point-based boolean unless we
5190   // can find the SETCC that produced it and inspect its operands. This is
5191   // fairly easy if C is the SETCC node, but it can potentially be
5192   // undiscoverable (or not reasonably discoverable). For example, it could be
5193   // in another basic block or it could require searching a complicated
5194   // expression.
5195   if (VT.isInteger() &&
5196       (CondVT == MVT::i1 || (CondVT.isInteger() &&
5197                              TLI.getBooleanContents(false, true) ==
5198                                  TargetLowering::ZeroOrOneBooleanContent &&
5199                              TLI.getBooleanContents(false, false) ==
5200                                  TargetLowering::ZeroOrOneBooleanContent)) &&
5201       isNullConstant(N1) && isOneConstant(N2)) {
5202     SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5203                                   DAG.getConstant(1, DL, CondVT));
5204     if (VT.bitsEq(CondVT))
5205       return NotCond;
5206     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5207   }
5208 
5209   return SDValue();
5210 }
5211 
5212 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5213   SDValue N0 = N->getOperand(0);
5214   SDValue N1 = N->getOperand(1);
5215   SDValue N2 = N->getOperand(2);
5216   EVT VT = N->getValueType(0);
5217   EVT VT0 = N0.getValueType();
5218 
5219   // fold (select C, X, X) -> X
5220   if (N1 == N2)
5221     return N1;
5222   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5223     // fold (select true, X, Y) -> X
5224     // fold (select false, X, Y) -> Y
5225     return !N0C->isNullValue() ? N1 : N2;
5226   }
5227   // fold (select C, 1, X) -> (or C, X)
5228   if (VT == MVT::i1 && isOneConstant(N1))
5229     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5230 
5231   if (SDValue V = foldSelectOfConstants(N))
5232     return V;
5233 
5234   // fold (select C, 0, X) -> (and (not C), X)
5235   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5236     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5237     AddToWorklist(NOTNode.getNode());
5238     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5239   }
5240   // fold (select C, X, 1) -> (or (not C), X)
5241   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5242     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5243     AddToWorklist(NOTNode.getNode());
5244     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5245   }
5246   // fold (select C, X, 0) -> (and C, X)
5247   if (VT == MVT::i1 && isNullConstant(N2))
5248     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5249   // fold (select X, X, Y) -> (or X, Y)
5250   // fold (select X, 1, Y) -> (or X, Y)
5251   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5252     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5253   // fold (select X, Y, X) -> (and X, Y)
5254   // fold (select X, Y, 0) -> (and X, Y)
5255   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5256     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5257 
5258   // If we can fold this based on the true/false value, do so.
5259   if (SimplifySelectOps(N, N1, N2))
5260     return SDValue(N, 0);  // Don't revisit N.
5261 
5262   if (VT0 == MVT::i1) {
5263     // The code in this block deals with the following 2 equivalences:
5264     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5265     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5266     // The target can specify its prefered form with the
5267     // shouldNormalizeToSelectSequence() callback. However we always transform
5268     // to the right anyway if we find the inner select exists in the DAG anyway
5269     // and we always transform to the left side if we know that we can further
5270     // optimize the combination of the conditions.
5271     bool normalizeToSequence
5272       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5273     // select (and Cond0, Cond1), X, Y
5274     //   -> select Cond0, (select Cond1, X, Y), Y
5275     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5276       SDValue Cond0 = N0->getOperand(0);
5277       SDValue Cond1 = N0->getOperand(1);
5278       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5279                                         N1.getValueType(), Cond1, N1, N2);
5280       if (normalizeToSequence || !InnerSelect.use_empty())
5281         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5282                            InnerSelect, N2);
5283     }
5284     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5285     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5286       SDValue Cond0 = N0->getOperand(0);
5287       SDValue Cond1 = N0->getOperand(1);
5288       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5289                                         N1.getValueType(), Cond1, N1, N2);
5290       if (normalizeToSequence || !InnerSelect.use_empty())
5291         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5292                            InnerSelect);
5293     }
5294 
5295     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5296     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5297       SDValue N1_0 = N1->getOperand(0);
5298       SDValue N1_1 = N1->getOperand(1);
5299       SDValue N1_2 = N1->getOperand(2);
5300       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5301         // Create the actual and node if we can generate good code for it.
5302         if (!normalizeToSequence) {
5303           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5304                                     N0, N1_0);
5305           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5306                              N1_1, N2);
5307         }
5308         // Otherwise see if we can optimize the "and" to a better pattern.
5309         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5310           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5311                              N1_1, N2);
5312       }
5313     }
5314     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5315     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5316       SDValue N2_0 = N2->getOperand(0);
5317       SDValue N2_1 = N2->getOperand(1);
5318       SDValue N2_2 = N2->getOperand(2);
5319       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5320         // Create the actual or node if we can generate good code for it.
5321         if (!normalizeToSequence) {
5322           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5323                                    N0, N2_0);
5324           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5325                              N1, N2_2);
5326         }
5327         // Otherwise see if we can optimize to a better pattern.
5328         if (SDValue Combined = visitORLike(N0, N2_0, N))
5329           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5330                              N1, N2_2);
5331       }
5332     }
5333   }
5334 
5335   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5336   // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5337   if (VT0 == MVT::i1) {
5338     if (N0->getOpcode() == ISD::XOR) {
5339       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5340         SDValue Cond0 = N0->getOperand(0);
5341         if (C->isOne())
5342           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5343                              Cond0, N2, N1);
5344         else
5345           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5346                              Cond0, N1, N2);
5347       }
5348     }
5349   }
5350 
5351   // fold selects based on a setcc into other things, such as min/max/abs
5352   if (N0.getOpcode() == ISD::SETCC) {
5353     // select x, y (fcmp lt x, y) -> fminnum x, y
5354     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5355     //
5356     // This is OK if we don't care about what happens if either operand is a
5357     // NaN.
5358     //
5359 
5360     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5361     // no signed zeros as well as no nans.
5362     const TargetOptions &Options = DAG.getTarget().Options;
5363     if (Options.UnsafeFPMath &&
5364         VT.isFloatingPoint() && N0.hasOneUse() &&
5365         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5366       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5367 
5368       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5369                                                 N0.getOperand(1), N1, N2, CC,
5370                                                 TLI, DAG))
5371         return FMinMax;
5372     }
5373 
5374     if ((!LegalOperations &&
5375          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5376         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5377       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5378                          N0.getOperand(0), N0.getOperand(1),
5379                          N1, N2, N0.getOperand(2));
5380     return SimplifySelect(SDLoc(N), N0, N1, N2);
5381   }
5382 
5383   return SDValue();
5384 }
5385 
5386 static
5387 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5388   SDLoc DL(N);
5389   EVT LoVT, HiVT;
5390   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5391 
5392   // Split the inputs.
5393   SDValue Lo, Hi, LL, LH, RL, RH;
5394   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5395   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5396 
5397   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5398   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5399 
5400   return std::make_pair(Lo, Hi);
5401 }
5402 
5403 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5404 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5405 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5406   SDLoc DL(N);
5407   SDValue Cond = N->getOperand(0);
5408   SDValue LHS = N->getOperand(1);
5409   SDValue RHS = N->getOperand(2);
5410   EVT VT = N->getValueType(0);
5411   int NumElems = VT.getVectorNumElements();
5412   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5413          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5414          Cond.getOpcode() == ISD::BUILD_VECTOR);
5415 
5416   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5417   // binary ones here.
5418   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5419     return SDValue();
5420 
5421   // We're sure we have an even number of elements due to the
5422   // concat_vectors we have as arguments to vselect.
5423   // Skip BV elements until we find one that's not an UNDEF
5424   // After we find an UNDEF element, keep looping until we get to half the
5425   // length of the BV and see if all the non-undef nodes are the same.
5426   ConstantSDNode *BottomHalf = nullptr;
5427   for (int i = 0; i < NumElems / 2; ++i) {
5428     if (Cond->getOperand(i)->isUndef())
5429       continue;
5430 
5431     if (BottomHalf == nullptr)
5432       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5433     else if (Cond->getOperand(i).getNode() != BottomHalf)
5434       return SDValue();
5435   }
5436 
5437   // Do the same for the second half of the BuildVector
5438   ConstantSDNode *TopHalf = nullptr;
5439   for (int i = NumElems / 2; i < NumElems; ++i) {
5440     if (Cond->getOperand(i)->isUndef())
5441       continue;
5442 
5443     if (TopHalf == nullptr)
5444       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5445     else if (Cond->getOperand(i).getNode() != TopHalf)
5446       return SDValue();
5447   }
5448 
5449   assert(TopHalf && BottomHalf &&
5450          "One half of the selector was all UNDEFs and the other was all the "
5451          "same value. This should have been addressed before this function.");
5452   return DAG.getNode(
5453       ISD::CONCAT_VECTORS, DL, VT,
5454       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5455       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5456 }
5457 
5458 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5459 
5460   if (Level >= AfterLegalizeTypes)
5461     return SDValue();
5462 
5463   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5464   SDValue Mask = MSC->getMask();
5465   SDValue Data  = MSC->getValue();
5466   SDLoc DL(N);
5467 
5468   // If the MSCATTER data type requires splitting and the mask is provided by a
5469   // SETCC, then split both nodes and its operands before legalization. This
5470   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5471   // and enables future optimizations (e.g. min/max pattern matching on X86).
5472   if (Mask.getOpcode() != ISD::SETCC)
5473     return SDValue();
5474 
5475   // Check if any splitting is required.
5476   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5477       TargetLowering::TypeSplitVector)
5478     return SDValue();
5479   SDValue MaskLo, MaskHi, Lo, Hi;
5480   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5481 
5482   EVT LoVT, HiVT;
5483   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5484 
5485   SDValue Chain = MSC->getChain();
5486 
5487   EVT MemoryVT = MSC->getMemoryVT();
5488   unsigned Alignment = MSC->getOriginalAlignment();
5489 
5490   EVT LoMemVT, HiMemVT;
5491   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5492 
5493   SDValue DataLo, DataHi;
5494   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5495 
5496   SDValue BasePtr = MSC->getBasePtr();
5497   SDValue IndexLo, IndexHi;
5498   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5499 
5500   MachineMemOperand *MMO = DAG.getMachineFunction().
5501     getMachineMemOperand(MSC->getPointerInfo(),
5502                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5503                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5504 
5505   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5506   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5507                             DL, OpsLo, MMO);
5508 
5509   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5510   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5511                             DL, OpsHi, MMO);
5512 
5513   AddToWorklist(Lo.getNode());
5514   AddToWorklist(Hi.getNode());
5515 
5516   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5517 }
5518 
5519 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5520 
5521   if (Level >= AfterLegalizeTypes)
5522     return SDValue();
5523 
5524   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5525   SDValue Mask = MST->getMask();
5526   SDValue Data  = MST->getValue();
5527   SDLoc DL(N);
5528 
5529   // If the MSTORE data type requires splitting and the mask is provided by a
5530   // SETCC, then split both nodes and its operands before legalization. This
5531   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5532   // and enables future optimizations (e.g. min/max pattern matching on X86).
5533   if (Mask.getOpcode() == ISD::SETCC) {
5534 
5535     // Check if any splitting is required.
5536     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5537         TargetLowering::TypeSplitVector)
5538       return SDValue();
5539 
5540     SDValue MaskLo, MaskHi, Lo, Hi;
5541     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5542 
5543     EVT LoVT, HiVT;
5544     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5545 
5546     SDValue Chain = MST->getChain();
5547     SDValue Ptr   = MST->getBasePtr();
5548 
5549     EVT MemoryVT = MST->getMemoryVT();
5550     unsigned Alignment = MST->getOriginalAlignment();
5551 
5552     // if Alignment is equal to the vector size,
5553     // take the half of it for the second part
5554     unsigned SecondHalfAlignment =
5555       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5556          Alignment/2 : Alignment;
5557 
5558     EVT LoMemVT, HiMemVT;
5559     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5560 
5561     SDValue DataLo, DataHi;
5562     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5563 
5564     MachineMemOperand *MMO = DAG.getMachineFunction().
5565       getMachineMemOperand(MST->getPointerInfo(),
5566                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5567                            Alignment, MST->getAAInfo(), MST->getRanges());
5568 
5569     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5570                             MST->isTruncatingStore());
5571 
5572     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5573     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5574                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5575 
5576     MMO = DAG.getMachineFunction().
5577       getMachineMemOperand(MST->getPointerInfo(),
5578                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5579                            SecondHalfAlignment, MST->getAAInfo(),
5580                            MST->getRanges());
5581 
5582     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5583                             MST->isTruncatingStore());
5584 
5585     AddToWorklist(Lo.getNode());
5586     AddToWorklist(Hi.getNode());
5587 
5588     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5589   }
5590   return SDValue();
5591 }
5592 
5593 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5594 
5595   if (Level >= AfterLegalizeTypes)
5596     return SDValue();
5597 
5598   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5599   SDValue Mask = MGT->getMask();
5600   SDLoc DL(N);
5601 
5602   // If the MGATHER result requires splitting and the mask is provided by a
5603   // SETCC, then split both nodes and its operands before legalization. This
5604   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5605   // and enables future optimizations (e.g. min/max pattern matching on X86).
5606 
5607   if (Mask.getOpcode() != ISD::SETCC)
5608     return SDValue();
5609 
5610   EVT VT = N->getValueType(0);
5611 
5612   // Check if any splitting is required.
5613   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5614       TargetLowering::TypeSplitVector)
5615     return SDValue();
5616 
5617   SDValue MaskLo, MaskHi, Lo, Hi;
5618   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5619 
5620   SDValue Src0 = MGT->getValue();
5621   SDValue Src0Lo, Src0Hi;
5622   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5623 
5624   EVT LoVT, HiVT;
5625   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5626 
5627   SDValue Chain = MGT->getChain();
5628   EVT MemoryVT = MGT->getMemoryVT();
5629   unsigned Alignment = MGT->getOriginalAlignment();
5630 
5631   EVT LoMemVT, HiMemVT;
5632   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5633 
5634   SDValue BasePtr = MGT->getBasePtr();
5635   SDValue Index = MGT->getIndex();
5636   SDValue IndexLo, IndexHi;
5637   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5638 
5639   MachineMemOperand *MMO = DAG.getMachineFunction().
5640     getMachineMemOperand(MGT->getPointerInfo(),
5641                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5642                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5643 
5644   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5645   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5646                             MMO);
5647 
5648   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5649   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5650                             MMO);
5651 
5652   AddToWorklist(Lo.getNode());
5653   AddToWorklist(Hi.getNode());
5654 
5655   // Build a factor node to remember that this load is independent of the
5656   // other one.
5657   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5658                       Hi.getValue(1));
5659 
5660   // Legalized the chain result - switch anything that used the old chain to
5661   // use the new one.
5662   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5663 
5664   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5665 
5666   SDValue RetOps[] = { GatherRes, Chain };
5667   return DAG.getMergeValues(RetOps, DL);
5668 }
5669 
5670 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5671 
5672   if (Level >= AfterLegalizeTypes)
5673     return SDValue();
5674 
5675   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5676   SDValue Mask = MLD->getMask();
5677   SDLoc DL(N);
5678 
5679   // If the MLOAD result requires splitting and the mask is provided by a
5680   // SETCC, then split both nodes and its operands before legalization. This
5681   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5682   // and enables future optimizations (e.g. min/max pattern matching on X86).
5683 
5684   if (Mask.getOpcode() == ISD::SETCC) {
5685     EVT VT = N->getValueType(0);
5686 
5687     // Check if any splitting is required.
5688     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5689         TargetLowering::TypeSplitVector)
5690       return SDValue();
5691 
5692     SDValue MaskLo, MaskHi, Lo, Hi;
5693     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5694 
5695     SDValue Src0 = MLD->getSrc0();
5696     SDValue Src0Lo, Src0Hi;
5697     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5698 
5699     EVT LoVT, HiVT;
5700     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5701 
5702     SDValue Chain = MLD->getChain();
5703     SDValue Ptr   = MLD->getBasePtr();
5704     EVT MemoryVT = MLD->getMemoryVT();
5705     unsigned Alignment = MLD->getOriginalAlignment();
5706 
5707     // if Alignment is equal to the vector size,
5708     // take the half of it for the second part
5709     unsigned SecondHalfAlignment =
5710       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5711          Alignment/2 : Alignment;
5712 
5713     EVT LoMemVT, HiMemVT;
5714     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5715 
5716     MachineMemOperand *MMO = DAG.getMachineFunction().
5717     getMachineMemOperand(MLD->getPointerInfo(),
5718                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5719                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5720 
5721     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5722                            ISD::NON_EXTLOAD);
5723 
5724     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5725     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5726                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5727 
5728     MMO = DAG.getMachineFunction().
5729     getMachineMemOperand(MLD->getPointerInfo(),
5730                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5731                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5732 
5733     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5734                            ISD::NON_EXTLOAD);
5735 
5736     AddToWorklist(Lo.getNode());
5737     AddToWorklist(Hi.getNode());
5738 
5739     // Build a factor node to remember that this load is independent of the
5740     // other one.
5741     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5742                         Hi.getValue(1));
5743 
5744     // Legalized the chain result - switch anything that used the old chain to
5745     // use the new one.
5746     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5747 
5748     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5749 
5750     SDValue RetOps[] = { LoadRes, Chain };
5751     return DAG.getMergeValues(RetOps, DL);
5752   }
5753   return SDValue();
5754 }
5755 
5756 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5757   SDValue N0 = N->getOperand(0);
5758   SDValue N1 = N->getOperand(1);
5759   SDValue N2 = N->getOperand(2);
5760   SDLoc DL(N);
5761 
5762   // Canonicalize integer abs.
5763   // vselect (setg[te] X,  0),  X, -X ->
5764   // vselect (setgt    X, -1),  X, -X ->
5765   // vselect (setl[te] X,  0), -X,  X ->
5766   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5767   if (N0.getOpcode() == ISD::SETCC) {
5768     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5769     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5770     bool isAbs = false;
5771     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5772 
5773     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5774          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5775         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5776       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5777     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5778              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5779       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5780 
5781     if (isAbs) {
5782       EVT VT = LHS.getValueType();
5783       SDValue Shift = DAG.getNode(
5784           ISD::SRA, DL, VT, LHS,
5785           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5786       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5787       AddToWorklist(Shift.getNode());
5788       AddToWorklist(Add.getNode());
5789       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5790     }
5791   }
5792 
5793   if (SimplifySelectOps(N, N1, N2))
5794     return SDValue(N, 0);  // Don't revisit N.
5795 
5796   // If the VSELECT result requires splitting and the mask is provided by a
5797   // SETCC, then split both nodes and its operands before legalization. This
5798   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5799   // and enables future optimizations (e.g. min/max pattern matching on X86).
5800   if (N0.getOpcode() == ISD::SETCC) {
5801     EVT VT = N->getValueType(0);
5802 
5803     // Check if any splitting is required.
5804     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5805         TargetLowering::TypeSplitVector)
5806       return SDValue();
5807 
5808     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5809     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5810     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5811     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5812 
5813     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5814     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5815 
5816     // Add the new VSELECT nodes to the work list in case they need to be split
5817     // again.
5818     AddToWorklist(Lo.getNode());
5819     AddToWorklist(Hi.getNode());
5820 
5821     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5822   }
5823 
5824   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5825   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5826     return N1;
5827   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5828   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5829     return N2;
5830 
5831   // The ConvertSelectToConcatVector function is assuming both the above
5832   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5833   // and addressed.
5834   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5835       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5836       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5837     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5838       return CV;
5839   }
5840 
5841   return SDValue();
5842 }
5843 
5844 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5845   SDValue N0 = N->getOperand(0);
5846   SDValue N1 = N->getOperand(1);
5847   SDValue N2 = N->getOperand(2);
5848   SDValue N3 = N->getOperand(3);
5849   SDValue N4 = N->getOperand(4);
5850   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5851 
5852   // fold select_cc lhs, rhs, x, x, cc -> x
5853   if (N2 == N3)
5854     return N2;
5855 
5856   // Determine if the condition we're dealing with is constant
5857   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5858                                   CC, SDLoc(N), false)) {
5859     AddToWorklist(SCC.getNode());
5860 
5861     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5862       if (!SCCC->isNullValue())
5863         return N2;    // cond always true -> true val
5864       else
5865         return N3;    // cond always false -> false val
5866     } else if (SCC->isUndef()) {
5867       // When the condition is UNDEF, just return the first operand. This is
5868       // coherent the DAG creation, no setcc node is created in this case
5869       return N2;
5870     } else if (SCC.getOpcode() == ISD::SETCC) {
5871       // Fold to a simpler select_cc
5872       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5873                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5874                          SCC.getOperand(2));
5875     }
5876   }
5877 
5878   // If we can fold this based on the true/false value, do so.
5879   if (SimplifySelectOps(N, N2, N3))
5880     return SDValue(N, 0);  // Don't revisit N.
5881 
5882   // fold select_cc into other things, such as min/max/abs
5883   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5884 }
5885 
5886 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5887   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5888                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5889                        SDLoc(N));
5890 }
5891 
5892 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5893   SDValue LHS = N->getOperand(0);
5894   SDValue RHS = N->getOperand(1);
5895   SDValue Carry = N->getOperand(2);
5896   SDValue Cond = N->getOperand(3);
5897 
5898   // If Carry is false, fold to a regular SETCC.
5899   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5900     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5901 
5902   return SDValue();
5903 }
5904 
5905 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5906 /// a build_vector of constants.
5907 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5908 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5909 /// Vector extends are not folded if operations are legal; this is to
5910 /// avoid introducing illegal build_vector dag nodes.
5911 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5912                                          SelectionDAG &DAG, bool LegalTypes,
5913                                          bool LegalOperations) {
5914   unsigned Opcode = N->getOpcode();
5915   SDValue N0 = N->getOperand(0);
5916   EVT VT = N->getValueType(0);
5917 
5918   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5919          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5920          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5921          && "Expected EXTEND dag node in input!");
5922 
5923   // fold (sext c1) -> c1
5924   // fold (zext c1) -> c1
5925   // fold (aext c1) -> c1
5926   if (isa<ConstantSDNode>(N0))
5927     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5928 
5929   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5930   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5931   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5932   EVT SVT = VT.getScalarType();
5933   if (!(VT.isVector() &&
5934       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5935       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5936     return nullptr;
5937 
5938   // We can fold this node into a build_vector.
5939   unsigned VTBits = SVT.getSizeInBits();
5940   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
5941   SmallVector<SDValue, 8> Elts;
5942   unsigned NumElts = VT.getVectorNumElements();
5943   SDLoc DL(N);
5944 
5945   for (unsigned i=0; i != NumElts; ++i) {
5946     SDValue Op = N0->getOperand(i);
5947     if (Op->isUndef()) {
5948       Elts.push_back(DAG.getUNDEF(SVT));
5949       continue;
5950     }
5951 
5952     SDLoc DL(Op);
5953     // Get the constant value and if needed trunc it to the size of the type.
5954     // Nodes like build_vector might have constants wider than the scalar type.
5955     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5956     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5957       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5958     else
5959       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5960   }
5961 
5962   return DAG.getBuildVector(VT, DL, Elts).getNode();
5963 }
5964 
5965 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5966 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5967 // transformation. Returns true if extension are possible and the above
5968 // mentioned transformation is profitable.
5969 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5970                                     unsigned ExtOpc,
5971                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5972                                     const TargetLowering &TLI) {
5973   bool HasCopyToRegUses = false;
5974   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5975   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5976                             UE = N0.getNode()->use_end();
5977        UI != UE; ++UI) {
5978     SDNode *User = *UI;
5979     if (User == N)
5980       continue;
5981     if (UI.getUse().getResNo() != N0.getResNo())
5982       continue;
5983     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5984     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5985       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5986       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5987         // Sign bits will be lost after a zext.
5988         return false;
5989       bool Add = false;
5990       for (unsigned i = 0; i != 2; ++i) {
5991         SDValue UseOp = User->getOperand(i);
5992         if (UseOp == N0)
5993           continue;
5994         if (!isa<ConstantSDNode>(UseOp))
5995           return false;
5996         Add = true;
5997       }
5998       if (Add)
5999         ExtendNodes.push_back(User);
6000       continue;
6001     }
6002     // If truncates aren't free and there are users we can't
6003     // extend, it isn't worthwhile.
6004     if (!isTruncFree)
6005       return false;
6006     // Remember if this value is live-out.
6007     if (User->getOpcode() == ISD::CopyToReg)
6008       HasCopyToRegUses = true;
6009   }
6010 
6011   if (HasCopyToRegUses) {
6012     bool BothLiveOut = false;
6013     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6014          UI != UE; ++UI) {
6015       SDUse &Use = UI.getUse();
6016       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6017         BothLiveOut = true;
6018         break;
6019       }
6020     }
6021     if (BothLiveOut)
6022       // Both unextended and extended values are live out. There had better be
6023       // a good reason for the transformation.
6024       return ExtendNodes.size();
6025   }
6026   return true;
6027 }
6028 
6029 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6030                                   SDValue Trunc, SDValue ExtLoad,
6031                                   const SDLoc &DL, ISD::NodeType ExtType) {
6032   // Extend SetCC uses if necessary.
6033   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6034     SDNode *SetCC = SetCCs[i];
6035     SmallVector<SDValue, 4> Ops;
6036 
6037     for (unsigned j = 0; j != 2; ++j) {
6038       SDValue SOp = SetCC->getOperand(j);
6039       if (SOp == Trunc)
6040         Ops.push_back(ExtLoad);
6041       else
6042         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6043     }
6044 
6045     Ops.push_back(SetCC->getOperand(2));
6046     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6047   }
6048 }
6049 
6050 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6051 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6052   SDValue N0 = N->getOperand(0);
6053   EVT DstVT = N->getValueType(0);
6054   EVT SrcVT = N0.getValueType();
6055 
6056   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6057           N->getOpcode() == ISD::ZERO_EXTEND) &&
6058          "Unexpected node type (not an extend)!");
6059 
6060   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6061   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6062   //   (v8i32 (sext (v8i16 (load x))))
6063   // into:
6064   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6065   //                          (v4i32 (sextload (x + 16)))))
6066   // Where uses of the original load, i.e.:
6067   //   (v8i16 (load x))
6068   // are replaced with:
6069   //   (v8i16 (truncate
6070   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6071   //                            (v4i32 (sextload (x + 16)))))))
6072   //
6073   // This combine is only applicable to illegal, but splittable, vectors.
6074   // All legal types, and illegal non-vector types, are handled elsewhere.
6075   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6076   //
6077   if (N0->getOpcode() != ISD::LOAD)
6078     return SDValue();
6079 
6080   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6081 
6082   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6083       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6084       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6085     return SDValue();
6086 
6087   SmallVector<SDNode *, 4> SetCCs;
6088   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6089     return SDValue();
6090 
6091   ISD::LoadExtType ExtType =
6092       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6093 
6094   // Try to split the vector types to get down to legal types.
6095   EVT SplitSrcVT = SrcVT;
6096   EVT SplitDstVT = DstVT;
6097   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6098          SplitSrcVT.getVectorNumElements() > 1) {
6099     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6100     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6101   }
6102 
6103   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6104     return SDValue();
6105 
6106   SDLoc DL(N);
6107   const unsigned NumSplits =
6108       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6109   const unsigned Stride = SplitSrcVT.getStoreSize();
6110   SmallVector<SDValue, 4> Loads;
6111   SmallVector<SDValue, 4> Chains;
6112 
6113   SDValue BasePtr = LN0->getBasePtr();
6114   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6115     const unsigned Offset = Idx * Stride;
6116     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6117 
6118     SDValue SplitLoad = DAG.getExtLoad(
6119         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6120         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6121         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6122 
6123     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6124                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6125 
6126     Loads.push_back(SplitLoad.getValue(0));
6127     Chains.push_back(SplitLoad.getValue(1));
6128   }
6129 
6130   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6131   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6132 
6133   CombineTo(N, NewValue);
6134 
6135   // Replace uses of the original load (before extension)
6136   // with a truncate of the concatenated sextloaded vectors.
6137   SDValue Trunc =
6138       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6139   CombineTo(N0.getNode(), Trunc, NewChain);
6140   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6141                   (ISD::NodeType)N->getOpcode());
6142   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6143 }
6144 
6145 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6146   SDValue N0 = N->getOperand(0);
6147   EVT VT = N->getValueType(0);
6148 
6149   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6150                                               LegalOperations))
6151     return SDValue(Res, 0);
6152 
6153   // fold (sext (sext x)) -> (sext x)
6154   // fold (sext (aext x)) -> (sext x)
6155   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6156     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6157                        N0.getOperand(0));
6158 
6159   if (N0.getOpcode() == ISD::TRUNCATE) {
6160     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6161     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6162     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6163       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6164       if (NarrowLoad.getNode() != N0.getNode()) {
6165         CombineTo(N0.getNode(), NarrowLoad);
6166         // CombineTo deleted the truncate, if needed, but not what's under it.
6167         AddToWorklist(oye);
6168       }
6169       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6170     }
6171 
6172     // See if the value being truncated is already sign extended.  If so, just
6173     // eliminate the trunc/sext pair.
6174     SDValue Op = N0.getOperand(0);
6175     unsigned OpBits   = Op.getScalarValueSizeInBits();
6176     unsigned MidBits  = N0.getScalarValueSizeInBits();
6177     unsigned DestBits = VT.getScalarSizeInBits();
6178     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6179 
6180     if (OpBits == DestBits) {
6181       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6182       // bits, it is already ready.
6183       if (NumSignBits > DestBits-MidBits)
6184         return Op;
6185     } else if (OpBits < DestBits) {
6186       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6187       // bits, just sext from i32.
6188       if (NumSignBits > OpBits-MidBits)
6189         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6190     } else {
6191       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6192       // bits, just truncate to i32.
6193       if (NumSignBits > OpBits-MidBits)
6194         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6195     }
6196 
6197     // fold (sext (truncate x)) -> (sextinreg x).
6198     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6199                                                  N0.getValueType())) {
6200       if (OpBits < DestBits)
6201         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6202       else if (OpBits > DestBits)
6203         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6204       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6205                          DAG.getValueType(N0.getValueType()));
6206     }
6207   }
6208 
6209   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6210   // Only generate vector extloads when 1) they're legal, and 2) they are
6211   // deemed desirable by the target.
6212   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6213       ((!LegalOperations && !VT.isVector() &&
6214         !cast<LoadSDNode>(N0)->isVolatile()) ||
6215        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6216     bool DoXform = true;
6217     SmallVector<SDNode*, 4> SetCCs;
6218     if (!N0.hasOneUse())
6219       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6220     if (VT.isVector())
6221       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6222     if (DoXform) {
6223       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6224       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6225                                        LN0->getChain(),
6226                                        LN0->getBasePtr(), N0.getValueType(),
6227                                        LN0->getMemOperand());
6228       CombineTo(N, ExtLoad);
6229       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6230                                   N0.getValueType(), ExtLoad);
6231       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6232       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6233                       ISD::SIGN_EXTEND);
6234       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6235     }
6236   }
6237 
6238   // fold (sext (load x)) to multiple smaller sextloads.
6239   // Only on illegal but splittable vectors.
6240   if (SDValue ExtLoad = CombineExtLoad(N))
6241     return ExtLoad;
6242 
6243   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6244   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6245   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6246       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6247     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6248     EVT MemVT = LN0->getMemoryVT();
6249     if ((!LegalOperations && !LN0->isVolatile()) ||
6250         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6251       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6252                                        LN0->getChain(),
6253                                        LN0->getBasePtr(), MemVT,
6254                                        LN0->getMemOperand());
6255       CombineTo(N, ExtLoad);
6256       CombineTo(N0.getNode(),
6257                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6258                             N0.getValueType(), ExtLoad),
6259                 ExtLoad.getValue(1));
6260       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6261     }
6262   }
6263 
6264   // fold (sext (and/or/xor (load x), cst)) ->
6265   //      (and/or/xor (sextload x), (sext cst))
6266   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6267        N0.getOpcode() == ISD::XOR) &&
6268       isa<LoadSDNode>(N0.getOperand(0)) &&
6269       N0.getOperand(1).getOpcode() == ISD::Constant &&
6270       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6271       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6272     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6273     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6274       bool DoXform = true;
6275       SmallVector<SDNode*, 4> SetCCs;
6276       if (!N0.hasOneUse())
6277         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6278                                           SetCCs, TLI);
6279       if (DoXform) {
6280         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6281                                          LN0->getChain(), LN0->getBasePtr(),
6282                                          LN0->getMemoryVT(),
6283                                          LN0->getMemOperand());
6284         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6285         Mask = Mask.sext(VT.getSizeInBits());
6286         SDLoc DL(N);
6287         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6288                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6289         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6290                                     SDLoc(N0.getOperand(0)),
6291                                     N0.getOperand(0).getValueType(), ExtLoad);
6292         CombineTo(N, And);
6293         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6294         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6295                         ISD::SIGN_EXTEND);
6296         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6297       }
6298     }
6299   }
6300 
6301   if (N0.getOpcode() == ISD::SETCC) {
6302     EVT N0VT = N0.getOperand(0).getValueType();
6303     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6304     // Only do this before legalize for now.
6305     if (VT.isVector() && !LegalOperations &&
6306         TLI.getBooleanContents(N0VT) ==
6307             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6308       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6309       // of the same size as the compared operands. Only optimize sext(setcc())
6310       // if this is the case.
6311       EVT SVT = getSetCCResultType(N0VT);
6312 
6313       // We know that the # elements of the results is the same as the
6314       // # elements of the compare (and the # elements of the compare result
6315       // for that matter).  Check to see that they are the same size.  If so,
6316       // we know that the element size of the sext'd result matches the
6317       // element size of the compare operands.
6318       if (VT.getSizeInBits() == SVT.getSizeInBits())
6319         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6320                              N0.getOperand(1),
6321                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6322 
6323       // If the desired elements are smaller or larger than the source
6324       // elements we can use a matching integer vector type and then
6325       // truncate/sign extend
6326       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6327       if (SVT == MatchingVectorType) {
6328         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6329                                N0.getOperand(0), N0.getOperand(1),
6330                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6331         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6332       }
6333     }
6334 
6335     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6336     // Here, T can be 1 or -1, depending on the type of the setcc and
6337     // getBooleanContents().
6338     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6339 
6340     SDLoc DL(N);
6341     // To determine the "true" side of the select, we need to know the high bit
6342     // of the value returned by the setcc if it evaluates to true.
6343     // If the type of the setcc is i1, then the true case of the select is just
6344     // sext(i1 1), that is, -1.
6345     // If the type of the setcc is larger (say, i8) then the value of the high
6346     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6347     // of the appropriate width.
6348     SDValue ExtTrueVal =
6349         (SetCCWidth == 1)
6350             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6351                               DL, VT)
6352             : TLI.getConstTrueVal(DAG, VT, DL);
6353 
6354     if (SDValue SCC = SimplifySelectCC(
6355             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6356             DAG.getConstant(0, DL, VT),
6357             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6358       return SCC;
6359 
6360     if (!VT.isVector()) {
6361       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6362       if (!LegalOperations ||
6363           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6364         SDLoc DL(N);
6365         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6366         SDValue SetCC =
6367             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6368         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6369                              DAG.getConstant(0, DL, VT));
6370       }
6371     }
6372   }
6373 
6374   // fold (sext x) -> (zext x) if the sign bit is known zero.
6375   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6376       DAG.SignBitIsZero(N0))
6377     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6378 
6379   return SDValue();
6380 }
6381 
6382 // isTruncateOf - If N is a truncate of some other value, return true, record
6383 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6384 // This function computes KnownZero to avoid a duplicated call to
6385 // computeKnownBits in the caller.
6386 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6387                          APInt &KnownZero) {
6388   APInt KnownOne;
6389   if (N->getOpcode() == ISD::TRUNCATE) {
6390     Op = N->getOperand(0);
6391     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6392     return true;
6393   }
6394 
6395   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6396       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6397     return false;
6398 
6399   SDValue Op0 = N->getOperand(0);
6400   SDValue Op1 = N->getOperand(1);
6401   assert(Op0.getValueType() == Op1.getValueType());
6402 
6403   if (isNullConstant(Op0))
6404     Op = Op1;
6405   else if (isNullConstant(Op1))
6406     Op = Op0;
6407   else
6408     return false;
6409 
6410   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6411 
6412   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6413     return false;
6414 
6415   return true;
6416 }
6417 
6418 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6419   SDValue N0 = N->getOperand(0);
6420   EVT VT = N->getValueType(0);
6421 
6422   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6423                                               LegalOperations))
6424     return SDValue(Res, 0);
6425 
6426   // fold (zext (zext x)) -> (zext x)
6427   // fold (zext (aext x)) -> (zext x)
6428   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6429     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6430                        N0.getOperand(0));
6431 
6432   // fold (zext (truncate x)) -> (zext x) or
6433   //      (zext (truncate x)) -> (truncate x)
6434   // This is valid when the truncated bits of x are already zero.
6435   // FIXME: We should extend this to work for vectors too.
6436   SDValue Op;
6437   APInt KnownZero;
6438   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6439     APInt TruncatedBits =
6440       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6441       APInt(Op.getValueSizeInBits(), 0) :
6442       APInt::getBitsSet(Op.getValueSizeInBits(),
6443                         N0.getValueSizeInBits(),
6444                         std::min(Op.getValueSizeInBits(),
6445                                  VT.getSizeInBits()));
6446     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6447       if (VT.bitsGT(Op.getValueType()))
6448         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6449       if (VT.bitsLT(Op.getValueType()))
6450         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6451 
6452       return Op;
6453     }
6454   }
6455 
6456   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6457   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6458   if (N0.getOpcode() == ISD::TRUNCATE) {
6459     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6460       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6461       if (NarrowLoad.getNode() != N0.getNode()) {
6462         CombineTo(N0.getNode(), NarrowLoad);
6463         // CombineTo deleted the truncate, if needed, but not what's under it.
6464         AddToWorklist(oye);
6465       }
6466       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6467     }
6468   }
6469 
6470   // fold (zext (truncate x)) -> (and x, mask)
6471   if (N0.getOpcode() == ISD::TRUNCATE) {
6472     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6473     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6474     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6475       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6476       if (NarrowLoad.getNode() != N0.getNode()) {
6477         CombineTo(N0.getNode(), NarrowLoad);
6478         // CombineTo deleted the truncate, if needed, but not what's under it.
6479         AddToWorklist(oye);
6480       }
6481       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6482     }
6483 
6484     EVT SrcVT = N0.getOperand(0).getValueType();
6485     EVT MinVT = N0.getValueType();
6486 
6487     // Try to mask before the extension to avoid having to generate a larger mask,
6488     // possibly over several sub-vectors.
6489     if (SrcVT.bitsLT(VT)) {
6490       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6491                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6492         SDValue Op = N0.getOperand(0);
6493         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6494         AddToWorklist(Op.getNode());
6495         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6496       }
6497     }
6498 
6499     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6500       SDValue Op = N0.getOperand(0);
6501       if (SrcVT.bitsLT(VT)) {
6502         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6503         AddToWorklist(Op.getNode());
6504       } else if (SrcVT.bitsGT(VT)) {
6505         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6506         AddToWorklist(Op.getNode());
6507       }
6508       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6509     }
6510   }
6511 
6512   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6513   // if either of the casts is not free.
6514   if (N0.getOpcode() == ISD::AND &&
6515       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6516       N0.getOperand(1).getOpcode() == ISD::Constant &&
6517       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6518                            N0.getValueType()) ||
6519        !TLI.isZExtFree(N0.getValueType(), VT))) {
6520     SDValue X = N0.getOperand(0).getOperand(0);
6521     if (X.getValueType().bitsLT(VT)) {
6522       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6523     } else if (X.getValueType().bitsGT(VT)) {
6524       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6525     }
6526     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6527     Mask = Mask.zext(VT.getSizeInBits());
6528     SDLoc DL(N);
6529     return DAG.getNode(ISD::AND, DL, VT,
6530                        X, DAG.getConstant(Mask, DL, VT));
6531   }
6532 
6533   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6534   // Only generate vector extloads when 1) they're legal, and 2) they are
6535   // deemed desirable by the target.
6536   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6537       ((!LegalOperations && !VT.isVector() &&
6538         !cast<LoadSDNode>(N0)->isVolatile()) ||
6539        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6540     bool DoXform = true;
6541     SmallVector<SDNode*, 4> SetCCs;
6542     if (!N0.hasOneUse())
6543       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6544     if (VT.isVector())
6545       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6546     if (DoXform) {
6547       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6548       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6549                                        LN0->getChain(),
6550                                        LN0->getBasePtr(), N0.getValueType(),
6551                                        LN0->getMemOperand());
6552       CombineTo(N, ExtLoad);
6553       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6554                                   N0.getValueType(), ExtLoad);
6555       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6556 
6557       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6558                       ISD::ZERO_EXTEND);
6559       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6560     }
6561   }
6562 
6563   // fold (zext (load x)) to multiple smaller zextloads.
6564   // Only on illegal but splittable vectors.
6565   if (SDValue ExtLoad = CombineExtLoad(N))
6566     return ExtLoad;
6567 
6568   // fold (zext (and/or/xor (load x), cst)) ->
6569   //      (and/or/xor (zextload x), (zext cst))
6570   // Unless (and (load x) cst) will match as a zextload already and has
6571   // additional users.
6572   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6573        N0.getOpcode() == ISD::XOR) &&
6574       isa<LoadSDNode>(N0.getOperand(0)) &&
6575       N0.getOperand(1).getOpcode() == ISD::Constant &&
6576       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6577       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6578     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6579     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6580       bool DoXform = true;
6581       SmallVector<SDNode*, 4> SetCCs;
6582       if (!N0.hasOneUse()) {
6583         if (N0.getOpcode() == ISD::AND) {
6584           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6585           auto NarrowLoad = false;
6586           EVT LoadResultTy = AndC->getValueType(0);
6587           EVT ExtVT, LoadedVT;
6588           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6589                                NarrowLoad))
6590             DoXform = false;
6591         }
6592         if (DoXform)
6593           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6594                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6595       }
6596       if (DoXform) {
6597         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6598                                          LN0->getChain(), LN0->getBasePtr(),
6599                                          LN0->getMemoryVT(),
6600                                          LN0->getMemOperand());
6601         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6602         Mask = Mask.zext(VT.getSizeInBits());
6603         SDLoc DL(N);
6604         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6605                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6606         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6607                                     SDLoc(N0.getOperand(0)),
6608                                     N0.getOperand(0).getValueType(), ExtLoad);
6609         CombineTo(N, And);
6610         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6611         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6612                         ISD::ZERO_EXTEND);
6613         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6614       }
6615     }
6616   }
6617 
6618   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6619   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6620   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6621       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6622     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6623     EVT MemVT = LN0->getMemoryVT();
6624     if ((!LegalOperations && !LN0->isVolatile()) ||
6625         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6626       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6627                                        LN0->getChain(),
6628                                        LN0->getBasePtr(), MemVT,
6629                                        LN0->getMemOperand());
6630       CombineTo(N, ExtLoad);
6631       CombineTo(N0.getNode(),
6632                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6633                             ExtLoad),
6634                 ExtLoad.getValue(1));
6635       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6636     }
6637   }
6638 
6639   if (N0.getOpcode() == ISD::SETCC) {
6640     // Only do this before legalize for now.
6641     if (!LegalOperations && VT.isVector() &&
6642         N0.getValueType().getVectorElementType() == MVT::i1) {
6643       EVT N00VT = N0.getOperand(0).getValueType();
6644       if (getSetCCResultType(N00VT) == N0.getValueType())
6645         return SDValue();
6646 
6647       // We know that the # elements of the results is the same as the #
6648       // elements of the compare (and the # elements of the compare result for
6649       // that matter). Check to see that they are the same size. If so, we know
6650       // that the element size of the sext'd result matches the element size of
6651       // the compare operands.
6652       SDLoc DL(N);
6653       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6654       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6655         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6656         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6657                                      N0.getOperand(1), N0.getOperand(2));
6658         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6659       }
6660 
6661       // If the desired elements are smaller or larger than the source
6662       // elements we can use a matching integer vector type and then
6663       // truncate/sign extend.
6664       EVT MatchingElementType = EVT::getIntegerVT(
6665           *DAG.getContext(), N00VT.getScalarSizeInBits());
6666       EVT MatchingVectorType = EVT::getVectorVT(
6667           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6668       SDValue VsetCC =
6669           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6670                       N0.getOperand(1), N0.getOperand(2));
6671       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6672                          VecOnes);
6673     }
6674 
6675     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6676     SDLoc DL(N);
6677     if (SDValue SCC = SimplifySelectCC(
6678             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6679             DAG.getConstant(0, DL, VT),
6680             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6681       return SCC;
6682   }
6683 
6684   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6685   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6686       isa<ConstantSDNode>(N0.getOperand(1)) &&
6687       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6688       N0.hasOneUse()) {
6689     SDValue ShAmt = N0.getOperand(1);
6690     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6691     if (N0.getOpcode() == ISD::SHL) {
6692       SDValue InnerZExt = N0.getOperand(0);
6693       // If the original shl may be shifting out bits, do not perform this
6694       // transformation.
6695       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6696         InnerZExt.getOperand(0).getValueSizeInBits();
6697       if (ShAmtVal > KnownZeroBits)
6698         return SDValue();
6699     }
6700 
6701     SDLoc DL(N);
6702 
6703     // Ensure that the shift amount is wide enough for the shifted value.
6704     if (VT.getSizeInBits() >= 256)
6705       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6706 
6707     return DAG.getNode(N0.getOpcode(), DL, VT,
6708                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6709                        ShAmt);
6710   }
6711 
6712   return SDValue();
6713 }
6714 
6715 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6716   SDValue N0 = N->getOperand(0);
6717   EVT VT = N->getValueType(0);
6718 
6719   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6720                                               LegalOperations))
6721     return SDValue(Res, 0);
6722 
6723   // fold (aext (aext x)) -> (aext x)
6724   // fold (aext (zext x)) -> (zext x)
6725   // fold (aext (sext x)) -> (sext x)
6726   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6727       N0.getOpcode() == ISD::ZERO_EXTEND ||
6728       N0.getOpcode() == ISD::SIGN_EXTEND)
6729     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6730 
6731   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6732   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6733   if (N0.getOpcode() == ISD::TRUNCATE) {
6734     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6735       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6736       if (NarrowLoad.getNode() != N0.getNode()) {
6737         CombineTo(N0.getNode(), NarrowLoad);
6738         // CombineTo deleted the truncate, if needed, but not what's under it.
6739         AddToWorklist(oye);
6740       }
6741       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6742     }
6743   }
6744 
6745   // fold (aext (truncate x))
6746   if (N0.getOpcode() == ISD::TRUNCATE) {
6747     SDValue TruncOp = N0.getOperand(0);
6748     if (TruncOp.getValueType() == VT)
6749       return TruncOp; // x iff x size == zext size.
6750     if (TruncOp.getValueType().bitsGT(VT))
6751       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6752     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6753   }
6754 
6755   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6756   // if the trunc is not free.
6757   if (N0.getOpcode() == ISD::AND &&
6758       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6759       N0.getOperand(1).getOpcode() == ISD::Constant &&
6760       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6761                           N0.getValueType())) {
6762     SDValue X = N0.getOperand(0).getOperand(0);
6763     if (X.getValueType().bitsLT(VT)) {
6764       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6765     } else if (X.getValueType().bitsGT(VT)) {
6766       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6767     }
6768     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6769     Mask = Mask.zext(VT.getSizeInBits());
6770     SDLoc DL(N);
6771     return DAG.getNode(ISD::AND, DL, VT,
6772                        X, DAG.getConstant(Mask, DL, VT));
6773   }
6774 
6775   // fold (aext (load x)) -> (aext (truncate (extload x)))
6776   // None of the supported targets knows how to perform load and any_ext
6777   // on vectors in one instruction.  We only perform this transformation on
6778   // scalars.
6779   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6780       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6781       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6782     bool DoXform = true;
6783     SmallVector<SDNode*, 4> SetCCs;
6784     if (!N0.hasOneUse())
6785       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6786     if (DoXform) {
6787       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6788       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6789                                        LN0->getChain(),
6790                                        LN0->getBasePtr(), N0.getValueType(),
6791                                        LN0->getMemOperand());
6792       CombineTo(N, ExtLoad);
6793       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6794                                   N0.getValueType(), ExtLoad);
6795       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6796       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6797                       ISD::ANY_EXTEND);
6798       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6799     }
6800   }
6801 
6802   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6803   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6804   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6805   if (N0.getOpcode() == ISD::LOAD &&
6806       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6807       N0.hasOneUse()) {
6808     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6809     ISD::LoadExtType ExtType = LN0->getExtensionType();
6810     EVT MemVT = LN0->getMemoryVT();
6811     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6812       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6813                                        VT, LN0->getChain(), LN0->getBasePtr(),
6814                                        MemVT, LN0->getMemOperand());
6815       CombineTo(N, ExtLoad);
6816       CombineTo(N0.getNode(),
6817                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6818                             N0.getValueType(), ExtLoad),
6819                 ExtLoad.getValue(1));
6820       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6821     }
6822   }
6823 
6824   if (N0.getOpcode() == ISD::SETCC) {
6825     // For vectors:
6826     // aext(setcc) -> vsetcc
6827     // aext(setcc) -> truncate(vsetcc)
6828     // aext(setcc) -> aext(vsetcc)
6829     // Only do this before legalize for now.
6830     if (VT.isVector() && !LegalOperations) {
6831       EVT N0VT = N0.getOperand(0).getValueType();
6832         // We know that the # elements of the results is the same as the
6833         // # elements of the compare (and the # elements of the compare result
6834         // for that matter).  Check to see that they are the same size.  If so,
6835         // we know that the element size of the sext'd result matches the
6836         // element size of the compare operands.
6837       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6838         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6839                              N0.getOperand(1),
6840                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6841       // If the desired elements are smaller or larger than the source
6842       // elements we can use a matching integer vector type and then
6843       // truncate/any extend
6844       else {
6845         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6846         SDValue VsetCC =
6847           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6848                         N0.getOperand(1),
6849                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6850         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6851       }
6852     }
6853 
6854     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6855     SDLoc DL(N);
6856     if (SDValue SCC = SimplifySelectCC(
6857             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6858             DAG.getConstant(0, DL, VT),
6859             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6860       return SCC;
6861   }
6862 
6863   return SDValue();
6864 }
6865 
6866 /// See if the specified operand can be simplified with the knowledge that only
6867 /// the bits specified by Mask are used.  If so, return the simpler operand,
6868 /// otherwise return a null SDValue.
6869 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6870   switch (V.getOpcode()) {
6871   default: break;
6872   case ISD::Constant: {
6873     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6874     assert(CV && "Const value should be ConstSDNode.");
6875     const APInt &CVal = CV->getAPIntValue();
6876     APInt NewVal = CVal & Mask;
6877     if (NewVal != CVal)
6878       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6879     break;
6880   }
6881   case ISD::OR:
6882   case ISD::XOR:
6883     // If the LHS or RHS don't contribute bits to the or, drop them.
6884     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6885       return V.getOperand(1);
6886     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6887       return V.getOperand(0);
6888     break;
6889   case ISD::SRL:
6890     // Only look at single-use SRLs.
6891     if (!V.getNode()->hasOneUse())
6892       break;
6893     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6894       // See if we can recursively simplify the LHS.
6895       unsigned Amt = RHSC->getZExtValue();
6896 
6897       // Watch out for shift count overflow though.
6898       if (Amt >= Mask.getBitWidth()) break;
6899       APInt NewMask = Mask << Amt;
6900       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6901         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6902                            SimplifyLHS, V.getOperand(1));
6903     }
6904   }
6905   return SDValue();
6906 }
6907 
6908 /// If the result of a wider load is shifted to right of N  bits and then
6909 /// truncated to a narrower type and where N is a multiple of number of bits of
6910 /// the narrower type, transform it to a narrower load from address + N / num of
6911 /// bits of new type. If the result is to be extended, also fold the extension
6912 /// to form a extending load.
6913 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6914   unsigned Opc = N->getOpcode();
6915 
6916   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6917   SDValue N0 = N->getOperand(0);
6918   EVT VT = N->getValueType(0);
6919   EVT ExtVT = VT;
6920 
6921   // This transformation isn't valid for vector loads.
6922   if (VT.isVector())
6923     return SDValue();
6924 
6925   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6926   // extended to VT.
6927   if (Opc == ISD::SIGN_EXTEND_INREG) {
6928     ExtType = ISD::SEXTLOAD;
6929     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6930   } else if (Opc == ISD::SRL) {
6931     // Another special-case: SRL is basically zero-extending a narrower value.
6932     ExtType = ISD::ZEXTLOAD;
6933     N0 = SDValue(N, 0);
6934     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6935     if (!N01) return SDValue();
6936     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6937                               VT.getSizeInBits() - N01->getZExtValue());
6938   }
6939   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6940     return SDValue();
6941 
6942   unsigned EVTBits = ExtVT.getSizeInBits();
6943 
6944   // Do not generate loads of non-round integer types since these can
6945   // be expensive (and would be wrong if the type is not byte sized).
6946   if (!ExtVT.isRound())
6947     return SDValue();
6948 
6949   unsigned ShAmt = 0;
6950   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6951     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6952       ShAmt = N01->getZExtValue();
6953       // Is the shift amount a multiple of size of VT?
6954       if ((ShAmt & (EVTBits-1)) == 0) {
6955         N0 = N0.getOperand(0);
6956         // Is the load width a multiple of size of VT?
6957         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
6958           return SDValue();
6959       }
6960 
6961       // At this point, we must have a load or else we can't do the transform.
6962       if (!isa<LoadSDNode>(N0)) return SDValue();
6963 
6964       // Because a SRL must be assumed to *need* to zero-extend the high bits
6965       // (as opposed to anyext the high bits), we can't combine the zextload
6966       // lowering of SRL and an sextload.
6967       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6968         return SDValue();
6969 
6970       // If the shift amount is larger than the input type then we're not
6971       // accessing any of the loaded bytes.  If the load was a zextload/extload
6972       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6973       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6974         return SDValue();
6975     }
6976   }
6977 
6978   // If the load is shifted left (and the result isn't shifted back right),
6979   // we can fold the truncate through the shift.
6980   unsigned ShLeftAmt = 0;
6981   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6982       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6983     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6984       ShLeftAmt = N01->getZExtValue();
6985       N0 = N0.getOperand(0);
6986     }
6987   }
6988 
6989   // If we haven't found a load, we can't narrow it.  Don't transform one with
6990   // multiple uses, this would require adding a new load.
6991   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6992     return SDValue();
6993 
6994   // Don't change the width of a volatile load.
6995   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6996   if (LN0->isVolatile())
6997     return SDValue();
6998 
6999   // Verify that we are actually reducing a load width here.
7000   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7001     return SDValue();
7002 
7003   // For the transform to be legal, the load must produce only two values
7004   // (the value loaded and the chain).  Don't transform a pre-increment
7005   // load, for example, which produces an extra value.  Otherwise the
7006   // transformation is not equivalent, and the downstream logic to replace
7007   // uses gets things wrong.
7008   if (LN0->getNumValues() > 2)
7009     return SDValue();
7010 
7011   // If the load that we're shrinking is an extload and we're not just
7012   // discarding the extension we can't simply shrink the load. Bail.
7013   // TODO: It would be possible to merge the extensions in some cases.
7014   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7015       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7016     return SDValue();
7017 
7018   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7019     return SDValue();
7020 
7021   EVT PtrType = N0.getOperand(1).getValueType();
7022 
7023   if (PtrType == MVT::Untyped || PtrType.isExtended())
7024     // It's not possible to generate a constant of extended or untyped type.
7025     return SDValue();
7026 
7027   // For big endian targets, we need to adjust the offset to the pointer to
7028   // load the correct bytes.
7029   if (DAG.getDataLayout().isBigEndian()) {
7030     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7031     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7032     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7033   }
7034 
7035   uint64_t PtrOff = ShAmt / 8;
7036   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7037   SDLoc DL(LN0);
7038   // The original load itself didn't wrap, so an offset within it doesn't.
7039   SDNodeFlags Flags;
7040   Flags.setNoUnsignedWrap(true);
7041   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7042                                PtrType, LN0->getBasePtr(),
7043                                DAG.getConstant(PtrOff, DL, PtrType),
7044                                &Flags);
7045   AddToWorklist(NewPtr.getNode());
7046 
7047   SDValue Load;
7048   if (ExtType == ISD::NON_EXTLOAD)
7049     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7050                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7051                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7052   else
7053     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7054                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7055                           NewAlign, LN0->getMemOperand()->getFlags(),
7056                           LN0->getAAInfo());
7057 
7058   // Replace the old load's chain with the new load's chain.
7059   WorklistRemover DeadNodes(*this);
7060   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7061 
7062   // Shift the result left, if we've swallowed a left shift.
7063   SDValue Result = Load;
7064   if (ShLeftAmt != 0) {
7065     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7066     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7067       ShImmTy = VT;
7068     // If the shift amount is as large as the result size (but, presumably,
7069     // no larger than the source) then the useful bits of the result are
7070     // zero; we can't simply return the shortened shift, because the result
7071     // of that operation is undefined.
7072     SDLoc DL(N0);
7073     if (ShLeftAmt >= VT.getSizeInBits())
7074       Result = DAG.getConstant(0, DL, VT);
7075     else
7076       Result = DAG.getNode(ISD::SHL, DL, VT,
7077                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7078   }
7079 
7080   // Return the new loaded value.
7081   return Result;
7082 }
7083 
7084 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7085   SDValue N0 = N->getOperand(0);
7086   SDValue N1 = N->getOperand(1);
7087   EVT VT = N->getValueType(0);
7088   EVT EVT = cast<VTSDNode>(N1)->getVT();
7089   unsigned VTBits = VT.getScalarSizeInBits();
7090   unsigned EVTBits = EVT.getScalarSizeInBits();
7091 
7092   if (N0.isUndef())
7093     return DAG.getUNDEF(VT);
7094 
7095   // fold (sext_in_reg c1) -> c1
7096   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7097     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7098 
7099   // If the input is already sign extended, just drop the extension.
7100   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7101     return N0;
7102 
7103   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7104   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7105       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7106     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7107                        N0.getOperand(0), N1);
7108 
7109   // fold (sext_in_reg (sext x)) -> (sext x)
7110   // fold (sext_in_reg (aext x)) -> (sext x)
7111   // if x is small enough.
7112   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7113     SDValue N00 = N0.getOperand(0);
7114     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7115         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7116       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7117   }
7118 
7119   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7120   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7121     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7122 
7123   // fold operands of sext_in_reg based on knowledge that the top bits are not
7124   // demanded.
7125   if (SimplifyDemandedBits(SDValue(N, 0)))
7126     return SDValue(N, 0);
7127 
7128   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7129   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7130   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7131     return NarrowLoad;
7132 
7133   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7134   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7135   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7136   if (N0.getOpcode() == ISD::SRL) {
7137     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7138       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7139         // We can turn this into an SRA iff the input to the SRL is already sign
7140         // extended enough.
7141         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7142         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7143           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7144                              N0.getOperand(0), N0.getOperand(1));
7145       }
7146   }
7147 
7148   // fold (sext_inreg (extload x)) -> (sextload x)
7149   if (ISD::isEXTLoad(N0.getNode()) &&
7150       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7151       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7152       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7153        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7154     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7155     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7156                                      LN0->getChain(),
7157                                      LN0->getBasePtr(), EVT,
7158                                      LN0->getMemOperand());
7159     CombineTo(N, ExtLoad);
7160     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7161     AddToWorklist(ExtLoad.getNode());
7162     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7163   }
7164   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7165   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7166       N0.hasOneUse() &&
7167       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7168       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7169        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7170     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7171     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7172                                      LN0->getChain(),
7173                                      LN0->getBasePtr(), EVT,
7174                                      LN0->getMemOperand());
7175     CombineTo(N, ExtLoad);
7176     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7177     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7178   }
7179 
7180   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7181   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7182     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7183                                            N0.getOperand(1), false))
7184       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7185                          BSwap, N1);
7186   }
7187 
7188   return SDValue();
7189 }
7190 
7191 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7192   SDValue N0 = N->getOperand(0);
7193   EVT VT = N->getValueType(0);
7194 
7195   if (N0.isUndef())
7196     return DAG.getUNDEF(VT);
7197 
7198   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7199                                               LegalOperations))
7200     return SDValue(Res, 0);
7201 
7202   return SDValue();
7203 }
7204 
7205 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7206   SDValue N0 = N->getOperand(0);
7207   EVT VT = N->getValueType(0);
7208 
7209   if (N0.isUndef())
7210     return DAG.getUNDEF(VT);
7211 
7212   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7213                                               LegalOperations))
7214     return SDValue(Res, 0);
7215 
7216   return SDValue();
7217 }
7218 
7219 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7220   SDValue N0 = N->getOperand(0);
7221   EVT VT = N->getValueType(0);
7222   bool isLE = DAG.getDataLayout().isLittleEndian();
7223 
7224   // noop truncate
7225   if (N0.getValueType() == N->getValueType(0))
7226     return N0;
7227   // fold (truncate c1) -> c1
7228   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7229     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7230   // fold (truncate (truncate x)) -> (truncate x)
7231   if (N0.getOpcode() == ISD::TRUNCATE)
7232     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7233   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7234   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7235       N0.getOpcode() == ISD::SIGN_EXTEND ||
7236       N0.getOpcode() == ISD::ANY_EXTEND) {
7237     // if the source is smaller than the dest, we still need an extend.
7238     if (N0.getOperand(0).getValueType().bitsLT(VT))
7239       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7240     // if the source is larger than the dest, than we just need the truncate.
7241     if (N0.getOperand(0).getValueType().bitsGT(VT))
7242       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7243     // if the source and dest are the same type, we can drop both the extend
7244     // and the truncate.
7245     return N0.getOperand(0);
7246   }
7247 
7248   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7249   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7250     return SDValue();
7251 
7252   // Fold extract-and-trunc into a narrow extract. For example:
7253   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7254   //   i32 y = TRUNCATE(i64 x)
7255   //        -- becomes --
7256   //   v16i8 b = BITCAST (v2i64 val)
7257   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7258   //
7259   // Note: We only run this optimization after type legalization (which often
7260   // creates this pattern) and before operation legalization after which
7261   // we need to be more careful about the vector instructions that we generate.
7262   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7263       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7264 
7265     EVT VecTy = N0.getOperand(0).getValueType();
7266     EVT ExTy = N0.getValueType();
7267     EVT TrTy = N->getValueType(0);
7268 
7269     unsigned NumElem = VecTy.getVectorNumElements();
7270     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7271 
7272     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7273     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7274 
7275     SDValue EltNo = N0->getOperand(1);
7276     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7277       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7278       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7279       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7280 
7281       SDLoc DL(N);
7282       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7283                          DAG.getBitcast(NVT, N0.getOperand(0)),
7284                          DAG.getConstant(Index, DL, IndexTy));
7285     }
7286   }
7287 
7288   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7289   if (N0.getOpcode() == ISD::SELECT) {
7290     EVT SrcVT = N0.getValueType();
7291     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7292         TLI.isTruncateFree(SrcVT, VT)) {
7293       SDLoc SL(N0);
7294       SDValue Cond = N0.getOperand(0);
7295       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7296       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7297       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7298     }
7299   }
7300 
7301   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7302   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7303       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7304       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7305     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7306       uint64_t Amt = CAmt->getZExtValue();
7307       unsigned Size = VT.getScalarSizeInBits();
7308 
7309       if (Amt < Size) {
7310         SDLoc SL(N);
7311         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7312 
7313         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7314         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7315                            DAG.getConstant(Amt, SL, AmtVT));
7316       }
7317     }
7318   }
7319 
7320   // Fold a series of buildvector, bitcast, and truncate if possible.
7321   // For example fold
7322   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7323   //   (2xi32 (buildvector x, y)).
7324   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7325       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7326       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7327       N0.getOperand(0).hasOneUse()) {
7328 
7329     SDValue BuildVect = N0.getOperand(0);
7330     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7331     EVT TruncVecEltTy = VT.getVectorElementType();
7332 
7333     // Check that the element types match.
7334     if (BuildVectEltTy == TruncVecEltTy) {
7335       // Now we only need to compute the offset of the truncated elements.
7336       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7337       unsigned TruncVecNumElts = VT.getVectorNumElements();
7338       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7339 
7340       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7341              "Invalid number of elements");
7342 
7343       SmallVector<SDValue, 8> Opnds;
7344       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7345         Opnds.push_back(BuildVect.getOperand(i));
7346 
7347       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7348     }
7349   }
7350 
7351   // See if we can simplify the input to this truncate through knowledge that
7352   // only the low bits are being used.
7353   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7354   // Currently we only perform this optimization on scalars because vectors
7355   // may have different active low bits.
7356   if (!VT.isVector()) {
7357     if (SDValue Shorter =
7358             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7359                                                      VT.getSizeInBits())))
7360       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7361   }
7362   // fold (truncate (load x)) -> (smaller load x)
7363   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7364   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7365     if (SDValue Reduced = ReduceLoadWidth(N))
7366       return Reduced;
7367 
7368     // Handle the case where the load remains an extending load even
7369     // after truncation.
7370     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7371       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7372       if (!LN0->isVolatile() &&
7373           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7374         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7375                                          VT, LN0->getChain(), LN0->getBasePtr(),
7376                                          LN0->getMemoryVT(),
7377                                          LN0->getMemOperand());
7378         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7379         return NewLoad;
7380       }
7381     }
7382   }
7383   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7384   // where ... are all 'undef'.
7385   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7386     SmallVector<EVT, 8> VTs;
7387     SDValue V;
7388     unsigned Idx = 0;
7389     unsigned NumDefs = 0;
7390 
7391     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7392       SDValue X = N0.getOperand(i);
7393       if (!X.isUndef()) {
7394         V = X;
7395         Idx = i;
7396         NumDefs++;
7397       }
7398       // Stop if more than one members are non-undef.
7399       if (NumDefs > 1)
7400         break;
7401       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7402                                      VT.getVectorElementType(),
7403                                      X.getValueType().getVectorNumElements()));
7404     }
7405 
7406     if (NumDefs == 0)
7407       return DAG.getUNDEF(VT);
7408 
7409     if (NumDefs == 1) {
7410       assert(V.getNode() && "The single defined operand is empty!");
7411       SmallVector<SDValue, 8> Opnds;
7412       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7413         if (i != Idx) {
7414           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7415           continue;
7416         }
7417         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7418         AddToWorklist(NV.getNode());
7419         Opnds.push_back(NV);
7420       }
7421       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7422     }
7423   }
7424 
7425   // Fold truncate of a bitcast of a vector to an extract of the low vector
7426   // element.
7427   //
7428   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7429   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7430     SDValue VecSrc = N0.getOperand(0);
7431     EVT SrcVT = VecSrc.getValueType();
7432     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7433         (!LegalOperations ||
7434          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7435       SDLoc SL(N);
7436 
7437       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7438       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7439                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7440     }
7441   }
7442 
7443   // Simplify the operands using demanded-bits information.
7444   if (!VT.isVector() &&
7445       SimplifyDemandedBits(SDValue(N, 0)))
7446     return SDValue(N, 0);
7447 
7448   return SDValue();
7449 }
7450 
7451 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7452   SDValue Elt = N->getOperand(i);
7453   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7454     return Elt.getNode();
7455   return Elt.getOperand(Elt.getResNo()).getNode();
7456 }
7457 
7458 /// build_pair (load, load) -> load
7459 /// if load locations are consecutive.
7460 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7461   assert(N->getOpcode() == ISD::BUILD_PAIR);
7462 
7463   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7464   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7465   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7466       LD1->getAddressSpace() != LD2->getAddressSpace())
7467     return SDValue();
7468   EVT LD1VT = LD1->getValueType(0);
7469   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7470   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7471       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7472     unsigned Align = LD1->getAlignment();
7473     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7474         VT.getTypeForEVT(*DAG.getContext()));
7475 
7476     if (NewAlign <= Align &&
7477         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7478       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7479                          LD1->getPointerInfo(), Align);
7480   }
7481 
7482   return SDValue();
7483 }
7484 
7485 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7486   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7487   // and Lo parts; on big-endian machines it doesn't.
7488   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7489 }
7490 
7491 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7492                                     const TargetLowering &TLI) {
7493   // If this is not a bitcast to an FP type or if the target doesn't have
7494   // IEEE754-compliant FP logic, we're done.
7495   EVT VT = N->getValueType(0);
7496   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7497     return SDValue();
7498 
7499   // TODO: Use splat values for the constant-checking below and remove this
7500   // restriction.
7501   SDValue N0 = N->getOperand(0);
7502   EVT SourceVT = N0.getValueType();
7503   if (SourceVT.isVector())
7504     return SDValue();
7505 
7506   unsigned FPOpcode;
7507   APInt SignMask;
7508   switch (N0.getOpcode()) {
7509   case ISD::AND:
7510     FPOpcode = ISD::FABS;
7511     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7512     break;
7513   case ISD::XOR:
7514     FPOpcode = ISD::FNEG;
7515     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7516     break;
7517   // TODO: ISD::OR --> ISD::FNABS?
7518   default:
7519     return SDValue();
7520   }
7521 
7522   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7523   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7524   SDValue LogicOp0 = N0.getOperand(0);
7525   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7526   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7527       LogicOp0.getOpcode() == ISD::BITCAST &&
7528       LogicOp0->getOperand(0).getValueType() == VT)
7529     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7530 
7531   return SDValue();
7532 }
7533 
7534 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7535   SDValue N0 = N->getOperand(0);
7536   EVT VT = N->getValueType(0);
7537 
7538   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7539   // Only do this before legalize, since afterward the target may be depending
7540   // on the bitconvert.
7541   // First check to see if this is all constant.
7542   if (!LegalTypes &&
7543       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7544       VT.isVector()) {
7545     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7546 
7547     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7548     assert(!DestEltVT.isVector() &&
7549            "Element type of vector ValueType must not be vector!");
7550     if (isSimple)
7551       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7552   }
7553 
7554   // If the input is a constant, let getNode fold it.
7555   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7556     // If we can't allow illegal operations, we need to check that this is just
7557     // a fp -> int or int -> conversion and that the resulting operation will
7558     // be legal.
7559     if (!LegalOperations ||
7560         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7561          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7562         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7563          TLI.isOperationLegal(ISD::Constant, VT)))
7564       return DAG.getBitcast(VT, N0);
7565   }
7566 
7567   // (conv (conv x, t1), t2) -> (conv x, t2)
7568   if (N0.getOpcode() == ISD::BITCAST)
7569     return DAG.getBitcast(VT, N0.getOperand(0));
7570 
7571   // fold (conv (load x)) -> (load (conv*)x)
7572   // If the resultant load doesn't need a higher alignment than the original!
7573   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7574       // Do not change the width of a volatile load.
7575       !cast<LoadSDNode>(N0)->isVolatile() &&
7576       // Do not remove the cast if the types differ in endian layout.
7577       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7578           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7579       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7580       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7581     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7582     unsigned OrigAlign = LN0->getAlignment();
7583 
7584     bool Fast = false;
7585     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7586                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7587         Fast) {
7588       SDValue Load =
7589           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7590                       LN0->getPointerInfo(), OrigAlign,
7591                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7592       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7593       return Load;
7594     }
7595   }
7596 
7597   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7598     return V;
7599 
7600   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7601   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7602   //
7603   // For ppc_fp128:
7604   // fold (bitcast (fneg x)) ->
7605   //     flipbit = signbit
7606   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7607   //
7608   // fold (bitcast (fabs x)) ->
7609   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7610   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7611   // This often reduces constant pool loads.
7612   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7613        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7614       N0.getNode()->hasOneUse() && VT.isInteger() &&
7615       !VT.isVector() && !N0.getValueType().isVector()) {
7616     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7617     AddToWorklist(NewConv.getNode());
7618 
7619     SDLoc DL(N);
7620     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7621       assert(VT.getSizeInBits() == 128);
7622       SDValue SignBit = DAG.getConstant(
7623           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7624       SDValue FlipBit;
7625       if (N0.getOpcode() == ISD::FNEG) {
7626         FlipBit = SignBit;
7627         AddToWorklist(FlipBit.getNode());
7628       } else {
7629         assert(N0.getOpcode() == ISD::FABS);
7630         SDValue Hi =
7631             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7632                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7633                                               SDLoc(NewConv)));
7634         AddToWorklist(Hi.getNode());
7635         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7636         AddToWorklist(FlipBit.getNode());
7637       }
7638       SDValue FlipBits =
7639           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7640       AddToWorklist(FlipBits.getNode());
7641       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7642     }
7643     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7644     if (N0.getOpcode() == ISD::FNEG)
7645       return DAG.getNode(ISD::XOR, DL, VT,
7646                          NewConv, DAG.getConstant(SignBit, DL, VT));
7647     assert(N0.getOpcode() == ISD::FABS);
7648     return DAG.getNode(ISD::AND, DL, VT,
7649                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7650   }
7651 
7652   // fold (bitconvert (fcopysign cst, x)) ->
7653   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7654   // Note that we don't handle (copysign x, cst) because this can always be
7655   // folded to an fneg or fabs.
7656   //
7657   // For ppc_fp128:
7658   // fold (bitcast (fcopysign cst, x)) ->
7659   //     flipbit = (and (extract_element
7660   //                     (xor (bitcast cst), (bitcast x)), 0),
7661   //                    signbit)
7662   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7663   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7664       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7665       VT.isInteger() && !VT.isVector()) {
7666     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7667     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7668     if (isTypeLegal(IntXVT)) {
7669       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7670       AddToWorklist(X.getNode());
7671 
7672       // If X has a different width than the result/lhs, sext it or truncate it.
7673       unsigned VTWidth = VT.getSizeInBits();
7674       if (OrigXWidth < VTWidth) {
7675         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7676         AddToWorklist(X.getNode());
7677       } else if (OrigXWidth > VTWidth) {
7678         // To get the sign bit in the right place, we have to shift it right
7679         // before truncating.
7680         SDLoc DL(X);
7681         X = DAG.getNode(ISD::SRL, DL,
7682                         X.getValueType(), X,
7683                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7684                                         X.getValueType()));
7685         AddToWorklist(X.getNode());
7686         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7687         AddToWorklist(X.getNode());
7688       }
7689 
7690       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7691         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7692         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7693         AddToWorklist(Cst.getNode());
7694         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7695         AddToWorklist(X.getNode());
7696         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7697         AddToWorklist(XorResult.getNode());
7698         SDValue XorResult64 = DAG.getNode(
7699             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7700             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7701                                   SDLoc(XorResult)));
7702         AddToWorklist(XorResult64.getNode());
7703         SDValue FlipBit =
7704             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7705                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7706         AddToWorklist(FlipBit.getNode());
7707         SDValue FlipBits =
7708             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7709         AddToWorklist(FlipBits.getNode());
7710         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7711       }
7712       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7713       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7714                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7715       AddToWorklist(X.getNode());
7716 
7717       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7718       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7719                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7720       AddToWorklist(Cst.getNode());
7721 
7722       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7723     }
7724   }
7725 
7726   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7727   if (N0.getOpcode() == ISD::BUILD_PAIR)
7728     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7729       return CombineLD;
7730 
7731   // Remove double bitcasts from shuffles - this is often a legacy of
7732   // XformToShuffleWithZero being used to combine bitmaskings (of
7733   // float vectors bitcast to integer vectors) into shuffles.
7734   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7735   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7736       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7737       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7738       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7739     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7740 
7741     // If operands are a bitcast, peek through if it casts the original VT.
7742     // If operands are a constant, just bitcast back to original VT.
7743     auto PeekThroughBitcast = [&](SDValue Op) {
7744       if (Op.getOpcode() == ISD::BITCAST &&
7745           Op.getOperand(0).getValueType() == VT)
7746         return SDValue(Op.getOperand(0));
7747       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7748           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7749         return DAG.getBitcast(VT, Op);
7750       return SDValue();
7751     };
7752 
7753     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7754     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7755     if (!(SV0 && SV1))
7756       return SDValue();
7757 
7758     int MaskScale =
7759         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7760     SmallVector<int, 8> NewMask;
7761     for (int M : SVN->getMask())
7762       for (int i = 0; i != MaskScale; ++i)
7763         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7764 
7765     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7766     if (!LegalMask) {
7767       std::swap(SV0, SV1);
7768       ShuffleVectorSDNode::commuteMask(NewMask);
7769       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7770     }
7771 
7772     if (LegalMask)
7773       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7774   }
7775 
7776   return SDValue();
7777 }
7778 
7779 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7780   EVT VT = N->getValueType(0);
7781   return CombineConsecutiveLoads(N, VT);
7782 }
7783 
7784 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7785 /// operands. DstEltVT indicates the destination element value type.
7786 SDValue DAGCombiner::
7787 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7788   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7789 
7790   // If this is already the right type, we're done.
7791   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7792 
7793   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7794   unsigned DstBitSize = DstEltVT.getSizeInBits();
7795 
7796   // If this is a conversion of N elements of one type to N elements of another
7797   // type, convert each element.  This handles FP<->INT cases.
7798   if (SrcBitSize == DstBitSize) {
7799     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7800                               BV->getValueType(0).getVectorNumElements());
7801 
7802     // Due to the FP element handling below calling this routine recursively,
7803     // we can end up with a scalar-to-vector node here.
7804     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7805       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7806                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7807 
7808     SmallVector<SDValue, 8> Ops;
7809     for (SDValue Op : BV->op_values()) {
7810       // If the vector element type is not legal, the BUILD_VECTOR operands
7811       // are promoted and implicitly truncated.  Make that explicit here.
7812       if (Op.getValueType() != SrcEltVT)
7813         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7814       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7815       AddToWorklist(Ops.back().getNode());
7816     }
7817     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7818   }
7819 
7820   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7821   // handle annoying details of growing/shrinking FP values, we convert them to
7822   // int first.
7823   if (SrcEltVT.isFloatingPoint()) {
7824     // Convert the input float vector to a int vector where the elements are the
7825     // same sizes.
7826     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7827     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7828     SrcEltVT = IntVT;
7829   }
7830 
7831   // Now we know the input is an integer vector.  If the output is a FP type,
7832   // convert to integer first, then to FP of the right size.
7833   if (DstEltVT.isFloatingPoint()) {
7834     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7835     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7836 
7837     // Next, convert to FP elements of the same size.
7838     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7839   }
7840 
7841   SDLoc DL(BV);
7842 
7843   // Okay, we know the src/dst types are both integers of differing types.
7844   // Handling growing first.
7845   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7846   if (SrcBitSize < DstBitSize) {
7847     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7848 
7849     SmallVector<SDValue, 8> Ops;
7850     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7851          i += NumInputsPerOutput) {
7852       bool isLE = DAG.getDataLayout().isLittleEndian();
7853       APInt NewBits = APInt(DstBitSize, 0);
7854       bool EltIsUndef = true;
7855       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7856         // Shift the previously computed bits over.
7857         NewBits <<= SrcBitSize;
7858         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7859         if (Op.isUndef()) continue;
7860         EltIsUndef = false;
7861 
7862         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7863                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7864       }
7865 
7866       if (EltIsUndef)
7867         Ops.push_back(DAG.getUNDEF(DstEltVT));
7868       else
7869         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7870     }
7871 
7872     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7873     return DAG.getBuildVector(VT, DL, Ops);
7874   }
7875 
7876   // Finally, this must be the case where we are shrinking elements: each input
7877   // turns into multiple outputs.
7878   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7879   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7880                             NumOutputsPerInput*BV->getNumOperands());
7881   SmallVector<SDValue, 8> Ops;
7882 
7883   for (const SDValue &Op : BV->op_values()) {
7884     if (Op.isUndef()) {
7885       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7886       continue;
7887     }
7888 
7889     APInt OpVal = cast<ConstantSDNode>(Op)->
7890                   getAPIntValue().zextOrTrunc(SrcBitSize);
7891 
7892     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7893       APInt ThisVal = OpVal.trunc(DstBitSize);
7894       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7895       OpVal = OpVal.lshr(DstBitSize);
7896     }
7897 
7898     // For big endian targets, swap the order of the pieces of each element.
7899     if (DAG.getDataLayout().isBigEndian())
7900       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7901   }
7902 
7903   return DAG.getBuildVector(VT, DL, Ops);
7904 }
7905 
7906 /// Try to perform FMA combining on a given FADD node.
7907 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7908   SDValue N0 = N->getOperand(0);
7909   SDValue N1 = N->getOperand(1);
7910   EVT VT = N->getValueType(0);
7911   SDLoc SL(N);
7912 
7913   const TargetOptions &Options = DAG.getTarget().Options;
7914   bool AllowFusion =
7915       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7916 
7917   // Floating-point multiply-add with intermediate rounding.
7918   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7919 
7920   // Floating-point multiply-add without intermediate rounding.
7921   bool HasFMA =
7922       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7923       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7924 
7925   // No valid opcode, do not combine.
7926   if (!HasFMAD && !HasFMA)
7927     return SDValue();
7928 
7929   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7930   ;
7931   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7932     return SDValue();
7933 
7934   // Always prefer FMAD to FMA for precision.
7935   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7936   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7937   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7938 
7939   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7940   // prefer to fold the multiply with fewer uses.
7941   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7942       N1.getOpcode() == ISD::FMUL) {
7943     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7944       std::swap(N0, N1);
7945   }
7946 
7947   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7948   if (N0.getOpcode() == ISD::FMUL &&
7949       (Aggressive || N0->hasOneUse())) {
7950     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7951                        N0.getOperand(0), N0.getOperand(1), N1);
7952   }
7953 
7954   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7955   // Note: Commutes FADD operands.
7956   if (N1.getOpcode() == ISD::FMUL &&
7957       (Aggressive || N1->hasOneUse())) {
7958     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7959                        N1.getOperand(0), N1.getOperand(1), N0);
7960   }
7961 
7962   // Look through FP_EXTEND nodes to do more combining.
7963   if (AllowFusion && LookThroughFPExt) {
7964     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7965     if (N0.getOpcode() == ISD::FP_EXTEND) {
7966       SDValue N00 = N0.getOperand(0);
7967       if (N00.getOpcode() == ISD::FMUL)
7968         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7969                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7970                                        N00.getOperand(0)),
7971                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7972                                        N00.getOperand(1)), N1);
7973     }
7974 
7975     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7976     // Note: Commutes FADD operands.
7977     if (N1.getOpcode() == ISD::FP_EXTEND) {
7978       SDValue N10 = N1.getOperand(0);
7979       if (N10.getOpcode() == ISD::FMUL)
7980         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7981                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7982                                        N10.getOperand(0)),
7983                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7984                                        N10.getOperand(1)), N0);
7985     }
7986   }
7987 
7988   // More folding opportunities when target permits.
7989   if ((AllowFusion || HasFMAD)  && Aggressive) {
7990     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7991     if (N0.getOpcode() == PreferredFusedOpcode &&
7992         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7993       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7994                          N0.getOperand(0), N0.getOperand(1),
7995                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7996                                      N0.getOperand(2).getOperand(0),
7997                                      N0.getOperand(2).getOperand(1),
7998                                      N1));
7999     }
8000 
8001     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8002     if (N1->getOpcode() == PreferredFusedOpcode &&
8003         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8004       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8005                          N1.getOperand(0), N1.getOperand(1),
8006                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8007                                      N1.getOperand(2).getOperand(0),
8008                                      N1.getOperand(2).getOperand(1),
8009                                      N0));
8010     }
8011 
8012     if (AllowFusion && LookThroughFPExt) {
8013       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8014       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8015       auto FoldFAddFMAFPExtFMul = [&] (
8016           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8017         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8018                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8019                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8020                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8021                                        Z));
8022       };
8023       if (N0.getOpcode() == PreferredFusedOpcode) {
8024         SDValue N02 = N0.getOperand(2);
8025         if (N02.getOpcode() == ISD::FP_EXTEND) {
8026           SDValue N020 = N02.getOperand(0);
8027           if (N020.getOpcode() == ISD::FMUL)
8028             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8029                                         N020.getOperand(0), N020.getOperand(1),
8030                                         N1);
8031         }
8032       }
8033 
8034       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8035       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8036       // FIXME: This turns two single-precision and one double-precision
8037       // operation into two double-precision operations, which might not be
8038       // interesting for all targets, especially GPUs.
8039       auto FoldFAddFPExtFMAFMul = [&] (
8040           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8041         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8042                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8043                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8044                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8045                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8046                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8047                                        Z));
8048       };
8049       if (N0.getOpcode() == ISD::FP_EXTEND) {
8050         SDValue N00 = N0.getOperand(0);
8051         if (N00.getOpcode() == PreferredFusedOpcode) {
8052           SDValue N002 = N00.getOperand(2);
8053           if (N002.getOpcode() == ISD::FMUL)
8054             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8055                                         N002.getOperand(0), N002.getOperand(1),
8056                                         N1);
8057         }
8058       }
8059 
8060       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8061       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8062       if (N1.getOpcode() == PreferredFusedOpcode) {
8063         SDValue N12 = N1.getOperand(2);
8064         if (N12.getOpcode() == ISD::FP_EXTEND) {
8065           SDValue N120 = N12.getOperand(0);
8066           if (N120.getOpcode() == ISD::FMUL)
8067             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8068                                         N120.getOperand(0), N120.getOperand(1),
8069                                         N0);
8070         }
8071       }
8072 
8073       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8074       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8075       // FIXME: This turns two single-precision and one double-precision
8076       // operation into two double-precision operations, which might not be
8077       // interesting for all targets, especially GPUs.
8078       if (N1.getOpcode() == ISD::FP_EXTEND) {
8079         SDValue N10 = N1.getOperand(0);
8080         if (N10.getOpcode() == PreferredFusedOpcode) {
8081           SDValue N102 = N10.getOperand(2);
8082           if (N102.getOpcode() == ISD::FMUL)
8083             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8084                                         N102.getOperand(0), N102.getOperand(1),
8085                                         N0);
8086         }
8087       }
8088     }
8089   }
8090 
8091   return SDValue();
8092 }
8093 
8094 /// Try to perform FMA combining on a given FSUB node.
8095 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8096   SDValue N0 = N->getOperand(0);
8097   SDValue N1 = N->getOperand(1);
8098   EVT VT = N->getValueType(0);
8099   SDLoc SL(N);
8100 
8101   const TargetOptions &Options = DAG.getTarget().Options;
8102   bool AllowFusion =
8103       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8104 
8105   // Floating-point multiply-add with intermediate rounding.
8106   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8107 
8108   // Floating-point multiply-add without intermediate rounding.
8109   bool HasFMA =
8110       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8111       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8112 
8113   // No valid opcode, do not combine.
8114   if (!HasFMAD && !HasFMA)
8115     return SDValue();
8116 
8117   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8118   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8119     return SDValue();
8120 
8121   // Always prefer FMAD to FMA for precision.
8122   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8123   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8124   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8125 
8126   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8127   if (N0.getOpcode() == ISD::FMUL &&
8128       (Aggressive || N0->hasOneUse())) {
8129     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8130                        N0.getOperand(0), N0.getOperand(1),
8131                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8132   }
8133 
8134   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8135   // Note: Commutes FSUB operands.
8136   if (N1.getOpcode() == ISD::FMUL &&
8137       (Aggressive || N1->hasOneUse()))
8138     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8139                        DAG.getNode(ISD::FNEG, SL, VT,
8140                                    N1.getOperand(0)),
8141                        N1.getOperand(1), N0);
8142 
8143   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8144   if (N0.getOpcode() == ISD::FNEG &&
8145       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8146       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8147     SDValue N00 = N0.getOperand(0).getOperand(0);
8148     SDValue N01 = N0.getOperand(0).getOperand(1);
8149     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8150                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8151                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8152   }
8153 
8154   // Look through FP_EXTEND nodes to do more combining.
8155   if (AllowFusion && LookThroughFPExt) {
8156     // fold (fsub (fpext (fmul x, y)), z)
8157     //   -> (fma (fpext x), (fpext y), (fneg z))
8158     if (N0.getOpcode() == ISD::FP_EXTEND) {
8159       SDValue N00 = N0.getOperand(0);
8160       if (N00.getOpcode() == ISD::FMUL)
8161         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8162                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8163                                        N00.getOperand(0)),
8164                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8165                                        N00.getOperand(1)),
8166                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8167     }
8168 
8169     // fold (fsub x, (fpext (fmul y, z)))
8170     //   -> (fma (fneg (fpext y)), (fpext z), x)
8171     // Note: Commutes FSUB operands.
8172     if (N1.getOpcode() == ISD::FP_EXTEND) {
8173       SDValue N10 = N1.getOperand(0);
8174       if (N10.getOpcode() == ISD::FMUL)
8175         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8176                            DAG.getNode(ISD::FNEG, SL, VT,
8177                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8178                                                    N10.getOperand(0))),
8179                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8180                                        N10.getOperand(1)),
8181                            N0);
8182     }
8183 
8184     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8185     //   -> (fneg (fma (fpext x), (fpext y), z))
8186     // Note: This could be removed with appropriate canonicalization of the
8187     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8188     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8189     // from implementing the canonicalization in visitFSUB.
8190     if (N0.getOpcode() == ISD::FP_EXTEND) {
8191       SDValue N00 = N0.getOperand(0);
8192       if (N00.getOpcode() == ISD::FNEG) {
8193         SDValue N000 = N00.getOperand(0);
8194         if (N000.getOpcode() == ISD::FMUL) {
8195           return DAG.getNode(ISD::FNEG, SL, VT,
8196                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8197                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8198                                                      N000.getOperand(0)),
8199                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8200                                                      N000.getOperand(1)),
8201                                          N1));
8202         }
8203       }
8204     }
8205 
8206     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8207     //   -> (fneg (fma (fpext x)), (fpext y), z)
8208     // Note: This could be removed with appropriate canonicalization of the
8209     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8210     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8211     // from implementing the canonicalization in visitFSUB.
8212     if (N0.getOpcode() == ISD::FNEG) {
8213       SDValue N00 = N0.getOperand(0);
8214       if (N00.getOpcode() == ISD::FP_EXTEND) {
8215         SDValue N000 = N00.getOperand(0);
8216         if (N000.getOpcode() == ISD::FMUL) {
8217           return DAG.getNode(ISD::FNEG, SL, VT,
8218                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8219                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8220                                                      N000.getOperand(0)),
8221                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8222                                                      N000.getOperand(1)),
8223                                          N1));
8224         }
8225       }
8226     }
8227 
8228   }
8229 
8230   // More folding opportunities when target permits.
8231   if ((AllowFusion || HasFMAD) && Aggressive) {
8232     // fold (fsub (fma x, y, (fmul u, v)), z)
8233     //   -> (fma x, y (fma u, v, (fneg z)))
8234     if (N0.getOpcode() == PreferredFusedOpcode &&
8235         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8236       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8237                          N0.getOperand(0), N0.getOperand(1),
8238                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8239                                      N0.getOperand(2).getOperand(0),
8240                                      N0.getOperand(2).getOperand(1),
8241                                      DAG.getNode(ISD::FNEG, SL, VT,
8242                                                  N1)));
8243     }
8244 
8245     // fold (fsub x, (fma y, z, (fmul u, v)))
8246     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8247     if (N1.getOpcode() == PreferredFusedOpcode &&
8248         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8249       SDValue N20 = N1.getOperand(2).getOperand(0);
8250       SDValue N21 = N1.getOperand(2).getOperand(1);
8251       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8252                          DAG.getNode(ISD::FNEG, SL, VT,
8253                                      N1.getOperand(0)),
8254                          N1.getOperand(1),
8255                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8256                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8257 
8258                                      N21, N0));
8259     }
8260 
8261     if (AllowFusion && LookThroughFPExt) {
8262       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8263       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8264       if (N0.getOpcode() == PreferredFusedOpcode) {
8265         SDValue N02 = N0.getOperand(2);
8266         if (N02.getOpcode() == ISD::FP_EXTEND) {
8267           SDValue N020 = N02.getOperand(0);
8268           if (N020.getOpcode() == ISD::FMUL)
8269             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8270                                N0.getOperand(0), N0.getOperand(1),
8271                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8272                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8273                                                        N020.getOperand(0)),
8274                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8275                                                        N020.getOperand(1)),
8276                                            DAG.getNode(ISD::FNEG, SL, VT,
8277                                                        N1)));
8278         }
8279       }
8280 
8281       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8282       //   -> (fma (fpext x), (fpext y),
8283       //           (fma (fpext u), (fpext v), (fneg z)))
8284       // FIXME: This turns two single-precision and one double-precision
8285       // operation into two double-precision operations, which might not be
8286       // interesting for all targets, especially GPUs.
8287       if (N0.getOpcode() == ISD::FP_EXTEND) {
8288         SDValue N00 = N0.getOperand(0);
8289         if (N00.getOpcode() == PreferredFusedOpcode) {
8290           SDValue N002 = N00.getOperand(2);
8291           if (N002.getOpcode() == ISD::FMUL)
8292             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8293                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8294                                            N00.getOperand(0)),
8295                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8296                                            N00.getOperand(1)),
8297                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8298                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8299                                                        N002.getOperand(0)),
8300                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8301                                                        N002.getOperand(1)),
8302                                            DAG.getNode(ISD::FNEG, SL, VT,
8303                                                        N1)));
8304         }
8305       }
8306 
8307       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8308       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8309       if (N1.getOpcode() == PreferredFusedOpcode &&
8310         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8311         SDValue N120 = N1.getOperand(2).getOperand(0);
8312         if (N120.getOpcode() == ISD::FMUL) {
8313           SDValue N1200 = N120.getOperand(0);
8314           SDValue N1201 = N120.getOperand(1);
8315           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8316                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8317                              N1.getOperand(1),
8318                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8319                                          DAG.getNode(ISD::FNEG, SL, VT,
8320                                              DAG.getNode(ISD::FP_EXTEND, SL,
8321                                                          VT, N1200)),
8322                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8323                                                      N1201),
8324                                          N0));
8325         }
8326       }
8327 
8328       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8329       //   -> (fma (fneg (fpext y)), (fpext z),
8330       //           (fma (fneg (fpext u)), (fpext v), x))
8331       // FIXME: This turns two single-precision and one double-precision
8332       // operation into two double-precision operations, which might not be
8333       // interesting for all targets, especially GPUs.
8334       if (N1.getOpcode() == ISD::FP_EXTEND &&
8335         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8336         SDValue N100 = N1.getOperand(0).getOperand(0);
8337         SDValue N101 = N1.getOperand(0).getOperand(1);
8338         SDValue N102 = N1.getOperand(0).getOperand(2);
8339         if (N102.getOpcode() == ISD::FMUL) {
8340           SDValue N1020 = N102.getOperand(0);
8341           SDValue N1021 = N102.getOperand(1);
8342           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8343                              DAG.getNode(ISD::FNEG, SL, VT,
8344                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8345                                                      N100)),
8346                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8347                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8348                                          DAG.getNode(ISD::FNEG, SL, VT,
8349                                              DAG.getNode(ISD::FP_EXTEND, SL,
8350                                                          VT, N1020)),
8351                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8352                                                      N1021),
8353                                          N0));
8354         }
8355       }
8356     }
8357   }
8358 
8359   return SDValue();
8360 }
8361 
8362 /// Try to perform FMA combining on a given FMUL node.
8363 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8364   SDValue N0 = N->getOperand(0);
8365   SDValue N1 = N->getOperand(1);
8366   EVT VT = N->getValueType(0);
8367   SDLoc SL(N);
8368 
8369   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8370 
8371   const TargetOptions &Options = DAG.getTarget().Options;
8372   bool AllowFusion =
8373       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8374 
8375   // Floating-point multiply-add with intermediate rounding.
8376   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8377 
8378   // Floating-point multiply-add without intermediate rounding.
8379   bool HasFMA =
8380       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8381       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8382 
8383   // No valid opcode, do not combine.
8384   if (!HasFMAD && !HasFMA)
8385     return SDValue();
8386 
8387   // Always prefer FMAD to FMA for precision.
8388   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8389   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8390 
8391   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8392   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8393   auto FuseFADD = [&](SDValue X, SDValue Y) {
8394     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8395       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8396       if (XC1 && XC1->isExactlyValue(+1.0))
8397         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8398       if (XC1 && XC1->isExactlyValue(-1.0))
8399         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8400                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8401     }
8402     return SDValue();
8403   };
8404 
8405   if (SDValue FMA = FuseFADD(N0, N1))
8406     return FMA;
8407   if (SDValue FMA = FuseFADD(N1, N0))
8408     return FMA;
8409 
8410   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8411   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8412   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8413   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8414   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8415     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8416       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8417       if (XC0 && XC0->isExactlyValue(+1.0))
8418         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8419                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8420                            Y);
8421       if (XC0 && XC0->isExactlyValue(-1.0))
8422         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8423                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8424                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8425 
8426       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8427       if (XC1 && XC1->isExactlyValue(+1.0))
8428         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8429                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8430       if (XC1 && XC1->isExactlyValue(-1.0))
8431         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8432     }
8433     return SDValue();
8434   };
8435 
8436   if (SDValue FMA = FuseFSUB(N0, N1))
8437     return FMA;
8438   if (SDValue FMA = FuseFSUB(N1, N0))
8439     return FMA;
8440 
8441   return SDValue();
8442 }
8443 
8444 SDValue DAGCombiner::visitFADD(SDNode *N) {
8445   SDValue N0 = N->getOperand(0);
8446   SDValue N1 = N->getOperand(1);
8447   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8448   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8449   EVT VT = N->getValueType(0);
8450   SDLoc DL(N);
8451   const TargetOptions &Options = DAG.getTarget().Options;
8452   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8453 
8454   // fold vector ops
8455   if (VT.isVector())
8456     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8457       return FoldedVOp;
8458 
8459   // fold (fadd c1, c2) -> c1 + c2
8460   if (N0CFP && N1CFP)
8461     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8462 
8463   // canonicalize constant to RHS
8464   if (N0CFP && !N1CFP)
8465     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8466 
8467   // fold (fadd A, (fneg B)) -> (fsub A, B)
8468   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8469       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8470     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8471                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8472 
8473   // fold (fadd (fneg A), B) -> (fsub B, A)
8474   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8475       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8476     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8477                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8478 
8479   // FIXME: Auto-upgrade the target/function-level option.
8480   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8481     // fold (fadd A, 0) -> A
8482     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8483       if (N1C->isZero())
8484         return N0;
8485   }
8486 
8487   // If 'unsafe math' is enabled, fold lots of things.
8488   if (Options.UnsafeFPMath) {
8489     // No FP constant should be created after legalization as Instruction
8490     // Selection pass has a hard time dealing with FP constants.
8491     bool AllowNewConst = (Level < AfterLegalizeDAG);
8492 
8493     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8494     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8495         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8496       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8497                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8498                                      Flags),
8499                          Flags);
8500 
8501     // If allowed, fold (fadd (fneg x), x) -> 0.0
8502     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8503       return DAG.getConstantFP(0.0, DL, VT);
8504 
8505     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8506     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8507       return DAG.getConstantFP(0.0, DL, VT);
8508 
8509     // We can fold chains of FADD's of the same value into multiplications.
8510     // This transform is not safe in general because we are reducing the number
8511     // of rounding steps.
8512     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8513       if (N0.getOpcode() == ISD::FMUL) {
8514         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8515         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8516 
8517         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8518         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8519           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8520                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8521           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8522         }
8523 
8524         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8525         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8526             N1.getOperand(0) == N1.getOperand(1) &&
8527             N0.getOperand(0) == N1.getOperand(0)) {
8528           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8529                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8530           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8531         }
8532       }
8533 
8534       if (N1.getOpcode() == ISD::FMUL) {
8535         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8536         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8537 
8538         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8539         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8540           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8541                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8542           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8543         }
8544 
8545         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8546         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8547             N0.getOperand(0) == N0.getOperand(1) &&
8548             N1.getOperand(0) == N0.getOperand(0)) {
8549           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8550                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8551           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8552         }
8553       }
8554 
8555       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8556         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8557         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8558         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8559             (N0.getOperand(0) == N1)) {
8560           return DAG.getNode(ISD::FMUL, DL, VT,
8561                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8562         }
8563       }
8564 
8565       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8566         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8567         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8568         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8569             N1.getOperand(0) == N0) {
8570           return DAG.getNode(ISD::FMUL, DL, VT,
8571                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8572         }
8573       }
8574 
8575       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8576       if (AllowNewConst &&
8577           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8578           N0.getOperand(0) == N0.getOperand(1) &&
8579           N1.getOperand(0) == N1.getOperand(1) &&
8580           N0.getOperand(0) == N1.getOperand(0)) {
8581         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8582                            DAG.getConstantFP(4.0, DL, VT), Flags);
8583       }
8584     }
8585   } // enable-unsafe-fp-math
8586 
8587   // FADD -> FMA combines:
8588   if (SDValue Fused = visitFADDForFMACombine(N)) {
8589     AddToWorklist(Fused.getNode());
8590     return Fused;
8591   }
8592   return SDValue();
8593 }
8594 
8595 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8596   SDValue N0 = N->getOperand(0);
8597   SDValue N1 = N->getOperand(1);
8598   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8599   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8600   EVT VT = N->getValueType(0);
8601   SDLoc DL(N);
8602   const TargetOptions &Options = DAG.getTarget().Options;
8603   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8604 
8605   // fold vector ops
8606   if (VT.isVector())
8607     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8608       return FoldedVOp;
8609 
8610   // fold (fsub c1, c2) -> c1-c2
8611   if (N0CFP && N1CFP)
8612     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8613 
8614   // fold (fsub A, (fneg B)) -> (fadd A, B)
8615   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8616     return DAG.getNode(ISD::FADD, DL, VT, N0,
8617                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8618 
8619   // FIXME: Auto-upgrade the target/function-level option.
8620   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8621     // (fsub 0, B) -> -B
8622     if (N0CFP && N0CFP->isZero()) {
8623       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8624         return GetNegatedExpression(N1, DAG, LegalOperations);
8625       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8626         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
8627     }
8628   }
8629 
8630   // If 'unsafe math' is enabled, fold lots of things.
8631   if (Options.UnsafeFPMath) {
8632     // (fsub A, 0) -> A
8633     if (N1CFP && N1CFP->isZero())
8634       return N0;
8635 
8636     // (fsub x, x) -> 0.0
8637     if (N0 == N1)
8638       return DAG.getConstantFP(0.0f, DL, VT);
8639 
8640     // (fsub x, (fadd x, y)) -> (fneg y)
8641     // (fsub x, (fadd y, x)) -> (fneg y)
8642     if (N1.getOpcode() == ISD::FADD) {
8643       SDValue N10 = N1->getOperand(0);
8644       SDValue N11 = N1->getOperand(1);
8645 
8646       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8647         return GetNegatedExpression(N11, DAG, LegalOperations);
8648 
8649       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8650         return GetNegatedExpression(N10, DAG, LegalOperations);
8651     }
8652   }
8653 
8654   // FSUB -> FMA combines:
8655   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8656     AddToWorklist(Fused.getNode());
8657     return Fused;
8658   }
8659 
8660   return SDValue();
8661 }
8662 
8663 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8664   SDValue N0 = N->getOperand(0);
8665   SDValue N1 = N->getOperand(1);
8666   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8667   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8668   EVT VT = N->getValueType(0);
8669   SDLoc DL(N);
8670   const TargetOptions &Options = DAG.getTarget().Options;
8671   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8672 
8673   // fold vector ops
8674   if (VT.isVector()) {
8675     // This just handles C1 * C2 for vectors. Other vector folds are below.
8676     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8677       return FoldedVOp;
8678   }
8679 
8680   // fold (fmul c1, c2) -> c1*c2
8681   if (N0CFP && N1CFP)
8682     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8683 
8684   // canonicalize constant to RHS
8685   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8686      !isConstantFPBuildVectorOrConstantFP(N1))
8687     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8688 
8689   // fold (fmul A, 1.0) -> A
8690   if (N1CFP && N1CFP->isExactlyValue(1.0))
8691     return N0;
8692 
8693   if (Options.UnsafeFPMath) {
8694     // fold (fmul A, 0) -> 0
8695     if (N1CFP && N1CFP->isZero())
8696       return N1;
8697 
8698     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8699     if (N0.getOpcode() == ISD::FMUL) {
8700       // Fold scalars or any vector constants (not just splats).
8701       // This fold is done in general by InstCombine, but extra fmul insts
8702       // may have been generated during lowering.
8703       SDValue N00 = N0.getOperand(0);
8704       SDValue N01 = N0.getOperand(1);
8705       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8706       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8707       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8708 
8709       // Check 1: Make sure that the first operand of the inner multiply is NOT
8710       // a constant. Otherwise, we may induce infinite looping.
8711       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8712         // Check 2: Make sure that the second operand of the inner multiply and
8713         // the second operand of the outer multiply are constants.
8714         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8715             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8716           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8717           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8718         }
8719       }
8720     }
8721 
8722     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8723     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8724     // during an early run of DAGCombiner can prevent folding with fmuls
8725     // inserted during lowering.
8726     if (N0.getOpcode() == ISD::FADD &&
8727         (N0.getOperand(0) == N0.getOperand(1)) &&
8728         N0.hasOneUse()) {
8729       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8730       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8731       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8732     }
8733   }
8734 
8735   // fold (fmul X, 2.0) -> (fadd X, X)
8736   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8737     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8738 
8739   // fold (fmul X, -1.0) -> (fneg X)
8740   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8741     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8742       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8743 
8744   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8745   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8746     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8747       // Both can be negated for free, check to see if at least one is cheaper
8748       // negated.
8749       if (LHSNeg == 2 || RHSNeg == 2)
8750         return DAG.getNode(ISD::FMUL, DL, VT,
8751                            GetNegatedExpression(N0, DAG, LegalOperations),
8752                            GetNegatedExpression(N1, DAG, LegalOperations),
8753                            Flags);
8754     }
8755   }
8756 
8757   // FMUL -> FMA combines:
8758   if (SDValue Fused = visitFMULForFMACombine(N)) {
8759     AddToWorklist(Fused.getNode());
8760     return Fused;
8761   }
8762 
8763   return SDValue();
8764 }
8765 
8766 SDValue DAGCombiner::visitFMA(SDNode *N) {
8767   SDValue N0 = N->getOperand(0);
8768   SDValue N1 = N->getOperand(1);
8769   SDValue N2 = N->getOperand(2);
8770   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8771   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8772   EVT VT = N->getValueType(0);
8773   SDLoc DL(N);
8774   const TargetOptions &Options = DAG.getTarget().Options;
8775 
8776   // Constant fold FMA.
8777   if (isa<ConstantFPSDNode>(N0) &&
8778       isa<ConstantFPSDNode>(N1) &&
8779       isa<ConstantFPSDNode>(N2)) {
8780     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8781   }
8782 
8783   if (Options.UnsafeFPMath) {
8784     if (N0CFP && N0CFP->isZero())
8785       return N2;
8786     if (N1CFP && N1CFP->isZero())
8787       return N2;
8788   }
8789   // TODO: The FMA node should have flags that propagate to these nodes.
8790   if (N0CFP && N0CFP->isExactlyValue(1.0))
8791     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8792   if (N1CFP && N1CFP->isExactlyValue(1.0))
8793     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8794 
8795   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8796   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8797      !isConstantFPBuildVectorOrConstantFP(N1))
8798     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8799 
8800   // TODO: FMA nodes should have flags that propagate to the created nodes.
8801   // For now, create a Flags object for use with all unsafe math transforms.
8802   SDNodeFlags Flags;
8803   Flags.setUnsafeAlgebra(true);
8804 
8805   if (Options.UnsafeFPMath) {
8806     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8807     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8808         isConstantFPBuildVectorOrConstantFP(N1) &&
8809         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8810       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8811                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8812                                      &Flags), &Flags);
8813     }
8814 
8815     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8816     if (N0.getOpcode() == ISD::FMUL &&
8817         isConstantFPBuildVectorOrConstantFP(N1) &&
8818         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8819       return DAG.getNode(ISD::FMA, DL, VT,
8820                          N0.getOperand(0),
8821                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8822                                      &Flags),
8823                          N2);
8824     }
8825   }
8826 
8827   // (fma x, 1, y) -> (fadd x, y)
8828   // (fma x, -1, y) -> (fadd (fneg x), y)
8829   if (N1CFP) {
8830     if (N1CFP->isExactlyValue(1.0))
8831       // TODO: The FMA node should have flags that propagate to this node.
8832       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8833 
8834     if (N1CFP->isExactlyValue(-1.0) &&
8835         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8836       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8837       AddToWorklist(RHSNeg.getNode());
8838       // TODO: The FMA node should have flags that propagate to this node.
8839       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8840     }
8841   }
8842 
8843   if (Options.UnsafeFPMath) {
8844     // (fma x, c, x) -> (fmul x, (c+1))
8845     if (N1CFP && N0 == N2) {
8846       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8847                          DAG.getNode(ISD::FADD, DL, VT, N1,
8848                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
8849                          &Flags);
8850     }
8851 
8852     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8853     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8854       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8855                          DAG.getNode(ISD::FADD, DL, VT, N1,
8856                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
8857                          &Flags);
8858     }
8859   }
8860 
8861   return SDValue();
8862 }
8863 
8864 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8865 // reciprocal.
8866 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8867 // Notice that this is not always beneficial. One reason is different target
8868 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8869 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8870 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8871 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8872   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8873   const SDNodeFlags *Flags = N->getFlags();
8874   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8875     return SDValue();
8876 
8877   // Skip if current node is a reciprocal.
8878   SDValue N0 = N->getOperand(0);
8879   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8880   if (N0CFP && N0CFP->isExactlyValue(1.0))
8881     return SDValue();
8882 
8883   // Exit early if the target does not want this transform or if there can't
8884   // possibly be enough uses of the divisor to make the transform worthwhile.
8885   SDValue N1 = N->getOperand(1);
8886   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8887   if (!MinUses || N1->use_size() < MinUses)
8888     return SDValue();
8889 
8890   // Find all FDIV users of the same divisor.
8891   // Use a set because duplicates may be present in the user list.
8892   SetVector<SDNode *> Users;
8893   for (auto *U : N1->uses()) {
8894     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8895       // This division is eligible for optimization only if global unsafe math
8896       // is enabled or if this division allows reciprocal formation.
8897       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8898         Users.insert(U);
8899     }
8900   }
8901 
8902   // Now that we have the actual number of divisor uses, make sure it meets
8903   // the minimum threshold specified by the target.
8904   if (Users.size() < MinUses)
8905     return SDValue();
8906 
8907   EVT VT = N->getValueType(0);
8908   SDLoc DL(N);
8909   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8910   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8911 
8912   // Dividend / Divisor -> Dividend * Reciprocal
8913   for (auto *U : Users) {
8914     SDValue Dividend = U->getOperand(0);
8915     if (Dividend != FPOne) {
8916       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8917                                     Reciprocal, Flags);
8918       CombineTo(U, NewNode);
8919     } else if (U != Reciprocal.getNode()) {
8920       // In the absence of fast-math-flags, this user node is always the
8921       // same node as Reciprocal, but with FMF they may be different nodes.
8922       CombineTo(U, Reciprocal);
8923     }
8924   }
8925   return SDValue(N, 0);  // N was replaced.
8926 }
8927 
8928 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8929   SDValue N0 = N->getOperand(0);
8930   SDValue N1 = N->getOperand(1);
8931   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8932   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8933   EVT VT = N->getValueType(0);
8934   SDLoc DL(N);
8935   const TargetOptions &Options = DAG.getTarget().Options;
8936   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8937 
8938   // fold vector ops
8939   if (VT.isVector())
8940     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8941       return FoldedVOp;
8942 
8943   // fold (fdiv c1, c2) -> c1/c2
8944   if (N0CFP && N1CFP)
8945     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8946 
8947   if (Options.UnsafeFPMath) {
8948     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8949     if (N1CFP) {
8950       // Compute the reciprocal 1.0 / c2.
8951       const APFloat &N1APF = N1CFP->getValueAPF();
8952       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8953       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8954       // Only do the transform if the reciprocal is a legal fp immediate that
8955       // isn't too nasty (eg NaN, denormal, ...).
8956       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8957           (!LegalOperations ||
8958            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8959            // backend)... we should handle this gracefully after Legalize.
8960            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8961            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8962            TLI.isFPImmLegal(Recip, VT)))
8963         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8964                            DAG.getConstantFP(Recip, DL, VT), Flags);
8965     }
8966 
8967     // If this FDIV is part of a reciprocal square root, it may be folded
8968     // into a target-specific square root estimate instruction.
8969     if (N1.getOpcode() == ISD::FSQRT) {
8970       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8971         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8972       }
8973     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8974                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8975       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8976                                           Flags)) {
8977         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8978         AddToWorklist(RV.getNode());
8979         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8980       }
8981     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8982                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8983       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8984                                           Flags)) {
8985         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8986         AddToWorklist(RV.getNode());
8987         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8988       }
8989     } else if (N1.getOpcode() == ISD::FMUL) {
8990       // Look through an FMUL. Even though this won't remove the FDIV directly,
8991       // it's still worthwhile to get rid of the FSQRT if possible.
8992       SDValue SqrtOp;
8993       SDValue OtherOp;
8994       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8995         SqrtOp = N1.getOperand(0);
8996         OtherOp = N1.getOperand(1);
8997       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8998         SqrtOp = N1.getOperand(1);
8999         OtherOp = N1.getOperand(0);
9000       }
9001       if (SqrtOp.getNode()) {
9002         // We found a FSQRT, so try to make this fold:
9003         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9004         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9005           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9006           AddToWorklist(RV.getNode());
9007           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9008         }
9009       }
9010     }
9011 
9012     // Fold into a reciprocal estimate and multiply instead of a real divide.
9013     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9014       AddToWorklist(RV.getNode());
9015       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9016     }
9017   }
9018 
9019   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9020   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9021     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9022       // Both can be negated for free, check to see if at least one is cheaper
9023       // negated.
9024       if (LHSNeg == 2 || RHSNeg == 2)
9025         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9026                            GetNegatedExpression(N0, DAG, LegalOperations),
9027                            GetNegatedExpression(N1, DAG, LegalOperations),
9028                            Flags);
9029     }
9030   }
9031 
9032   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9033     return CombineRepeatedDivisors;
9034 
9035   return SDValue();
9036 }
9037 
9038 SDValue DAGCombiner::visitFREM(SDNode *N) {
9039   SDValue N0 = N->getOperand(0);
9040   SDValue N1 = N->getOperand(1);
9041   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9042   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9043   EVT VT = N->getValueType(0);
9044 
9045   // fold (frem c1, c2) -> fmod(c1,c2)
9046   if (N0CFP && N1CFP)
9047     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9048                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9049 
9050   return SDValue();
9051 }
9052 
9053 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9054   if (!DAG.getTarget().Options.UnsafeFPMath)
9055     return SDValue();
9056 
9057   SDValue N0 = N->getOperand(0);
9058   if (TLI.isFsqrtCheap(N0, DAG))
9059     return SDValue();
9060 
9061   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9062   // For now, create a Flags object for use with all unsafe math transforms.
9063   SDNodeFlags Flags;
9064   Flags.setUnsafeAlgebra(true);
9065   return buildSqrtEstimate(N0, &Flags);
9066 }
9067 
9068 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9069 /// copysign(x, fp_round(y)) -> copysign(x, y)
9070 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9071   SDValue N1 = N->getOperand(1);
9072   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9073        N1.getOpcode() == ISD::FP_ROUND)) {
9074     // Do not optimize out type conversion of f128 type yet.
9075     // For some targets like x86_64, configuration is changed to keep one f128
9076     // value in one SSE register, but instruction selection cannot handle
9077     // FCOPYSIGN on SSE registers yet.
9078     EVT N1VT = N1->getValueType(0);
9079     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9080     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9081   }
9082   return false;
9083 }
9084 
9085 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9086   SDValue N0 = N->getOperand(0);
9087   SDValue N1 = N->getOperand(1);
9088   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9089   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9090   EVT VT = N->getValueType(0);
9091 
9092   if (N0CFP && N1CFP) // Constant fold
9093     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9094 
9095   if (N1CFP) {
9096     const APFloat &V = N1CFP->getValueAPF();
9097     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9098     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9099     if (!V.isNegative()) {
9100       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9101         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9102     } else {
9103       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9104         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9105                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9106     }
9107   }
9108 
9109   // copysign(fabs(x), y) -> copysign(x, y)
9110   // copysign(fneg(x), y) -> copysign(x, y)
9111   // copysign(copysign(x,z), y) -> copysign(x, y)
9112   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9113       N0.getOpcode() == ISD::FCOPYSIGN)
9114     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9115 
9116   // copysign(x, abs(y)) -> abs(x)
9117   if (N1.getOpcode() == ISD::FABS)
9118     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9119 
9120   // copysign(x, copysign(y,z)) -> copysign(x, z)
9121   if (N1.getOpcode() == ISD::FCOPYSIGN)
9122     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9123 
9124   // copysign(x, fp_extend(y)) -> copysign(x, y)
9125   // copysign(x, fp_round(y)) -> copysign(x, y)
9126   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9127     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9128 
9129   return SDValue();
9130 }
9131 
9132 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9133   SDValue N0 = N->getOperand(0);
9134   EVT VT = N->getValueType(0);
9135   EVT OpVT = N0.getValueType();
9136 
9137   // fold (sint_to_fp c1) -> c1fp
9138   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9139       // ...but only if the target supports immediate floating-point values
9140       (!LegalOperations ||
9141        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9142     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9143 
9144   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9145   // but UINT_TO_FP is legal on this target, try to convert.
9146   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9147       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9148     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9149     if (DAG.SignBitIsZero(N0))
9150       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9151   }
9152 
9153   // The next optimizations are desirable only if SELECT_CC can be lowered.
9154   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9155     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9156     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9157         !VT.isVector() &&
9158         (!LegalOperations ||
9159          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9160       SDLoc DL(N);
9161       SDValue Ops[] =
9162         { N0.getOperand(0), N0.getOperand(1),
9163           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9164           N0.getOperand(2) };
9165       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9166     }
9167 
9168     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9169     //      (select_cc x, y, 1.0, 0.0,, cc)
9170     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9171         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9172         (!LegalOperations ||
9173          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9174       SDLoc DL(N);
9175       SDValue Ops[] =
9176         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9177           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9178           N0.getOperand(0).getOperand(2) };
9179       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9180     }
9181   }
9182 
9183   return SDValue();
9184 }
9185 
9186 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9187   SDValue N0 = N->getOperand(0);
9188   EVT VT = N->getValueType(0);
9189   EVT OpVT = N0.getValueType();
9190 
9191   // fold (uint_to_fp c1) -> c1fp
9192   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9193       // ...but only if the target supports immediate floating-point values
9194       (!LegalOperations ||
9195        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9196     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9197 
9198   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9199   // but SINT_TO_FP is legal on this target, try to convert.
9200   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9201       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9202     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9203     if (DAG.SignBitIsZero(N0))
9204       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9205   }
9206 
9207   // The next optimizations are desirable only if SELECT_CC can be lowered.
9208   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9209     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9210 
9211     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9212         (!LegalOperations ||
9213          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9214       SDLoc DL(N);
9215       SDValue Ops[] =
9216         { N0.getOperand(0), N0.getOperand(1),
9217           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9218           N0.getOperand(2) };
9219       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9220     }
9221   }
9222 
9223   return SDValue();
9224 }
9225 
9226 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9227 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9228   SDValue N0 = N->getOperand(0);
9229   EVT VT = N->getValueType(0);
9230 
9231   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9232     return SDValue();
9233 
9234   SDValue Src = N0.getOperand(0);
9235   EVT SrcVT = Src.getValueType();
9236   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9237   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9238 
9239   // We can safely assume the conversion won't overflow the output range,
9240   // because (for example) (uint8_t)18293.f is undefined behavior.
9241 
9242   // Since we can assume the conversion won't overflow, our decision as to
9243   // whether the input will fit in the float should depend on the minimum
9244   // of the input range and output range.
9245 
9246   // This means this is also safe for a signed input and unsigned output, since
9247   // a negative input would lead to undefined behavior.
9248   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9249   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9250   unsigned ActualSize = std::min(InputSize, OutputSize);
9251   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9252 
9253   // We can only fold away the float conversion if the input range can be
9254   // represented exactly in the float range.
9255   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9256     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9257       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9258                                                        : ISD::ZERO_EXTEND;
9259       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9260     }
9261     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9262       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9263     return DAG.getBitcast(VT, Src);
9264   }
9265   return SDValue();
9266 }
9267 
9268 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9269   SDValue N0 = N->getOperand(0);
9270   EVT VT = N->getValueType(0);
9271 
9272   // fold (fp_to_sint c1fp) -> c1
9273   if (isConstantFPBuildVectorOrConstantFP(N0))
9274     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9275 
9276   return FoldIntToFPToInt(N, DAG);
9277 }
9278 
9279 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9280   SDValue N0 = N->getOperand(0);
9281   EVT VT = N->getValueType(0);
9282 
9283   // fold (fp_to_uint c1fp) -> c1
9284   if (isConstantFPBuildVectorOrConstantFP(N0))
9285     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9286 
9287   return FoldIntToFPToInt(N, DAG);
9288 }
9289 
9290 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9291   SDValue N0 = N->getOperand(0);
9292   SDValue N1 = N->getOperand(1);
9293   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9294   EVT VT = N->getValueType(0);
9295 
9296   // fold (fp_round c1fp) -> c1fp
9297   if (N0CFP)
9298     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9299 
9300   // fold (fp_round (fp_extend x)) -> x
9301   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9302     return N0.getOperand(0);
9303 
9304   // fold (fp_round (fp_round x)) -> (fp_round x)
9305   if (N0.getOpcode() == ISD::FP_ROUND) {
9306     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9307     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9308 
9309     // Skip this folding if it results in an fp_round from f80 to f16.
9310     //
9311     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9312     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9313     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9314     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9315     // x86.
9316     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9317       return SDValue();
9318 
9319     // If the first fp_round isn't a value preserving truncation, it might
9320     // introduce a tie in the second fp_round, that wouldn't occur in the
9321     // single-step fp_round we want to fold to.
9322     // In other words, double rounding isn't the same as rounding.
9323     // Also, this is a value preserving truncation iff both fp_round's are.
9324     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9325       SDLoc DL(N);
9326       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9327                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9328     }
9329   }
9330 
9331   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9332   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9333     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9334                               N0.getOperand(0), N1);
9335     AddToWorklist(Tmp.getNode());
9336     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9337                        Tmp, N0.getOperand(1));
9338   }
9339 
9340   return SDValue();
9341 }
9342 
9343 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9344   SDValue N0 = N->getOperand(0);
9345   EVT VT = N->getValueType(0);
9346   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9347   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9348 
9349   // fold (fp_round_inreg c1fp) -> c1fp
9350   if (N0CFP && isTypeLegal(EVT)) {
9351     SDLoc DL(N);
9352     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9353     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9354   }
9355 
9356   return SDValue();
9357 }
9358 
9359 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9360   SDValue N0 = N->getOperand(0);
9361   EVT VT = N->getValueType(0);
9362 
9363   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9364   if (N->hasOneUse() &&
9365       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9366     return SDValue();
9367 
9368   // fold (fp_extend c1fp) -> c1fp
9369   if (isConstantFPBuildVectorOrConstantFP(N0))
9370     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9371 
9372   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9373   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9374       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9375     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9376 
9377   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9378   // value of X.
9379   if (N0.getOpcode() == ISD::FP_ROUND
9380       && N0.getNode()->getConstantOperandVal(1) == 1) {
9381     SDValue In = N0.getOperand(0);
9382     if (In.getValueType() == VT) return In;
9383     if (VT.bitsLT(In.getValueType()))
9384       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9385                          In, N0.getOperand(1));
9386     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9387   }
9388 
9389   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9390   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9391        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9392     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9393     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9394                                      LN0->getChain(),
9395                                      LN0->getBasePtr(), N0.getValueType(),
9396                                      LN0->getMemOperand());
9397     CombineTo(N, ExtLoad);
9398     CombineTo(N0.getNode(),
9399               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9400                           N0.getValueType(), ExtLoad,
9401                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9402               ExtLoad.getValue(1));
9403     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9404   }
9405 
9406   return SDValue();
9407 }
9408 
9409 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9410   SDValue N0 = N->getOperand(0);
9411   EVT VT = N->getValueType(0);
9412 
9413   // fold (fceil c1) -> fceil(c1)
9414   if (isConstantFPBuildVectorOrConstantFP(N0))
9415     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9416 
9417   return SDValue();
9418 }
9419 
9420 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9421   SDValue N0 = N->getOperand(0);
9422   EVT VT = N->getValueType(0);
9423 
9424   // fold (ftrunc c1) -> ftrunc(c1)
9425   if (isConstantFPBuildVectorOrConstantFP(N0))
9426     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9427 
9428   return SDValue();
9429 }
9430 
9431 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9432   SDValue N0 = N->getOperand(0);
9433   EVT VT = N->getValueType(0);
9434 
9435   // fold (ffloor c1) -> ffloor(c1)
9436   if (isConstantFPBuildVectorOrConstantFP(N0))
9437     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9438 
9439   return SDValue();
9440 }
9441 
9442 // FIXME: FNEG and FABS have a lot in common; refactor.
9443 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9444   SDValue N0 = N->getOperand(0);
9445   EVT VT = N->getValueType(0);
9446 
9447   // Constant fold FNEG.
9448   if (isConstantFPBuildVectorOrConstantFP(N0))
9449     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9450 
9451   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9452                          &DAG.getTarget().Options))
9453     return GetNegatedExpression(N0, DAG, LegalOperations);
9454 
9455   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9456   // constant pool values.
9457   if (!TLI.isFNegFree(VT) &&
9458       N0.getOpcode() == ISD::BITCAST &&
9459       N0.getNode()->hasOneUse()) {
9460     SDValue Int = N0.getOperand(0);
9461     EVT IntVT = Int.getValueType();
9462     if (IntVT.isInteger() && !IntVT.isVector()) {
9463       APInt SignMask;
9464       if (N0.getValueType().isVector()) {
9465         // For a vector, get a mask such as 0x80... per scalar element
9466         // and splat it.
9467         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9468         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9469       } else {
9470         // For a scalar, just generate 0x80...
9471         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9472       }
9473       SDLoc DL0(N0);
9474       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9475                         DAG.getConstant(SignMask, DL0, IntVT));
9476       AddToWorklist(Int.getNode());
9477       return DAG.getBitcast(VT, Int);
9478     }
9479   }
9480 
9481   // (fneg (fmul c, x)) -> (fmul -c, x)
9482   if (N0.getOpcode() == ISD::FMUL &&
9483       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9484     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9485     if (CFP1) {
9486       APFloat CVal = CFP1->getValueAPF();
9487       CVal.changeSign();
9488       if (Level >= AfterLegalizeDAG &&
9489           (TLI.isFPImmLegal(CVal, VT) ||
9490            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9491         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9492                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9493                                        N0.getOperand(1)),
9494                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9495     }
9496   }
9497 
9498   return SDValue();
9499 }
9500 
9501 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9502   SDValue N0 = N->getOperand(0);
9503   SDValue N1 = N->getOperand(1);
9504   EVT VT = N->getValueType(0);
9505   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9506   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9507 
9508   if (N0CFP && N1CFP) {
9509     const APFloat &C0 = N0CFP->getValueAPF();
9510     const APFloat &C1 = N1CFP->getValueAPF();
9511     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9512   }
9513 
9514   // Canonicalize to constant on RHS.
9515   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9516      !isConstantFPBuildVectorOrConstantFP(N1))
9517     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9518 
9519   return SDValue();
9520 }
9521 
9522 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9523   SDValue N0 = N->getOperand(0);
9524   SDValue N1 = N->getOperand(1);
9525   EVT VT = N->getValueType(0);
9526   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9527   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9528 
9529   if (N0CFP && N1CFP) {
9530     const APFloat &C0 = N0CFP->getValueAPF();
9531     const APFloat &C1 = N1CFP->getValueAPF();
9532     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9533   }
9534 
9535   // Canonicalize to constant on RHS.
9536   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9537      !isConstantFPBuildVectorOrConstantFP(N1))
9538     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9539 
9540   return SDValue();
9541 }
9542 
9543 SDValue DAGCombiner::visitFABS(SDNode *N) {
9544   SDValue N0 = N->getOperand(0);
9545   EVT VT = N->getValueType(0);
9546 
9547   // fold (fabs c1) -> fabs(c1)
9548   if (isConstantFPBuildVectorOrConstantFP(N0))
9549     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9550 
9551   // fold (fabs (fabs x)) -> (fabs x)
9552   if (N0.getOpcode() == ISD::FABS)
9553     return N->getOperand(0);
9554 
9555   // fold (fabs (fneg x)) -> (fabs x)
9556   // fold (fabs (fcopysign x, y)) -> (fabs x)
9557   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9558     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9559 
9560   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9561   // constant pool values.
9562   if (!TLI.isFAbsFree(VT) &&
9563       N0.getOpcode() == ISD::BITCAST &&
9564       N0.getNode()->hasOneUse()) {
9565     SDValue Int = N0.getOperand(0);
9566     EVT IntVT = Int.getValueType();
9567     if (IntVT.isInteger() && !IntVT.isVector()) {
9568       APInt SignMask;
9569       if (N0.getValueType().isVector()) {
9570         // For a vector, get a mask such as 0x7f... per scalar element
9571         // and splat it.
9572         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9573         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9574       } else {
9575         // For a scalar, just generate 0x7f...
9576         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9577       }
9578       SDLoc DL(N0);
9579       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9580                         DAG.getConstant(SignMask, DL, IntVT));
9581       AddToWorklist(Int.getNode());
9582       return DAG.getBitcast(N->getValueType(0), Int);
9583     }
9584   }
9585 
9586   return SDValue();
9587 }
9588 
9589 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9590   SDValue Chain = N->getOperand(0);
9591   SDValue N1 = N->getOperand(1);
9592   SDValue N2 = N->getOperand(2);
9593 
9594   // If N is a constant we could fold this into a fallthrough or unconditional
9595   // branch. However that doesn't happen very often in normal code, because
9596   // Instcombine/SimplifyCFG should have handled the available opportunities.
9597   // If we did this folding here, it would be necessary to update the
9598   // MachineBasicBlock CFG, which is awkward.
9599 
9600   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9601   // on the target.
9602   if (N1.getOpcode() == ISD::SETCC &&
9603       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9604                                    N1.getOperand(0).getValueType())) {
9605     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9606                        Chain, N1.getOperand(2),
9607                        N1.getOperand(0), N1.getOperand(1), N2);
9608   }
9609 
9610   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9611       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9612        (N1.getOperand(0).hasOneUse() &&
9613         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9614     SDNode *Trunc = nullptr;
9615     if (N1.getOpcode() == ISD::TRUNCATE) {
9616       // Look pass the truncate.
9617       Trunc = N1.getNode();
9618       N1 = N1.getOperand(0);
9619     }
9620 
9621     // Match this pattern so that we can generate simpler code:
9622     //
9623     //   %a = ...
9624     //   %b = and i32 %a, 2
9625     //   %c = srl i32 %b, 1
9626     //   brcond i32 %c ...
9627     //
9628     // into
9629     //
9630     //   %a = ...
9631     //   %b = and i32 %a, 2
9632     //   %c = setcc eq %b, 0
9633     //   brcond %c ...
9634     //
9635     // This applies only when the AND constant value has one bit set and the
9636     // SRL constant is equal to the log2 of the AND constant. The back-end is
9637     // smart enough to convert the result into a TEST/JMP sequence.
9638     SDValue Op0 = N1.getOperand(0);
9639     SDValue Op1 = N1.getOperand(1);
9640 
9641     if (Op0.getOpcode() == ISD::AND &&
9642         Op1.getOpcode() == ISD::Constant) {
9643       SDValue AndOp1 = Op0.getOperand(1);
9644 
9645       if (AndOp1.getOpcode() == ISD::Constant) {
9646         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9647 
9648         if (AndConst.isPowerOf2() &&
9649             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9650           SDLoc DL(N);
9651           SDValue SetCC =
9652             DAG.getSetCC(DL,
9653                          getSetCCResultType(Op0.getValueType()),
9654                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9655                          ISD::SETNE);
9656 
9657           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9658                                           MVT::Other, Chain, SetCC, N2);
9659           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9660           // will convert it back to (X & C1) >> C2.
9661           CombineTo(N, NewBRCond, false);
9662           // Truncate is dead.
9663           if (Trunc)
9664             deleteAndRecombine(Trunc);
9665           // Replace the uses of SRL with SETCC
9666           WorklistRemover DeadNodes(*this);
9667           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9668           deleteAndRecombine(N1.getNode());
9669           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9670         }
9671       }
9672     }
9673 
9674     if (Trunc)
9675       // Restore N1 if the above transformation doesn't match.
9676       N1 = N->getOperand(1);
9677   }
9678 
9679   // Transform br(xor(x, y)) -> br(x != y)
9680   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9681   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9682     SDNode *TheXor = N1.getNode();
9683     SDValue Op0 = TheXor->getOperand(0);
9684     SDValue Op1 = TheXor->getOperand(1);
9685     if (Op0.getOpcode() == Op1.getOpcode()) {
9686       // Avoid missing important xor optimizations.
9687       if (SDValue Tmp = visitXOR(TheXor)) {
9688         if (Tmp.getNode() != TheXor) {
9689           DEBUG(dbgs() << "\nReplacing.8 ";
9690                 TheXor->dump(&DAG);
9691                 dbgs() << "\nWith: ";
9692                 Tmp.getNode()->dump(&DAG);
9693                 dbgs() << '\n');
9694           WorklistRemover DeadNodes(*this);
9695           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9696           deleteAndRecombine(TheXor);
9697           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9698                              MVT::Other, Chain, Tmp, N2);
9699         }
9700 
9701         // visitXOR has changed XOR's operands or replaced the XOR completely,
9702         // bail out.
9703         return SDValue(N, 0);
9704       }
9705     }
9706 
9707     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9708       bool Equal = false;
9709       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9710           Op0.getOpcode() == ISD::XOR) {
9711         TheXor = Op0.getNode();
9712         Equal = true;
9713       }
9714 
9715       EVT SetCCVT = N1.getValueType();
9716       if (LegalTypes)
9717         SetCCVT = getSetCCResultType(SetCCVT);
9718       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9719                                    SetCCVT,
9720                                    Op0, Op1,
9721                                    Equal ? ISD::SETEQ : ISD::SETNE);
9722       // Replace the uses of XOR with SETCC
9723       WorklistRemover DeadNodes(*this);
9724       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9725       deleteAndRecombine(N1.getNode());
9726       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9727                          MVT::Other, Chain, SetCC, N2);
9728     }
9729   }
9730 
9731   return SDValue();
9732 }
9733 
9734 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9735 //
9736 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9737   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9738   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9739 
9740   // If N is a constant we could fold this into a fallthrough or unconditional
9741   // branch. However that doesn't happen very often in normal code, because
9742   // Instcombine/SimplifyCFG should have handled the available opportunities.
9743   // If we did this folding here, it would be necessary to update the
9744   // MachineBasicBlock CFG, which is awkward.
9745 
9746   // Use SimplifySetCC to simplify SETCC's.
9747   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9748                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9749                                false);
9750   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9751 
9752   // fold to a simpler setcc
9753   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9754     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9755                        N->getOperand(0), Simp.getOperand(2),
9756                        Simp.getOperand(0), Simp.getOperand(1),
9757                        N->getOperand(4));
9758 
9759   return SDValue();
9760 }
9761 
9762 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9763 /// and that N may be folded in the load / store addressing mode.
9764 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9765                                     SelectionDAG &DAG,
9766                                     const TargetLowering &TLI) {
9767   EVT VT;
9768   unsigned AS;
9769 
9770   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9771     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9772       return false;
9773     VT = LD->getMemoryVT();
9774     AS = LD->getAddressSpace();
9775   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9776     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9777       return false;
9778     VT = ST->getMemoryVT();
9779     AS = ST->getAddressSpace();
9780   } else
9781     return false;
9782 
9783   TargetLowering::AddrMode AM;
9784   if (N->getOpcode() == ISD::ADD) {
9785     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9786     if (Offset)
9787       // [reg +/- imm]
9788       AM.BaseOffs = Offset->getSExtValue();
9789     else
9790       // [reg +/- reg]
9791       AM.Scale = 1;
9792   } else if (N->getOpcode() == ISD::SUB) {
9793     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9794     if (Offset)
9795       // [reg +/- imm]
9796       AM.BaseOffs = -Offset->getSExtValue();
9797     else
9798       // [reg +/- reg]
9799       AM.Scale = 1;
9800   } else
9801     return false;
9802 
9803   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9804                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9805 }
9806 
9807 /// Try turning a load/store into a pre-indexed load/store when the base
9808 /// pointer is an add or subtract and it has other uses besides the load/store.
9809 /// After the transformation, the new indexed load/store has effectively folded
9810 /// the add/subtract in and all of its other uses are redirected to the
9811 /// new load/store.
9812 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9813   if (Level < AfterLegalizeDAG)
9814     return false;
9815 
9816   bool isLoad = true;
9817   SDValue Ptr;
9818   EVT VT;
9819   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9820     if (LD->isIndexed())
9821       return false;
9822     VT = LD->getMemoryVT();
9823     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9824         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9825       return false;
9826     Ptr = LD->getBasePtr();
9827   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9828     if (ST->isIndexed())
9829       return false;
9830     VT = ST->getMemoryVT();
9831     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9832         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9833       return false;
9834     Ptr = ST->getBasePtr();
9835     isLoad = false;
9836   } else {
9837     return false;
9838   }
9839 
9840   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9841   // out.  There is no reason to make this a preinc/predec.
9842   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9843       Ptr.getNode()->hasOneUse())
9844     return false;
9845 
9846   // Ask the target to do addressing mode selection.
9847   SDValue BasePtr;
9848   SDValue Offset;
9849   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9850   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9851     return false;
9852 
9853   // Backends without true r+i pre-indexed forms may need to pass a
9854   // constant base with a variable offset so that constant coercion
9855   // will work with the patterns in canonical form.
9856   bool Swapped = false;
9857   if (isa<ConstantSDNode>(BasePtr)) {
9858     std::swap(BasePtr, Offset);
9859     Swapped = true;
9860   }
9861 
9862   // Don't create a indexed load / store with zero offset.
9863   if (isNullConstant(Offset))
9864     return false;
9865 
9866   // Try turning it into a pre-indexed load / store except when:
9867   // 1) The new base ptr is a frame index.
9868   // 2) If N is a store and the new base ptr is either the same as or is a
9869   //    predecessor of the value being stored.
9870   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9871   //    that would create a cycle.
9872   // 4) All uses are load / store ops that use it as old base ptr.
9873 
9874   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9875   // (plus the implicit offset) to a register to preinc anyway.
9876   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9877     return false;
9878 
9879   // Check #2.
9880   if (!isLoad) {
9881     SDValue Val = cast<StoreSDNode>(N)->getValue();
9882     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9883       return false;
9884   }
9885 
9886   // Caches for hasPredecessorHelper.
9887   SmallPtrSet<const SDNode *, 32> Visited;
9888   SmallVector<const SDNode *, 16> Worklist;
9889   Worklist.push_back(N);
9890 
9891   // If the offset is a constant, there may be other adds of constants that
9892   // can be folded with this one. We should do this to avoid having to keep
9893   // a copy of the original base pointer.
9894   SmallVector<SDNode *, 16> OtherUses;
9895   if (isa<ConstantSDNode>(Offset))
9896     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9897                               UE = BasePtr.getNode()->use_end();
9898          UI != UE; ++UI) {
9899       SDUse &Use = UI.getUse();
9900       // Skip the use that is Ptr and uses of other results from BasePtr's
9901       // node (important for nodes that return multiple results).
9902       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9903         continue;
9904 
9905       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9906         continue;
9907 
9908       if (Use.getUser()->getOpcode() != ISD::ADD &&
9909           Use.getUser()->getOpcode() != ISD::SUB) {
9910         OtherUses.clear();
9911         break;
9912       }
9913 
9914       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9915       if (!isa<ConstantSDNode>(Op1)) {
9916         OtherUses.clear();
9917         break;
9918       }
9919 
9920       // FIXME: In some cases, we can be smarter about this.
9921       if (Op1.getValueType() != Offset.getValueType()) {
9922         OtherUses.clear();
9923         break;
9924       }
9925 
9926       OtherUses.push_back(Use.getUser());
9927     }
9928 
9929   if (Swapped)
9930     std::swap(BasePtr, Offset);
9931 
9932   // Now check for #3 and #4.
9933   bool RealUse = false;
9934 
9935   for (SDNode *Use : Ptr.getNode()->uses()) {
9936     if (Use == N)
9937       continue;
9938     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9939       return false;
9940 
9941     // If Ptr may be folded in addressing mode of other use, then it's
9942     // not profitable to do this transformation.
9943     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9944       RealUse = true;
9945   }
9946 
9947   if (!RealUse)
9948     return false;
9949 
9950   SDValue Result;
9951   if (isLoad)
9952     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9953                                 BasePtr, Offset, AM);
9954   else
9955     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9956                                  BasePtr, Offset, AM);
9957   ++PreIndexedNodes;
9958   ++NodesCombined;
9959   DEBUG(dbgs() << "\nReplacing.4 ";
9960         N->dump(&DAG);
9961         dbgs() << "\nWith: ";
9962         Result.getNode()->dump(&DAG);
9963         dbgs() << '\n');
9964   WorklistRemover DeadNodes(*this);
9965   if (isLoad) {
9966     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9967     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9968   } else {
9969     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9970   }
9971 
9972   // Finally, since the node is now dead, remove it from the graph.
9973   deleteAndRecombine(N);
9974 
9975   if (Swapped)
9976     std::swap(BasePtr, Offset);
9977 
9978   // Replace other uses of BasePtr that can be updated to use Ptr
9979   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9980     unsigned OffsetIdx = 1;
9981     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9982       OffsetIdx = 0;
9983     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9984            BasePtr.getNode() && "Expected BasePtr operand");
9985 
9986     // We need to replace ptr0 in the following expression:
9987     //   x0 * offset0 + y0 * ptr0 = t0
9988     // knowing that
9989     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9990     //
9991     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9992     // indexed load/store and the expresion that needs to be re-written.
9993     //
9994     // Therefore, we have:
9995     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9996 
9997     ConstantSDNode *CN =
9998       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9999     int X0, X1, Y0, Y1;
10000     const APInt &Offset0 = CN->getAPIntValue();
10001     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10002 
10003     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10004     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10005     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10006     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10007 
10008     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10009 
10010     APInt CNV = Offset0;
10011     if (X0 < 0) CNV = -CNV;
10012     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10013     else CNV = CNV - Offset1;
10014 
10015     SDLoc DL(OtherUses[i]);
10016 
10017     // We can now generate the new expression.
10018     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10019     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10020 
10021     SDValue NewUse = DAG.getNode(Opcode,
10022                                  DL,
10023                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10024     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10025     deleteAndRecombine(OtherUses[i]);
10026   }
10027 
10028   // Replace the uses of Ptr with uses of the updated base value.
10029   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10030   deleteAndRecombine(Ptr.getNode());
10031 
10032   return true;
10033 }
10034 
10035 /// Try to combine a load/store with a add/sub of the base pointer node into a
10036 /// post-indexed load/store. The transformation folded the add/subtract into the
10037 /// new indexed load/store effectively and all of its uses are redirected to the
10038 /// new load/store.
10039 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10040   if (Level < AfterLegalizeDAG)
10041     return false;
10042 
10043   bool isLoad = true;
10044   SDValue Ptr;
10045   EVT VT;
10046   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10047     if (LD->isIndexed())
10048       return false;
10049     VT = LD->getMemoryVT();
10050     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10051         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10052       return false;
10053     Ptr = LD->getBasePtr();
10054   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10055     if (ST->isIndexed())
10056       return false;
10057     VT = ST->getMemoryVT();
10058     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10059         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10060       return false;
10061     Ptr = ST->getBasePtr();
10062     isLoad = false;
10063   } else {
10064     return false;
10065   }
10066 
10067   if (Ptr.getNode()->hasOneUse())
10068     return false;
10069 
10070   for (SDNode *Op : Ptr.getNode()->uses()) {
10071     if (Op == N ||
10072         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10073       continue;
10074 
10075     SDValue BasePtr;
10076     SDValue Offset;
10077     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10078     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10079       // Don't create a indexed load / store with zero offset.
10080       if (isNullConstant(Offset))
10081         continue;
10082 
10083       // Try turning it into a post-indexed load / store except when
10084       // 1) All uses are load / store ops that use it as base ptr (and
10085       //    it may be folded as addressing mmode).
10086       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10087       //    nor a successor of N. Otherwise, if Op is folded that would
10088       //    create a cycle.
10089 
10090       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10091         continue;
10092 
10093       // Check for #1.
10094       bool TryNext = false;
10095       for (SDNode *Use : BasePtr.getNode()->uses()) {
10096         if (Use == Ptr.getNode())
10097           continue;
10098 
10099         // If all the uses are load / store addresses, then don't do the
10100         // transformation.
10101         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10102           bool RealUse = false;
10103           for (SDNode *UseUse : Use->uses()) {
10104             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10105               RealUse = true;
10106           }
10107 
10108           if (!RealUse) {
10109             TryNext = true;
10110             break;
10111           }
10112         }
10113       }
10114 
10115       if (TryNext)
10116         continue;
10117 
10118       // Check for #2
10119       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10120         SDValue Result = isLoad
10121           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10122                                BasePtr, Offset, AM)
10123           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10124                                 BasePtr, Offset, AM);
10125         ++PostIndexedNodes;
10126         ++NodesCombined;
10127         DEBUG(dbgs() << "\nReplacing.5 ";
10128               N->dump(&DAG);
10129               dbgs() << "\nWith: ";
10130               Result.getNode()->dump(&DAG);
10131               dbgs() << '\n');
10132         WorklistRemover DeadNodes(*this);
10133         if (isLoad) {
10134           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10135           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10136         } else {
10137           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10138         }
10139 
10140         // Finally, since the node is now dead, remove it from the graph.
10141         deleteAndRecombine(N);
10142 
10143         // Replace the uses of Use with uses of the updated base value.
10144         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10145                                       Result.getValue(isLoad ? 1 : 0));
10146         deleteAndRecombine(Op);
10147         return true;
10148       }
10149     }
10150   }
10151 
10152   return false;
10153 }
10154 
10155 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10156 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10157   ISD::MemIndexedMode AM = LD->getAddressingMode();
10158   assert(AM != ISD::UNINDEXED);
10159   SDValue BP = LD->getOperand(1);
10160   SDValue Inc = LD->getOperand(2);
10161 
10162   // Some backends use TargetConstants for load offsets, but don't expect
10163   // TargetConstants in general ADD nodes. We can convert these constants into
10164   // regular Constants (if the constant is not opaque).
10165   assert((Inc.getOpcode() != ISD::TargetConstant ||
10166           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10167          "Cannot split out indexing using opaque target constants");
10168   if (Inc.getOpcode() == ISD::TargetConstant) {
10169     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10170     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10171                           ConstInc->getValueType(0));
10172   }
10173 
10174   unsigned Opc =
10175       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10176   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10177 }
10178 
10179 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10180   LoadSDNode *LD  = cast<LoadSDNode>(N);
10181   SDValue Chain = LD->getChain();
10182   SDValue Ptr   = LD->getBasePtr();
10183 
10184   // If load is not volatile and there are no uses of the loaded value (and
10185   // the updated indexed value in case of indexed loads), change uses of the
10186   // chain value into uses of the chain input (i.e. delete the dead load).
10187   if (!LD->isVolatile()) {
10188     if (N->getValueType(1) == MVT::Other) {
10189       // Unindexed loads.
10190       if (!N->hasAnyUseOfValue(0)) {
10191         // It's not safe to use the two value CombineTo variant here. e.g.
10192         // v1, chain2 = load chain1, loc
10193         // v2, chain3 = load chain2, loc
10194         // v3         = add v2, c
10195         // Now we replace use of chain2 with chain1.  This makes the second load
10196         // isomorphic to the one we are deleting, and thus makes this load live.
10197         DEBUG(dbgs() << "\nReplacing.6 ";
10198               N->dump(&DAG);
10199               dbgs() << "\nWith chain: ";
10200               Chain.getNode()->dump(&DAG);
10201               dbgs() << "\n");
10202         WorklistRemover DeadNodes(*this);
10203         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10204 
10205         if (N->use_empty())
10206           deleteAndRecombine(N);
10207 
10208         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10209       }
10210     } else {
10211       // Indexed loads.
10212       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10213 
10214       // If this load has an opaque TargetConstant offset, then we cannot split
10215       // the indexing into an add/sub directly (that TargetConstant may not be
10216       // valid for a different type of node, and we cannot convert an opaque
10217       // target constant into a regular constant).
10218       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10219                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10220 
10221       if (!N->hasAnyUseOfValue(0) &&
10222           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10223         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10224         SDValue Index;
10225         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10226           Index = SplitIndexingFromLoad(LD);
10227           // Try to fold the base pointer arithmetic into subsequent loads and
10228           // stores.
10229           AddUsersToWorklist(N);
10230         } else
10231           Index = DAG.getUNDEF(N->getValueType(1));
10232         DEBUG(dbgs() << "\nReplacing.7 ";
10233               N->dump(&DAG);
10234               dbgs() << "\nWith: ";
10235               Undef.getNode()->dump(&DAG);
10236               dbgs() << " and 2 other values\n");
10237         WorklistRemover DeadNodes(*this);
10238         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10239         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10240         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10241         deleteAndRecombine(N);
10242         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10243       }
10244     }
10245   }
10246 
10247   // If this load is directly stored, replace the load value with the stored
10248   // value.
10249   // TODO: Handle store large -> read small portion.
10250   // TODO: Handle TRUNCSTORE/LOADEXT
10251   if (OptLevel != CodeGenOpt::None &&
10252       ISD::isNormalLoad(N) && !LD->isVolatile()) {
10253     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10254       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10255       if (PrevST->getBasePtr() == Ptr &&
10256           PrevST->getValue().getValueType() == N->getValueType(0))
10257       return CombineTo(N, Chain.getOperand(1), Chain);
10258     }
10259   }
10260 
10261   // Try to infer better alignment information than the load already has.
10262   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10263     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10264       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10265         SDValue NewLoad = DAG.getExtLoad(
10266             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10267             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10268             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10269         if (NewLoad.getNode() != N)
10270           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10271       }
10272     }
10273   }
10274 
10275   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10276                                                   : DAG.getSubtarget().useAA();
10277 #ifndef NDEBUG
10278   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10279       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10280     UseAA = false;
10281 #endif
10282   if (UseAA && LD->isUnindexed()) {
10283     // Walk up chain skipping non-aliasing memory nodes.
10284     SDValue BetterChain = FindBetterChain(N, Chain);
10285 
10286     // If there is a better chain.
10287     if (Chain != BetterChain) {
10288       SDValue ReplLoad;
10289 
10290       // Replace the chain to void dependency.
10291       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10292         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10293                                BetterChain, Ptr, LD->getMemOperand());
10294       } else {
10295         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10296                                   LD->getValueType(0),
10297                                   BetterChain, Ptr, LD->getMemoryVT(),
10298                                   LD->getMemOperand());
10299       }
10300 
10301       // Create token factor to keep old chain connected.
10302       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10303                                   MVT::Other, Chain, ReplLoad.getValue(1));
10304 
10305       // Make sure the new and old chains are cleaned up.
10306       AddToWorklist(Token.getNode());
10307 
10308       // Replace uses with load result and token factor. Don't add users
10309       // to work list.
10310       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10311     }
10312   }
10313 
10314   // Try transforming N to an indexed load.
10315   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10316     return SDValue(N, 0);
10317 
10318   // Try to slice up N to more direct loads if the slices are mapped to
10319   // different register banks or pairing can take place.
10320   if (SliceUpLoad(N))
10321     return SDValue(N, 0);
10322 
10323   return SDValue();
10324 }
10325 
10326 namespace {
10327 /// \brief Helper structure used to slice a load in smaller loads.
10328 /// Basically a slice is obtained from the following sequence:
10329 /// Origin = load Ty1, Base
10330 /// Shift = srl Ty1 Origin, CstTy Amount
10331 /// Inst = trunc Shift to Ty2
10332 ///
10333 /// Then, it will be rewriten into:
10334 /// Slice = load SliceTy, Base + SliceOffset
10335 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10336 ///
10337 /// SliceTy is deduced from the number of bits that are actually used to
10338 /// build Inst.
10339 struct LoadedSlice {
10340   /// \brief Helper structure used to compute the cost of a slice.
10341   struct Cost {
10342     /// Are we optimizing for code size.
10343     bool ForCodeSize;
10344     /// Various cost.
10345     unsigned Loads;
10346     unsigned Truncates;
10347     unsigned CrossRegisterBanksCopies;
10348     unsigned ZExts;
10349     unsigned Shift;
10350 
10351     Cost(bool ForCodeSize = false)
10352         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10353           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10354 
10355     /// \brief Get the cost of one isolated slice.
10356     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10357         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10358           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10359       EVT TruncType = LS.Inst->getValueType(0);
10360       EVT LoadedType = LS.getLoadedType();
10361       if (TruncType != LoadedType &&
10362           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10363         ZExts = 1;
10364     }
10365 
10366     /// \brief Account for slicing gain in the current cost.
10367     /// Slicing provide a few gains like removing a shift or a
10368     /// truncate. This method allows to grow the cost of the original
10369     /// load with the gain from this slice.
10370     void addSliceGain(const LoadedSlice &LS) {
10371       // Each slice saves a truncate.
10372       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10373       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10374                               LS.Inst->getValueType(0)))
10375         ++Truncates;
10376       // If there is a shift amount, this slice gets rid of it.
10377       if (LS.Shift)
10378         ++Shift;
10379       // If this slice can merge a cross register bank copy, account for it.
10380       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10381         ++CrossRegisterBanksCopies;
10382     }
10383 
10384     Cost &operator+=(const Cost &RHS) {
10385       Loads += RHS.Loads;
10386       Truncates += RHS.Truncates;
10387       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10388       ZExts += RHS.ZExts;
10389       Shift += RHS.Shift;
10390       return *this;
10391     }
10392 
10393     bool operator==(const Cost &RHS) const {
10394       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10395              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10396              ZExts == RHS.ZExts && Shift == RHS.Shift;
10397     }
10398 
10399     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10400 
10401     bool operator<(const Cost &RHS) const {
10402       // Assume cross register banks copies are as expensive as loads.
10403       // FIXME: Do we want some more target hooks?
10404       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10405       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10406       // Unless we are optimizing for code size, consider the
10407       // expensive operation first.
10408       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10409         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10410       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10411              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10412     }
10413 
10414     bool operator>(const Cost &RHS) const { return RHS < *this; }
10415 
10416     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10417 
10418     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10419   };
10420   // The last instruction that represent the slice. This should be a
10421   // truncate instruction.
10422   SDNode *Inst;
10423   // The original load instruction.
10424   LoadSDNode *Origin;
10425   // The right shift amount in bits from the original load.
10426   unsigned Shift;
10427   // The DAG from which Origin came from.
10428   // This is used to get some contextual information about legal types, etc.
10429   SelectionDAG *DAG;
10430 
10431   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10432               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10433       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10434 
10435   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10436   /// \return Result is \p BitWidth and has used bits set to 1 and
10437   ///         not used bits set to 0.
10438   APInt getUsedBits() const {
10439     // Reproduce the trunc(lshr) sequence:
10440     // - Start from the truncated value.
10441     // - Zero extend to the desired bit width.
10442     // - Shift left.
10443     assert(Origin && "No original load to compare against.");
10444     unsigned BitWidth = Origin->getValueSizeInBits(0);
10445     assert(Inst && "This slice is not bound to an instruction");
10446     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10447            "Extracted slice is bigger than the whole type!");
10448     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10449     UsedBits.setAllBits();
10450     UsedBits = UsedBits.zext(BitWidth);
10451     UsedBits <<= Shift;
10452     return UsedBits;
10453   }
10454 
10455   /// \brief Get the size of the slice to be loaded in bytes.
10456   unsigned getLoadedSize() const {
10457     unsigned SliceSize = getUsedBits().countPopulation();
10458     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10459     return SliceSize / 8;
10460   }
10461 
10462   /// \brief Get the type that will be loaded for this slice.
10463   /// Note: This may not be the final type for the slice.
10464   EVT getLoadedType() const {
10465     assert(DAG && "Missing context");
10466     LLVMContext &Ctxt = *DAG->getContext();
10467     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10468   }
10469 
10470   /// \brief Get the alignment of the load used for this slice.
10471   unsigned getAlignment() const {
10472     unsigned Alignment = Origin->getAlignment();
10473     unsigned Offset = getOffsetFromBase();
10474     if (Offset != 0)
10475       Alignment = MinAlign(Alignment, Alignment + Offset);
10476     return Alignment;
10477   }
10478 
10479   /// \brief Check if this slice can be rewritten with legal operations.
10480   bool isLegal() const {
10481     // An invalid slice is not legal.
10482     if (!Origin || !Inst || !DAG)
10483       return false;
10484 
10485     // Offsets are for indexed load only, we do not handle that.
10486     if (!Origin->getOffset().isUndef())
10487       return false;
10488 
10489     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10490 
10491     // Check that the type is legal.
10492     EVT SliceType = getLoadedType();
10493     if (!TLI.isTypeLegal(SliceType))
10494       return false;
10495 
10496     // Check that the load is legal for this type.
10497     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10498       return false;
10499 
10500     // Check that the offset can be computed.
10501     // 1. Check its type.
10502     EVT PtrType = Origin->getBasePtr().getValueType();
10503     if (PtrType == MVT::Untyped || PtrType.isExtended())
10504       return false;
10505 
10506     // 2. Check that it fits in the immediate.
10507     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10508       return false;
10509 
10510     // 3. Check that the computation is legal.
10511     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10512       return false;
10513 
10514     // Check that the zext is legal if it needs one.
10515     EVT TruncateType = Inst->getValueType(0);
10516     if (TruncateType != SliceType &&
10517         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10518       return false;
10519 
10520     return true;
10521   }
10522 
10523   /// \brief Get the offset in bytes of this slice in the original chunk of
10524   /// bits.
10525   /// \pre DAG != nullptr.
10526   uint64_t getOffsetFromBase() const {
10527     assert(DAG && "Missing context.");
10528     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10529     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10530     uint64_t Offset = Shift / 8;
10531     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10532     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10533            "The size of the original loaded type is not a multiple of a"
10534            " byte.");
10535     // If Offset is bigger than TySizeInBytes, it means we are loading all
10536     // zeros. This should have been optimized before in the process.
10537     assert(TySizeInBytes > Offset &&
10538            "Invalid shift amount for given loaded size");
10539     if (IsBigEndian)
10540       Offset = TySizeInBytes - Offset - getLoadedSize();
10541     return Offset;
10542   }
10543 
10544   /// \brief Generate the sequence of instructions to load the slice
10545   /// represented by this object and redirect the uses of this slice to
10546   /// this new sequence of instructions.
10547   /// \pre this->Inst && this->Origin are valid Instructions and this
10548   /// object passed the legal check: LoadedSlice::isLegal returned true.
10549   /// \return The last instruction of the sequence used to load the slice.
10550   SDValue loadSlice() const {
10551     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10552     const SDValue &OldBaseAddr = Origin->getBasePtr();
10553     SDValue BaseAddr = OldBaseAddr;
10554     // Get the offset in that chunk of bytes w.r.t. the endianess.
10555     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10556     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10557     if (Offset) {
10558       // BaseAddr = BaseAddr + Offset.
10559       EVT ArithType = BaseAddr.getValueType();
10560       SDLoc DL(Origin);
10561       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10562                               DAG->getConstant(Offset, DL, ArithType));
10563     }
10564 
10565     // Create the type of the loaded slice according to its size.
10566     EVT SliceType = getLoadedType();
10567 
10568     // Create the load for the slice.
10569     SDValue LastInst =
10570         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10571                      Origin->getPointerInfo().getWithOffset(Offset),
10572                      getAlignment(), Origin->getMemOperand()->getFlags());
10573     // If the final type is not the same as the loaded type, this means that
10574     // we have to pad with zero. Create a zero extend for that.
10575     EVT FinalType = Inst->getValueType(0);
10576     if (SliceType != FinalType)
10577       LastInst =
10578           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10579     return LastInst;
10580   }
10581 
10582   /// \brief Check if this slice can be merged with an expensive cross register
10583   /// bank copy. E.g.,
10584   /// i = load i32
10585   /// f = bitcast i32 i to float
10586   bool canMergeExpensiveCrossRegisterBankCopy() const {
10587     if (!Inst || !Inst->hasOneUse())
10588       return false;
10589     SDNode *Use = *Inst->use_begin();
10590     if (Use->getOpcode() != ISD::BITCAST)
10591       return false;
10592     assert(DAG && "Missing context");
10593     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10594     EVT ResVT = Use->getValueType(0);
10595     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10596     const TargetRegisterClass *ArgRC =
10597         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10598     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10599       return false;
10600 
10601     // At this point, we know that we perform a cross-register-bank copy.
10602     // Check if it is expensive.
10603     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10604     // Assume bitcasts are cheap, unless both register classes do not
10605     // explicitly share a common sub class.
10606     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10607       return false;
10608 
10609     // Check if it will be merged with the load.
10610     // 1. Check the alignment constraint.
10611     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10612         ResVT.getTypeForEVT(*DAG->getContext()));
10613 
10614     if (RequiredAlignment > getAlignment())
10615       return false;
10616 
10617     // 2. Check that the load is a legal operation for that type.
10618     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10619       return false;
10620 
10621     // 3. Check that we do not have a zext in the way.
10622     if (Inst->getValueType(0) != getLoadedType())
10623       return false;
10624 
10625     return true;
10626   }
10627 };
10628 }
10629 
10630 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10631 /// \p UsedBits looks like 0..0 1..1 0..0.
10632 static bool areUsedBitsDense(const APInt &UsedBits) {
10633   // If all the bits are one, this is dense!
10634   if (UsedBits.isAllOnesValue())
10635     return true;
10636 
10637   // Get rid of the unused bits on the right.
10638   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10639   // Get rid of the unused bits on the left.
10640   if (NarrowedUsedBits.countLeadingZeros())
10641     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10642   // Check that the chunk of bits is completely used.
10643   return NarrowedUsedBits.isAllOnesValue();
10644 }
10645 
10646 /// \brief Check whether or not \p First and \p Second are next to each other
10647 /// in memory. This means that there is no hole between the bits loaded
10648 /// by \p First and the bits loaded by \p Second.
10649 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10650                                      const LoadedSlice &Second) {
10651   assert(First.Origin == Second.Origin && First.Origin &&
10652          "Unable to match different memory origins.");
10653   APInt UsedBits = First.getUsedBits();
10654   assert((UsedBits & Second.getUsedBits()) == 0 &&
10655          "Slices are not supposed to overlap.");
10656   UsedBits |= Second.getUsedBits();
10657   return areUsedBitsDense(UsedBits);
10658 }
10659 
10660 /// \brief Adjust the \p GlobalLSCost according to the target
10661 /// paring capabilities and the layout of the slices.
10662 /// \pre \p GlobalLSCost should account for at least as many loads as
10663 /// there is in the slices in \p LoadedSlices.
10664 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10665                                  LoadedSlice::Cost &GlobalLSCost) {
10666   unsigned NumberOfSlices = LoadedSlices.size();
10667   // If there is less than 2 elements, no pairing is possible.
10668   if (NumberOfSlices < 2)
10669     return;
10670 
10671   // Sort the slices so that elements that are likely to be next to each
10672   // other in memory are next to each other in the list.
10673   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10674             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10675     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10676     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10677   });
10678   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10679   // First (resp. Second) is the first (resp. Second) potentially candidate
10680   // to be placed in a paired load.
10681   const LoadedSlice *First = nullptr;
10682   const LoadedSlice *Second = nullptr;
10683   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10684                 // Set the beginning of the pair.
10685                                                            First = Second) {
10686 
10687     Second = &LoadedSlices[CurrSlice];
10688 
10689     // If First is NULL, it means we start a new pair.
10690     // Get to the next slice.
10691     if (!First)
10692       continue;
10693 
10694     EVT LoadedType = First->getLoadedType();
10695 
10696     // If the types of the slices are different, we cannot pair them.
10697     if (LoadedType != Second->getLoadedType())
10698       continue;
10699 
10700     // Check if the target supplies paired loads for this type.
10701     unsigned RequiredAlignment = 0;
10702     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10703       // move to the next pair, this type is hopeless.
10704       Second = nullptr;
10705       continue;
10706     }
10707     // Check if we meet the alignment requirement.
10708     if (RequiredAlignment > First->getAlignment())
10709       continue;
10710 
10711     // Check that both loads are next to each other in memory.
10712     if (!areSlicesNextToEachOther(*First, *Second))
10713       continue;
10714 
10715     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10716     --GlobalLSCost.Loads;
10717     // Move to the next pair.
10718     Second = nullptr;
10719   }
10720 }
10721 
10722 /// \brief Check the profitability of all involved LoadedSlice.
10723 /// Currently, it is considered profitable if there is exactly two
10724 /// involved slices (1) which are (2) next to each other in memory, and
10725 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10726 ///
10727 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10728 /// the elements themselves.
10729 ///
10730 /// FIXME: When the cost model will be mature enough, we can relax
10731 /// constraints (1) and (2).
10732 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10733                                 const APInt &UsedBits, bool ForCodeSize) {
10734   unsigned NumberOfSlices = LoadedSlices.size();
10735   if (StressLoadSlicing)
10736     return NumberOfSlices > 1;
10737 
10738   // Check (1).
10739   if (NumberOfSlices != 2)
10740     return false;
10741 
10742   // Check (2).
10743   if (!areUsedBitsDense(UsedBits))
10744     return false;
10745 
10746   // Check (3).
10747   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10748   // The original code has one big load.
10749   OrigCost.Loads = 1;
10750   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10751     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10752     // Accumulate the cost of all the slices.
10753     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10754     GlobalSlicingCost += SliceCost;
10755 
10756     // Account as cost in the original configuration the gain obtained
10757     // with the current slices.
10758     OrigCost.addSliceGain(LS);
10759   }
10760 
10761   // If the target supports paired load, adjust the cost accordingly.
10762   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10763   return OrigCost > GlobalSlicingCost;
10764 }
10765 
10766 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10767 /// operations, split it in the various pieces being extracted.
10768 ///
10769 /// This sort of thing is introduced by SROA.
10770 /// This slicing takes care not to insert overlapping loads.
10771 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10772 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10773   if (Level < AfterLegalizeDAG)
10774     return false;
10775 
10776   LoadSDNode *LD = cast<LoadSDNode>(N);
10777   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10778       !LD->getValueType(0).isInteger())
10779     return false;
10780 
10781   // Keep track of already used bits to detect overlapping values.
10782   // In that case, we will just abort the transformation.
10783   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10784 
10785   SmallVector<LoadedSlice, 4> LoadedSlices;
10786 
10787   // Check if this load is used as several smaller chunks of bits.
10788   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10789   // of computation for each trunc.
10790   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10791        UI != UIEnd; ++UI) {
10792     // Skip the uses of the chain.
10793     if (UI.getUse().getResNo() != 0)
10794       continue;
10795 
10796     SDNode *User = *UI;
10797     unsigned Shift = 0;
10798 
10799     // Check if this is a trunc(lshr).
10800     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10801         isa<ConstantSDNode>(User->getOperand(1))) {
10802       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10803       User = *User->use_begin();
10804     }
10805 
10806     // At this point, User is a Truncate, iff we encountered, trunc or
10807     // trunc(lshr).
10808     if (User->getOpcode() != ISD::TRUNCATE)
10809       return false;
10810 
10811     // The width of the type must be a power of 2 and greater than 8-bits.
10812     // Otherwise the load cannot be represented in LLVM IR.
10813     // Moreover, if we shifted with a non-8-bits multiple, the slice
10814     // will be across several bytes. We do not support that.
10815     unsigned Width = User->getValueSizeInBits(0);
10816     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10817       return 0;
10818 
10819     // Build the slice for this chain of computations.
10820     LoadedSlice LS(User, LD, Shift, &DAG);
10821     APInt CurrentUsedBits = LS.getUsedBits();
10822 
10823     // Check if this slice overlaps with another.
10824     if ((CurrentUsedBits & UsedBits) != 0)
10825       return false;
10826     // Update the bits used globally.
10827     UsedBits |= CurrentUsedBits;
10828 
10829     // Check if the new slice would be legal.
10830     if (!LS.isLegal())
10831       return false;
10832 
10833     // Record the slice.
10834     LoadedSlices.push_back(LS);
10835   }
10836 
10837   // Abort slicing if it does not seem to be profitable.
10838   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10839     return false;
10840 
10841   ++SlicedLoads;
10842 
10843   // Rewrite each chain to use an independent load.
10844   // By construction, each chain can be represented by a unique load.
10845 
10846   // Prepare the argument for the new token factor for all the slices.
10847   SmallVector<SDValue, 8> ArgChains;
10848   for (SmallVectorImpl<LoadedSlice>::const_iterator
10849            LSIt = LoadedSlices.begin(),
10850            LSItEnd = LoadedSlices.end();
10851        LSIt != LSItEnd; ++LSIt) {
10852     SDValue SliceInst = LSIt->loadSlice();
10853     CombineTo(LSIt->Inst, SliceInst, true);
10854     if (SliceInst.getOpcode() != ISD::LOAD)
10855       SliceInst = SliceInst.getOperand(0);
10856     assert(SliceInst->getOpcode() == ISD::LOAD &&
10857            "It takes more than a zext to get to the loaded slice!!");
10858     ArgChains.push_back(SliceInst.getValue(1));
10859   }
10860 
10861   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10862                               ArgChains);
10863   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10864   return true;
10865 }
10866 
10867 /// Check to see if V is (and load (ptr), imm), where the load is having
10868 /// specific bytes cleared out.  If so, return the byte size being masked out
10869 /// and the shift amount.
10870 static std::pair<unsigned, unsigned>
10871 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10872   std::pair<unsigned, unsigned> Result(0, 0);
10873 
10874   // Check for the structure we're looking for.
10875   if (V->getOpcode() != ISD::AND ||
10876       !isa<ConstantSDNode>(V->getOperand(1)) ||
10877       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10878     return Result;
10879 
10880   // Check the chain and pointer.
10881   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10882   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10883 
10884   // The store should be chained directly to the load or be an operand of a
10885   // tokenfactor.
10886   if (LD == Chain.getNode())
10887     ; // ok.
10888   else if (Chain->getOpcode() != ISD::TokenFactor)
10889     return Result; // Fail.
10890   else {
10891     bool isOk = false;
10892     for (const SDValue &ChainOp : Chain->op_values())
10893       if (ChainOp.getNode() == LD) {
10894         isOk = true;
10895         break;
10896       }
10897     if (!isOk) return Result;
10898   }
10899 
10900   // This only handles simple types.
10901   if (V.getValueType() != MVT::i16 &&
10902       V.getValueType() != MVT::i32 &&
10903       V.getValueType() != MVT::i64)
10904     return Result;
10905 
10906   // Check the constant mask.  Invert it so that the bits being masked out are
10907   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10908   // follow the sign bit for uniformity.
10909   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10910   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10911   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10912   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10913   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10914   if (NotMaskLZ == 64) return Result;  // All zero mask.
10915 
10916   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10917   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10918     return Result;
10919 
10920   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10921   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10922     NotMaskLZ -= 64-V.getValueSizeInBits();
10923 
10924   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10925   switch (MaskedBytes) {
10926   case 1:
10927   case 2:
10928   case 4: break;
10929   default: return Result; // All one mask, or 5-byte mask.
10930   }
10931 
10932   // Verify that the first bit starts at a multiple of mask so that the access
10933   // is aligned the same as the access width.
10934   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10935 
10936   Result.first = MaskedBytes;
10937   Result.second = NotMaskTZ/8;
10938   return Result;
10939 }
10940 
10941 
10942 /// Check to see if IVal is something that provides a value as specified by
10943 /// MaskInfo. If so, replace the specified store with a narrower store of
10944 /// truncated IVal.
10945 static SDNode *
10946 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10947                                 SDValue IVal, StoreSDNode *St,
10948                                 DAGCombiner *DC) {
10949   unsigned NumBytes = MaskInfo.first;
10950   unsigned ByteShift = MaskInfo.second;
10951   SelectionDAG &DAG = DC->getDAG();
10952 
10953   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10954   // that uses this.  If not, this is not a replacement.
10955   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10956                                   ByteShift*8, (ByteShift+NumBytes)*8);
10957   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10958 
10959   // Check that it is legal on the target to do this.  It is legal if the new
10960   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10961   // legalization.
10962   MVT VT = MVT::getIntegerVT(NumBytes*8);
10963   if (!DC->isTypeLegal(VT))
10964     return nullptr;
10965 
10966   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10967   // shifted by ByteShift and truncated down to NumBytes.
10968   if (ByteShift) {
10969     SDLoc DL(IVal);
10970     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10971                        DAG.getConstant(ByteShift*8, DL,
10972                                     DC->getShiftAmountTy(IVal.getValueType())));
10973   }
10974 
10975   // Figure out the offset for the store and the alignment of the access.
10976   unsigned StOffset;
10977   unsigned NewAlign = St->getAlignment();
10978 
10979   if (DAG.getDataLayout().isLittleEndian())
10980     StOffset = ByteShift;
10981   else
10982     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10983 
10984   SDValue Ptr = St->getBasePtr();
10985   if (StOffset) {
10986     SDLoc DL(IVal);
10987     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10988                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10989     NewAlign = MinAlign(NewAlign, StOffset);
10990   }
10991 
10992   // Truncate down to the new size.
10993   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10994 
10995   ++OpsNarrowed;
10996   return DAG
10997       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10998                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
10999       .getNode();
11000 }
11001 
11002 
11003 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11004 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11005 /// narrowing the load and store if it would end up being a win for performance
11006 /// or code size.
11007 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11008   StoreSDNode *ST  = cast<StoreSDNode>(N);
11009   if (ST->isVolatile())
11010     return SDValue();
11011 
11012   SDValue Chain = ST->getChain();
11013   SDValue Value = ST->getValue();
11014   SDValue Ptr   = ST->getBasePtr();
11015   EVT VT = Value.getValueType();
11016 
11017   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11018     return SDValue();
11019 
11020   unsigned Opc = Value.getOpcode();
11021 
11022   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11023   // is a byte mask indicating a consecutive number of bytes, check to see if
11024   // Y is known to provide just those bytes.  If so, we try to replace the
11025   // load + replace + store sequence with a single (narrower) store, which makes
11026   // the load dead.
11027   if (Opc == ISD::OR) {
11028     std::pair<unsigned, unsigned> MaskedLoad;
11029     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11030     if (MaskedLoad.first)
11031       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11032                                                   Value.getOperand(1), ST,this))
11033         return SDValue(NewST, 0);
11034 
11035     // Or is commutative, so try swapping X and Y.
11036     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11037     if (MaskedLoad.first)
11038       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11039                                                   Value.getOperand(0), ST,this))
11040         return SDValue(NewST, 0);
11041   }
11042 
11043   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11044       Value.getOperand(1).getOpcode() != ISD::Constant)
11045     return SDValue();
11046 
11047   SDValue N0 = Value.getOperand(0);
11048   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11049       Chain == SDValue(N0.getNode(), 1)) {
11050     LoadSDNode *LD = cast<LoadSDNode>(N0);
11051     if (LD->getBasePtr() != Ptr ||
11052         LD->getPointerInfo().getAddrSpace() !=
11053         ST->getPointerInfo().getAddrSpace())
11054       return SDValue();
11055 
11056     // Find the type to narrow it the load / op / store to.
11057     SDValue N1 = Value.getOperand(1);
11058     unsigned BitWidth = N1.getValueSizeInBits();
11059     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11060     if (Opc == ISD::AND)
11061       Imm ^= APInt::getAllOnesValue(BitWidth);
11062     if (Imm == 0 || Imm.isAllOnesValue())
11063       return SDValue();
11064     unsigned ShAmt = Imm.countTrailingZeros();
11065     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11066     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11067     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11068     // The narrowing should be profitable, the load/store operation should be
11069     // legal (or custom) and the store size should be equal to the NewVT width.
11070     while (NewBW < BitWidth &&
11071            (NewVT.getStoreSizeInBits() != NewBW ||
11072             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11073             !TLI.isNarrowingProfitable(VT, NewVT))) {
11074       NewBW = NextPowerOf2(NewBW);
11075       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11076     }
11077     if (NewBW >= BitWidth)
11078       return SDValue();
11079 
11080     // If the lsb changed does not start at the type bitwidth boundary,
11081     // start at the previous one.
11082     if (ShAmt % NewBW)
11083       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11084     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11085                                    std::min(BitWidth, ShAmt + NewBW));
11086     if ((Imm & Mask) == Imm) {
11087       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11088       if (Opc == ISD::AND)
11089         NewImm ^= APInt::getAllOnesValue(NewBW);
11090       uint64_t PtrOff = ShAmt / 8;
11091       // For big endian targets, we need to adjust the offset to the pointer to
11092       // load the correct bytes.
11093       if (DAG.getDataLayout().isBigEndian())
11094         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11095 
11096       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11097       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11098       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11099         return SDValue();
11100 
11101       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11102                                    Ptr.getValueType(), Ptr,
11103                                    DAG.getConstant(PtrOff, SDLoc(LD),
11104                                                    Ptr.getValueType()));
11105       SDValue NewLD =
11106           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11107                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11108                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11109       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11110                                    DAG.getConstant(NewImm, SDLoc(Value),
11111                                                    NewVT));
11112       SDValue NewST =
11113           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11114                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11115 
11116       AddToWorklist(NewPtr.getNode());
11117       AddToWorklist(NewLD.getNode());
11118       AddToWorklist(NewVal.getNode());
11119       WorklistRemover DeadNodes(*this);
11120       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11121       ++OpsNarrowed;
11122       return NewST;
11123     }
11124   }
11125 
11126   return SDValue();
11127 }
11128 
11129 /// For a given floating point load / store pair, if the load value isn't used
11130 /// by any other operations, then consider transforming the pair to integer
11131 /// load / store operations if the target deems the transformation profitable.
11132 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11133   StoreSDNode *ST  = cast<StoreSDNode>(N);
11134   SDValue Chain = ST->getChain();
11135   SDValue Value = ST->getValue();
11136   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11137       Value.hasOneUse() &&
11138       Chain == SDValue(Value.getNode(), 1)) {
11139     LoadSDNode *LD = cast<LoadSDNode>(Value);
11140     EVT VT = LD->getMemoryVT();
11141     if (!VT.isFloatingPoint() ||
11142         VT != ST->getMemoryVT() ||
11143         LD->isNonTemporal() ||
11144         ST->isNonTemporal() ||
11145         LD->getPointerInfo().getAddrSpace() != 0 ||
11146         ST->getPointerInfo().getAddrSpace() != 0)
11147       return SDValue();
11148 
11149     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11150     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11151         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11152         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11153         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11154       return SDValue();
11155 
11156     unsigned LDAlign = LD->getAlignment();
11157     unsigned STAlign = ST->getAlignment();
11158     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11159     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11160     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11161       return SDValue();
11162 
11163     SDValue NewLD =
11164         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11165                     LD->getPointerInfo(), LDAlign);
11166 
11167     SDValue NewST =
11168         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11169                      ST->getPointerInfo(), STAlign);
11170 
11171     AddToWorklist(NewLD.getNode());
11172     AddToWorklist(NewST.getNode());
11173     WorklistRemover DeadNodes(*this);
11174     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11175     ++LdStFP2Int;
11176     return NewST;
11177   }
11178 
11179   return SDValue();
11180 }
11181 
11182 namespace {
11183 /// Helper struct to parse and store a memory address as base + index + offset.
11184 /// We ignore sign extensions when it is safe to do so.
11185 /// The following two expressions are not equivalent. To differentiate we need
11186 /// to store whether there was a sign extension involved in the index
11187 /// computation.
11188 ///  (load (i64 add (i64 copyfromreg %c)
11189 ///                 (i64 signextend (add (i8 load %index)
11190 ///                                      (i8 1))))
11191 /// vs
11192 ///
11193 /// (load (i64 add (i64 copyfromreg %c)
11194 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11195 ///                                         (i32 1)))))
11196 struct BaseIndexOffset {
11197   SDValue Base;
11198   SDValue Index;
11199   int64_t Offset;
11200   bool IsIndexSignExt;
11201 
11202   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11203 
11204   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11205                   bool IsIndexSignExt) :
11206     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11207 
11208   bool equalBaseIndex(const BaseIndexOffset &Other) {
11209     return Other.Base == Base && Other.Index == Index &&
11210       Other.IsIndexSignExt == IsIndexSignExt;
11211   }
11212 
11213   /// Parses tree in Ptr for base, index, offset addresses.
11214   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11215     bool IsIndexSignExt = false;
11216 
11217     // Split up a folded GlobalAddress+Offset into its component parts.
11218     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11219       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11220         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11221                                                     SDLoc(GA),
11222                                                     GA->getValueType(0),
11223                                                     /*Offset=*/0,
11224                                                     /*isTargetGA=*/false,
11225                                                     GA->getTargetFlags()),
11226                                SDValue(),
11227                                GA->getOffset(),
11228                                IsIndexSignExt);
11229       }
11230 
11231     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11232     // instruction, then it could be just the BASE or everything else we don't
11233     // know how to handle. Just use Ptr as BASE and give up.
11234     if (Ptr->getOpcode() != ISD::ADD)
11235       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11236 
11237     // We know that we have at least an ADD instruction. Try to pattern match
11238     // the simple case of BASE + OFFSET.
11239     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11240       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11241       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11242                               IsIndexSignExt);
11243     }
11244 
11245     // Inside a loop the current BASE pointer is calculated using an ADD and a
11246     // MUL instruction. In this case Ptr is the actual BASE pointer.
11247     // (i64 add (i64 %array_ptr)
11248     //          (i64 mul (i64 %induction_var)
11249     //                   (i64 %element_size)))
11250     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11251       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11252 
11253     // Look at Base + Index + Offset cases.
11254     SDValue Base = Ptr->getOperand(0);
11255     SDValue IndexOffset = Ptr->getOperand(1);
11256 
11257     // Skip signextends.
11258     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11259       IndexOffset = IndexOffset->getOperand(0);
11260       IsIndexSignExt = true;
11261     }
11262 
11263     // Either the case of Base + Index (no offset) or something else.
11264     if (IndexOffset->getOpcode() != ISD::ADD)
11265       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11266 
11267     // Now we have the case of Base + Index + offset.
11268     SDValue Index = IndexOffset->getOperand(0);
11269     SDValue Offset = IndexOffset->getOperand(1);
11270 
11271     if (!isa<ConstantSDNode>(Offset))
11272       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11273 
11274     // Ignore signextends.
11275     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11276       Index = Index->getOperand(0);
11277       IsIndexSignExt = true;
11278     } else IsIndexSignExt = false;
11279 
11280     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11281     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11282   }
11283 };
11284 } // namespace
11285 
11286 // This is a helper function for visitMUL to check the profitability
11287 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11288 // MulNode is the original multiply, AddNode is (add x, c1),
11289 // and ConstNode is c2.
11290 //
11291 // If the (add x, c1) has multiple uses, we could increase
11292 // the number of adds if we make this transformation.
11293 // It would only be worth doing this if we can remove a
11294 // multiply in the process. Check for that here.
11295 // To illustrate:
11296 //     (A + c1) * c3
11297 //     (A + c2) * c3
11298 // We're checking for cases where we have common "c3 * A" expressions.
11299 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11300                                               SDValue &AddNode,
11301                                               SDValue &ConstNode) {
11302   APInt Val;
11303 
11304   // If the add only has one use, this would be OK to do.
11305   if (AddNode.getNode()->hasOneUse())
11306     return true;
11307 
11308   // Walk all the users of the constant with which we're multiplying.
11309   for (SDNode *Use : ConstNode->uses()) {
11310 
11311     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11312       continue;
11313 
11314     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11315       SDNode *OtherOp;
11316       SDNode *MulVar = AddNode.getOperand(0).getNode();
11317 
11318       // OtherOp is what we're multiplying against the constant.
11319       if (Use->getOperand(0) == ConstNode)
11320         OtherOp = Use->getOperand(1).getNode();
11321       else
11322         OtherOp = Use->getOperand(0).getNode();
11323 
11324       // Check to see if multiply is with the same operand of our "add".
11325       //
11326       //     ConstNode  = CONST
11327       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11328       //     ...
11329       //     AddNode  = (A + c1)  <-- MulVar is A.
11330       //         = AddNode * ConstNode   <-- current visiting instruction.
11331       //
11332       // If we make this transformation, we will have a common
11333       // multiply (ConstNode * A) that we can save.
11334       if (OtherOp == MulVar)
11335         return true;
11336 
11337       // Now check to see if a future expansion will give us a common
11338       // multiply.
11339       //
11340       //     ConstNode  = CONST
11341       //     AddNode    = (A + c1)
11342       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11343       //     ...
11344       //     OtherOp = (A + c2)
11345       //     Use     = OtherOp * ConstNode <-- visiting Use.
11346       //
11347       // If we make this transformation, we will have a common
11348       // multiply (CONST * A) after we also do the same transformation
11349       // to the "t2" instruction.
11350       if (OtherOp->getOpcode() == ISD::ADD &&
11351           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11352           OtherOp->getOperand(0).getNode() == MulVar)
11353         return true;
11354     }
11355   }
11356 
11357   // Didn't find a case where this would be profitable.
11358   return false;
11359 }
11360 
11361 SDValue DAGCombiner::getMergedConstantVectorStore(
11362     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11363     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11364   SmallVector<SDValue, 8> BuildVector;
11365 
11366   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11367     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11368     Chains.push_back(St->getChain());
11369     BuildVector.push_back(St->getValue());
11370   }
11371 
11372   return DAG.getBuildVector(Ty, SL, BuildVector);
11373 }
11374 
11375 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11376                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11377                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11378   // Make sure we have something to merge.
11379   if (NumStores < 2)
11380     return false;
11381 
11382   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11383   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11384   unsigned LatestNodeUsed = 0;
11385 
11386   for (unsigned i=0; i < NumStores; ++i) {
11387     // Find a chain for the new wide-store operand. Notice that some
11388     // of the store nodes that we found may not be selected for inclusion
11389     // in the wide store. The chain we use needs to be the chain of the
11390     // latest store node which is *used* and replaced by the wide store.
11391     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11392       LatestNodeUsed = i;
11393   }
11394 
11395   SmallVector<SDValue, 8> Chains;
11396 
11397   // The latest Node in the DAG.
11398   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11399   SDLoc DL(StoreNodes[0].MemNode);
11400 
11401   SDValue StoredVal;
11402   if (UseVector) {
11403     bool IsVec = MemVT.isVector();
11404     unsigned Elts = NumStores;
11405     if (IsVec) {
11406       // When merging vector stores, get the total number of elements.
11407       Elts *= MemVT.getVectorNumElements();
11408     }
11409     // Get the type for the merged vector store.
11410     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11411     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11412 
11413     if (IsConstantSrc) {
11414       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11415     } else {
11416       SmallVector<SDValue, 8> Ops;
11417       for (unsigned i = 0; i < NumStores; ++i) {
11418         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11419         SDValue Val = St->getValue();
11420         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11421         if (Val.getValueType() != MemVT)
11422           return false;
11423         Ops.push_back(Val);
11424         Chains.push_back(St->getChain());
11425       }
11426 
11427       // Build the extracted vector elements back into a vector.
11428       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11429                               DL, Ty, Ops);    }
11430   } else {
11431     // We should always use a vector store when merging extracted vector
11432     // elements, so this path implies a store of constants.
11433     assert(IsConstantSrc && "Merged vector elements should use vector store");
11434 
11435     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11436     APInt StoreInt(SizeInBits, 0);
11437 
11438     // Construct a single integer constant which is made of the smaller
11439     // constant inputs.
11440     bool IsLE = DAG.getDataLayout().isLittleEndian();
11441     for (unsigned i = 0; i < NumStores; ++i) {
11442       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11443       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11444       Chains.push_back(St->getChain());
11445 
11446       SDValue Val = St->getValue();
11447       StoreInt <<= ElementSizeBytes * 8;
11448       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11449         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11450       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11451         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11452       } else {
11453         llvm_unreachable("Invalid constant element type");
11454       }
11455     }
11456 
11457     // Create the new Load and Store operations.
11458     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11459     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11460   }
11461 
11462   assert(!Chains.empty());
11463 
11464   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11465   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11466                                   FirstInChain->getBasePtr(),
11467                                   FirstInChain->getPointerInfo(),
11468                                   FirstInChain->getAlignment());
11469 
11470   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11471                                                   : DAG.getSubtarget().useAA();
11472   if (UseAA) {
11473     // Replace all merged stores with the new store.
11474     for (unsigned i = 0; i < NumStores; ++i)
11475       CombineTo(StoreNodes[i].MemNode, NewStore);
11476   } else {
11477     // Replace the last store with the new store.
11478     CombineTo(LatestOp, NewStore);
11479     // Erase all other stores.
11480     for (unsigned i = 0; i < NumStores; ++i) {
11481       if (StoreNodes[i].MemNode == LatestOp)
11482         continue;
11483       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11484       // ReplaceAllUsesWith will replace all uses that existed when it was
11485       // called, but graph optimizations may cause new ones to appear. For
11486       // example, the case in pr14333 looks like
11487       //
11488       //  St's chain -> St -> another store -> X
11489       //
11490       // And the only difference from St to the other store is the chain.
11491       // When we change it's chain to be St's chain they become identical,
11492       // get CSEed and the net result is that X is now a use of St.
11493       // Since we know that St is redundant, just iterate.
11494       while (!St->use_empty())
11495         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11496       deleteAndRecombine(St);
11497     }
11498   }
11499 
11500   return true;
11501 }
11502 
11503 void DAGCombiner::getStoreMergeAndAliasCandidates(
11504     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11505     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11506   // This holds the base pointer, index, and the offset in bytes from the base
11507   // pointer.
11508   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11509 
11510   // We must have a base and an offset.
11511   if (!BasePtr.Base.getNode())
11512     return;
11513 
11514   // Do not handle stores to undef base pointers.
11515   if (BasePtr.Base.isUndef())
11516     return;
11517 
11518   // Walk up the chain and look for nodes with offsets from the same
11519   // base pointer. Stop when reaching an instruction with a different kind
11520   // or instruction which has a different base pointer.
11521   EVT MemVT = St->getMemoryVT();
11522   unsigned Seq = 0;
11523   StoreSDNode *Index = St;
11524 
11525 
11526   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11527                                                   : DAG.getSubtarget().useAA();
11528 
11529   if (UseAA) {
11530     // Look at other users of the same chain. Stores on the same chain do not
11531     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11532     // to be on the same chain, so don't bother looking at adjacent chains.
11533 
11534     SDValue Chain = St->getChain();
11535     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11536       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11537         if (I.getOperandNo() != 0)
11538           continue;
11539 
11540         if (OtherST->isVolatile() || OtherST->isIndexed())
11541           continue;
11542 
11543         if (OtherST->getMemoryVT() != MemVT)
11544           continue;
11545 
11546         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11547 
11548         if (Ptr.equalBaseIndex(BasePtr))
11549           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11550       }
11551     }
11552 
11553     return;
11554   }
11555 
11556   while (Index) {
11557     // If the chain has more than one use, then we can't reorder the mem ops.
11558     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11559       break;
11560 
11561     // Find the base pointer and offset for this memory node.
11562     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11563 
11564     // Check that the base pointer is the same as the original one.
11565     if (!Ptr.equalBaseIndex(BasePtr))
11566       break;
11567 
11568     // The memory operands must not be volatile.
11569     if (Index->isVolatile() || Index->isIndexed())
11570       break;
11571 
11572     // No truncation.
11573     if (Index->isTruncatingStore())
11574       break;
11575 
11576     // The stored memory type must be the same.
11577     if (Index->getMemoryVT() != MemVT)
11578       break;
11579 
11580     // We do not allow under-aligned stores in order to prevent
11581     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11582     // be irrelevant here; what MATTERS is that we not move memory
11583     // operations that potentially overlap past each-other.
11584     if (Index->getAlignment() < MemVT.getStoreSize())
11585       break;
11586 
11587     // We found a potential memory operand to merge.
11588     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11589 
11590     // Find the next memory operand in the chain. If the next operand in the
11591     // chain is a store then move up and continue the scan with the next
11592     // memory operand. If the next operand is a load save it and use alias
11593     // information to check if it interferes with anything.
11594     SDNode *NextInChain = Index->getChain().getNode();
11595     while (1) {
11596       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11597         // We found a store node. Use it for the next iteration.
11598         Index = STn;
11599         break;
11600       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11601         if (Ldn->isVolatile()) {
11602           Index = nullptr;
11603           break;
11604         }
11605 
11606         // Save the load node for later. Continue the scan.
11607         AliasLoadNodes.push_back(Ldn);
11608         NextInChain = Ldn->getChain().getNode();
11609         continue;
11610       } else {
11611         Index = nullptr;
11612         break;
11613       }
11614     }
11615   }
11616 }
11617 
11618 // We need to check that merging these stores does not cause a loop
11619 // in the DAG. Any store candidate may depend on another candidate
11620 // indirectly through its operand (we already consider dependencies
11621 // through the chain). Check in parallel by searching up from
11622 // non-chain operands of candidates.
11623 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11624     SmallVectorImpl<MemOpLink> &StoreNodes) {
11625   SmallPtrSet<const SDNode *, 16> Visited;
11626   SmallVector<const SDNode *, 8> Worklist;
11627   // search ops of store candidates
11628   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11629     SDNode *n = StoreNodes[i].MemNode;
11630     // Potential loops may happen only through non-chain operands
11631     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11632       Worklist.push_back(n->getOperand(j).getNode());
11633   }
11634   // search through DAG. We can stop early if we find a storenode
11635   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11636     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11637       return false;
11638   }
11639   return true;
11640 }
11641 
11642 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11643   if (OptLevel == CodeGenOpt::None)
11644     return false;
11645 
11646   EVT MemVT = St->getMemoryVT();
11647   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11648   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11649       Attribute::NoImplicitFloat);
11650 
11651   // This function cannot currently deal with non-byte-sized memory sizes.
11652   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11653     return false;
11654 
11655   if (!MemVT.isSimple())
11656     return false;
11657 
11658   // Perform an early exit check. Do not bother looking at stored values that
11659   // are not constants, loads, or extracted vector elements.
11660   SDValue StoredVal = St->getValue();
11661   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11662   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11663                        isa<ConstantFPSDNode>(StoredVal);
11664   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11665                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11666 
11667   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11668     return false;
11669 
11670   // Don't merge vectors into wider vectors if the source data comes from loads.
11671   // TODO: This restriction can be lifted by using logic similar to the
11672   // ExtractVecSrc case.
11673   if (MemVT.isVector() && IsLoadSrc)
11674     return false;
11675 
11676   // Only look at ends of store sequences.
11677   SDValue Chain = SDValue(St, 0);
11678   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11679     return false;
11680 
11681   // Save the LoadSDNodes that we find in the chain.
11682   // We need to make sure that these nodes do not interfere with
11683   // any of the store nodes.
11684   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11685 
11686   // Save the StoreSDNodes that we find in the chain.
11687   SmallVector<MemOpLink, 8> StoreNodes;
11688 
11689   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11690 
11691   // Check if there is anything to merge.
11692   if (StoreNodes.size() < 2)
11693     return false;
11694 
11695   // only do dependence check in AA case
11696   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11697                                                   : DAG.getSubtarget().useAA();
11698   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11699     return false;
11700 
11701   // Sort the memory operands according to their distance from the
11702   // base pointer.  As a secondary criteria: make sure stores coming
11703   // later in the code come first in the list. This is important for
11704   // the non-UseAA case, because we're merging stores into the FINAL
11705   // store along a chain which potentially contains aliasing stores.
11706   // Thus, if there are multiple stores to the same address, the last
11707   // one can be considered for merging but not the others.
11708   std::sort(StoreNodes.begin(), StoreNodes.end(),
11709             [](MemOpLink LHS, MemOpLink RHS) {
11710     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11711            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11712             LHS.SequenceNum < RHS.SequenceNum);
11713   });
11714 
11715   // Scan the memory operations on the chain and find the first non-consecutive
11716   // store memory address.
11717   unsigned LastConsecutiveStore = 0;
11718   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11719   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11720 
11721     // Check that the addresses are consecutive starting from the second
11722     // element in the list of stores.
11723     if (i > 0) {
11724       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11725       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11726         break;
11727     }
11728 
11729     // Check if this store interferes with any of the loads that we found.
11730     // If we find a load that alias with this store. Stop the sequence.
11731     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11732           return isAlias(Ldn, StoreNodes[i].MemNode);
11733         }))
11734       break;
11735 
11736     // Mark this node as useful.
11737     LastConsecutiveStore = i;
11738   }
11739 
11740   // The node with the lowest store address.
11741   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11742   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11743   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11744   LLVMContext &Context = *DAG.getContext();
11745   const DataLayout &DL = DAG.getDataLayout();
11746 
11747   // Store the constants into memory as one consecutive store.
11748   if (IsConstantSrc) {
11749     unsigned LastLegalType = 0;
11750     unsigned LastLegalVectorType = 0;
11751     bool NonZero = false;
11752     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11753       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11754       SDValue StoredVal = St->getValue();
11755 
11756       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11757         NonZero |= !C->isNullValue();
11758       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11759         NonZero |= !C->getConstantFPValue()->isNullValue();
11760       } else {
11761         // Non-constant.
11762         break;
11763       }
11764 
11765       // Find a legal type for the constant store.
11766       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11767       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11768       bool IsFast;
11769       if (TLI.isTypeLegal(StoreTy) &&
11770           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11771                                  FirstStoreAlign, &IsFast) && IsFast) {
11772         LastLegalType = i+1;
11773       // Or check whether a truncstore is legal.
11774       } else if (TLI.getTypeAction(Context, StoreTy) ==
11775                  TargetLowering::TypePromoteInteger) {
11776         EVT LegalizedStoredValueTy =
11777           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11778         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11779             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11780                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11781             IsFast) {
11782           LastLegalType = i + 1;
11783         }
11784       }
11785 
11786       // We only use vectors if the constant is known to be zero or the target
11787       // allows it and the function is not marked with the noimplicitfloat
11788       // attribute.
11789       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11790                                                         FirstStoreAS)) &&
11791           !NoVectors) {
11792         // Find a legal type for the vector store.
11793         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11794         if (TLI.isTypeLegal(Ty) &&
11795             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11796                                    FirstStoreAlign, &IsFast) && IsFast)
11797           LastLegalVectorType = i + 1;
11798       }
11799     }
11800 
11801     // Check if we found a legal integer type to store.
11802     if (LastLegalType == 0 && LastLegalVectorType == 0)
11803       return false;
11804 
11805     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11806     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11807 
11808     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11809                                            true, UseVector);
11810   }
11811 
11812   // When extracting multiple vector elements, try to store them
11813   // in one vector store rather than a sequence of scalar stores.
11814   if (IsExtractVecSrc) {
11815     unsigned NumStoresToMerge = 0;
11816     bool IsVec = MemVT.isVector();
11817     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11818       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11819       unsigned StoreValOpcode = St->getValue().getOpcode();
11820       // This restriction could be loosened.
11821       // Bail out if any stored values are not elements extracted from a vector.
11822       // It should be possible to handle mixed sources, but load sources need
11823       // more careful handling (see the block of code below that handles
11824       // consecutive loads).
11825       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11826           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11827         return false;
11828 
11829       // Find a legal type for the vector store.
11830       unsigned Elts = i + 1;
11831       if (IsVec) {
11832         // When merging vector stores, get the total number of elements.
11833         Elts *= MemVT.getVectorNumElements();
11834       }
11835       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11836       bool IsFast;
11837       if (TLI.isTypeLegal(Ty) &&
11838           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11839                                  FirstStoreAlign, &IsFast) && IsFast)
11840         NumStoresToMerge = i + 1;
11841     }
11842 
11843     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11844                                            false, true);
11845   }
11846 
11847   // Below we handle the case of multiple consecutive stores that
11848   // come from multiple consecutive loads. We merge them into a single
11849   // wide load and a single wide store.
11850 
11851   // Look for load nodes which are used by the stored values.
11852   SmallVector<MemOpLink, 8> LoadNodes;
11853 
11854   // Find acceptable loads. Loads need to have the same chain (token factor),
11855   // must not be zext, volatile, indexed, and they must be consecutive.
11856   BaseIndexOffset LdBasePtr;
11857   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11858     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11859     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11860     if (!Ld) break;
11861 
11862     // Loads must only have one use.
11863     if (!Ld->hasNUsesOfValue(1, 0))
11864       break;
11865 
11866     // The memory operands must not be volatile.
11867     if (Ld->isVolatile() || Ld->isIndexed())
11868       break;
11869 
11870     // We do not accept ext loads.
11871     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11872       break;
11873 
11874     // The stored memory type must be the same.
11875     if (Ld->getMemoryVT() != MemVT)
11876       break;
11877 
11878     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11879     // If this is not the first ptr that we check.
11880     if (LdBasePtr.Base.getNode()) {
11881       // The base ptr must be the same.
11882       if (!LdPtr.equalBaseIndex(LdBasePtr))
11883         break;
11884     } else {
11885       // Check that all other base pointers are the same as this one.
11886       LdBasePtr = LdPtr;
11887     }
11888 
11889     // We found a potential memory operand to merge.
11890     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11891   }
11892 
11893   if (LoadNodes.size() < 2)
11894     return false;
11895 
11896   // If we have load/store pair instructions and we only have two values,
11897   // don't bother.
11898   unsigned RequiredAlignment;
11899   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11900       St->getAlignment() >= RequiredAlignment)
11901     return false;
11902 
11903   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11904   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11905   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11906 
11907   // Scan the memory operations on the chain and find the first non-consecutive
11908   // load memory address. These variables hold the index in the store node
11909   // array.
11910   unsigned LastConsecutiveLoad = 0;
11911   // This variable refers to the size and not index in the array.
11912   unsigned LastLegalVectorType = 0;
11913   unsigned LastLegalIntegerType = 0;
11914   StartAddress = LoadNodes[0].OffsetFromBase;
11915   SDValue FirstChain = FirstLoad->getChain();
11916   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11917     // All loads must share the same chain.
11918     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11919       break;
11920 
11921     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11922     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11923       break;
11924     LastConsecutiveLoad = i;
11925     // Find a legal type for the vector store.
11926     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11927     bool IsFastSt, IsFastLd;
11928     if (TLI.isTypeLegal(StoreTy) &&
11929         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11930                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11931         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11932                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11933       LastLegalVectorType = i + 1;
11934     }
11935 
11936     // Find a legal type for the integer store.
11937     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11938     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11939     if (TLI.isTypeLegal(StoreTy) &&
11940         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11941                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11942         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11943                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11944       LastLegalIntegerType = i + 1;
11945     // Or check whether a truncstore and extload is legal.
11946     else if (TLI.getTypeAction(Context, StoreTy) ==
11947              TargetLowering::TypePromoteInteger) {
11948       EVT LegalizedStoredValueTy =
11949         TLI.getTypeToTransformTo(Context, StoreTy);
11950       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11951           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11952           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11953           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11954           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11955                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11956           IsFastSt &&
11957           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11958                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11959           IsFastLd)
11960         LastLegalIntegerType = i+1;
11961     }
11962   }
11963 
11964   // Only use vector types if the vector type is larger than the integer type.
11965   // If they are the same, use integers.
11966   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11967   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11968 
11969   // We add +1 here because the LastXXX variables refer to location while
11970   // the NumElem refers to array/index size.
11971   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11972   NumElem = std::min(LastLegalType, NumElem);
11973 
11974   if (NumElem < 2)
11975     return false;
11976 
11977   // Collect the chains from all merged stores.
11978   SmallVector<SDValue, 8> MergeStoreChains;
11979   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11980 
11981   // The latest Node in the DAG.
11982   unsigned LatestNodeUsed = 0;
11983   for (unsigned i=1; i<NumElem; ++i) {
11984     // Find a chain for the new wide-store operand. Notice that some
11985     // of the store nodes that we found may not be selected for inclusion
11986     // in the wide store. The chain we use needs to be the chain of the
11987     // latest store node which is *used* and replaced by the wide store.
11988     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11989       LatestNodeUsed = i;
11990 
11991     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11992   }
11993 
11994   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11995 
11996   // Find if it is better to use vectors or integers to load and store
11997   // to memory.
11998   EVT JointMemOpVT;
11999   if (UseVectorTy) {
12000     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12001   } else {
12002     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12003     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12004   }
12005 
12006   SDLoc LoadDL(LoadNodes[0].MemNode);
12007   SDLoc StoreDL(StoreNodes[0].MemNode);
12008 
12009   // The merged loads are required to have the same incoming chain, so
12010   // using the first's chain is acceptable.
12011   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12012                                 FirstLoad->getBasePtr(),
12013                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12014 
12015   SDValue NewStoreChain =
12016     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12017 
12018   SDValue NewStore =
12019       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12020                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12021 
12022   // Transfer chain users from old loads to the new load.
12023   for (unsigned i = 0; i < NumElem; ++i) {
12024     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12025     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12026                                   SDValue(NewLoad.getNode(), 1));
12027   }
12028 
12029   if (UseAA) {
12030     // Replace the all stores with the new store.
12031     for (unsigned i = 0; i < NumElem; ++i)
12032       CombineTo(StoreNodes[i].MemNode, NewStore);
12033   } else {
12034     // Replace the last store with the new store.
12035     CombineTo(LatestOp, NewStore);
12036     // Erase all other stores.
12037     for (unsigned i = 0; i < NumElem; ++i) {
12038       // Remove all Store nodes.
12039       if (StoreNodes[i].MemNode == LatestOp)
12040         continue;
12041       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12042       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12043       deleteAndRecombine(St);
12044     }
12045   }
12046 
12047   return true;
12048 }
12049 
12050 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12051   SDLoc SL(ST);
12052   SDValue ReplStore;
12053 
12054   // Replace the chain to avoid dependency.
12055   if (ST->isTruncatingStore()) {
12056     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12057                                   ST->getBasePtr(), ST->getMemoryVT(),
12058                                   ST->getMemOperand());
12059   } else {
12060     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12061                              ST->getMemOperand());
12062   }
12063 
12064   // Create token to keep both nodes around.
12065   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12066                               MVT::Other, ST->getChain(), ReplStore);
12067 
12068   // Make sure the new and old chains are cleaned up.
12069   AddToWorklist(Token.getNode());
12070 
12071   // Don't add users to work list.
12072   return CombineTo(ST, Token, false);
12073 }
12074 
12075 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12076   SDValue Value = ST->getValue();
12077   if (Value.getOpcode() == ISD::TargetConstantFP)
12078     return SDValue();
12079 
12080   SDLoc DL(ST);
12081 
12082   SDValue Chain = ST->getChain();
12083   SDValue Ptr = ST->getBasePtr();
12084 
12085   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12086 
12087   // NOTE: If the original store is volatile, this transform must not increase
12088   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12089   // processor operation but an i64 (which is not legal) requires two.  So the
12090   // transform should not be done in this case.
12091 
12092   SDValue Tmp;
12093   switch (CFP->getSimpleValueType(0).SimpleTy) {
12094   default:
12095     llvm_unreachable("Unknown FP type");
12096   case MVT::f16:    // We don't do this for these yet.
12097   case MVT::f80:
12098   case MVT::f128:
12099   case MVT::ppcf128:
12100     return SDValue();
12101   case MVT::f32:
12102     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12103         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12104       ;
12105       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12106                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12107                             MVT::i32);
12108       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12109     }
12110 
12111     return SDValue();
12112   case MVT::f64:
12113     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12114          !ST->isVolatile()) ||
12115         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12116       ;
12117       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12118                             getZExtValue(), SDLoc(CFP), MVT::i64);
12119       return DAG.getStore(Chain, DL, Tmp,
12120                           Ptr, ST->getMemOperand());
12121     }
12122 
12123     if (!ST->isVolatile() &&
12124         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12125       // Many FP stores are not made apparent until after legalize, e.g. for
12126       // argument passing.  Since this is so common, custom legalize the
12127       // 64-bit integer store into two 32-bit stores.
12128       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12129       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12130       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12131       if (DAG.getDataLayout().isBigEndian())
12132         std::swap(Lo, Hi);
12133 
12134       unsigned Alignment = ST->getAlignment();
12135       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12136       AAMDNodes AAInfo = ST->getAAInfo();
12137 
12138       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12139                                  ST->getAlignment(), MMOFlags, AAInfo);
12140       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12141                         DAG.getConstant(4, DL, Ptr.getValueType()));
12142       Alignment = MinAlign(Alignment, 4U);
12143       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12144                                  ST->getPointerInfo().getWithOffset(4),
12145                                  Alignment, MMOFlags, AAInfo);
12146       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12147                          St0, St1);
12148     }
12149 
12150     return SDValue();
12151   }
12152 }
12153 
12154 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12155   StoreSDNode *ST  = cast<StoreSDNode>(N);
12156   SDValue Chain = ST->getChain();
12157   SDValue Value = ST->getValue();
12158   SDValue Ptr   = ST->getBasePtr();
12159 
12160   // If this is a store of a bit convert, store the input value if the
12161   // resultant store does not need a higher alignment than the original.
12162   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12163       ST->isUnindexed()) {
12164     EVT SVT = Value.getOperand(0).getValueType();
12165     if (((!LegalOperations && !ST->isVolatile()) ||
12166          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12167         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12168       unsigned OrigAlign = ST->getAlignment();
12169       bool Fast = false;
12170       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12171                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12172           Fast) {
12173         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12174                             ST->getPointerInfo(), OrigAlign,
12175                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12176       }
12177     }
12178   }
12179 
12180   // Turn 'store undef, Ptr' -> nothing.
12181   if (Value.isUndef() && ST->isUnindexed())
12182     return Chain;
12183 
12184   // Try to infer better alignment information than the store already has.
12185   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12186     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12187       if (Align > ST->getAlignment()) {
12188         SDValue NewStore =
12189             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12190                               ST->getMemoryVT(), Align,
12191                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12192         if (NewStore.getNode() != N)
12193           return CombineTo(ST, NewStore, true);
12194       }
12195     }
12196   }
12197 
12198   // Try transforming a pair floating point load / store ops to integer
12199   // load / store ops.
12200   if (SDValue NewST = TransformFPLoadStorePair(N))
12201     return NewST;
12202 
12203   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12204                                                   : DAG.getSubtarget().useAA();
12205 #ifndef NDEBUG
12206   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12207       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12208     UseAA = false;
12209 #endif
12210   if (UseAA && ST->isUnindexed()) {
12211     // FIXME: We should do this even without AA enabled. AA will just allow
12212     // FindBetterChain to work in more situations. The problem with this is that
12213     // any combine that expects memory operations to be on consecutive chains
12214     // first needs to be updated to look for users of the same chain.
12215 
12216     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12217     // adjacent stores.
12218     if (findBetterNeighborChains(ST)) {
12219       // replaceStoreChain uses CombineTo, which handled all of the worklist
12220       // manipulation. Return the original node to not do anything else.
12221       return SDValue(ST, 0);
12222     }
12223     Chain = ST->getChain();
12224   }
12225 
12226   // Try transforming N to an indexed store.
12227   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12228     return SDValue(N, 0);
12229 
12230   // FIXME: is there such a thing as a truncating indexed store?
12231   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12232       Value.getValueType().isInteger()) {
12233     // See if we can simplify the input to this truncstore with knowledge that
12234     // only the low bits are being used.  For example:
12235     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12236     SDValue Shorter = GetDemandedBits(
12237         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12238                                     ST->getMemoryVT().getScalarSizeInBits()));
12239     AddToWorklist(Value.getNode());
12240     if (Shorter.getNode())
12241       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12242                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12243 
12244     // Otherwise, see if we can simplify the operation with
12245     // SimplifyDemandedBits, which only works if the value has a single use.
12246     if (SimplifyDemandedBits(
12247             Value,
12248             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12249                                  ST->getMemoryVT().getScalarSizeInBits())))
12250       return SDValue(N, 0);
12251   }
12252 
12253   // If this is a load followed by a store to the same location, then the store
12254   // is dead/noop.
12255   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12256     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12257         ST->isUnindexed() && !ST->isVolatile() &&
12258         // There can't be any side effects between the load and store, such as
12259         // a call or store.
12260         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12261       // The store is dead, remove it.
12262       return Chain;
12263     }
12264   }
12265 
12266   // If this is a store followed by a store with the same value to the same
12267   // location, then the store is dead/noop.
12268   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12269     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12270         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12271         ST1->isUnindexed() && !ST1->isVolatile()) {
12272       // The store is dead, remove it.
12273       return Chain;
12274     }
12275   }
12276 
12277   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12278   // truncating store.  We can do this even if this is already a truncstore.
12279   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12280       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12281       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12282                             ST->getMemoryVT())) {
12283     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12284                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12285   }
12286 
12287   // Only perform this optimization before the types are legal, because we
12288   // don't want to perform this optimization on every DAGCombine invocation.
12289   if (!LegalTypes) {
12290     bool EverChanged = false;
12291 
12292     do {
12293       // There can be multiple store sequences on the same chain.
12294       // Keep trying to merge store sequences until we are unable to do so
12295       // or until we merge the last store on the chain.
12296       bool Changed = MergeConsecutiveStores(ST);
12297       EverChanged |= Changed;
12298       if (!Changed) break;
12299     } while (ST->getOpcode() != ISD::DELETED_NODE);
12300 
12301     if (EverChanged)
12302       return SDValue(N, 0);
12303   }
12304 
12305   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12306   //
12307   // Make sure to do this only after attempting to merge stores in order to
12308   //  avoid changing the types of some subset of stores due to visit order,
12309   //  preventing their merging.
12310   if (isa<ConstantFPSDNode>(Value)) {
12311     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12312       return NewSt;
12313   }
12314 
12315   if (SDValue NewSt = splitMergedValStore(ST))
12316     return NewSt;
12317 
12318   return ReduceLoadOpStoreWidth(N);
12319 }
12320 
12321 /// For the instruction sequence of store below, F and I values
12322 /// are bundled together as an i64 value before being stored into memory.
12323 /// Sometimes it is more efficent to generate separate stores for F and I,
12324 /// which can remove the bitwise instructions or sink them to colder places.
12325 ///
12326 ///   (store (or (zext (bitcast F to i32) to i64),
12327 ///              (shl (zext I to i64), 32)), addr)  -->
12328 ///   (store F, addr) and (store I, addr+4)
12329 ///
12330 /// Similarly, splitting for other merged store can also be beneficial, like:
12331 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12332 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12333 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12334 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12335 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12336 ///
12337 /// We allow each target to determine specifically which kind of splitting is
12338 /// supported.
12339 ///
12340 /// The store patterns are commonly seen from the simple code snippet below
12341 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12342 ///   void goo(const std::pair<int, float> &);
12343 ///   hoo() {
12344 ///     ...
12345 ///     goo(std::make_pair(tmp, ftmp));
12346 ///     ...
12347 ///   }
12348 ///
12349 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12350   if (OptLevel == CodeGenOpt::None)
12351     return SDValue();
12352 
12353   SDValue Val = ST->getValue();
12354   SDLoc DL(ST);
12355 
12356   // Match OR operand.
12357   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12358     return SDValue();
12359 
12360   // Match SHL operand and get Lower and Higher parts of Val.
12361   SDValue Op1 = Val.getOperand(0);
12362   SDValue Op2 = Val.getOperand(1);
12363   SDValue Lo, Hi;
12364   if (Op1.getOpcode() != ISD::SHL) {
12365     std::swap(Op1, Op2);
12366     if (Op1.getOpcode() != ISD::SHL)
12367       return SDValue();
12368   }
12369   Lo = Op2;
12370   Hi = Op1.getOperand(0);
12371   if (!Op1.hasOneUse())
12372     return SDValue();
12373 
12374   // Match shift amount to HalfValBitSize.
12375   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12376   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12377   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12378     return SDValue();
12379 
12380   // Lo and Hi are zero-extended from int with size less equal than 32
12381   // to i64.
12382   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12383       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12384       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12385       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12386       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12387       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12388     return SDValue();
12389 
12390   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12391                                              Hi.getOperand(0)))
12392     return SDValue();
12393 
12394   // Start to split store.
12395   unsigned Alignment = ST->getAlignment();
12396   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12397   AAMDNodes AAInfo = ST->getAAInfo();
12398 
12399   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12400   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12401   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12402   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12403 
12404   SDValue Chain = ST->getChain();
12405   SDValue Ptr = ST->getBasePtr();
12406   // Lower value store.
12407   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12408                              ST->getAlignment(), MMOFlags, AAInfo);
12409   Ptr =
12410       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12411                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12412   // Higher value store.
12413   SDValue St1 =
12414       DAG.getStore(St0, DL, Hi, Ptr,
12415                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12416                    Alignment / 2, MMOFlags, AAInfo);
12417   return St1;
12418 }
12419 
12420 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12421   SDValue InVec = N->getOperand(0);
12422   SDValue InVal = N->getOperand(1);
12423   SDValue EltNo = N->getOperand(2);
12424   SDLoc DL(N);
12425 
12426   // If the inserted element is an UNDEF, just use the input vector.
12427   if (InVal.isUndef())
12428     return InVec;
12429 
12430   EVT VT = InVec.getValueType();
12431 
12432   // If we can't generate a legal BUILD_VECTOR, exit
12433   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12434     return SDValue();
12435 
12436   // Check that we know which element is being inserted
12437   if (!isa<ConstantSDNode>(EltNo))
12438     return SDValue();
12439   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12440 
12441   // Canonicalize insert_vector_elt dag nodes.
12442   // Example:
12443   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12444   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12445   //
12446   // Do this only if the child insert_vector node has one use; also
12447   // do this only if indices are both constants and Idx1 < Idx0.
12448   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12449       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12450     unsigned OtherElt =
12451       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12452     if (Elt < OtherElt) {
12453       // Swap nodes.
12454       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12455                                   InVec.getOperand(0), InVal, EltNo);
12456       AddToWorklist(NewOp.getNode());
12457       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12458                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12459     }
12460   }
12461 
12462   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12463   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12464   // vector elements.
12465   SmallVector<SDValue, 8> Ops;
12466   // Do not combine these two vectors if the output vector will not replace
12467   // the input vector.
12468   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12469     Ops.append(InVec.getNode()->op_begin(),
12470                InVec.getNode()->op_end());
12471   } else if (InVec.isUndef()) {
12472     unsigned NElts = VT.getVectorNumElements();
12473     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12474   } else {
12475     return SDValue();
12476   }
12477 
12478   // Insert the element
12479   if (Elt < Ops.size()) {
12480     // All the operands of BUILD_VECTOR must have the same type;
12481     // we enforce that here.
12482     EVT OpVT = Ops[0].getValueType();
12483     if (InVal.getValueType() != OpVT)
12484       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12485                 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12486                 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12487     Ops[Elt] = InVal;
12488   }
12489 
12490   // Return the new vector
12491   return DAG.getBuildVector(VT, DL, Ops);
12492 }
12493 
12494 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12495     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12496   assert(!OriginalLoad->isVolatile());
12497 
12498   EVT ResultVT = EVE->getValueType(0);
12499   EVT VecEltVT = InVecVT.getVectorElementType();
12500   unsigned Align = OriginalLoad->getAlignment();
12501   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12502       VecEltVT.getTypeForEVT(*DAG.getContext()));
12503 
12504   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12505     return SDValue();
12506 
12507   Align = NewAlign;
12508 
12509   SDValue NewPtr = OriginalLoad->getBasePtr();
12510   SDValue Offset;
12511   EVT PtrType = NewPtr.getValueType();
12512   MachinePointerInfo MPI;
12513   SDLoc DL(EVE);
12514   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12515     int Elt = ConstEltNo->getZExtValue();
12516     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12517     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12518     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12519   } else {
12520     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12521     Offset = DAG.getNode(
12522         ISD::MUL, DL, PtrType, Offset,
12523         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12524     MPI = OriginalLoad->getPointerInfo();
12525   }
12526   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12527 
12528   // The replacement we need to do here is a little tricky: we need to
12529   // replace an extractelement of a load with a load.
12530   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12531   // Note that this replacement assumes that the extractvalue is the only
12532   // use of the load; that's okay because we don't want to perform this
12533   // transformation in other cases anyway.
12534   SDValue Load;
12535   SDValue Chain;
12536   if (ResultVT.bitsGT(VecEltVT)) {
12537     // If the result type of vextract is wider than the load, then issue an
12538     // extending load instead.
12539     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12540                                                   VecEltVT)
12541                                    ? ISD::ZEXTLOAD
12542                                    : ISD::EXTLOAD;
12543     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12544                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12545                           Align, OriginalLoad->getMemOperand()->getFlags(),
12546                           OriginalLoad->getAAInfo());
12547     Chain = Load.getValue(1);
12548   } else {
12549     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12550                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12551                        OriginalLoad->getAAInfo());
12552     Chain = Load.getValue(1);
12553     if (ResultVT.bitsLT(VecEltVT))
12554       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12555     else
12556       Load = DAG.getBitcast(ResultVT, Load);
12557   }
12558   WorklistRemover DeadNodes(*this);
12559   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12560   SDValue To[] = { Load, Chain };
12561   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12562   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12563   // worklist explicitly as well.
12564   AddToWorklist(Load.getNode());
12565   AddUsersToWorklist(Load.getNode()); // Add users too
12566   // Make sure to revisit this node to clean it up; it will usually be dead.
12567   AddToWorklist(EVE);
12568   ++OpsNarrowed;
12569   return SDValue(EVE, 0);
12570 }
12571 
12572 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12573   // (vextract (scalar_to_vector val, 0) -> val
12574   SDValue InVec = N->getOperand(0);
12575   EVT VT = InVec.getValueType();
12576   EVT NVT = N->getValueType(0);
12577 
12578   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12579     // Check if the result type doesn't match the inserted element type. A
12580     // SCALAR_TO_VECTOR may truncate the inserted element and the
12581     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12582     SDValue InOp = InVec.getOperand(0);
12583     if (InOp.getValueType() != NVT) {
12584       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12585       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12586     }
12587     return InOp;
12588   }
12589 
12590   SDValue EltNo = N->getOperand(1);
12591   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12592 
12593   // extract_vector_elt (build_vector x, y), 1 -> y
12594   if (ConstEltNo &&
12595       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12596       TLI.isTypeLegal(VT) &&
12597       (InVec.hasOneUse() ||
12598        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12599     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12600     EVT InEltVT = Elt.getValueType();
12601 
12602     // Sometimes build_vector's scalar input types do not match result type.
12603     if (NVT == InEltVT)
12604       return Elt;
12605 
12606     // TODO: It may be useful to truncate if free if the build_vector implicitly
12607     // converts.
12608   }
12609 
12610   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12611   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12612       ConstEltNo->isNullValue() && VT.isInteger()) {
12613     SDValue BCSrc = InVec.getOperand(0);
12614     if (BCSrc.getValueType().isScalarInteger())
12615       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12616   }
12617 
12618   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12619   //
12620   // This only really matters if the index is non-constant since other combines
12621   // on the constant elements already work.
12622   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12623       EltNo == InVec.getOperand(2)) {
12624     SDValue Elt = InVec.getOperand(1);
12625     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12626   }
12627 
12628   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12629   // We only perform this optimization before the op legalization phase because
12630   // we may introduce new vector instructions which are not backed by TD
12631   // patterns. For example on AVX, extracting elements from a wide vector
12632   // without using extract_subvector. However, if we can find an underlying
12633   // scalar value, then we can always use that.
12634   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12635     int NumElem = VT.getVectorNumElements();
12636     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12637     // Find the new index to extract from.
12638     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12639 
12640     // Extracting an undef index is undef.
12641     if (OrigElt == -1)
12642       return DAG.getUNDEF(NVT);
12643 
12644     // Select the right vector half to extract from.
12645     SDValue SVInVec;
12646     if (OrigElt < NumElem) {
12647       SVInVec = InVec->getOperand(0);
12648     } else {
12649       SVInVec = InVec->getOperand(1);
12650       OrigElt -= NumElem;
12651     }
12652 
12653     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12654       SDValue InOp = SVInVec.getOperand(OrigElt);
12655       if (InOp.getValueType() != NVT) {
12656         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12657         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12658       }
12659 
12660       return InOp;
12661     }
12662 
12663     // FIXME: We should handle recursing on other vector shuffles and
12664     // scalar_to_vector here as well.
12665 
12666     if (!LegalOperations) {
12667       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12668       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12669                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12670     }
12671   }
12672 
12673   bool BCNumEltsChanged = false;
12674   EVT ExtVT = VT.getVectorElementType();
12675   EVT LVT = ExtVT;
12676 
12677   // If the result of load has to be truncated, then it's not necessarily
12678   // profitable.
12679   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12680     return SDValue();
12681 
12682   if (InVec.getOpcode() == ISD::BITCAST) {
12683     // Don't duplicate a load with other uses.
12684     if (!InVec.hasOneUse())
12685       return SDValue();
12686 
12687     EVT BCVT = InVec.getOperand(0).getValueType();
12688     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12689       return SDValue();
12690     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12691       BCNumEltsChanged = true;
12692     InVec = InVec.getOperand(0);
12693     ExtVT = BCVT.getVectorElementType();
12694   }
12695 
12696   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12697   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12698       ISD::isNormalLoad(InVec.getNode()) &&
12699       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12700     SDValue Index = N->getOperand(1);
12701     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12702       if (!OrigLoad->isVolatile()) {
12703         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12704                                                              OrigLoad);
12705       }
12706     }
12707   }
12708 
12709   // Perform only after legalization to ensure build_vector / vector_shuffle
12710   // optimizations have already been done.
12711   if (!LegalOperations) return SDValue();
12712 
12713   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12714   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12715   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12716 
12717   if (ConstEltNo) {
12718     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12719 
12720     LoadSDNode *LN0 = nullptr;
12721     const ShuffleVectorSDNode *SVN = nullptr;
12722     if (ISD::isNormalLoad(InVec.getNode())) {
12723       LN0 = cast<LoadSDNode>(InVec);
12724     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12725                InVec.getOperand(0).getValueType() == ExtVT &&
12726                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12727       // Don't duplicate a load with other uses.
12728       if (!InVec.hasOneUse())
12729         return SDValue();
12730 
12731       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12732     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12733       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12734       // =>
12735       // (load $addr+1*size)
12736 
12737       // Don't duplicate a load with other uses.
12738       if (!InVec.hasOneUse())
12739         return SDValue();
12740 
12741       // If the bit convert changed the number of elements, it is unsafe
12742       // to examine the mask.
12743       if (BCNumEltsChanged)
12744         return SDValue();
12745 
12746       // Select the input vector, guarding against out of range extract vector.
12747       unsigned NumElems = VT.getVectorNumElements();
12748       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12749       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12750 
12751       if (InVec.getOpcode() == ISD::BITCAST) {
12752         // Don't duplicate a load with other uses.
12753         if (!InVec.hasOneUse())
12754           return SDValue();
12755 
12756         InVec = InVec.getOperand(0);
12757       }
12758       if (ISD::isNormalLoad(InVec.getNode())) {
12759         LN0 = cast<LoadSDNode>(InVec);
12760         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12761         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12762       }
12763     }
12764 
12765     // Make sure we found a non-volatile load and the extractelement is
12766     // the only use.
12767     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12768       return SDValue();
12769 
12770     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12771     if (Elt == -1)
12772       return DAG.getUNDEF(LVT);
12773 
12774     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12775   }
12776 
12777   return SDValue();
12778 }
12779 
12780 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12781 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12782   // We perform this optimization post type-legalization because
12783   // the type-legalizer often scalarizes integer-promoted vectors.
12784   // Performing this optimization before may create bit-casts which
12785   // will be type-legalized to complex code sequences.
12786   // We perform this optimization only before the operation legalizer because we
12787   // may introduce illegal operations.
12788   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12789     return SDValue();
12790 
12791   unsigned NumInScalars = N->getNumOperands();
12792   SDLoc DL(N);
12793   EVT VT = N->getValueType(0);
12794 
12795   // Check to see if this is a BUILD_VECTOR of a bunch of values
12796   // which come from any_extend or zero_extend nodes. If so, we can create
12797   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12798   // optimizations. We do not handle sign-extend because we can't fill the sign
12799   // using shuffles.
12800   EVT SourceType = MVT::Other;
12801   bool AllAnyExt = true;
12802 
12803   for (unsigned i = 0; i != NumInScalars; ++i) {
12804     SDValue In = N->getOperand(i);
12805     // Ignore undef inputs.
12806     if (In.isUndef()) continue;
12807 
12808     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12809     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12810 
12811     // Abort if the element is not an extension.
12812     if (!ZeroExt && !AnyExt) {
12813       SourceType = MVT::Other;
12814       break;
12815     }
12816 
12817     // The input is a ZeroExt or AnyExt. Check the original type.
12818     EVT InTy = In.getOperand(0).getValueType();
12819 
12820     // Check that all of the widened source types are the same.
12821     if (SourceType == MVT::Other)
12822       // First time.
12823       SourceType = InTy;
12824     else if (InTy != SourceType) {
12825       // Multiple income types. Abort.
12826       SourceType = MVT::Other;
12827       break;
12828     }
12829 
12830     // Check if all of the extends are ANY_EXTENDs.
12831     AllAnyExt &= AnyExt;
12832   }
12833 
12834   // In order to have valid types, all of the inputs must be extended from the
12835   // same source type and all of the inputs must be any or zero extend.
12836   // Scalar sizes must be a power of two.
12837   EVT OutScalarTy = VT.getScalarType();
12838   bool ValidTypes = SourceType != MVT::Other &&
12839                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12840                  isPowerOf2_32(SourceType.getSizeInBits());
12841 
12842   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12843   // turn into a single shuffle instruction.
12844   if (!ValidTypes)
12845     return SDValue();
12846 
12847   bool isLE = DAG.getDataLayout().isLittleEndian();
12848   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12849   assert(ElemRatio > 1 && "Invalid element size ratio");
12850   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12851                                DAG.getConstant(0, DL, SourceType);
12852 
12853   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12854   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12855 
12856   // Populate the new build_vector
12857   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12858     SDValue Cast = N->getOperand(i);
12859     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12860             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12861             Cast.isUndef()) && "Invalid cast opcode");
12862     SDValue In;
12863     if (Cast.isUndef())
12864       In = DAG.getUNDEF(SourceType);
12865     else
12866       In = Cast->getOperand(0);
12867     unsigned Index = isLE ? (i * ElemRatio) :
12868                             (i * ElemRatio + (ElemRatio - 1));
12869 
12870     assert(Index < Ops.size() && "Invalid index");
12871     Ops[Index] = In;
12872   }
12873 
12874   // The type of the new BUILD_VECTOR node.
12875   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12876   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12877          "Invalid vector size");
12878   // Check if the new vector type is legal.
12879   if (!isTypeLegal(VecVT)) return SDValue();
12880 
12881   // Make the new BUILD_VECTOR.
12882   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12883 
12884   // The new BUILD_VECTOR node has the potential to be further optimized.
12885   AddToWorklist(BV.getNode());
12886   // Bitcast to the desired type.
12887   return DAG.getBitcast(VT, BV);
12888 }
12889 
12890 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12891   EVT VT = N->getValueType(0);
12892 
12893   unsigned NumInScalars = N->getNumOperands();
12894   SDLoc DL(N);
12895 
12896   EVT SrcVT = MVT::Other;
12897   unsigned Opcode = ISD::DELETED_NODE;
12898   unsigned NumDefs = 0;
12899 
12900   for (unsigned i = 0; i != NumInScalars; ++i) {
12901     SDValue In = N->getOperand(i);
12902     unsigned Opc = In.getOpcode();
12903 
12904     if (Opc == ISD::UNDEF)
12905       continue;
12906 
12907     // If all scalar values are floats and converted from integers.
12908     if (Opcode == ISD::DELETED_NODE &&
12909         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12910       Opcode = Opc;
12911     }
12912 
12913     if (Opc != Opcode)
12914       return SDValue();
12915 
12916     EVT InVT = In.getOperand(0).getValueType();
12917 
12918     // If all scalar values are typed differently, bail out. It's chosen to
12919     // simplify BUILD_VECTOR of integer types.
12920     if (SrcVT == MVT::Other)
12921       SrcVT = InVT;
12922     if (SrcVT != InVT)
12923       return SDValue();
12924     NumDefs++;
12925   }
12926 
12927   // If the vector has just one element defined, it's not worth to fold it into
12928   // a vectorized one.
12929   if (NumDefs < 2)
12930     return SDValue();
12931 
12932   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12933          && "Should only handle conversion from integer to float.");
12934   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12935 
12936   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12937 
12938   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12939     return SDValue();
12940 
12941   // Just because the floating-point vector type is legal does not necessarily
12942   // mean that the corresponding integer vector type is.
12943   if (!isTypeLegal(NVT))
12944     return SDValue();
12945 
12946   SmallVector<SDValue, 8> Opnds;
12947   for (unsigned i = 0; i != NumInScalars; ++i) {
12948     SDValue In = N->getOperand(i);
12949 
12950     if (In.isUndef())
12951       Opnds.push_back(DAG.getUNDEF(SrcVT));
12952     else
12953       Opnds.push_back(In.getOperand(0));
12954   }
12955   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
12956   AddToWorklist(BV.getNode());
12957 
12958   return DAG.getNode(Opcode, DL, VT, BV);
12959 }
12960 
12961 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
12962                                            ArrayRef<int> VectorMask,
12963                                            SDValue VecIn1, SDValue VecIn2,
12964                                            unsigned LeftIdx) {
12965   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12966   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
12967 
12968   EVT VT = N->getValueType(0);
12969   EVT InVT1 = VecIn1.getValueType();
12970   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
12971 
12972   unsigned Vec2Offset = InVT1.getVectorNumElements();
12973   unsigned NumElems = VT.getVectorNumElements();
12974   unsigned ShuffleNumElems = NumElems;
12975 
12976   // We can't generate a shuffle node with mismatched input and output types.
12977   // Try to make the types match the type of the output.
12978   if (InVT1 != VT || InVT2 != VT) {
12979     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
12980       // If the output vector length is a multiple of both input lengths,
12981       // we can concatenate them and pad the rest with undefs.
12982       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
12983       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
12984       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
12985       ConcatOps[0] = VecIn1;
12986       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
12987       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
12988       VecIn2 = SDValue();
12989     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
12990       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
12991         return SDValue();
12992 
12993       if (!VecIn2.getNode()) {
12994         // If we only have one input vector, and it's twice the size of the
12995         // output, split it in two.
12996         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
12997                              DAG.getConstant(NumElems, DL, IdxTy));
12998         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
12999         // Since we now have shorter input vectors, adjust the offset of the
13000         // second vector's start.
13001         Vec2Offset = NumElems;
13002       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13003         // VecIn1 is wider than the output, and we have another, possibly
13004         // smaller input. Pad the smaller input with undefs, shuffle at the
13005         // input vector width, and extract the output.
13006         // The shuffle type is different than VT, so check legality again.
13007         if (LegalOperations &&
13008             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13009           return SDValue();
13010 
13011         if (InVT1 != InVT2)
13012           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13013                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13014         ShuffleNumElems = NumElems * 2;
13015       } else {
13016         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13017         // than VecIn1. We can't handle this for now - this case will disappear
13018         // when we start sorting the vectors by type.
13019         return SDValue();
13020       }
13021     } else {
13022       // TODO: Support cases where the length mismatch isn't exactly by a
13023       // factor of 2.
13024       // TODO: Move this check upwards, so that if we have bad type
13025       // mismatches, we don't create any DAG nodes.
13026       return SDValue();
13027     }
13028   }
13029 
13030   // Initialize mask to undef.
13031   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13032 
13033   // Only need to run up to the number of elements actually used, not the
13034   // total number of elements in the shuffle - if we are shuffling a wider
13035   // vector, the high lanes should be set to undef.
13036   for (unsigned i = 0; i != NumElems; ++i) {
13037     if (VectorMask[i] <= 0)
13038       continue;
13039 
13040     SDValue Extract = N->getOperand(i);
13041     unsigned ExtIndex =
13042         cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
13043 
13044     if (VectorMask[i] == (int)LeftIdx) {
13045       Mask[i] = ExtIndex;
13046     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13047       Mask[i] = Vec2Offset + ExtIndex;
13048     }
13049   }
13050 
13051   // The type the input vectors may have changed above.
13052   InVT1 = VecIn1.getValueType();
13053 
13054   // If we already have a VecIn2, it should have the same type as VecIn1.
13055   // If we don't, get an undef/zero vector of the appropriate type.
13056   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13057   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13058 
13059   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13060   if (ShuffleNumElems > NumElems)
13061     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13062 
13063   return Shuffle;
13064 }
13065 
13066 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13067 // operations. If the types of the vectors we're extracting from allow it,
13068 // turn this into a vector_shuffle node.
13069 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13070   SDLoc DL(N);
13071   EVT VT = N->getValueType(0);
13072 
13073   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13074   if (!isTypeLegal(VT))
13075     return SDValue();
13076 
13077   // May only combine to shuffle after legalize if shuffle is legal.
13078   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13079     return SDValue();
13080 
13081   bool UsesZeroVector = false;
13082   unsigned NumElems = N->getNumOperands();
13083 
13084   // Record, for each element of the newly built vector, which input vector
13085   // that element comes from. -1 stands for undef, 0 for the zero vector,
13086   // and positive values for the input vectors.
13087   // VectorMask maps each element to its vector number, and VecIn maps vector
13088   // numbers to their initial SDValues.
13089 
13090   SmallVector<int, 8> VectorMask(NumElems, -1);
13091   SmallVector<SDValue, 8> VecIn;
13092   VecIn.push_back(SDValue());
13093 
13094   for (unsigned i = 0; i != NumElems; ++i) {
13095     SDValue Op = N->getOperand(i);
13096 
13097     if (Op.isUndef())
13098       continue;
13099 
13100     // See if we can use a blend with a zero vector.
13101     // TODO: Should we generalize this to a blend with an arbitrary constant
13102     // vector?
13103     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13104       UsesZeroVector = true;
13105       VectorMask[i] = 0;
13106       continue;
13107     }
13108 
13109     // Not an undef or zero. If the input is something other than an
13110     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13111     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13112         !isa<ConstantSDNode>(Op.getOperand(1)))
13113       return SDValue();
13114 
13115     SDValue ExtractedFromVec = Op.getOperand(0);
13116 
13117     // All inputs must have the same element type as the output.
13118     if (VT.getVectorElementType() !=
13119         ExtractedFromVec.getValueType().getVectorElementType())
13120       return SDValue();
13121 
13122     // Have we seen this input vector before?
13123     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13124     // a map back from SDValues to numbers isn't worth it.
13125     unsigned Idx = std::distance(
13126         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13127     if (Idx == VecIn.size())
13128       VecIn.push_back(ExtractedFromVec);
13129 
13130     VectorMask[i] = Idx;
13131   }
13132 
13133   // If we didn't find at least one input vector, bail out.
13134   if (VecIn.size() < 2)
13135     return SDValue();
13136 
13137   // TODO: We want to sort the vectors by descending length, so that adjacent
13138   // pairs have similar length, and the longer vector is always first in the
13139   // pair.
13140 
13141   // TODO: Should this fire if some of the input vectors has illegal type (like
13142   // it does now), or should we let legalization run its course first?
13143 
13144   // Shuffle phase:
13145   // Take pairs of vectors, and shuffle them so that the result has elements
13146   // from these vectors in the correct places.
13147   // For example, given:
13148   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13149   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13150   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13151   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13152   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13153   // We will generate:
13154   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13155   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13156   SmallVector<SDValue, 4> Shuffles;
13157   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13158     unsigned LeftIdx = 2 * In + 1;
13159     SDValue VecLeft = VecIn[LeftIdx];
13160     SDValue VecRight =
13161         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13162 
13163     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13164                                                 VecRight, LeftIdx))
13165       Shuffles.push_back(Shuffle);
13166     else
13167       return SDValue();
13168   }
13169 
13170   // If we need the zero vector as an "ingredient" in the blend tree, add it
13171   // to the list of shuffles.
13172   if (UsesZeroVector)
13173     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13174                                       : DAG.getConstantFP(0.0, DL, VT));
13175 
13176   // If we only have one shuffle, we're done.
13177   if (Shuffles.size() == 1)
13178     return Shuffles[0];
13179 
13180   // Update the vector mask to point to the post-shuffle vectors.
13181   for (int &Vec : VectorMask)
13182     if (Vec == 0)
13183       Vec = Shuffles.size() - 1;
13184     else
13185       Vec = (Vec - 1) / 2;
13186 
13187   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13188   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13189   // generate:
13190   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13191   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13192   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13193   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13194   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13195   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13196   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13197 
13198   // Make sure the initial size of the shuffle list is even.
13199   if (Shuffles.size() % 2)
13200     Shuffles.push_back(DAG.getUNDEF(VT));
13201 
13202   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13203     if (CurSize % 2) {
13204       Shuffles[CurSize] = DAG.getUNDEF(VT);
13205       CurSize++;
13206     }
13207     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13208       int Left = 2 * In;
13209       int Right = 2 * In + 1;
13210       SmallVector<int, 8> Mask(NumElems, -1);
13211       for (unsigned i = 0; i != NumElems; ++i) {
13212         if (VectorMask[i] == Left) {
13213           Mask[i] = i;
13214           VectorMask[i] = In;
13215         } else if (VectorMask[i] == Right) {
13216           Mask[i] = i + NumElems;
13217           VectorMask[i] = In;
13218         }
13219       }
13220 
13221       Shuffles[In] =
13222           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13223     }
13224   }
13225 
13226   return Shuffles[0];
13227 }
13228 
13229 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13230   EVT VT = N->getValueType(0);
13231 
13232   // A vector built entirely of undefs is undef.
13233   if (ISD::allOperandsUndef(N))
13234     return DAG.getUNDEF(VT);
13235 
13236   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13237     return V;
13238 
13239   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13240     return V;
13241 
13242   if (SDValue V = reduceBuildVecToShuffle(N))
13243     return V;
13244 
13245   return SDValue();
13246 }
13247 
13248 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13249   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13250   EVT OpVT = N->getOperand(0).getValueType();
13251 
13252   // If the operands are legal vectors, leave them alone.
13253   if (TLI.isTypeLegal(OpVT))
13254     return SDValue();
13255 
13256   SDLoc DL(N);
13257   EVT VT = N->getValueType(0);
13258   SmallVector<SDValue, 8> Ops;
13259 
13260   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13261   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13262 
13263   // Keep track of what we encounter.
13264   bool AnyInteger = false;
13265   bool AnyFP = false;
13266   for (const SDValue &Op : N->ops()) {
13267     if (ISD::BITCAST == Op.getOpcode() &&
13268         !Op.getOperand(0).getValueType().isVector())
13269       Ops.push_back(Op.getOperand(0));
13270     else if (ISD::UNDEF == Op.getOpcode())
13271       Ops.push_back(ScalarUndef);
13272     else
13273       return SDValue();
13274 
13275     // Note whether we encounter an integer or floating point scalar.
13276     // If it's neither, bail out, it could be something weird like x86mmx.
13277     EVT LastOpVT = Ops.back().getValueType();
13278     if (LastOpVT.isFloatingPoint())
13279       AnyFP = true;
13280     else if (LastOpVT.isInteger())
13281       AnyInteger = true;
13282     else
13283       return SDValue();
13284   }
13285 
13286   // If any of the operands is a floating point scalar bitcast to a vector,
13287   // use floating point types throughout, and bitcast everything.
13288   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13289   if (AnyFP) {
13290     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13291     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13292     if (AnyInteger) {
13293       for (SDValue &Op : Ops) {
13294         if (Op.getValueType() == SVT)
13295           continue;
13296         if (Op.isUndef())
13297           Op = ScalarUndef;
13298         else
13299           Op = DAG.getBitcast(SVT, Op);
13300       }
13301     }
13302   }
13303 
13304   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13305                                VT.getSizeInBits() / SVT.getSizeInBits());
13306   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13307 }
13308 
13309 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13310 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13311 // most two distinct vectors the same size as the result, attempt to turn this
13312 // into a legal shuffle.
13313 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13314   EVT VT = N->getValueType(0);
13315   EVT OpVT = N->getOperand(0).getValueType();
13316   int NumElts = VT.getVectorNumElements();
13317   int NumOpElts = OpVT.getVectorNumElements();
13318 
13319   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13320   SmallVector<int, 8> Mask;
13321 
13322   for (SDValue Op : N->ops()) {
13323     // Peek through any bitcast.
13324     while (Op.getOpcode() == ISD::BITCAST)
13325       Op = Op.getOperand(0);
13326 
13327     // UNDEF nodes convert to UNDEF shuffle mask values.
13328     if (Op.isUndef()) {
13329       Mask.append((unsigned)NumOpElts, -1);
13330       continue;
13331     }
13332 
13333     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13334       return SDValue();
13335 
13336     // What vector are we extracting the subvector from and at what index?
13337     SDValue ExtVec = Op.getOperand(0);
13338 
13339     // We want the EVT of the original extraction to correctly scale the
13340     // extraction index.
13341     EVT ExtVT = ExtVec.getValueType();
13342 
13343     // Peek through any bitcast.
13344     while (ExtVec.getOpcode() == ISD::BITCAST)
13345       ExtVec = ExtVec.getOperand(0);
13346 
13347     // UNDEF nodes convert to UNDEF shuffle mask values.
13348     if (ExtVec.isUndef()) {
13349       Mask.append((unsigned)NumOpElts, -1);
13350       continue;
13351     }
13352 
13353     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13354       return SDValue();
13355     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13356 
13357     // Ensure that we are extracting a subvector from a vector the same
13358     // size as the result.
13359     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13360       return SDValue();
13361 
13362     // Scale the subvector index to account for any bitcast.
13363     int NumExtElts = ExtVT.getVectorNumElements();
13364     if (0 == (NumExtElts % NumElts))
13365       ExtIdx /= (NumExtElts / NumElts);
13366     else if (0 == (NumElts % NumExtElts))
13367       ExtIdx *= (NumElts / NumExtElts);
13368     else
13369       return SDValue();
13370 
13371     // At most we can reference 2 inputs in the final shuffle.
13372     if (SV0.isUndef() || SV0 == ExtVec) {
13373       SV0 = ExtVec;
13374       for (int i = 0; i != NumOpElts; ++i)
13375         Mask.push_back(i + ExtIdx);
13376     } else if (SV1.isUndef() || SV1 == ExtVec) {
13377       SV1 = ExtVec;
13378       for (int i = 0; i != NumOpElts; ++i)
13379         Mask.push_back(i + ExtIdx + NumElts);
13380     } else {
13381       return SDValue();
13382     }
13383   }
13384 
13385   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13386     return SDValue();
13387 
13388   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13389                               DAG.getBitcast(VT, SV1), Mask);
13390 }
13391 
13392 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13393   // If we only have one input vector, we don't need to do any concatenation.
13394   if (N->getNumOperands() == 1)
13395     return N->getOperand(0);
13396 
13397   // Check if all of the operands are undefs.
13398   EVT VT = N->getValueType(0);
13399   if (ISD::allOperandsUndef(N))
13400     return DAG.getUNDEF(VT);
13401 
13402   // Optimize concat_vectors where all but the first of the vectors are undef.
13403   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13404         return Op.isUndef();
13405       })) {
13406     SDValue In = N->getOperand(0);
13407     assert(In.getValueType().isVector() && "Must concat vectors");
13408 
13409     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13410     if (In->getOpcode() == ISD::BITCAST &&
13411         !In->getOperand(0)->getValueType(0).isVector()) {
13412       SDValue Scalar = In->getOperand(0);
13413 
13414       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13415       // look through the trunc so we can still do the transform:
13416       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13417       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13418           !TLI.isTypeLegal(Scalar.getValueType()) &&
13419           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13420         Scalar = Scalar->getOperand(0);
13421 
13422       EVT SclTy = Scalar->getValueType(0);
13423 
13424       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13425         return SDValue();
13426 
13427       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13428                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13429       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13430         return SDValue();
13431 
13432       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13433       return DAG.getBitcast(VT, Res);
13434     }
13435   }
13436 
13437   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13438   // We have already tested above for an UNDEF only concatenation.
13439   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13440   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13441   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13442     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13443   };
13444   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13445     SmallVector<SDValue, 8> Opnds;
13446     EVT SVT = VT.getScalarType();
13447 
13448     EVT MinVT = SVT;
13449     if (!SVT.isFloatingPoint()) {
13450       // If BUILD_VECTOR are from built from integer, they may have different
13451       // operand types. Get the smallest type and truncate all operands to it.
13452       bool FoundMinVT = false;
13453       for (const SDValue &Op : N->ops())
13454         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13455           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13456           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13457           FoundMinVT = true;
13458         }
13459       assert(FoundMinVT && "Concat vector type mismatch");
13460     }
13461 
13462     for (const SDValue &Op : N->ops()) {
13463       EVT OpVT = Op.getValueType();
13464       unsigned NumElts = OpVT.getVectorNumElements();
13465 
13466       if (ISD::UNDEF == Op.getOpcode())
13467         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13468 
13469       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13470         if (SVT.isFloatingPoint()) {
13471           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13472           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13473         } else {
13474           for (unsigned i = 0; i != NumElts; ++i)
13475             Opnds.push_back(
13476                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13477         }
13478       }
13479     }
13480 
13481     assert(VT.getVectorNumElements() == Opnds.size() &&
13482            "Concat vector type mismatch");
13483     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13484   }
13485 
13486   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13487   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13488     return V;
13489 
13490   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13491   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13492     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13493       return V;
13494 
13495   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13496   // nodes often generate nop CONCAT_VECTOR nodes.
13497   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13498   // place the incoming vectors at the exact same location.
13499   SDValue SingleSource = SDValue();
13500   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13501 
13502   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13503     SDValue Op = N->getOperand(i);
13504 
13505     if (Op.isUndef())
13506       continue;
13507 
13508     // Check if this is the identity extract:
13509     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13510       return SDValue();
13511 
13512     // Find the single incoming vector for the extract_subvector.
13513     if (SingleSource.getNode()) {
13514       if (Op.getOperand(0) != SingleSource)
13515         return SDValue();
13516     } else {
13517       SingleSource = Op.getOperand(0);
13518 
13519       // Check the source type is the same as the type of the result.
13520       // If not, this concat may extend the vector, so we can not
13521       // optimize it away.
13522       if (SingleSource.getValueType() != N->getValueType(0))
13523         return SDValue();
13524     }
13525 
13526     unsigned IdentityIndex = i * PartNumElem;
13527     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13528     // The extract index must be constant.
13529     if (!CS)
13530       return SDValue();
13531 
13532     // Check that we are reading from the identity index.
13533     if (CS->getZExtValue() != IdentityIndex)
13534       return SDValue();
13535   }
13536 
13537   if (SingleSource.getNode())
13538     return SingleSource;
13539 
13540   return SDValue();
13541 }
13542 
13543 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13544   EVT NVT = N->getValueType(0);
13545   SDValue V = N->getOperand(0);
13546 
13547   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13548     // Combine:
13549     //    (extract_subvec (concat V1, V2, ...), i)
13550     // Into:
13551     //    Vi if possible
13552     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13553     // type.
13554     if (V->getOperand(0).getValueType() != NVT)
13555       return SDValue();
13556     unsigned Idx = N->getConstantOperandVal(1);
13557     unsigned NumElems = NVT.getVectorNumElements();
13558     assert((Idx % NumElems) == 0 &&
13559            "IDX in concat is not a multiple of the result vector length.");
13560     return V->getOperand(Idx / NumElems);
13561   }
13562 
13563   // Skip bitcasting
13564   if (V->getOpcode() == ISD::BITCAST)
13565     V = V.getOperand(0);
13566 
13567   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13568     // Handle only simple case where vector being inserted and vector
13569     // being extracted are of same type, and are half size of larger vectors.
13570     EVT BigVT = V->getOperand(0).getValueType();
13571     EVT SmallVT = V->getOperand(1).getValueType();
13572     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13573       return SDValue();
13574 
13575     // Only handle cases where both indexes are constants with the same type.
13576     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13577     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13578 
13579     if (InsIdx && ExtIdx &&
13580         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13581         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13582       // Combine:
13583       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13584       // Into:
13585       //    indices are equal or bit offsets are equal => V1
13586       //    otherwise => (extract_subvec V1, ExtIdx)
13587       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13588           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13589         return DAG.getBitcast(NVT, V->getOperand(1));
13590       return DAG.getNode(
13591           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13592           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13593           N->getOperand(1));
13594     }
13595   }
13596 
13597   return SDValue();
13598 }
13599 
13600 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13601                                                  SDValue V, SelectionDAG &DAG) {
13602   SDLoc DL(V);
13603   EVT VT = V.getValueType();
13604 
13605   switch (V.getOpcode()) {
13606   default:
13607     return V;
13608 
13609   case ISD::CONCAT_VECTORS: {
13610     EVT OpVT = V->getOperand(0).getValueType();
13611     int OpSize = OpVT.getVectorNumElements();
13612     SmallBitVector OpUsedElements(OpSize, false);
13613     bool FoundSimplification = false;
13614     SmallVector<SDValue, 4> NewOps;
13615     NewOps.reserve(V->getNumOperands());
13616     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13617       SDValue Op = V->getOperand(i);
13618       bool OpUsed = false;
13619       for (int j = 0; j < OpSize; ++j)
13620         if (UsedElements[i * OpSize + j]) {
13621           OpUsedElements[j] = true;
13622           OpUsed = true;
13623         }
13624       NewOps.push_back(
13625           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13626                  : DAG.getUNDEF(OpVT));
13627       FoundSimplification |= Op == NewOps.back();
13628       OpUsedElements.reset();
13629     }
13630     if (FoundSimplification)
13631       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13632     return V;
13633   }
13634 
13635   case ISD::INSERT_SUBVECTOR: {
13636     SDValue BaseV = V->getOperand(0);
13637     SDValue SubV = V->getOperand(1);
13638     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13639     if (!IdxN)
13640       return V;
13641 
13642     int SubSize = SubV.getValueType().getVectorNumElements();
13643     int Idx = IdxN->getZExtValue();
13644     bool SubVectorUsed = false;
13645     SmallBitVector SubUsedElements(SubSize, false);
13646     for (int i = 0; i < SubSize; ++i)
13647       if (UsedElements[i + Idx]) {
13648         SubVectorUsed = true;
13649         SubUsedElements[i] = true;
13650         UsedElements[i + Idx] = false;
13651       }
13652 
13653     // Now recurse on both the base and sub vectors.
13654     SDValue SimplifiedSubV =
13655         SubVectorUsed
13656             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13657             : DAG.getUNDEF(SubV.getValueType());
13658     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13659     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13660       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13661                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13662     return V;
13663   }
13664   }
13665 }
13666 
13667 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13668                                        SDValue N1, SelectionDAG &DAG) {
13669   EVT VT = SVN->getValueType(0);
13670   int NumElts = VT.getVectorNumElements();
13671   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13672   for (int M : SVN->getMask())
13673     if (M >= 0 && M < NumElts)
13674       N0UsedElements[M] = true;
13675     else if (M >= NumElts)
13676       N1UsedElements[M - NumElts] = true;
13677 
13678   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13679   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13680   if (S0 == N0 && S1 == N1)
13681     return SDValue();
13682 
13683   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13684 }
13685 
13686 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13687 // or turn a shuffle of a single concat into simpler shuffle then concat.
13688 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13689   EVT VT = N->getValueType(0);
13690   unsigned NumElts = VT.getVectorNumElements();
13691 
13692   SDValue N0 = N->getOperand(0);
13693   SDValue N1 = N->getOperand(1);
13694   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13695 
13696   SmallVector<SDValue, 4> Ops;
13697   EVT ConcatVT = N0.getOperand(0).getValueType();
13698   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13699   unsigned NumConcats = NumElts / NumElemsPerConcat;
13700 
13701   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13702   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13703   // half vector elements.
13704   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13705       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13706                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13707     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13708                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13709     N1 = DAG.getUNDEF(ConcatVT);
13710     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13711   }
13712 
13713   // Look at every vector that's inserted. We're looking for exact
13714   // subvector-sized copies from a concatenated vector
13715   for (unsigned I = 0; I != NumConcats; ++I) {
13716     // Make sure we're dealing with a copy.
13717     unsigned Begin = I * NumElemsPerConcat;
13718     bool AllUndef = true, NoUndef = true;
13719     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13720       if (SVN->getMaskElt(J) >= 0)
13721         AllUndef = false;
13722       else
13723         NoUndef = false;
13724     }
13725 
13726     if (NoUndef) {
13727       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13728         return SDValue();
13729 
13730       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13731         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13732           return SDValue();
13733 
13734       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13735       if (FirstElt < N0.getNumOperands())
13736         Ops.push_back(N0.getOperand(FirstElt));
13737       else
13738         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13739 
13740     } else if (AllUndef) {
13741       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13742     } else { // Mixed with general masks and undefs, can't do optimization.
13743       return SDValue();
13744     }
13745   }
13746 
13747   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13748 }
13749 
13750 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13751   EVT VT = N->getValueType(0);
13752   unsigned NumElts = VT.getVectorNumElements();
13753 
13754   SDValue N0 = N->getOperand(0);
13755   SDValue N1 = N->getOperand(1);
13756 
13757   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13758 
13759   // Canonicalize shuffle undef, undef -> undef
13760   if (N0.isUndef() && N1.isUndef())
13761     return DAG.getUNDEF(VT);
13762 
13763   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13764 
13765   // Canonicalize shuffle v, v -> v, undef
13766   if (N0 == N1) {
13767     SmallVector<int, 8> NewMask;
13768     for (unsigned i = 0; i != NumElts; ++i) {
13769       int Idx = SVN->getMaskElt(i);
13770       if (Idx >= (int)NumElts) Idx -= NumElts;
13771       NewMask.push_back(Idx);
13772     }
13773     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13774   }
13775 
13776   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13777   if (N0.isUndef())
13778     return DAG.getCommutedVectorShuffle(*SVN);
13779 
13780   // Remove references to rhs if it is undef
13781   if (N1.isUndef()) {
13782     bool Changed = false;
13783     SmallVector<int, 8> NewMask;
13784     for (unsigned i = 0; i != NumElts; ++i) {
13785       int Idx = SVN->getMaskElt(i);
13786       if (Idx >= (int)NumElts) {
13787         Idx = -1;
13788         Changed = true;
13789       }
13790       NewMask.push_back(Idx);
13791     }
13792     if (Changed)
13793       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13794   }
13795 
13796   // If it is a splat, check if the argument vector is another splat or a
13797   // build_vector.
13798   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13799     SDNode *V = N0.getNode();
13800 
13801     // If this is a bit convert that changes the element type of the vector but
13802     // not the number of vector elements, look through it.  Be careful not to
13803     // look though conversions that change things like v4f32 to v2f64.
13804     if (V->getOpcode() == ISD::BITCAST) {
13805       SDValue ConvInput = V->getOperand(0);
13806       if (ConvInput.getValueType().isVector() &&
13807           ConvInput.getValueType().getVectorNumElements() == NumElts)
13808         V = ConvInput.getNode();
13809     }
13810 
13811     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13812       assert(V->getNumOperands() == NumElts &&
13813              "BUILD_VECTOR has wrong number of operands");
13814       SDValue Base;
13815       bool AllSame = true;
13816       for (unsigned i = 0; i != NumElts; ++i) {
13817         if (!V->getOperand(i).isUndef()) {
13818           Base = V->getOperand(i);
13819           break;
13820         }
13821       }
13822       // Splat of <u, u, u, u>, return <u, u, u, u>
13823       if (!Base.getNode())
13824         return N0;
13825       for (unsigned i = 0; i != NumElts; ++i) {
13826         if (V->getOperand(i) != Base) {
13827           AllSame = false;
13828           break;
13829         }
13830       }
13831       // Splat of <x, x, x, x>, return <x, x, x, x>
13832       if (AllSame)
13833         return N0;
13834 
13835       // Canonicalize any other splat as a build_vector.
13836       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13837       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13838       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13839 
13840       // We may have jumped through bitcasts, so the type of the
13841       // BUILD_VECTOR may not match the type of the shuffle.
13842       if (V->getValueType(0) != VT)
13843         NewBV = DAG.getBitcast(VT, NewBV);
13844       return NewBV;
13845     }
13846   }
13847 
13848   // There are various patterns used to build up a vector from smaller vectors,
13849   // subvectors, or elements. Scan chains of these and replace unused insertions
13850   // or components with undef.
13851   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13852     return S;
13853 
13854   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13855       Level < AfterLegalizeVectorOps &&
13856       (N1.isUndef() ||
13857       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13858        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13859     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13860       return V;
13861   }
13862 
13863   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13864   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13865   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13866     SmallVector<SDValue, 8> Ops;
13867     for (int M : SVN->getMask()) {
13868       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13869       if (M >= 0) {
13870         int Idx = M % NumElts;
13871         SDValue &S = (M < (int)NumElts ? N0 : N1);
13872         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13873           Op = S.getOperand(Idx);
13874         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13875           if (Idx == 0)
13876             Op = S.getOperand(0);
13877         } else {
13878           // Operand can't be combined - bail out.
13879           break;
13880         }
13881       }
13882       Ops.push_back(Op);
13883     }
13884     if (Ops.size() == VT.getVectorNumElements()) {
13885       // BUILD_VECTOR requires all inputs to be of the same type, find the
13886       // maximum type and extend them all.
13887       EVT SVT = VT.getScalarType();
13888       if (SVT.isInteger())
13889         for (SDValue &Op : Ops)
13890           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13891       if (SVT != VT.getScalarType())
13892         for (SDValue &Op : Ops)
13893           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13894                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13895                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13896       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13897     }
13898   }
13899 
13900   // If this shuffle only has a single input that is a bitcasted shuffle,
13901   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13902   // back to their original types.
13903   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13904       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13905       TLI.isTypeLegal(VT)) {
13906 
13907     // Peek through the bitcast only if there is one user.
13908     SDValue BC0 = N0;
13909     while (BC0.getOpcode() == ISD::BITCAST) {
13910       if (!BC0.hasOneUse())
13911         break;
13912       BC0 = BC0.getOperand(0);
13913     }
13914 
13915     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13916       if (Scale == 1)
13917         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13918 
13919       SmallVector<int, 8> NewMask;
13920       for (int M : Mask)
13921         for (int s = 0; s != Scale; ++s)
13922           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13923       return NewMask;
13924     };
13925 
13926     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13927       EVT SVT = VT.getScalarType();
13928       EVT InnerVT = BC0->getValueType(0);
13929       EVT InnerSVT = InnerVT.getScalarType();
13930 
13931       // Determine which shuffle works with the smaller scalar type.
13932       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13933       EVT ScaleSVT = ScaleVT.getScalarType();
13934 
13935       if (TLI.isTypeLegal(ScaleVT) &&
13936           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13937           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13938 
13939         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13940         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13941 
13942         // Scale the shuffle masks to the smaller scalar type.
13943         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13944         SmallVector<int, 8> InnerMask =
13945             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13946         SmallVector<int, 8> OuterMask =
13947             ScaleShuffleMask(SVN->getMask(), OuterScale);
13948 
13949         // Merge the shuffle masks.
13950         SmallVector<int, 8> NewMask;
13951         for (int M : OuterMask)
13952           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13953 
13954         // Test for shuffle mask legality over both commutations.
13955         SDValue SV0 = BC0->getOperand(0);
13956         SDValue SV1 = BC0->getOperand(1);
13957         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13958         if (!LegalMask) {
13959           std::swap(SV0, SV1);
13960           ShuffleVectorSDNode::commuteMask(NewMask);
13961           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13962         }
13963 
13964         if (LegalMask) {
13965           SV0 = DAG.getBitcast(ScaleVT, SV0);
13966           SV1 = DAG.getBitcast(ScaleVT, SV1);
13967           return DAG.getBitcast(
13968               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13969         }
13970       }
13971     }
13972   }
13973 
13974   // Canonicalize shuffles according to rules:
13975   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13976   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13977   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13978   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13979       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13980       TLI.isTypeLegal(VT)) {
13981     // The incoming shuffle must be of the same type as the result of the
13982     // current shuffle.
13983     assert(N1->getOperand(0).getValueType() == VT &&
13984            "Shuffle types don't match");
13985 
13986     SDValue SV0 = N1->getOperand(0);
13987     SDValue SV1 = N1->getOperand(1);
13988     bool HasSameOp0 = N0 == SV0;
13989     bool IsSV1Undef = SV1.isUndef();
13990     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13991       // Commute the operands of this shuffle so that next rule
13992       // will trigger.
13993       return DAG.getCommutedVectorShuffle(*SVN);
13994   }
13995 
13996   // Try to fold according to rules:
13997   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13998   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13999   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14000   // Don't try to fold shuffles with illegal type.
14001   // Only fold if this shuffle is the only user of the other shuffle.
14002   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14003       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14004     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14005 
14006     // The incoming shuffle must be of the same type as the result of the
14007     // current shuffle.
14008     assert(OtherSV->getOperand(0).getValueType() == VT &&
14009            "Shuffle types don't match");
14010 
14011     SDValue SV0, SV1;
14012     SmallVector<int, 4> Mask;
14013     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14014     // operand, and SV1 as the second operand.
14015     for (unsigned i = 0; i != NumElts; ++i) {
14016       int Idx = SVN->getMaskElt(i);
14017       if (Idx < 0) {
14018         // Propagate Undef.
14019         Mask.push_back(Idx);
14020         continue;
14021       }
14022 
14023       SDValue CurrentVec;
14024       if (Idx < (int)NumElts) {
14025         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14026         // shuffle mask to identify which vector is actually referenced.
14027         Idx = OtherSV->getMaskElt(Idx);
14028         if (Idx < 0) {
14029           // Propagate Undef.
14030           Mask.push_back(Idx);
14031           continue;
14032         }
14033 
14034         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14035                                            : OtherSV->getOperand(1);
14036       } else {
14037         // This shuffle index references an element within N1.
14038         CurrentVec = N1;
14039       }
14040 
14041       // Simple case where 'CurrentVec' is UNDEF.
14042       if (CurrentVec.isUndef()) {
14043         Mask.push_back(-1);
14044         continue;
14045       }
14046 
14047       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14048       // will be the first or second operand of the combined shuffle.
14049       Idx = Idx % NumElts;
14050       if (!SV0.getNode() || SV0 == CurrentVec) {
14051         // Ok. CurrentVec is the left hand side.
14052         // Update the mask accordingly.
14053         SV0 = CurrentVec;
14054         Mask.push_back(Idx);
14055         continue;
14056       }
14057 
14058       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14059       if (SV1.getNode() && SV1 != CurrentVec)
14060         return SDValue();
14061 
14062       // Ok. CurrentVec is the right hand side.
14063       // Update the mask accordingly.
14064       SV1 = CurrentVec;
14065       Mask.push_back(Idx + NumElts);
14066     }
14067 
14068     // Check if all indices in Mask are Undef. In case, propagate Undef.
14069     bool isUndefMask = true;
14070     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14071       isUndefMask &= Mask[i] < 0;
14072 
14073     if (isUndefMask)
14074       return DAG.getUNDEF(VT);
14075 
14076     if (!SV0.getNode())
14077       SV0 = DAG.getUNDEF(VT);
14078     if (!SV1.getNode())
14079       SV1 = DAG.getUNDEF(VT);
14080 
14081     // Avoid introducing shuffles with illegal mask.
14082     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14083       ShuffleVectorSDNode::commuteMask(Mask);
14084 
14085       if (!TLI.isShuffleMaskLegal(Mask, VT))
14086         return SDValue();
14087 
14088       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14089       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14090       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14091       std::swap(SV0, SV1);
14092     }
14093 
14094     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14095     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14096     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14097     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14098   }
14099 
14100   return SDValue();
14101 }
14102 
14103 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14104   SDValue InVal = N->getOperand(0);
14105   EVT VT = N->getValueType(0);
14106 
14107   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14108   // with a VECTOR_SHUFFLE.
14109   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14110     SDValue InVec = InVal->getOperand(0);
14111     SDValue EltNo = InVal->getOperand(1);
14112 
14113     // FIXME: We could support implicit truncation if the shuffle can be
14114     // scaled to a smaller vector scalar type.
14115     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14116     if (C0 && VT == InVec.getValueType() &&
14117         VT.getScalarType() == InVal.getValueType()) {
14118       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14119       int Elt = C0->getZExtValue();
14120       NewMask[0] = Elt;
14121 
14122       if (TLI.isShuffleMaskLegal(NewMask, VT))
14123         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14124                                     NewMask);
14125     }
14126   }
14127 
14128   return SDValue();
14129 }
14130 
14131 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14132   EVT VT = N->getValueType(0);
14133   SDValue N0 = N->getOperand(0);
14134   SDValue N1 = N->getOperand(1);
14135   SDValue N2 = N->getOperand(2);
14136 
14137   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14138   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14139   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14140   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14141       N0.getOperand(1).getValueType() == N1.getValueType() &&
14142       N0.getOperand(2) == N2)
14143     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14144                        N1, N2);
14145 
14146   if (N0.getValueType() != N1.getValueType())
14147     return SDValue();
14148 
14149   // If the input vector is a concatenation, and the insert replaces
14150   // one of the halves, we can optimize into a single concat_vectors.
14151   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14152       N2.getOpcode() == ISD::Constant) {
14153     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14154 
14155     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14156     // (concat_vectors Z, Y)
14157     if (InsIdx == 0)
14158       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14159                          N0.getOperand(1));
14160 
14161     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14162     // (concat_vectors X, Z)
14163     if (InsIdx == VT.getVectorNumElements() / 2)
14164       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14165                          N1);
14166   }
14167 
14168   return SDValue();
14169 }
14170 
14171 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14172   SDValue N0 = N->getOperand(0);
14173 
14174   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14175   if (N0->getOpcode() == ISD::FP16_TO_FP)
14176     return N0->getOperand(0);
14177 
14178   return SDValue();
14179 }
14180 
14181 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14182   SDValue N0 = N->getOperand(0);
14183 
14184   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14185   if (N0->getOpcode() == ISD::AND) {
14186     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14187     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14188       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14189                          N0.getOperand(0));
14190     }
14191   }
14192 
14193   return SDValue();
14194 }
14195 
14196 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14197 /// with the destination vector and a zero vector.
14198 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14199 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14200 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14201   EVT VT = N->getValueType(0);
14202   SDValue LHS = N->getOperand(0);
14203   SDValue RHS = N->getOperand(1);
14204   SDLoc DL(N);
14205 
14206   // Make sure we're not running after operation legalization where it
14207   // may have custom lowered the vector shuffles.
14208   if (LegalOperations)
14209     return SDValue();
14210 
14211   if (N->getOpcode() != ISD::AND)
14212     return SDValue();
14213 
14214   if (RHS.getOpcode() == ISD::BITCAST)
14215     RHS = RHS.getOperand(0);
14216 
14217   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14218     return SDValue();
14219 
14220   EVT RVT = RHS.getValueType();
14221   unsigned NumElts = RHS.getNumOperands();
14222 
14223   // Attempt to create a valid clear mask, splitting the mask into
14224   // sub elements and checking to see if each is
14225   // all zeros or all ones - suitable for shuffle masking.
14226   auto BuildClearMask = [&](int Split) {
14227     int NumSubElts = NumElts * Split;
14228     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14229 
14230     SmallVector<int, 8> Indices;
14231     for (int i = 0; i != NumSubElts; ++i) {
14232       int EltIdx = i / Split;
14233       int SubIdx = i % Split;
14234       SDValue Elt = RHS.getOperand(EltIdx);
14235       if (Elt.isUndef()) {
14236         Indices.push_back(-1);
14237         continue;
14238       }
14239 
14240       APInt Bits;
14241       if (isa<ConstantSDNode>(Elt))
14242         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14243       else if (isa<ConstantFPSDNode>(Elt))
14244         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14245       else
14246         return SDValue();
14247 
14248       // Extract the sub element from the constant bit mask.
14249       if (DAG.getDataLayout().isBigEndian()) {
14250         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14251       } else {
14252         Bits = Bits.lshr(SubIdx * NumSubBits);
14253       }
14254 
14255       if (Split > 1)
14256         Bits = Bits.trunc(NumSubBits);
14257 
14258       if (Bits.isAllOnesValue())
14259         Indices.push_back(i);
14260       else if (Bits == 0)
14261         Indices.push_back(i + NumSubElts);
14262       else
14263         return SDValue();
14264     }
14265 
14266     // Let's see if the target supports this vector_shuffle.
14267     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14268     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14269     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14270       return SDValue();
14271 
14272     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14273     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14274                                                    DAG.getBitcast(ClearVT, LHS),
14275                                                    Zero, Indices));
14276   };
14277 
14278   // Determine maximum split level (byte level masking).
14279   int MaxSplit = 1;
14280   if (RVT.getScalarSizeInBits() % 8 == 0)
14281     MaxSplit = RVT.getScalarSizeInBits() / 8;
14282 
14283   for (int Split = 1; Split <= MaxSplit; ++Split)
14284     if (RVT.getScalarSizeInBits() % Split == 0)
14285       if (SDValue S = BuildClearMask(Split))
14286         return S;
14287 
14288   return SDValue();
14289 }
14290 
14291 /// Visit a binary vector operation, like ADD.
14292 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14293   assert(N->getValueType(0).isVector() &&
14294          "SimplifyVBinOp only works on vectors!");
14295 
14296   SDValue LHS = N->getOperand(0);
14297   SDValue RHS = N->getOperand(1);
14298   SDValue Ops[] = {LHS, RHS};
14299 
14300   // See if we can constant fold the vector operation.
14301   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14302           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14303     return Fold;
14304 
14305   // Try to convert a constant mask AND into a shuffle clear mask.
14306   if (SDValue Shuffle = XformToShuffleWithZero(N))
14307     return Shuffle;
14308 
14309   // Type legalization might introduce new shuffles in the DAG.
14310   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14311   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14312   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14313       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14314       LHS.getOperand(1).isUndef() &&
14315       RHS.getOperand(1).isUndef()) {
14316     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14317     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14318 
14319     if (SVN0->getMask().equals(SVN1->getMask())) {
14320       EVT VT = N->getValueType(0);
14321       SDValue UndefVector = LHS.getOperand(1);
14322       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14323                                      LHS.getOperand(0), RHS.getOperand(0),
14324                                      N->getFlags());
14325       AddUsersToWorklist(N);
14326       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14327                                   SVN0->getMask());
14328     }
14329   }
14330 
14331   return SDValue();
14332 }
14333 
14334 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14335                                     SDValue N2) {
14336   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14337 
14338   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14339                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14340 
14341   // If we got a simplified select_cc node back from SimplifySelectCC, then
14342   // break it down into a new SETCC node, and a new SELECT node, and then return
14343   // the SELECT node, since we were called with a SELECT node.
14344   if (SCC.getNode()) {
14345     // Check to see if we got a select_cc back (to turn into setcc/select).
14346     // Otherwise, just return whatever node we got back, like fabs.
14347     if (SCC.getOpcode() == ISD::SELECT_CC) {
14348       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14349                                   N0.getValueType(),
14350                                   SCC.getOperand(0), SCC.getOperand(1),
14351                                   SCC.getOperand(4));
14352       AddToWorklist(SETCC.getNode());
14353       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14354                            SCC.getOperand(2), SCC.getOperand(3));
14355     }
14356 
14357     return SCC;
14358   }
14359   return SDValue();
14360 }
14361 
14362 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14363 /// being selected between, see if we can simplify the select.  Callers of this
14364 /// should assume that TheSelect is deleted if this returns true.  As such, they
14365 /// should return the appropriate thing (e.g. the node) back to the top-level of
14366 /// the DAG combiner loop to avoid it being looked at.
14367 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14368                                     SDValue RHS) {
14369 
14370   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14371   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14372   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14373     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14374       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14375       SDValue Sqrt = RHS;
14376       ISD::CondCode CC;
14377       SDValue CmpLHS;
14378       const ConstantFPSDNode *Zero = nullptr;
14379 
14380       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14381         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14382         CmpLHS = TheSelect->getOperand(0);
14383         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14384       } else {
14385         // SELECT or VSELECT
14386         SDValue Cmp = TheSelect->getOperand(0);
14387         if (Cmp.getOpcode() == ISD::SETCC) {
14388           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14389           CmpLHS = Cmp.getOperand(0);
14390           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14391         }
14392       }
14393       if (Zero && Zero->isZero() &&
14394           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14395           CC == ISD::SETULT || CC == ISD::SETLT)) {
14396         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14397         CombineTo(TheSelect, Sqrt);
14398         return true;
14399       }
14400     }
14401   }
14402   // Cannot simplify select with vector condition
14403   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14404 
14405   // If this is a select from two identical things, try to pull the operation
14406   // through the select.
14407   if (LHS.getOpcode() != RHS.getOpcode() ||
14408       !LHS.hasOneUse() || !RHS.hasOneUse())
14409     return false;
14410 
14411   // If this is a load and the token chain is identical, replace the select
14412   // of two loads with a load through a select of the address to load from.
14413   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14414   // constants have been dropped into the constant pool.
14415   if (LHS.getOpcode() == ISD::LOAD) {
14416     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14417     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14418 
14419     // Token chains must be identical.
14420     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14421         // Do not let this transformation reduce the number of volatile loads.
14422         LLD->isVolatile() || RLD->isVolatile() ||
14423         // FIXME: If either is a pre/post inc/dec load,
14424         // we'd need to split out the address adjustment.
14425         LLD->isIndexed() || RLD->isIndexed() ||
14426         // If this is an EXTLOAD, the VT's must match.
14427         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14428         // If this is an EXTLOAD, the kind of extension must match.
14429         (LLD->getExtensionType() != RLD->getExtensionType() &&
14430          // The only exception is if one of the extensions is anyext.
14431          LLD->getExtensionType() != ISD::EXTLOAD &&
14432          RLD->getExtensionType() != ISD::EXTLOAD) ||
14433         // FIXME: this discards src value information.  This is
14434         // over-conservative. It would be beneficial to be able to remember
14435         // both potential memory locations.  Since we are discarding
14436         // src value info, don't do the transformation if the memory
14437         // locations are not in the default address space.
14438         LLD->getPointerInfo().getAddrSpace() != 0 ||
14439         RLD->getPointerInfo().getAddrSpace() != 0 ||
14440         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14441                                       LLD->getBasePtr().getValueType()))
14442       return false;
14443 
14444     // Check that the select condition doesn't reach either load.  If so,
14445     // folding this will induce a cycle into the DAG.  If not, this is safe to
14446     // xform, so create a select of the addresses.
14447     SDValue Addr;
14448     if (TheSelect->getOpcode() == ISD::SELECT) {
14449       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14450       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14451           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14452         return false;
14453       // The loads must not depend on one another.
14454       if (LLD->isPredecessorOf(RLD) ||
14455           RLD->isPredecessorOf(LLD))
14456         return false;
14457       Addr = DAG.getSelect(SDLoc(TheSelect),
14458                            LLD->getBasePtr().getValueType(),
14459                            TheSelect->getOperand(0), LLD->getBasePtr(),
14460                            RLD->getBasePtr());
14461     } else {  // Otherwise SELECT_CC
14462       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14463       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14464 
14465       if ((LLD->hasAnyUseOfValue(1) &&
14466            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14467           (RLD->hasAnyUseOfValue(1) &&
14468            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14469         return false;
14470 
14471       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14472                          LLD->getBasePtr().getValueType(),
14473                          TheSelect->getOperand(0),
14474                          TheSelect->getOperand(1),
14475                          LLD->getBasePtr(), RLD->getBasePtr(),
14476                          TheSelect->getOperand(4));
14477     }
14478 
14479     SDValue Load;
14480     // It is safe to replace the two loads if they have different alignments,
14481     // but the new load must be the minimum (most restrictive) alignment of the
14482     // inputs.
14483     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14484     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14485     if (!RLD->isInvariant())
14486       MMOFlags &= ~MachineMemOperand::MOInvariant;
14487     if (!RLD->isDereferenceable())
14488       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14489     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14490       // FIXME: Discards pointer and AA info.
14491       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14492                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14493                          MMOFlags);
14494     } else {
14495       // FIXME: Discards pointer and AA info.
14496       Load = DAG.getExtLoad(
14497           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14498                                                   : LLD->getExtensionType(),
14499           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14500           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14501     }
14502 
14503     // Users of the select now use the result of the load.
14504     CombineTo(TheSelect, Load);
14505 
14506     // Users of the old loads now use the new load's chain.  We know the
14507     // old-load value is dead now.
14508     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14509     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14510     return true;
14511   }
14512 
14513   return false;
14514 }
14515 
14516 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14517 /// where 'cond' is the comparison specified by CC.
14518 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14519                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14520                                       bool NotExtCompare) {
14521   // (x ? y : y) -> y.
14522   if (N2 == N3) return N2;
14523 
14524   EVT VT = N2.getValueType();
14525   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14526   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14527 
14528   // Determine if the condition we're dealing with is constant
14529   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14530                               N0, N1, CC, DL, false);
14531   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14532 
14533   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14534     // fold select_cc true, x, y -> x
14535     // fold select_cc false, x, y -> y
14536     return !SCCC->isNullValue() ? N2 : N3;
14537   }
14538 
14539   // Check to see if we can simplify the select into an fabs node
14540   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14541     // Allow either -0.0 or 0.0
14542     if (CFP->isZero()) {
14543       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14544       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14545           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14546           N2 == N3.getOperand(0))
14547         return DAG.getNode(ISD::FABS, DL, VT, N0);
14548 
14549       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14550       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14551           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14552           N2.getOperand(0) == N3)
14553         return DAG.getNode(ISD::FABS, DL, VT, N3);
14554     }
14555   }
14556 
14557   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14558   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14559   // in it.  This is a win when the constant is not otherwise available because
14560   // it replaces two constant pool loads with one.  We only do this if the FP
14561   // type is known to be legal, because if it isn't, then we are before legalize
14562   // types an we want the other legalization to happen first (e.g. to avoid
14563   // messing with soft float) and if the ConstantFP is not legal, because if
14564   // it is legal, we may not need to store the FP constant in a constant pool.
14565   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14566     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14567       if (TLI.isTypeLegal(N2.getValueType()) &&
14568           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14569                TargetLowering::Legal &&
14570            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14571            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14572           // If both constants have multiple uses, then we won't need to do an
14573           // extra load, they are likely around in registers for other users.
14574           (TV->hasOneUse() || FV->hasOneUse())) {
14575         Constant *Elts[] = {
14576           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14577           const_cast<ConstantFP*>(TV->getConstantFPValue())
14578         };
14579         Type *FPTy = Elts[0]->getType();
14580         const DataLayout &TD = DAG.getDataLayout();
14581 
14582         // Create a ConstantArray of the two constants.
14583         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14584         SDValue CPIdx =
14585             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14586                                 TD.getPrefTypeAlignment(FPTy));
14587         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14588 
14589         // Get the offsets to the 0 and 1 element of the array so that we can
14590         // select between them.
14591         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14592         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14593         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14594 
14595         SDValue Cond = DAG.getSetCC(DL,
14596                                     getSetCCResultType(N0.getValueType()),
14597                                     N0, N1, CC);
14598         AddToWorklist(Cond.getNode());
14599         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14600                                           Cond, One, Zero);
14601         AddToWorklist(CstOffset.getNode());
14602         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14603                             CstOffset);
14604         AddToWorklist(CPIdx.getNode());
14605         return DAG.getLoad(
14606             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14607             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14608             Alignment);
14609       }
14610     }
14611 
14612   // Check to see if we can perform the "gzip trick", transforming
14613   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14614   if (isNullConstant(N3) && CC == ISD::SETLT &&
14615       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14616        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14617     EVT XType = N0.getValueType();
14618     EVT AType = N2.getValueType();
14619     if (XType.bitsGE(AType)) {
14620       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14621       // single-bit constant.
14622       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14623         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14624         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14625         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14626                                        getShiftAmountTy(N0.getValueType()));
14627         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14628                                     XType, N0, ShCt);
14629         AddToWorklist(Shift.getNode());
14630 
14631         if (XType.bitsGT(AType)) {
14632           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14633           AddToWorklist(Shift.getNode());
14634         }
14635 
14636         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14637       }
14638 
14639       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14640                                   XType, N0,
14641                                   DAG.getConstant(XType.getSizeInBits() - 1,
14642                                                   SDLoc(N0),
14643                                          getShiftAmountTy(N0.getValueType())));
14644       AddToWorklist(Shift.getNode());
14645 
14646       if (XType.bitsGT(AType)) {
14647         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14648         AddToWorklist(Shift.getNode());
14649       }
14650 
14651       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14652     }
14653   }
14654 
14655   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14656   // where y is has a single bit set.
14657   // A plaintext description would be, we can turn the SELECT_CC into an AND
14658   // when the condition can be materialized as an all-ones register.  Any
14659   // single bit-test can be materialized as an all-ones register with
14660   // shift-left and shift-right-arith.
14661   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14662       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14663     SDValue AndLHS = N0->getOperand(0);
14664     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14665     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14666       // Shift the tested bit over the sign bit.
14667       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14668       SDValue ShlAmt =
14669         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14670                         getShiftAmountTy(AndLHS.getValueType()));
14671       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14672 
14673       // Now arithmetic right shift it all the way over, so the result is either
14674       // all-ones, or zero.
14675       SDValue ShrAmt =
14676         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14677                         getShiftAmountTy(Shl.getValueType()));
14678       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14679 
14680       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14681     }
14682   }
14683 
14684   // fold select C, 16, 0 -> shl C, 4
14685   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14686       TLI.getBooleanContents(N0.getValueType()) ==
14687           TargetLowering::ZeroOrOneBooleanContent) {
14688 
14689     // If the caller doesn't want us to simplify this into a zext of a compare,
14690     // don't do it.
14691     if (NotExtCompare && N2C->isOne())
14692       return SDValue();
14693 
14694     // Get a SetCC of the condition
14695     // NOTE: Don't create a SETCC if it's not legal on this target.
14696     if (!LegalOperations ||
14697         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14698       SDValue Temp, SCC;
14699       // cast from setcc result type to select result type
14700       if (LegalTypes) {
14701         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14702                             N0, N1, CC);
14703         if (N2.getValueType().bitsLT(SCC.getValueType()))
14704           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14705                                         N2.getValueType());
14706         else
14707           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14708                              N2.getValueType(), SCC);
14709       } else {
14710         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14711         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14712                            N2.getValueType(), SCC);
14713       }
14714 
14715       AddToWorklist(SCC.getNode());
14716       AddToWorklist(Temp.getNode());
14717 
14718       if (N2C->isOne())
14719         return Temp;
14720 
14721       // shl setcc result by log2 n2c
14722       return DAG.getNode(
14723           ISD::SHL, DL, N2.getValueType(), Temp,
14724           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14725                           getShiftAmountTy(Temp.getValueType())));
14726     }
14727   }
14728 
14729   // Check to see if this is an integer abs.
14730   // select_cc setg[te] X,  0,  X, -X ->
14731   // select_cc setgt    X, -1,  X, -X ->
14732   // select_cc setl[te] X,  0, -X,  X ->
14733   // select_cc setlt    X,  1, -X,  X ->
14734   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14735   if (N1C) {
14736     ConstantSDNode *SubC = nullptr;
14737     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14738          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14739         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14740       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14741     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14742               (N1C->isOne() && CC == ISD::SETLT)) &&
14743              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14744       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14745 
14746     EVT XType = N0.getValueType();
14747     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14748       SDLoc DL(N0);
14749       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14750                                   N0,
14751                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14752                                          getShiftAmountTy(N0.getValueType())));
14753       SDValue Add = DAG.getNode(ISD::ADD, DL,
14754                                 XType, N0, Shift);
14755       AddToWorklist(Shift.getNode());
14756       AddToWorklist(Add.getNode());
14757       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14758     }
14759   }
14760 
14761   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14762   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14763   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14764   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14765   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14766   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14767   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14768   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14769   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14770     SDValue ValueOnZero = N2;
14771     SDValue Count = N3;
14772     // If the condition is NE instead of E, swap the operands.
14773     if (CC == ISD::SETNE)
14774       std::swap(ValueOnZero, Count);
14775     // Check if the value on zero is a constant equal to the bits in the type.
14776     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14777       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14778         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14779         // legal, combine to just cttz.
14780         if ((Count.getOpcode() == ISD::CTTZ ||
14781              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14782             N0 == Count.getOperand(0) &&
14783             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14784           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14785         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14786         // legal, combine to just ctlz.
14787         if ((Count.getOpcode() == ISD::CTLZ ||
14788              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14789             N0 == Count.getOperand(0) &&
14790             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14791           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14792       }
14793     }
14794   }
14795 
14796   return SDValue();
14797 }
14798 
14799 /// This is a stub for TargetLowering::SimplifySetCC.
14800 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14801                                    ISD::CondCode Cond, const SDLoc &DL,
14802                                    bool foldBooleans) {
14803   TargetLowering::DAGCombinerInfo
14804     DagCombineInfo(DAG, Level, false, this);
14805   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14806 }
14807 
14808 /// Given an ISD::SDIV node expressing a divide by constant, return
14809 /// a DAG expression to select that will generate the same value by multiplying
14810 /// by a magic number.
14811 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14812 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14813   // when optimising for minimum size, we don't want to expand a div to a mul
14814   // and a shift.
14815   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14816     return SDValue();
14817 
14818   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14819   if (!C)
14820     return SDValue();
14821 
14822   // Avoid division by zero.
14823   if (C->isNullValue())
14824     return SDValue();
14825 
14826   std::vector<SDNode*> Built;
14827   SDValue S =
14828       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14829 
14830   for (SDNode *N : Built)
14831     AddToWorklist(N);
14832   return S;
14833 }
14834 
14835 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14836 /// DAG expression that will generate the same value by right shifting.
14837 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14838   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14839   if (!C)
14840     return SDValue();
14841 
14842   // Avoid division by zero.
14843   if (C->isNullValue())
14844     return SDValue();
14845 
14846   std::vector<SDNode *> Built;
14847   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14848 
14849   for (SDNode *N : Built)
14850     AddToWorklist(N);
14851   return S;
14852 }
14853 
14854 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14855 /// expression that will generate the same value by multiplying by a magic
14856 /// number.
14857 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14858 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14859   // when optimising for minimum size, we don't want to expand a div to a mul
14860   // and a shift.
14861   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14862     return SDValue();
14863 
14864   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14865   if (!C)
14866     return SDValue();
14867 
14868   // Avoid division by zero.
14869   if (C->isNullValue())
14870     return SDValue();
14871 
14872   std::vector<SDNode*> Built;
14873   SDValue S =
14874       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14875 
14876   for (SDNode *N : Built)
14877     AddToWorklist(N);
14878   return S;
14879 }
14880 
14881 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14882   if (Level >= AfterLegalizeDAG)
14883     return SDValue();
14884 
14885   // TODO: Handle half and/or extended types?
14886   EVT VT = Op.getValueType();
14887   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
14888     return SDValue();
14889 
14890   // If estimates are explicitly disabled for this function, we're done.
14891   MachineFunction &MF = DAG.getMachineFunction();
14892   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
14893   if (Enabled == TLI.ReciprocalEstimate::Disabled)
14894     return SDValue();
14895 
14896   // Estimates may be explicitly enabled for this type with a custom number of
14897   // refinement steps.
14898   int Iterations = TLI.getDivRefinementSteps(VT, MF);
14899   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
14900     if (Iterations) {
14901       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14902       // For the reciprocal, we need to find the zero of the function:
14903       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14904       //     =>
14905       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14906       //     does not require additional intermediate precision]
14907       EVT VT = Op.getValueType();
14908       SDLoc DL(Op);
14909       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14910 
14911       AddToWorklist(Est.getNode());
14912 
14913       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14914       for (int i = 0; i < Iterations; ++i) {
14915         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14916         AddToWorklist(NewEst.getNode());
14917 
14918         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14919         AddToWorklist(NewEst.getNode());
14920 
14921         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14922         AddToWorklist(NewEst.getNode());
14923 
14924         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14925         AddToWorklist(Est.getNode());
14926       }
14927     }
14928     return Est;
14929   }
14930 
14931   return SDValue();
14932 }
14933 
14934 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14935 /// For the reciprocal sqrt, we need to find the zero of the function:
14936 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14937 ///     =>
14938 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14939 /// As a result, we precompute A/2 prior to the iteration loop.
14940 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14941                                          unsigned Iterations,
14942                                          SDNodeFlags *Flags, bool Reciprocal) {
14943   EVT VT = Arg.getValueType();
14944   SDLoc DL(Arg);
14945   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14946 
14947   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14948   // this entire sequence requires only one FP constant.
14949   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14950   AddToWorklist(HalfArg.getNode());
14951 
14952   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14953   AddToWorklist(HalfArg.getNode());
14954 
14955   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14956   for (unsigned i = 0; i < Iterations; ++i) {
14957     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14958     AddToWorklist(NewEst.getNode());
14959 
14960     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14961     AddToWorklist(NewEst.getNode());
14962 
14963     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14964     AddToWorklist(NewEst.getNode());
14965 
14966     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14967     AddToWorklist(Est.getNode());
14968   }
14969 
14970   // If non-reciprocal square root is requested, multiply the result by Arg.
14971   if (!Reciprocal) {
14972     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14973     AddToWorklist(Est.getNode());
14974   }
14975 
14976   return Est;
14977 }
14978 
14979 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14980 /// For the reciprocal sqrt, we need to find the zero of the function:
14981 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14982 ///     =>
14983 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14984 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
14985                                          unsigned Iterations,
14986                                          SDNodeFlags *Flags, bool Reciprocal) {
14987   EVT VT = Arg.getValueType();
14988   SDLoc DL(Arg);
14989   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14990   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14991 
14992   // This routine must enter the loop below to work correctly
14993   // when (Reciprocal == false).
14994   assert(Iterations > 0);
14995 
14996   // Newton iterations for reciprocal square root:
14997   // E = (E * -0.5) * ((A * E) * E + -3.0)
14998   for (unsigned i = 0; i < Iterations; ++i) {
14999     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15000     AddToWorklist(AE.getNode());
15001 
15002     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15003     AddToWorklist(AEE.getNode());
15004 
15005     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15006     AddToWorklist(RHS.getNode());
15007 
15008     // When calculating a square root at the last iteration build:
15009     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15010     // (notice a common subexpression)
15011     SDValue LHS;
15012     if (Reciprocal || (i + 1) < Iterations) {
15013       // RSQRT: LHS = (E * -0.5)
15014       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15015     } else {
15016       // SQRT: LHS = (A * E) * -0.5
15017       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15018     }
15019     AddToWorklist(LHS.getNode());
15020 
15021     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15022     AddToWorklist(Est.getNode());
15023   }
15024 
15025   return Est;
15026 }
15027 
15028 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15029 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15030 /// Op can be zero.
15031 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15032                                            bool Reciprocal) {
15033   if (Level >= AfterLegalizeDAG)
15034     return SDValue();
15035 
15036   // TODO: Handle half and/or extended types?
15037   EVT VT = Op.getValueType();
15038   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15039     return SDValue();
15040 
15041   // If estimates are explicitly disabled for this function, we're done.
15042   MachineFunction &MF = DAG.getMachineFunction();
15043   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15044   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15045     return SDValue();
15046 
15047   // Estimates may be explicitly enabled for this type with a custom number of
15048   // refinement steps.
15049   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15050 
15051   bool UseOneConstNR = false;
15052   if (SDValue Est =
15053       TLI.getRsqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR)) {
15054     AddToWorklist(Est.getNode());
15055     if (Iterations) {
15056       Est = UseOneConstNR
15057       ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15058       : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15059     }
15060     return Est;
15061   }
15062 
15063   return SDValue();
15064 }
15065 
15066 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15067   return buildSqrtEstimateImpl(Op, Flags, true);
15068 }
15069 
15070 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15071   SDValue Est = buildSqrtEstimateImpl(Op, Flags, false);
15072   if (!Est)
15073     return SDValue();
15074 
15075   // Unfortunately, Est is now NaN if the input was exactly 0.
15076   // Select out this case and force the answer to 0.
15077   EVT VT = Est.getValueType();
15078   SDLoc DL(Op);
15079   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
15080   EVT CCVT = getSetCCResultType(VT);
15081   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ);
15082   AddToWorklist(ZeroCmp.getNode());
15083 
15084   Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp,
15085                     Zero, Est);
15086   AddToWorklist(Est.getNode());
15087   return Est;
15088 }
15089 
15090 /// Return true if base is a frame index, which is known not to alias with
15091 /// anything but itself.  Provides base object and offset as results.
15092 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15093                            const GlobalValue *&GV, const void *&CV) {
15094   // Assume it is a primitive operation.
15095   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15096 
15097   // If it's an adding a simple constant then integrate the offset.
15098   if (Base.getOpcode() == ISD::ADD) {
15099     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15100       Base = Base.getOperand(0);
15101       Offset += C->getZExtValue();
15102     }
15103   }
15104 
15105   // Return the underlying GlobalValue, and update the Offset.  Return false
15106   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15107   // by multiple nodes with different offsets.
15108   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15109     GV = G->getGlobal();
15110     Offset += G->getOffset();
15111     return false;
15112   }
15113 
15114   // Return the underlying Constant value, and update the Offset.  Return false
15115   // for ConstantSDNodes since the same constant pool entry may be represented
15116   // by multiple nodes with different offsets.
15117   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15118     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15119                                          : (const void *)C->getConstVal();
15120     Offset += C->getOffset();
15121     return false;
15122   }
15123   // If it's any of the following then it can't alias with anything but itself.
15124   return isa<FrameIndexSDNode>(Base);
15125 }
15126 
15127 /// Return true if there is any possibility that the two addresses overlap.
15128 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15129   // If they are the same then they must be aliases.
15130   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15131 
15132   // If they are both volatile then they cannot be reordered.
15133   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15134 
15135   // If one operation reads from invariant memory, and the other may store, they
15136   // cannot alias. These should really be checking the equivalent of mayWrite,
15137   // but it only matters for memory nodes other than load /store.
15138   if (Op0->isInvariant() && Op1->writeMem())
15139     return false;
15140 
15141   if (Op1->isInvariant() && Op0->writeMem())
15142     return false;
15143 
15144   // Gather base node and offset information.
15145   SDValue Base1, Base2;
15146   int64_t Offset1, Offset2;
15147   const GlobalValue *GV1, *GV2;
15148   const void *CV1, *CV2;
15149   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15150                                       Base1, Offset1, GV1, CV1);
15151   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15152                                       Base2, Offset2, GV2, CV2);
15153 
15154   // If they have a same base address then check to see if they overlap.
15155   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15156     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15157              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15158 
15159   // It is possible for different frame indices to alias each other, mostly
15160   // when tail call optimization reuses return address slots for arguments.
15161   // To catch this case, look up the actual index of frame indices to compute
15162   // the real alias relationship.
15163   if (isFrameIndex1 && isFrameIndex2) {
15164     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15165     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15166     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15167     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15168              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15169   }
15170 
15171   // Otherwise, if we know what the bases are, and they aren't identical, then
15172   // we know they cannot alias.
15173   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15174     return false;
15175 
15176   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15177   // compared to the size and offset of the access, we may be able to prove they
15178   // do not alias.  This check is conservative for now to catch cases created by
15179   // splitting vector types.
15180   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15181       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15182       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15183        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15184       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15185     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15186     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15187 
15188     // There is no overlap between these relatively aligned accesses of similar
15189     // size, return no alias.
15190     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15191         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15192       return false;
15193   }
15194 
15195   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15196                    ? CombinerGlobalAA
15197                    : DAG.getSubtarget().useAA();
15198 #ifndef NDEBUG
15199   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15200       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15201     UseAA = false;
15202 #endif
15203   if (UseAA &&
15204       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15205     // Use alias analysis information.
15206     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15207                                  Op1->getSrcValueOffset());
15208     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15209         Op0->getSrcValueOffset() - MinOffset;
15210     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15211         Op1->getSrcValueOffset() - MinOffset;
15212     AliasResult AAResult =
15213         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15214                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15215                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15216                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15217     if (AAResult == NoAlias)
15218       return false;
15219   }
15220 
15221   // Otherwise we have to assume they alias.
15222   return true;
15223 }
15224 
15225 /// Walk up chain skipping non-aliasing memory nodes,
15226 /// looking for aliasing nodes and adding them to the Aliases vector.
15227 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15228                                    SmallVectorImpl<SDValue> &Aliases) {
15229   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15230   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15231 
15232   // Get alias information for node.
15233   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15234 
15235   // Starting off.
15236   Chains.push_back(OriginalChain);
15237   unsigned Depth = 0;
15238 
15239   // Look at each chain and determine if it is an alias.  If so, add it to the
15240   // aliases list.  If not, then continue up the chain looking for the next
15241   // candidate.
15242   while (!Chains.empty()) {
15243     SDValue Chain = Chains.pop_back_val();
15244 
15245     // For TokenFactor nodes, look at each operand and only continue up the
15246     // chain until we reach the depth limit.
15247     //
15248     // FIXME: The depth check could be made to return the last non-aliasing
15249     // chain we found before we hit a tokenfactor rather than the original
15250     // chain.
15251     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15252       Aliases.clear();
15253       Aliases.push_back(OriginalChain);
15254       return;
15255     }
15256 
15257     // Don't bother if we've been before.
15258     if (!Visited.insert(Chain.getNode()).second)
15259       continue;
15260 
15261     switch (Chain.getOpcode()) {
15262     case ISD::EntryToken:
15263       // Entry token is ideal chain operand, but handled in FindBetterChain.
15264       break;
15265 
15266     case ISD::LOAD:
15267     case ISD::STORE: {
15268       // Get alias information for Chain.
15269       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15270           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15271 
15272       // If chain is alias then stop here.
15273       if (!(IsLoad && IsOpLoad) &&
15274           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15275         Aliases.push_back(Chain);
15276       } else {
15277         // Look further up the chain.
15278         Chains.push_back(Chain.getOperand(0));
15279         ++Depth;
15280       }
15281       break;
15282     }
15283 
15284     case ISD::TokenFactor:
15285       // We have to check each of the operands of the token factor for "small"
15286       // token factors, so we queue them up.  Adding the operands to the queue
15287       // (stack) in reverse order maintains the original order and increases the
15288       // likelihood that getNode will find a matching token factor (CSE.)
15289       if (Chain.getNumOperands() > 16) {
15290         Aliases.push_back(Chain);
15291         break;
15292       }
15293       for (unsigned n = Chain.getNumOperands(); n;)
15294         Chains.push_back(Chain.getOperand(--n));
15295       ++Depth;
15296       break;
15297 
15298     default:
15299       // For all other instructions we will just have to take what we can get.
15300       Aliases.push_back(Chain);
15301       break;
15302     }
15303   }
15304 }
15305 
15306 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15307 /// (aliasing node.)
15308 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15309   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15310 
15311   // Accumulate all the aliases to this node.
15312   GatherAllAliases(N, OldChain, Aliases);
15313 
15314   // If no operands then chain to entry token.
15315   if (Aliases.size() == 0)
15316     return DAG.getEntryNode();
15317 
15318   // If a single operand then chain to it.  We don't need to revisit it.
15319   if (Aliases.size() == 1)
15320     return Aliases[0];
15321 
15322   // Construct a custom tailored token factor.
15323   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15324 }
15325 
15326 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15327   // This holds the base pointer, index, and the offset in bytes from the base
15328   // pointer.
15329   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15330 
15331   // We must have a base and an offset.
15332   if (!BasePtr.Base.getNode())
15333     return false;
15334 
15335   // Do not handle stores to undef base pointers.
15336   if (BasePtr.Base.isUndef())
15337     return false;
15338 
15339   SmallVector<StoreSDNode *, 8> ChainedStores;
15340   ChainedStores.push_back(St);
15341 
15342   // Walk up the chain and look for nodes with offsets from the same
15343   // base pointer. Stop when reaching an instruction with a different kind
15344   // or instruction which has a different base pointer.
15345   StoreSDNode *Index = St;
15346   while (Index) {
15347     // If the chain has more than one use, then we can't reorder the mem ops.
15348     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15349       break;
15350 
15351     if (Index->isVolatile() || Index->isIndexed())
15352       break;
15353 
15354     // Find the base pointer and offset for this memory node.
15355     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15356 
15357     // Check that the base pointer is the same as the original one.
15358     if (!Ptr.equalBaseIndex(BasePtr))
15359       break;
15360 
15361     // Find the next memory operand in the chain. If the next operand in the
15362     // chain is a store then move up and continue the scan with the next
15363     // memory operand. If the next operand is a load save it and use alias
15364     // information to check if it interferes with anything.
15365     SDNode *NextInChain = Index->getChain().getNode();
15366     while (true) {
15367       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15368         // We found a store node. Use it for the next iteration.
15369         if (STn->isVolatile() || STn->isIndexed()) {
15370           Index = nullptr;
15371           break;
15372         }
15373         ChainedStores.push_back(STn);
15374         Index = STn;
15375         break;
15376       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15377         NextInChain = Ldn->getChain().getNode();
15378         continue;
15379       } else {
15380         Index = nullptr;
15381         break;
15382       }
15383     }
15384   }
15385 
15386   bool MadeChangeToSt = false;
15387   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15388 
15389   for (StoreSDNode *ChainedStore : ChainedStores) {
15390     SDValue Chain = ChainedStore->getChain();
15391     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15392 
15393     if (Chain != BetterChain) {
15394       if (ChainedStore == St)
15395         MadeChangeToSt = true;
15396       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15397     }
15398   }
15399 
15400   // Do all replacements after finding the replacements to make to avoid making
15401   // the chains more complicated by introducing new TokenFactors.
15402   for (auto Replacement : BetterChains)
15403     replaceStoreChain(Replacement.first, Replacement.second);
15404 
15405   return MadeChangeToSt;
15406 }
15407 
15408 /// This is the entry point for the file.
15409 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15410                            CodeGenOpt::Level OptLevel) {
15411   /// This is the main entry point to this class.
15412   DAGCombiner(*this, AA, OptLevel).Run(Level);
15413 }
15414