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.getValueType().getScalarType().getSizeInBits();
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     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
338     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
339     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
340     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
341                              SDValue N2, SDValue N3, ISD::CondCode CC,
342                              bool NotExtCompare = false);
343     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
344                           const SDLoc &DL, bool foldBooleans = true);
345 
346     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
347                            SDValue &CC) const;
348     bool isOneUseSetCC(SDValue N) const;
349 
350     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
351                                          unsigned HiOp);
352     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
353     SDValue CombineExtLoad(SDNode *N);
354     SDValue combineRepeatedFPDivisors(SDNode *N);
355     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
356     SDValue BuildSDIV(SDNode *N);
357     SDValue BuildSDIVPow2(SDNode *N);
358     SDValue BuildUDIV(SDNode *N);
359     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
360     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
361     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
362     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
363     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
364                                 SDNodeFlags *Flags, bool Reciprocal);
365     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
366                                 SDNodeFlags *Flags, bool Reciprocal);
367     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
368                                bool DemandHighBits = true);
369     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
370     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
371                               SDValue InnerPos, SDValue InnerNeg,
372                               unsigned PosOpcode, unsigned NegOpcode,
373                               const SDLoc &DL);
374     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
375     SDValue ReduceLoadWidth(SDNode *N);
376     SDValue ReduceLoadOpStoreWidth(SDNode *N);
377     SDValue TransformFPLoadStorePair(SDNode *N);
378     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
379     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
380 
381     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
382 
383     /// Walk up chain skipping non-aliasing memory nodes,
384     /// looking for aliasing nodes and adding them to the Aliases vector.
385     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
386                           SmallVectorImpl<SDValue> &Aliases);
387 
388     /// Return true if there is any possibility that the two addresses overlap.
389     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
390 
391     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
392     /// chain (aliasing node.)
393     SDValue FindBetterChain(SDNode *N, SDValue Chain);
394 
395     /// Do FindBetterChain for a store and any possibly adjacent stores on
396     /// consecutive chains.
397     bool findBetterNeighborChains(StoreSDNode *St);
398 
399     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
400     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
401 
402     /// Holds a pointer to an LSBaseSDNode as well as information on where it
403     /// is located in a sequence of memory operations connected by a chain.
404     struct MemOpLink {
405       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
406       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
407       // Ptr to the mem node.
408       LSBaseSDNode *MemNode;
409       // Offset from the base ptr.
410       int64_t OffsetFromBase;
411       // What is the sequence number of this mem node.
412       // Lowest mem operand in the DAG starts at zero.
413       unsigned SequenceNum;
414     };
415 
416     /// This is a helper function for visitMUL to check the profitability
417     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
418     /// MulNode is the original multiply, AddNode is (add x, c1),
419     /// and ConstNode is c2.
420     bool isMulAddWithConstProfitable(SDNode *MulNode,
421                                      SDValue &AddNode,
422                                      SDValue &ConstNode);
423 
424     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
425     /// constant build_vector of the stored constant values in Stores.
426     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
427                                          ArrayRef<MemOpLink> Stores,
428                                          SmallVectorImpl<SDValue> &Chains,
429                                          EVT Ty) const;
430 
431     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
432     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
433     /// the type of the loaded value to be extended.  LoadedVT returns the type
434     /// of the original loaded value.  NarrowLoad returns whether the load would
435     /// need to be narrowed in order to match.
436     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
437                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
438                           bool &NarrowLoad);
439 
440     /// This is a helper function for MergeConsecutiveStores. When the source
441     /// elements of the consecutive stores are all constants or all extracted
442     /// vector elements, try to merge them into one larger store.
443     /// \return True if a merged store was created.
444     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
445                                          EVT MemVT, unsigned NumStores,
446                                          bool IsConstantSrc, bool UseVector);
447 
448     /// This is a helper function for MergeConsecutiveStores.
449     /// Stores that may be merged are placed in StoreNodes.
450     /// Loads that may alias with those stores are placed in AliasLoadNodes.
451     void getStoreMergeAndAliasCandidates(
452         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
453         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
454 
455     /// Helper function for MergeConsecutiveStores. Checks if
456     /// Candidate stores have indirect dependency through their
457     /// operands. \return True if safe to merge
458     bool checkMergeStoreCandidatesForDependencies(
459         SmallVectorImpl<MemOpLink> &StoreNodes);
460 
461     /// Merge consecutive store operations into a wide store.
462     /// This optimization uses wide integers or vectors when possible.
463     /// \return True if some memory operations were changed.
464     bool MergeConsecutiveStores(StoreSDNode *N);
465 
466     /// \brief Try to transform a truncation where C is a constant:
467     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
468     ///
469     /// \p N needs to be a truncation and its first operand an AND. Other
470     /// requirements are checked by the function (e.g. that trunc is
471     /// single-use) and if missed an empty SDValue is returned.
472     SDValue distributeTruncateThroughAnd(SDNode *N);
473 
474   public:
475     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
476         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
477           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
478       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
479     }
480 
481     /// Runs the dag combiner on all nodes in the work list
482     void Run(CombineLevel AtLevel);
483 
484     SelectionDAG &getDAG() const { return DAG; }
485 
486     /// Returns a type large enough to hold any valid shift amount - before type
487     /// legalization these can be huge.
488     EVT getShiftAmountTy(EVT LHSTy) {
489       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
490       if (LHSTy.isVector())
491         return LHSTy;
492       auto &DL = DAG.getDataLayout();
493       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
494                         : TLI.getPointerTy(DL);
495     }
496 
497     /// This method returns true if we are running before type legalization or
498     /// if the specified VT is legal.
499     bool isTypeLegal(const EVT &VT) {
500       if (!LegalTypes) return true;
501       return TLI.isTypeLegal(VT);
502     }
503 
504     /// Convenience wrapper around TargetLowering::getSetCCResultType
505     EVT getSetCCResultType(EVT VT) const {
506       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
507     }
508   };
509 }
510 
511 
512 namespace {
513 /// This class is a DAGUpdateListener that removes any deleted
514 /// nodes from the worklist.
515 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
516   DAGCombiner &DC;
517 public:
518   explicit WorklistRemover(DAGCombiner &dc)
519     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
520 
521   void NodeDeleted(SDNode *N, SDNode *E) override {
522     DC.removeFromWorklist(N);
523   }
524 };
525 }
526 
527 //===----------------------------------------------------------------------===//
528 //  TargetLowering::DAGCombinerInfo implementation
529 //===----------------------------------------------------------------------===//
530 
531 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
532   ((DAGCombiner*)DC)->AddToWorklist(N);
533 }
534 
535 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
536   ((DAGCombiner*)DC)->removeFromWorklist(N);
537 }
538 
539 SDValue TargetLowering::DAGCombinerInfo::
540 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
541   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
542 }
543 
544 SDValue TargetLowering::DAGCombinerInfo::
545 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
546   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
547 }
548 
549 
550 SDValue TargetLowering::DAGCombinerInfo::
551 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
552   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
553 }
554 
555 void TargetLowering::DAGCombinerInfo::
556 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
557   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
558 }
559 
560 //===----------------------------------------------------------------------===//
561 // Helper Functions
562 //===----------------------------------------------------------------------===//
563 
564 void DAGCombiner::deleteAndRecombine(SDNode *N) {
565   removeFromWorklist(N);
566 
567   // If the operands of this node are only used by the node, they will now be
568   // dead. Make sure to re-visit them and recursively delete dead nodes.
569   for (const SDValue &Op : N->ops())
570     // For an operand generating multiple values, one of the values may
571     // become dead allowing further simplification (e.g. split index
572     // arithmetic from an indexed load).
573     if (Op->hasOneUse() || Op->getNumValues() > 1)
574       AddToWorklist(Op.getNode());
575 
576   DAG.DeleteNode(N);
577 }
578 
579 /// Return 1 if we can compute the negated form of the specified expression for
580 /// the same cost as the expression itself, or 2 if we can compute the negated
581 /// form more cheaply than the expression itself.
582 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
583                                const TargetLowering &TLI,
584                                const TargetOptions *Options,
585                                unsigned Depth = 0) {
586   // fneg is removable even if it has multiple uses.
587   if (Op.getOpcode() == ISD::FNEG) return 2;
588 
589   // Don't allow anything with multiple uses.
590   if (!Op.hasOneUse()) return 0;
591 
592   // Don't recurse exponentially.
593   if (Depth > 6) return 0;
594 
595   switch (Op.getOpcode()) {
596   default: return false;
597   case ISD::ConstantFP:
598     // Don't invert constant FP values after legalize.  The negated constant
599     // isn't necessarily legal.
600     return LegalOperations ? 0 : 1;
601   case ISD::FADD:
602     // FIXME: determine better conditions for this xform.
603     if (!Options->UnsafeFPMath) return 0;
604 
605     // After operation legalization, it might not be legal to create new FSUBs.
606     if (LegalOperations &&
607         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
608       return 0;
609 
610     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
611     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
612                                     Options, Depth + 1))
613       return V;
614     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
615     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
616                               Depth + 1);
617   case ISD::FSUB:
618     // We can't turn -(A-B) into B-A when we honor signed zeros.
619     if (!Options->UnsafeFPMath) return 0;
620 
621     // fold (fneg (fsub A, B)) -> (fsub B, A)
622     return 1;
623 
624   case ISD::FMUL:
625   case ISD::FDIV:
626     if (Options->HonorSignDependentRoundingFPMath()) return 0;
627 
628     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
629     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
630                                     Options, Depth + 1))
631       return V;
632 
633     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
634                               Depth + 1);
635 
636   case ISD::FP_EXTEND:
637   case ISD::FP_ROUND:
638   case ISD::FSIN:
639     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
640                               Depth + 1);
641   }
642 }
643 
644 /// If isNegatibleForFree returns true, return the newly negated expression.
645 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
646                                     bool LegalOperations, unsigned Depth = 0) {
647   const TargetOptions &Options = DAG.getTarget().Options;
648   // fneg is removable even if it has multiple uses.
649   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
650 
651   // Don't allow anything with multiple uses.
652   assert(Op.hasOneUse() && "Unknown reuse!");
653 
654   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
655 
656   const SDNodeFlags *Flags = Op.getNode()->getFlags();
657 
658   switch (Op.getOpcode()) {
659   default: llvm_unreachable("Unknown code");
660   case ISD::ConstantFP: {
661     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
662     V.changeSign();
663     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
664   }
665   case ISD::FADD:
666     // FIXME: determine better conditions for this xform.
667     assert(Options.UnsafeFPMath);
668 
669     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
670     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
671                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
672       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
673                          GetNegatedExpression(Op.getOperand(0), DAG,
674                                               LegalOperations, Depth+1),
675                          Op.getOperand(1), Flags);
676     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
677     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
678                        GetNegatedExpression(Op.getOperand(1), DAG,
679                                             LegalOperations, Depth+1),
680                        Op.getOperand(0), Flags);
681   case ISD::FSUB:
682     // We can't turn -(A-B) into B-A when we honor signed zeros.
683     assert(Options.UnsafeFPMath);
684 
685     // fold (fneg (fsub 0, B)) -> B
686     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
687       if (N0CFP->isZero())
688         return Op.getOperand(1);
689 
690     // fold (fneg (fsub A, B)) -> (fsub B, A)
691     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
692                        Op.getOperand(1), Op.getOperand(0), Flags);
693 
694   case ISD::FMUL:
695   case ISD::FDIV:
696     assert(!Options.HonorSignDependentRoundingFPMath());
697 
698     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
699     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
700                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
701       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
702                          GetNegatedExpression(Op.getOperand(0), DAG,
703                                               LegalOperations, Depth+1),
704                          Op.getOperand(1), Flags);
705 
706     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
707     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
708                        Op.getOperand(0),
709                        GetNegatedExpression(Op.getOperand(1), DAG,
710                                             LegalOperations, Depth+1), Flags);
711 
712   case ISD::FP_EXTEND:
713   case ISD::FSIN:
714     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
715                        GetNegatedExpression(Op.getOperand(0), DAG,
716                                             LegalOperations, Depth+1));
717   case ISD::FP_ROUND:
718       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
719                          GetNegatedExpression(Op.getOperand(0), DAG,
720                                               LegalOperations, Depth+1),
721                          Op.getOperand(1));
722   }
723 }
724 
725 // Return true if this node is a setcc, or is a select_cc
726 // that selects between the target values used for true and false, making it
727 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
728 // the appropriate nodes based on the type of node we are checking. This
729 // simplifies life a bit for the callers.
730 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
731                                     SDValue &CC) const {
732   if (N.getOpcode() == ISD::SETCC) {
733     LHS = N.getOperand(0);
734     RHS = N.getOperand(1);
735     CC  = N.getOperand(2);
736     return true;
737   }
738 
739   if (N.getOpcode() != ISD::SELECT_CC ||
740       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
741       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
742     return false;
743 
744   if (TLI.getBooleanContents(N.getValueType()) ==
745       TargetLowering::UndefinedBooleanContent)
746     return false;
747 
748   LHS = N.getOperand(0);
749   RHS = N.getOperand(1);
750   CC  = N.getOperand(4);
751   return true;
752 }
753 
754 /// Return true if this is a SetCC-equivalent operation with only one use.
755 /// If this is true, it allows the users to invert the operation for free when
756 /// it is profitable to do so.
757 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
758   SDValue N0, N1, N2;
759   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
760     return true;
761   return false;
762 }
763 
764 /// Returns true if N is a BUILD_VECTOR node whose
765 /// elements are all the same constant or undefined.
766 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
767   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
768   if (!C)
769     return false;
770 
771   APInt SplatUndef;
772   unsigned SplatBitSize;
773   bool HasAnyUndefs;
774   EVT EltVT = N->getValueType(0).getVectorElementType();
775   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
776                              HasAnyUndefs) &&
777           EltVT.getSizeInBits() >= SplatBitSize);
778 }
779 
780 // \brief Returns the SDNode if it is a constant float BuildVector
781 // or constant float.
782 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
783   if (isa<ConstantFPSDNode>(N))
784     return N.getNode();
785   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
786     return N.getNode();
787   return nullptr;
788 }
789 
790 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
791 // int.
792 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
793   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
794     return CN;
795 
796   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
797     BitVector UndefElements;
798     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
799 
800     // BuildVectors can truncate their operands. Ignore that case here.
801     // FIXME: We blindly ignore splats which include undef which is overly
802     // pessimistic.
803     if (CN && UndefElements.none() &&
804         CN->getValueType(0) == N.getValueType().getScalarType())
805       return CN;
806   }
807 
808   return nullptr;
809 }
810 
811 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
812 // float.
813 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
814   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
815     return CN;
816 
817   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
818     BitVector UndefElements;
819     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
820 
821     if (CN && UndefElements.none())
822       return CN;
823   }
824 
825   return nullptr;
826 }
827 
828 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
829                                     SDValue N1) {
830   EVT VT = N0.getValueType();
831   if (N0.getOpcode() == Opc) {
832     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
833       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
834         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
835         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
836           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
837         return SDValue();
838       }
839       if (N0.hasOneUse()) {
840         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
841         // use
842         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
843         if (!OpNode.getNode())
844           return SDValue();
845         AddToWorklist(OpNode.getNode());
846         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
847       }
848     }
849   }
850 
851   if (N1.getOpcode() == Opc) {
852     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
853       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
854         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
855         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
856           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
857         return SDValue();
858       }
859       if (N1.hasOneUse()) {
860         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
861         // use
862         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
863         if (!OpNode.getNode())
864           return SDValue();
865         AddToWorklist(OpNode.getNode());
866         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
867       }
868     }
869   }
870 
871   return SDValue();
872 }
873 
874 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
875                                bool AddTo) {
876   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
877   ++NodesCombined;
878   DEBUG(dbgs() << "\nReplacing.1 ";
879         N->dump(&DAG);
880         dbgs() << "\nWith: ";
881         To[0].getNode()->dump(&DAG);
882         dbgs() << " and " << NumTo-1 << " other values\n");
883   for (unsigned i = 0, e = NumTo; i != e; ++i)
884     assert((!To[i].getNode() ||
885             N->getValueType(i) == To[i].getValueType()) &&
886            "Cannot combine value to value of different type!");
887 
888   WorklistRemover DeadNodes(*this);
889   DAG.ReplaceAllUsesWith(N, To);
890   if (AddTo) {
891     // Push the new nodes and any users onto the worklist
892     for (unsigned i = 0, e = NumTo; i != e; ++i) {
893       if (To[i].getNode()) {
894         AddToWorklist(To[i].getNode());
895         AddUsersToWorklist(To[i].getNode());
896       }
897     }
898   }
899 
900   // Finally, if the node is now dead, remove it from the graph.  The node
901   // may not be dead if the replacement process recursively simplified to
902   // something else needing this node.
903   if (N->use_empty())
904     deleteAndRecombine(N);
905   return SDValue(N, 0);
906 }
907 
908 void DAGCombiner::
909 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
910   // Replace all uses.  If any nodes become isomorphic to other nodes and
911   // are deleted, make sure to remove them from our worklist.
912   WorklistRemover DeadNodes(*this);
913   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
914 
915   // Push the new node and any (possibly new) users onto the worklist.
916   AddToWorklist(TLO.New.getNode());
917   AddUsersToWorklist(TLO.New.getNode());
918 
919   // Finally, if the node is now dead, remove it from the graph.  The node
920   // may not be dead if the replacement process recursively simplified to
921   // something else needing this node.
922   if (TLO.Old.getNode()->use_empty())
923     deleteAndRecombine(TLO.Old.getNode());
924 }
925 
926 /// Check the specified integer node value to see if it can be simplified or if
927 /// things it uses can be simplified by bit propagation. If so, return true.
928 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
929   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
930   APInt KnownZero, KnownOne;
931   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
932     return false;
933 
934   // Revisit the node.
935   AddToWorklist(Op.getNode());
936 
937   // Replace the old value with the new one.
938   ++NodesCombined;
939   DEBUG(dbgs() << "\nReplacing.2 ";
940         TLO.Old.getNode()->dump(&DAG);
941         dbgs() << "\nWith: ";
942         TLO.New.getNode()->dump(&DAG);
943         dbgs() << '\n');
944 
945   CommitTargetLoweringOpt(TLO);
946   return true;
947 }
948 
949 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
950   SDLoc dl(Load);
951   EVT VT = Load->getValueType(0);
952   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
953 
954   DEBUG(dbgs() << "\nReplacing.9 ";
955         Load->dump(&DAG);
956         dbgs() << "\nWith: ";
957         Trunc.getNode()->dump(&DAG);
958         dbgs() << '\n');
959   WorklistRemover DeadNodes(*this);
960   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
961   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
962   deleteAndRecombine(Load);
963   AddToWorklist(Trunc.getNode());
964 }
965 
966 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
967   Replace = false;
968   SDLoc dl(Op);
969   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
970     LoadSDNode *LD = cast<LoadSDNode>(Op);
971     EVT MemVT = LD->getMemoryVT();
972     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
973       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
974                                                        : ISD::EXTLOAD)
975       : LD->getExtensionType();
976     Replace = true;
977     return DAG.getExtLoad(ExtType, dl, PVT,
978                           LD->getChain(), LD->getBasePtr(),
979                           MemVT, LD->getMemOperand());
980   }
981 
982   unsigned Opc = Op.getOpcode();
983   switch (Opc) {
984   default: break;
985   case ISD::AssertSext:
986     return DAG.getNode(ISD::AssertSext, dl, PVT,
987                        SExtPromoteOperand(Op.getOperand(0), PVT),
988                        Op.getOperand(1));
989   case ISD::AssertZext:
990     return DAG.getNode(ISD::AssertZext, dl, PVT,
991                        ZExtPromoteOperand(Op.getOperand(0), PVT),
992                        Op.getOperand(1));
993   case ISD::Constant: {
994     unsigned ExtOpc =
995       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
996     return DAG.getNode(ExtOpc, dl, PVT, Op);
997   }
998   }
999 
1000   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1001     return SDValue();
1002   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
1003 }
1004 
1005 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1006   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1007     return SDValue();
1008   EVT OldVT = Op.getValueType();
1009   SDLoc dl(Op);
1010   bool Replace = false;
1011   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1012   if (!NewOp.getNode())
1013     return SDValue();
1014   AddToWorklist(NewOp.getNode());
1015 
1016   if (Replace)
1017     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1018   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1019                      DAG.getValueType(OldVT));
1020 }
1021 
1022 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1023   EVT OldVT = Op.getValueType();
1024   SDLoc dl(Op);
1025   bool Replace = false;
1026   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1027   if (!NewOp.getNode())
1028     return SDValue();
1029   AddToWorklist(NewOp.getNode());
1030 
1031   if (Replace)
1032     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1033   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1034 }
1035 
1036 /// Promote the specified integer binary operation if the target indicates it is
1037 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1038 /// i32 since i16 instructions are longer.
1039 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1040   if (!LegalOperations)
1041     return SDValue();
1042 
1043   EVT VT = Op.getValueType();
1044   if (VT.isVector() || !VT.isInteger())
1045     return SDValue();
1046 
1047   // If operation type is 'undesirable', e.g. i16 on x86, consider
1048   // promoting it.
1049   unsigned Opc = Op.getOpcode();
1050   if (TLI.isTypeDesirableForOp(Opc, VT))
1051     return SDValue();
1052 
1053   EVT PVT = VT;
1054   // Consult target whether it is a good idea to promote this operation and
1055   // what's the right type to promote it to.
1056   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1057     assert(PVT != VT && "Don't know what type to promote to!");
1058 
1059     bool Replace0 = false;
1060     SDValue N0 = Op.getOperand(0);
1061     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1062     if (!NN0.getNode())
1063       return SDValue();
1064 
1065     bool Replace1 = false;
1066     SDValue N1 = Op.getOperand(1);
1067     SDValue NN1;
1068     if (N0 == N1)
1069       NN1 = NN0;
1070     else {
1071       NN1 = PromoteOperand(N1, PVT, Replace1);
1072       if (!NN1.getNode())
1073         return SDValue();
1074     }
1075 
1076     AddToWorklist(NN0.getNode());
1077     if (NN1.getNode())
1078       AddToWorklist(NN1.getNode());
1079 
1080     if (Replace0)
1081       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1082     if (Replace1)
1083       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1084 
1085     DEBUG(dbgs() << "\nPromoting ";
1086           Op.getNode()->dump(&DAG));
1087     SDLoc dl(Op);
1088     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1089                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1090   }
1091   return SDValue();
1092 }
1093 
1094 /// Promote the specified integer shift operation if the target indicates it is
1095 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1096 /// i32 since i16 instructions are longer.
1097 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1098   if (!LegalOperations)
1099     return SDValue();
1100 
1101   EVT VT = Op.getValueType();
1102   if (VT.isVector() || !VT.isInteger())
1103     return SDValue();
1104 
1105   // If operation type is 'undesirable', e.g. i16 on x86, consider
1106   // promoting it.
1107   unsigned Opc = Op.getOpcode();
1108   if (TLI.isTypeDesirableForOp(Opc, VT))
1109     return SDValue();
1110 
1111   EVT PVT = VT;
1112   // Consult target whether it is a good idea to promote this operation and
1113   // what's the right type to promote it to.
1114   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1115     assert(PVT != VT && "Don't know what type to promote to!");
1116 
1117     bool Replace = false;
1118     SDValue N0 = Op.getOperand(0);
1119     if (Opc == ISD::SRA)
1120       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1121     else if (Opc == ISD::SRL)
1122       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1123     else
1124       N0 = PromoteOperand(N0, PVT, Replace);
1125     if (!N0.getNode())
1126       return SDValue();
1127 
1128     AddToWorklist(N0.getNode());
1129     if (Replace)
1130       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1131 
1132     DEBUG(dbgs() << "\nPromoting ";
1133           Op.getNode()->dump(&DAG));
1134     SDLoc dl(Op);
1135     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1136                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1137   }
1138   return SDValue();
1139 }
1140 
1141 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1142   if (!LegalOperations)
1143     return SDValue();
1144 
1145   EVT VT = Op.getValueType();
1146   if (VT.isVector() || !VT.isInteger())
1147     return SDValue();
1148 
1149   // If operation type is 'undesirable', e.g. i16 on x86, consider
1150   // promoting it.
1151   unsigned Opc = Op.getOpcode();
1152   if (TLI.isTypeDesirableForOp(Opc, VT))
1153     return SDValue();
1154 
1155   EVT PVT = VT;
1156   // Consult target whether it is a good idea to promote this operation and
1157   // what's the right type to promote it to.
1158   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1159     assert(PVT != VT && "Don't know what type to promote to!");
1160     // fold (aext (aext x)) -> (aext x)
1161     // fold (aext (zext x)) -> (zext x)
1162     // fold (aext (sext x)) -> (sext x)
1163     DEBUG(dbgs() << "\nPromoting ";
1164           Op.getNode()->dump(&DAG));
1165     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1166   }
1167   return SDValue();
1168 }
1169 
1170 bool DAGCombiner::PromoteLoad(SDValue Op) {
1171   if (!LegalOperations)
1172     return false;
1173 
1174   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1175     return false;
1176 
1177   EVT VT = Op.getValueType();
1178   if (VT.isVector() || !VT.isInteger())
1179     return false;
1180 
1181   // If operation type is 'undesirable', e.g. i16 on x86, consider
1182   // promoting it.
1183   unsigned Opc = Op.getOpcode();
1184   if (TLI.isTypeDesirableForOp(Opc, VT))
1185     return false;
1186 
1187   EVT PVT = VT;
1188   // Consult target whether it is a good idea to promote this operation and
1189   // what's the right type to promote it to.
1190   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1191     assert(PVT != VT && "Don't know what type to promote to!");
1192 
1193     SDLoc dl(Op);
1194     SDNode *N = Op.getNode();
1195     LoadSDNode *LD = cast<LoadSDNode>(N);
1196     EVT MemVT = LD->getMemoryVT();
1197     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1198       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1199                                                        : ISD::EXTLOAD)
1200       : LD->getExtensionType();
1201     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1202                                    LD->getChain(), LD->getBasePtr(),
1203                                    MemVT, LD->getMemOperand());
1204     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1205 
1206     DEBUG(dbgs() << "\nPromoting ";
1207           N->dump(&DAG);
1208           dbgs() << "\nTo: ";
1209           Result.getNode()->dump(&DAG);
1210           dbgs() << '\n');
1211     WorklistRemover DeadNodes(*this);
1212     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1213     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1214     deleteAndRecombine(N);
1215     AddToWorklist(Result.getNode());
1216     return true;
1217   }
1218   return false;
1219 }
1220 
1221 /// \brief Recursively delete a node which has no uses and any operands for
1222 /// which it is the only use.
1223 ///
1224 /// Note that this both deletes the nodes and removes them from the worklist.
1225 /// It also adds any nodes who have had a user deleted to the worklist as they
1226 /// may now have only one use and subject to other combines.
1227 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1228   if (!N->use_empty())
1229     return false;
1230 
1231   SmallSetVector<SDNode *, 16> Nodes;
1232   Nodes.insert(N);
1233   do {
1234     N = Nodes.pop_back_val();
1235     if (!N)
1236       continue;
1237 
1238     if (N->use_empty()) {
1239       for (const SDValue &ChildN : N->op_values())
1240         Nodes.insert(ChildN.getNode());
1241 
1242       removeFromWorklist(N);
1243       DAG.DeleteNode(N);
1244     } else {
1245       AddToWorklist(N);
1246     }
1247   } while (!Nodes.empty());
1248   return true;
1249 }
1250 
1251 //===----------------------------------------------------------------------===//
1252 //  Main DAG Combiner implementation
1253 //===----------------------------------------------------------------------===//
1254 
1255 void DAGCombiner::Run(CombineLevel AtLevel) {
1256   // set the instance variables, so that the various visit routines may use it.
1257   Level = AtLevel;
1258   LegalOperations = Level >= AfterLegalizeVectorOps;
1259   LegalTypes = Level >= AfterLegalizeTypes;
1260 
1261   // Add all the dag nodes to the worklist.
1262   for (SDNode &Node : DAG.allnodes())
1263     AddToWorklist(&Node);
1264 
1265   // Create a dummy node (which is not added to allnodes), that adds a reference
1266   // to the root node, preventing it from being deleted, and tracking any
1267   // changes of the root.
1268   HandleSDNode Dummy(DAG.getRoot());
1269 
1270   // While the worklist isn't empty, find a node and try to combine it.
1271   while (!WorklistMap.empty()) {
1272     SDNode *N;
1273     // The Worklist holds the SDNodes in order, but it may contain null entries.
1274     do {
1275       N = Worklist.pop_back_val();
1276     } while (!N);
1277 
1278     bool GoodWorklistEntry = WorklistMap.erase(N);
1279     (void)GoodWorklistEntry;
1280     assert(GoodWorklistEntry &&
1281            "Found a worklist entry without a corresponding map entry!");
1282 
1283     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1284     // N is deleted from the DAG, since they too may now be dead or may have a
1285     // reduced number of uses, allowing other xforms.
1286     if (recursivelyDeleteUnusedNodes(N))
1287       continue;
1288 
1289     WorklistRemover DeadNodes(*this);
1290 
1291     // If this combine is running after legalizing the DAG, re-legalize any
1292     // nodes pulled off the worklist.
1293     if (Level == AfterLegalizeDAG) {
1294       SmallSetVector<SDNode *, 16> UpdatedNodes;
1295       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1296 
1297       for (SDNode *LN : UpdatedNodes) {
1298         AddToWorklist(LN);
1299         AddUsersToWorklist(LN);
1300       }
1301       if (!NIsValid)
1302         continue;
1303     }
1304 
1305     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1306 
1307     // Add any operands of the new node which have not yet been combined to the
1308     // worklist as well. Because the worklist uniques things already, this
1309     // won't repeatedly process the same operand.
1310     CombinedNodes.insert(N);
1311     for (const SDValue &ChildN : N->op_values())
1312       if (!CombinedNodes.count(ChildN.getNode()))
1313         AddToWorklist(ChildN.getNode());
1314 
1315     SDValue RV = combine(N);
1316 
1317     if (!RV.getNode())
1318       continue;
1319 
1320     ++NodesCombined;
1321 
1322     // If we get back the same node we passed in, rather than a new node or
1323     // zero, we know that the node must have defined multiple values and
1324     // CombineTo was used.  Since CombineTo takes care of the worklist
1325     // mechanics for us, we have no work to do in this case.
1326     if (RV.getNode() == N)
1327       continue;
1328 
1329     assert(N->getOpcode() != ISD::DELETED_NODE &&
1330            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1331            "Node was deleted but visit returned new node!");
1332 
1333     DEBUG(dbgs() << " ... into: ";
1334           RV.getNode()->dump(&DAG));
1335 
1336     if (N->getNumValues() == RV.getNode()->getNumValues())
1337       DAG.ReplaceAllUsesWith(N, RV.getNode());
1338     else {
1339       assert(N->getValueType(0) == RV.getValueType() &&
1340              N->getNumValues() == 1 && "Type mismatch");
1341       SDValue OpV = RV;
1342       DAG.ReplaceAllUsesWith(N, &OpV);
1343     }
1344 
1345     // Push the new node and any users onto the worklist
1346     AddToWorklist(RV.getNode());
1347     AddUsersToWorklist(RV.getNode());
1348 
1349     // Finally, if the node is now dead, remove it from the graph.  The node
1350     // may not be dead if the replacement process recursively simplified to
1351     // something else needing this node. This will also take care of adding any
1352     // operands which have lost a user to the worklist.
1353     recursivelyDeleteUnusedNodes(N);
1354   }
1355 
1356   // If the root changed (e.g. it was a dead load, update the root).
1357   DAG.setRoot(Dummy.getValue());
1358   DAG.RemoveDeadNodes();
1359 }
1360 
1361 SDValue DAGCombiner::visit(SDNode *N) {
1362   switch (N->getOpcode()) {
1363   default: break;
1364   case ISD::TokenFactor:        return visitTokenFactor(N);
1365   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1366   case ISD::ADD:                return visitADD(N);
1367   case ISD::SUB:                return visitSUB(N);
1368   case ISD::ADDC:               return visitADDC(N);
1369   case ISD::SUBC:               return visitSUBC(N);
1370   case ISD::ADDE:               return visitADDE(N);
1371   case ISD::SUBE:               return visitSUBE(N);
1372   case ISD::MUL:                return visitMUL(N);
1373   case ISD::SDIV:               return visitSDIV(N);
1374   case ISD::UDIV:               return visitUDIV(N);
1375   case ISD::SREM:
1376   case ISD::UREM:               return visitREM(N);
1377   case ISD::MULHU:              return visitMULHU(N);
1378   case ISD::MULHS:              return visitMULHS(N);
1379   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1380   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1381   case ISD::SMULO:              return visitSMULO(N);
1382   case ISD::UMULO:              return visitUMULO(N);
1383   case ISD::SMIN:
1384   case ISD::SMAX:
1385   case ISD::UMIN:
1386   case ISD::UMAX:               return visitIMINMAX(N);
1387   case ISD::AND:                return visitAND(N);
1388   case ISD::OR:                 return visitOR(N);
1389   case ISD::XOR:                return visitXOR(N);
1390   case ISD::SHL:                return visitSHL(N);
1391   case ISD::SRA:                return visitSRA(N);
1392   case ISD::SRL:                return visitSRL(N);
1393   case ISD::ROTR:
1394   case ISD::ROTL:               return visitRotate(N);
1395   case ISD::BSWAP:              return visitBSWAP(N);
1396   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1397   case ISD::CTLZ:               return visitCTLZ(N);
1398   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1399   case ISD::CTTZ:               return visitCTTZ(N);
1400   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1401   case ISD::CTPOP:              return visitCTPOP(N);
1402   case ISD::SELECT:             return visitSELECT(N);
1403   case ISD::VSELECT:            return visitVSELECT(N);
1404   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1405   case ISD::SETCC:              return visitSETCC(N);
1406   case ISD::SETCCE:             return visitSETCCE(N);
1407   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1408   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1409   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1410   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1411   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1412   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1413   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1414   case ISD::BITCAST:            return visitBITCAST(N);
1415   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1416   case ISD::FADD:               return visitFADD(N);
1417   case ISD::FSUB:               return visitFSUB(N);
1418   case ISD::FMUL:               return visitFMUL(N);
1419   case ISD::FMA:                return visitFMA(N);
1420   case ISD::FDIV:               return visitFDIV(N);
1421   case ISD::FREM:               return visitFREM(N);
1422   case ISD::FSQRT:              return visitFSQRT(N);
1423   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1424   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1425   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1426   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1427   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1428   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1429   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1430   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1431   case ISD::FNEG:               return visitFNEG(N);
1432   case ISD::FABS:               return visitFABS(N);
1433   case ISD::FFLOOR:             return visitFFLOOR(N);
1434   case ISD::FMINNUM:            return visitFMINNUM(N);
1435   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1436   case ISD::FCEIL:              return visitFCEIL(N);
1437   case ISD::FTRUNC:             return visitFTRUNC(N);
1438   case ISD::BRCOND:             return visitBRCOND(N);
1439   case ISD::BR_CC:              return visitBR_CC(N);
1440   case ISD::LOAD:               return visitLOAD(N);
1441   case ISD::STORE:              return visitSTORE(N);
1442   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1443   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1444   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1445   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1446   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1447   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1448   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1449   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1450   case ISD::MGATHER:            return visitMGATHER(N);
1451   case ISD::MLOAD:              return visitMLOAD(N);
1452   case ISD::MSCATTER:           return visitMSCATTER(N);
1453   case ISD::MSTORE:             return visitMSTORE(N);
1454   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1455   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1456   }
1457   return SDValue();
1458 }
1459 
1460 SDValue DAGCombiner::combine(SDNode *N) {
1461   SDValue RV = visit(N);
1462 
1463   // If nothing happened, try a target-specific DAG combine.
1464   if (!RV.getNode()) {
1465     assert(N->getOpcode() != ISD::DELETED_NODE &&
1466            "Node was deleted but visit returned NULL!");
1467 
1468     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1469         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1470 
1471       // Expose the DAG combiner to the target combiner impls.
1472       TargetLowering::DAGCombinerInfo
1473         DagCombineInfo(DAG, Level, false, this);
1474 
1475       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1476     }
1477   }
1478 
1479   // If nothing happened still, try promoting the operation.
1480   if (!RV.getNode()) {
1481     switch (N->getOpcode()) {
1482     default: break;
1483     case ISD::ADD:
1484     case ISD::SUB:
1485     case ISD::MUL:
1486     case ISD::AND:
1487     case ISD::OR:
1488     case ISD::XOR:
1489       RV = PromoteIntBinOp(SDValue(N, 0));
1490       break;
1491     case ISD::SHL:
1492     case ISD::SRA:
1493     case ISD::SRL:
1494       RV = PromoteIntShiftOp(SDValue(N, 0));
1495       break;
1496     case ISD::SIGN_EXTEND:
1497     case ISD::ZERO_EXTEND:
1498     case ISD::ANY_EXTEND:
1499       RV = PromoteExtend(SDValue(N, 0));
1500       break;
1501     case ISD::LOAD:
1502       if (PromoteLoad(SDValue(N, 0)))
1503         RV = SDValue(N, 0);
1504       break;
1505     }
1506   }
1507 
1508   // If N is a commutative binary node, try commuting it to enable more
1509   // sdisel CSE.
1510   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1511       N->getNumValues() == 1) {
1512     SDValue N0 = N->getOperand(0);
1513     SDValue N1 = N->getOperand(1);
1514 
1515     // Constant operands are canonicalized to RHS.
1516     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1517       SDValue Ops[] = {N1, N0};
1518       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1519                                             N->getFlags());
1520       if (CSENode)
1521         return SDValue(CSENode, 0);
1522     }
1523   }
1524 
1525   return RV;
1526 }
1527 
1528 /// Given a node, return its input chain if it has one, otherwise return a null
1529 /// sd operand.
1530 static SDValue getInputChainForNode(SDNode *N) {
1531   if (unsigned NumOps = N->getNumOperands()) {
1532     if (N->getOperand(0).getValueType() == MVT::Other)
1533       return N->getOperand(0);
1534     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1535       return N->getOperand(NumOps-1);
1536     for (unsigned i = 1; i < NumOps-1; ++i)
1537       if (N->getOperand(i).getValueType() == MVT::Other)
1538         return N->getOperand(i);
1539   }
1540   return SDValue();
1541 }
1542 
1543 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1544   // If N has two operands, where one has an input chain equal to the other,
1545   // the 'other' chain is redundant.
1546   if (N->getNumOperands() == 2) {
1547     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1548       return N->getOperand(0);
1549     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1550       return N->getOperand(1);
1551   }
1552 
1553   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1554   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1555   SmallPtrSet<SDNode*, 16> SeenOps;
1556   bool Changed = false;             // If we should replace this token factor.
1557 
1558   // Start out with this token factor.
1559   TFs.push_back(N);
1560 
1561   // Iterate through token factors.  The TFs grows when new token factors are
1562   // encountered.
1563   for (unsigned i = 0; i < TFs.size(); ++i) {
1564     SDNode *TF = TFs[i];
1565 
1566     // Check each of the operands.
1567     for (const SDValue &Op : TF->op_values()) {
1568 
1569       switch (Op.getOpcode()) {
1570       case ISD::EntryToken:
1571         // Entry tokens don't need to be added to the list. They are
1572         // redundant.
1573         Changed = true;
1574         break;
1575 
1576       case ISD::TokenFactor:
1577         if (Op.hasOneUse() &&
1578             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1579           // Queue up for processing.
1580           TFs.push_back(Op.getNode());
1581           // Clean up in case the token factor is removed.
1582           AddToWorklist(Op.getNode());
1583           Changed = true;
1584           break;
1585         }
1586         // Fall thru
1587 
1588       default:
1589         // Only add if it isn't already in the list.
1590         if (SeenOps.insert(Op.getNode()).second)
1591           Ops.push_back(Op);
1592         else
1593           Changed = true;
1594         break;
1595       }
1596     }
1597   }
1598 
1599   SDValue Result;
1600 
1601   // If we've changed things around then replace token factor.
1602   if (Changed) {
1603     if (Ops.empty()) {
1604       // The entry token is the only possible outcome.
1605       Result = DAG.getEntryNode();
1606     } else {
1607       // New and improved token factor.
1608       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1609     }
1610 
1611     // Add users to worklist if AA is enabled, since it may introduce
1612     // a lot of new chained token factors while removing memory deps.
1613     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1614       : DAG.getSubtarget().useAA();
1615     return CombineTo(N, Result, UseAA /*add to worklist*/);
1616   }
1617 
1618   return Result;
1619 }
1620 
1621 /// MERGE_VALUES can always be eliminated.
1622 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1623   WorklistRemover DeadNodes(*this);
1624   // Replacing results may cause a different MERGE_VALUES to suddenly
1625   // be CSE'd with N, and carry its uses with it. Iterate until no
1626   // uses remain, to ensure that the node can be safely deleted.
1627   // First add the users of this node to the work list so that they
1628   // can be tried again once they have new operands.
1629   AddUsersToWorklist(N);
1630   do {
1631     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1632       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1633   } while (!N->use_empty());
1634   deleteAndRecombine(N);
1635   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1636 }
1637 
1638 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1639 /// ConstantSDNode pointer else nullptr.
1640 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1641   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1642   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1643 }
1644 
1645 SDValue DAGCombiner::visitADD(SDNode *N) {
1646   SDValue N0 = N->getOperand(0);
1647   SDValue N1 = N->getOperand(1);
1648   EVT VT = N0.getValueType();
1649 
1650   // fold vector ops
1651   if (VT.isVector()) {
1652     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1653       return FoldedVOp;
1654 
1655     // fold (add x, 0) -> x, vector edition
1656     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1657       return N0;
1658     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1659       return N1;
1660   }
1661 
1662   // fold (add x, undef) -> undef
1663   if (N0.isUndef())
1664     return N0;
1665   if (N1.isUndef())
1666     return N1;
1667   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1668     // canonicalize constant to RHS
1669     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1670       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1671     // fold (add c1, c2) -> c1+c2
1672     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT,
1673                                       N0.getNode(), N1.getNode());
1674   }
1675   // fold (add x, 0) -> x
1676   if (isNullConstant(N1))
1677     return N0;
1678   // fold ((c1-A)+c2) -> (c1+c2)-A
1679   if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) {
1680     if (N0.getOpcode() == ISD::SUB)
1681       if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1682         SDLoc DL(N);
1683         return DAG.getNode(ISD::SUB, DL, VT,
1684                            DAG.getConstant(N1C->getAPIntValue()+
1685                                            N0C->getAPIntValue(), DL, VT),
1686                            N0.getOperand(1));
1687       }
1688   }
1689   // reassociate add
1690   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1691     return RADD;
1692   // fold ((0-A) + B) -> B-A
1693   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1694     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1695   // fold (A + (0-B)) -> A-B
1696   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1697     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1698   // fold (A+(B-A)) -> B
1699   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1700     return N1.getOperand(0);
1701   // fold ((B-A)+A) -> B
1702   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1703     return N0.getOperand(0);
1704   // fold (A+(B-(A+C))) to (B-C)
1705   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1706       N0 == N1.getOperand(1).getOperand(0))
1707     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1708                        N1.getOperand(1).getOperand(1));
1709   // fold (A+(B-(C+A))) to (B-C)
1710   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1711       N0 == N1.getOperand(1).getOperand(1))
1712     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1713                        N1.getOperand(1).getOperand(0));
1714   // fold (A+((B-A)+or-C)) to (B+or-C)
1715   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1716       N1.getOperand(0).getOpcode() == ISD::SUB &&
1717       N0 == N1.getOperand(0).getOperand(1))
1718     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1719                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1720 
1721   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1722   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1723     SDValue N00 = N0.getOperand(0);
1724     SDValue N01 = N0.getOperand(1);
1725     SDValue N10 = N1.getOperand(0);
1726     SDValue N11 = N1.getOperand(1);
1727 
1728     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1729       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1731                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1732   }
1733 
1734   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1735     return SDValue(N, 0);
1736 
1737   // fold (a+b) -> (a|b) iff a and b share no bits.
1738   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::OR, VT)) &&
1739       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1740     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1741 
1742   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1743   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1744       isNullConstant(N1.getOperand(0).getOperand(0)))
1745     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1746                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1747                                    N1.getOperand(0).getOperand(1),
1748                                    N1.getOperand(1)));
1749   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1750       isNullConstant(N0.getOperand(0).getOperand(0)))
1751     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1752                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1753                                    N0.getOperand(0).getOperand(1),
1754                                    N0.getOperand(1)));
1755 
1756   if (N1.getOpcode() == ISD::AND) {
1757     SDValue AndOp0 = N1.getOperand(0);
1758     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1759     unsigned DestBits = VT.getScalarType().getSizeInBits();
1760 
1761     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1762     // and similar xforms where the inner op is either ~0 or 0.
1763     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1764       SDLoc DL(N);
1765       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1766     }
1767   }
1768 
1769   // add (sext i1), X -> sub X, (zext i1)
1770   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1771       N0.getOperand(0).getValueType() == MVT::i1 &&
1772       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1773     SDLoc DL(N);
1774     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1775     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1776   }
1777 
1778   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1779   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1780     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1781     if (TN->getVT() == MVT::i1) {
1782       SDLoc DL(N);
1783       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1784                                  DAG.getConstant(1, DL, VT));
1785       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1786     }
1787   }
1788 
1789   return SDValue();
1790 }
1791 
1792 SDValue DAGCombiner::visitADDC(SDNode *N) {
1793   SDValue N0 = N->getOperand(0);
1794   SDValue N1 = N->getOperand(1);
1795   EVT VT = N0.getValueType();
1796 
1797   // If the flag result is dead, turn this into an ADD.
1798   if (!N->hasAnyUseOfValue(1))
1799     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1800                      DAG.getNode(ISD::CARRY_FALSE,
1801                                  SDLoc(N), MVT::Glue));
1802 
1803   // canonicalize constant to RHS.
1804   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1805   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1806   if (N0C && !N1C)
1807     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1808 
1809   // fold (addc x, 0) -> x + no carry out
1810   if (isNullConstant(N1))
1811     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1812                                         SDLoc(N), MVT::Glue));
1813 
1814   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1815   APInt LHSZero, LHSOne;
1816   APInt RHSZero, RHSOne;
1817   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1818 
1819   if (LHSZero.getBoolValue()) {
1820     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1821 
1822     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1823     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1824     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1825       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1826                        DAG.getNode(ISD::CARRY_FALSE,
1827                                    SDLoc(N), MVT::Glue));
1828   }
1829 
1830   return SDValue();
1831 }
1832 
1833 SDValue DAGCombiner::visitADDE(SDNode *N) {
1834   SDValue N0 = N->getOperand(0);
1835   SDValue N1 = N->getOperand(1);
1836   SDValue CarryIn = N->getOperand(2);
1837 
1838   // canonicalize constant to RHS
1839   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1840   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1841   if (N0C && !N1C)
1842     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1843                        N1, N0, CarryIn);
1844 
1845   // fold (adde x, y, false) -> (addc x, y)
1846   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1847     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1848 
1849   return SDValue();
1850 }
1851 
1852 // Since it may not be valid to emit a fold to zero for vector initializers
1853 // check if we can before folding.
1854 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1855                              SelectionDAG &DAG, bool LegalOperations,
1856                              bool LegalTypes) {
1857   if (!VT.isVector())
1858     return DAG.getConstant(0, DL, VT);
1859   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1860     return DAG.getConstant(0, DL, VT);
1861   return SDValue();
1862 }
1863 
1864 SDValue DAGCombiner::visitSUB(SDNode *N) {
1865   SDValue N0 = N->getOperand(0);
1866   SDValue N1 = N->getOperand(1);
1867   EVT VT = N0.getValueType();
1868 
1869   // fold vector ops
1870   if (VT.isVector()) {
1871     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1872       return FoldedVOp;
1873 
1874     // fold (sub x, 0) -> x, vector edition
1875     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1876       return N0;
1877   }
1878 
1879   // fold (sub x, x) -> 0
1880   // FIXME: Refactor this and xor and other similar operations together.
1881   if (N0 == N1)
1882     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1883   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1884       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1885     // fold (sub c1, c2) -> c1-c2
1886     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT,
1887                                       N0.getNode(), N1.getNode());
1888   }
1889   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1890   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1891   // fold (sub x, c) -> (add x, -c)
1892   if (N1C) {
1893     SDLoc DL(N);
1894     return DAG.getNode(ISD::ADD, DL, VT, N0,
1895                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1896   }
1897   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1898   if (isAllOnesConstant(N0))
1899     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1900   // fold A-(A-B) -> B
1901   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1902     return N1.getOperand(1);
1903   // fold (A+B)-A -> B
1904   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1905     return N0.getOperand(1);
1906   // fold (A+B)-B -> A
1907   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1908     return N0.getOperand(0);
1909   // fold C2-(A+C1) -> (C2-C1)-A
1910   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1911     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1912   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1913     SDLoc DL(N);
1914     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1915                                    DL, VT);
1916     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1917                        N1.getOperand(0));
1918   }
1919   // fold ((A+(B+or-C))-B) -> A+or-C
1920   if (N0.getOpcode() == ISD::ADD &&
1921       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1922        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1923       N0.getOperand(1).getOperand(0) == N1)
1924     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1925                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1926   // fold ((A+(C+B))-B) -> A+C
1927   if (N0.getOpcode() == ISD::ADD &&
1928       N0.getOperand(1).getOpcode() == ISD::ADD &&
1929       N0.getOperand(1).getOperand(1) == N1)
1930     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1931                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1932   // fold ((A-(B-C))-C) -> A-B
1933   if (N0.getOpcode() == ISD::SUB &&
1934       N0.getOperand(1).getOpcode() == ISD::SUB &&
1935       N0.getOperand(1).getOperand(1) == N1)
1936     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1937                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1938 
1939   // If either operand of a sub is undef, the result is undef
1940   if (N0.isUndef())
1941     return N0;
1942   if (N1.isUndef())
1943     return N1;
1944 
1945   // If the relocation model supports it, consider symbol offsets.
1946   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1947     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1948       // fold (sub Sym, c) -> Sym-c
1949       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1950         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1951                                     GA->getOffset() -
1952                                       (uint64_t)N1C->getSExtValue());
1953       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1954       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1955         if (GA->getGlobal() == GB->getGlobal())
1956           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1957                                  SDLoc(N), VT);
1958     }
1959 
1960   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1961   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1962     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1963     if (TN->getVT() == MVT::i1) {
1964       SDLoc DL(N);
1965       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1966                                  DAG.getConstant(1, DL, VT));
1967       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1968     }
1969   }
1970 
1971   return SDValue();
1972 }
1973 
1974 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1975   SDValue N0 = N->getOperand(0);
1976   SDValue N1 = N->getOperand(1);
1977   EVT VT = N0.getValueType();
1978   SDLoc DL(N);
1979 
1980   // If the flag result is dead, turn this into an SUB.
1981   if (!N->hasAnyUseOfValue(1))
1982     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1983                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1984 
1985   // fold (subc x, x) -> 0 + no borrow
1986   if (N0 == N1)
1987     return CombineTo(N, DAG.getConstant(0, DL, VT),
1988                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1989 
1990   // fold (subc x, 0) -> x + no borrow
1991   if (isNullConstant(N1))
1992     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1993 
1994   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1995   if (isAllOnesConstant(N0))
1996     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
1997                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1998 
1999   return SDValue();
2000 }
2001 
2002 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2003   SDValue N0 = N->getOperand(0);
2004   SDValue N1 = N->getOperand(1);
2005   SDValue CarryIn = N->getOperand(2);
2006 
2007   // fold (sube x, y, false) -> (subc x, y)
2008   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2009     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2010 
2011   return SDValue();
2012 }
2013 
2014 SDValue DAGCombiner::visitMUL(SDNode *N) {
2015   SDValue N0 = N->getOperand(0);
2016   SDValue N1 = N->getOperand(1);
2017   EVT VT = N0.getValueType();
2018 
2019   // fold (mul x, undef) -> 0
2020   if (N0.isUndef() || N1.isUndef())
2021     return DAG.getConstant(0, SDLoc(N), VT);
2022 
2023   bool N0IsConst = false;
2024   bool N1IsConst = false;
2025   bool N1IsOpaqueConst = false;
2026   bool N0IsOpaqueConst = false;
2027   APInt ConstValue0, ConstValue1;
2028   // fold vector ops
2029   if (VT.isVector()) {
2030     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2031       return FoldedVOp;
2032 
2033     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2034     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2035   } else {
2036     N0IsConst = isa<ConstantSDNode>(N0);
2037     if (N0IsConst) {
2038       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2039       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2040     }
2041     N1IsConst = isa<ConstantSDNode>(N1);
2042     if (N1IsConst) {
2043       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2044       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2045     }
2046   }
2047 
2048   // fold (mul c1, c2) -> c1*c2
2049   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2050     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2051                                       N0.getNode(), N1.getNode());
2052 
2053   // canonicalize constant to RHS (vector doesn't have to splat)
2054   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2055      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2056     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2057   // fold (mul x, 0) -> 0
2058   if (N1IsConst && ConstValue1 == 0)
2059     return N1;
2060   // We require a splat of the entire scalar bit width for non-contiguous
2061   // bit patterns.
2062   bool IsFullSplat =
2063     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2064   // fold (mul x, 1) -> x
2065   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2066     return N0;
2067   // fold (mul x, -1) -> 0-x
2068   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2069     SDLoc DL(N);
2070     return DAG.getNode(ISD::SUB, DL, VT,
2071                        DAG.getConstant(0, DL, VT), N0);
2072   }
2073   // fold (mul x, (1 << c)) -> x << c
2074   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2075       IsFullSplat) {
2076     SDLoc DL(N);
2077     return DAG.getNode(ISD::SHL, DL, VT, N0,
2078                        DAG.getConstant(ConstValue1.logBase2(), DL,
2079                                        getShiftAmountTy(N0.getValueType())));
2080   }
2081   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2082   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2083       IsFullSplat) {
2084     unsigned Log2Val = (-ConstValue1).logBase2();
2085     SDLoc DL(N);
2086     // FIXME: If the input is something that is easily negated (e.g. a
2087     // single-use add), we should put the negate there.
2088     return DAG.getNode(ISD::SUB, DL, VT,
2089                        DAG.getConstant(0, DL, VT),
2090                        DAG.getNode(ISD::SHL, DL, VT, N0,
2091                             DAG.getConstant(Log2Val, DL,
2092                                       getShiftAmountTy(N0.getValueType()))));
2093   }
2094 
2095   APInt Val;
2096   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2097   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2098       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2099                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2100     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2101                              N1, N0.getOperand(1));
2102     AddToWorklist(C3.getNode());
2103     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2104                        N0.getOperand(0), C3);
2105   }
2106 
2107   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2108   // use.
2109   {
2110     SDValue Sh(nullptr,0), Y(nullptr,0);
2111     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2112     if (N0.getOpcode() == ISD::SHL &&
2113         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2114                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2115         N0.getNode()->hasOneUse()) {
2116       Sh = N0; Y = N1;
2117     } else if (N1.getOpcode() == ISD::SHL &&
2118                isa<ConstantSDNode>(N1.getOperand(1)) &&
2119                N1.getNode()->hasOneUse()) {
2120       Sh = N1; Y = N0;
2121     }
2122 
2123     if (Sh.getNode()) {
2124       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2125                                 Sh.getOperand(0), Y);
2126       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2127                          Mul, Sh.getOperand(1));
2128     }
2129   }
2130 
2131   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2132   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2133       N0.getOpcode() == ISD::ADD &&
2134       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2135       isMulAddWithConstProfitable(N, N0, N1))
2136       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2137                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2138                                      N0.getOperand(0), N1),
2139                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2140                                      N0.getOperand(1), N1));
2141 
2142   // reassociate mul
2143   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2144     return RMUL;
2145 
2146   return SDValue();
2147 }
2148 
2149 /// Return true if divmod libcall is available.
2150 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2151                                      const TargetLowering &TLI) {
2152   RTLIB::Libcall LC;
2153   EVT NodeType = Node->getValueType(0);
2154   if (!NodeType.isSimple())
2155     return false;
2156   switch (NodeType.getSimpleVT().SimpleTy) {
2157   default: return false; // No libcall for vector types.
2158   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2159   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2160   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2161   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2162   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2163   }
2164 
2165   return TLI.getLibcallName(LC) != nullptr;
2166 }
2167 
2168 /// Issue divrem if both quotient and remainder are needed.
2169 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2170   if (Node->use_empty())
2171     return SDValue(); // This is a dead node, leave it alone.
2172 
2173   unsigned Opcode = Node->getOpcode();
2174   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2175   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2176 
2177   // DivMod lib calls can still work on non-legal types if using lib-calls.
2178   EVT VT = Node->getValueType(0);
2179   if (VT.isVector() || !VT.isInteger())
2180     return SDValue();
2181 
2182   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2183     return SDValue();
2184 
2185   // If DIVREM is going to get expanded into a libcall,
2186   // but there is no libcall available, then don't combine.
2187   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2188       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2189     return SDValue();
2190 
2191   // If div is legal, it's better to do the normal expansion
2192   unsigned OtherOpcode = 0;
2193   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2194     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2195     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2196       return SDValue();
2197   } else {
2198     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2199     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2200       return SDValue();
2201   }
2202 
2203   SDValue Op0 = Node->getOperand(0);
2204   SDValue Op1 = Node->getOperand(1);
2205   SDValue combined;
2206   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2207          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2208     SDNode *User = *UI;
2209     if (User == Node || User->use_empty())
2210       continue;
2211     // Convert the other matching node(s), too;
2212     // otherwise, the DIVREM may get target-legalized into something
2213     // target-specific that we won't be able to recognize.
2214     unsigned UserOpc = User->getOpcode();
2215     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2216         User->getOperand(0) == Op0 &&
2217         User->getOperand(1) == Op1) {
2218       if (!combined) {
2219         if (UserOpc == OtherOpcode) {
2220           SDVTList VTs = DAG.getVTList(VT, VT);
2221           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2222         } else if (UserOpc == DivRemOpc) {
2223           combined = SDValue(User, 0);
2224         } else {
2225           assert(UserOpc == Opcode);
2226           continue;
2227         }
2228       }
2229       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2230         CombineTo(User, combined);
2231       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2232         CombineTo(User, combined.getValue(1));
2233     }
2234   }
2235   return combined;
2236 }
2237 
2238 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2239   SDValue N0 = N->getOperand(0);
2240   SDValue N1 = N->getOperand(1);
2241   EVT VT = N->getValueType(0);
2242 
2243   // fold vector ops
2244   if (VT.isVector())
2245     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2246       return FoldedVOp;
2247 
2248   SDLoc DL(N);
2249 
2250   // fold (sdiv c1, c2) -> c1/c2
2251   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2252   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2253   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2254     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2255   // fold (sdiv X, 1) -> X
2256   if (N1C && N1C->isOne())
2257     return N0;
2258   // fold (sdiv X, -1) -> 0-X
2259   if (N1C && N1C->isAllOnesValue())
2260     return DAG.getNode(ISD::SUB, DL, VT,
2261                        DAG.getConstant(0, DL, VT), N0);
2262 
2263   // If we know the sign bits of both operands are zero, strength reduce to a
2264   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2265   if (!VT.isVector()) {
2266     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2267       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2268   }
2269 
2270   // fold (sdiv X, pow2) -> simple ops after legalize
2271   // FIXME: We check for the exact bit here because the generic lowering gives
2272   // better results in that case. The target-specific lowering should learn how
2273   // to handle exact sdivs efficiently.
2274   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2275       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2276       (N1C->getAPIntValue().isPowerOf2() ||
2277        (-N1C->getAPIntValue()).isPowerOf2())) {
2278     // Target-specific implementation of sdiv x, pow2.
2279     if (SDValue Res = BuildSDIVPow2(N))
2280       return Res;
2281 
2282     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2283 
2284     // Splat the sign bit into the register
2285     SDValue SGN =
2286         DAG.getNode(ISD::SRA, DL, VT, N0,
2287                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2288                                     getShiftAmountTy(N0.getValueType())));
2289     AddToWorklist(SGN.getNode());
2290 
2291     // Add (N0 < 0) ? abs2 - 1 : 0;
2292     SDValue SRL =
2293         DAG.getNode(ISD::SRL, DL, VT, SGN,
2294                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2295                                     getShiftAmountTy(SGN.getValueType())));
2296     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2297     AddToWorklist(SRL.getNode());
2298     AddToWorklist(ADD.getNode());    // Divide by pow2
2299     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2300                   DAG.getConstant(lg2, DL,
2301                                   getShiftAmountTy(ADD.getValueType())));
2302 
2303     // If we're dividing by a positive value, we're done.  Otherwise, we must
2304     // negate the result.
2305     if (N1C->getAPIntValue().isNonNegative())
2306       return SRA;
2307 
2308     AddToWorklist(SRA.getNode());
2309     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2310   }
2311 
2312   // If integer divide is expensive and we satisfy the requirements, emit an
2313   // alternate sequence.  Targets may check function attributes for size/speed
2314   // trade-offs.
2315   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2316   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2317     if (SDValue Op = BuildSDIV(N))
2318       return Op;
2319 
2320   // sdiv, srem -> sdivrem
2321   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2322   // Otherwise, we break the simplification logic in visitREM().
2323   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2324     if (SDValue DivRem = useDivRem(N))
2325         return DivRem;
2326 
2327   // undef / X -> 0
2328   if (N0.isUndef())
2329     return DAG.getConstant(0, DL, VT);
2330   // X / undef -> undef
2331   if (N1.isUndef())
2332     return N1;
2333 
2334   return SDValue();
2335 }
2336 
2337 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2338   SDValue N0 = N->getOperand(0);
2339   SDValue N1 = N->getOperand(1);
2340   EVT VT = N->getValueType(0);
2341 
2342   // fold vector ops
2343   if (VT.isVector())
2344     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2345       return FoldedVOp;
2346 
2347   SDLoc DL(N);
2348 
2349   // fold (udiv c1, c2) -> c1/c2
2350   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2351   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2352   if (N0C && N1C)
2353     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2354                                                     N0C, N1C))
2355       return Folded;
2356   // fold (udiv x, (1 << c)) -> x >>u c
2357   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2358     return DAG.getNode(ISD::SRL, DL, VT, N0,
2359                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2360                                        getShiftAmountTy(N0.getValueType())));
2361 
2362   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2363   if (N1.getOpcode() == ISD::SHL) {
2364     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2365       if (SHC->getAPIntValue().isPowerOf2()) {
2366         EVT ADDVT = N1.getOperand(1).getValueType();
2367         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2368                                   N1.getOperand(1),
2369                                   DAG.getConstant(SHC->getAPIntValue()
2370                                                                   .logBase2(),
2371                                                   DL, ADDVT));
2372         AddToWorklist(Add.getNode());
2373         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2374       }
2375     }
2376   }
2377 
2378   // fold (udiv x, c) -> alternate
2379   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2380   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2381     if (SDValue Op = BuildUDIV(N))
2382       return Op;
2383 
2384   // sdiv, srem -> sdivrem
2385   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2386   // Otherwise, we break the simplification logic in visitREM().
2387   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2388     if (SDValue DivRem = useDivRem(N))
2389         return DivRem;
2390 
2391   // undef / X -> 0
2392   if (N0.isUndef())
2393     return DAG.getConstant(0, DL, VT);
2394   // X / undef -> undef
2395   if (N1.isUndef())
2396     return N1;
2397 
2398   return SDValue();
2399 }
2400 
2401 // handles ISD::SREM and ISD::UREM
2402 SDValue DAGCombiner::visitREM(SDNode *N) {
2403   unsigned Opcode = N->getOpcode();
2404   SDValue N0 = N->getOperand(0);
2405   SDValue N1 = N->getOperand(1);
2406   EVT VT = N->getValueType(0);
2407   bool isSigned = (Opcode == ISD::SREM);
2408   SDLoc DL(N);
2409 
2410   // fold (rem c1, c2) -> c1%c2
2411   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2412   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2413   if (N0C && N1C)
2414     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2415       return Folded;
2416 
2417   if (isSigned) {
2418     // If we know the sign bits of both operands are zero, strength reduce to a
2419     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2420     if (!VT.isVector()) {
2421       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2422         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2423     }
2424   } else {
2425     // fold (urem x, pow2) -> (and x, pow2-1)
2426     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2427         N1C->getAPIntValue().isPowerOf2()) {
2428       return DAG.getNode(ISD::AND, DL, VT, N0,
2429                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2430     }
2431     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2432     if (N1.getOpcode() == ISD::SHL) {
2433       ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0));
2434       if (SHC && SHC->getAPIntValue().isPowerOf2()) {
2435         APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits());
2436         SDValue Add =
2437             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2438         AddToWorklist(Add.getNode());
2439         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2440       }
2441     }
2442   }
2443 
2444   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2445 
2446   // If X/C can be simplified by the division-by-constant logic, lower
2447   // X%C to the equivalent of X-X/C*C.
2448   // To avoid mangling nodes, this simplification requires that the combine()
2449   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2450   // against this by skipping the simplification if isIntDivCheap().  When
2451   // div is not cheap, combine will not return a DIVREM.  Regardless,
2452   // checking cheapness here makes sense since the simplification results in
2453   // fatter code.
2454   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2455     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2456     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2457     AddToWorklist(Div.getNode());
2458     SDValue OptimizedDiv = combine(Div.getNode());
2459     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2460       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2461              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2462       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2463       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2464       AddToWorklist(Mul.getNode());
2465       return Sub;
2466     }
2467   }
2468 
2469   // sdiv, srem -> sdivrem
2470   if (SDValue DivRem = useDivRem(N))
2471     return DivRem.getValue(1);
2472 
2473   // undef % X -> 0
2474   if (N0.isUndef())
2475     return DAG.getConstant(0, DL, VT);
2476   // X % undef -> undef
2477   if (N1.isUndef())
2478     return N1;
2479 
2480   return SDValue();
2481 }
2482 
2483 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2484   SDValue N0 = N->getOperand(0);
2485   SDValue N1 = N->getOperand(1);
2486   EVT VT = N->getValueType(0);
2487   SDLoc DL(N);
2488 
2489   // fold (mulhs x, 0) -> 0
2490   if (isNullConstant(N1))
2491     return N1;
2492   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2493   if (isOneConstant(N1)) {
2494     SDLoc DL(N);
2495     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2496                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2497                                        DL,
2498                                        getShiftAmountTy(N0.getValueType())));
2499   }
2500   // fold (mulhs x, undef) -> 0
2501   if (N0.isUndef() || N1.isUndef())
2502     return DAG.getConstant(0, SDLoc(N), VT);
2503 
2504   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2505   // plus a shift.
2506   if (VT.isSimple() && !VT.isVector()) {
2507     MVT Simple = VT.getSimpleVT();
2508     unsigned SimpleSize = Simple.getSizeInBits();
2509     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2510     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2511       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2512       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2513       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2514       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2515             DAG.getConstant(SimpleSize, DL,
2516                             getShiftAmountTy(N1.getValueType())));
2517       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2518     }
2519   }
2520 
2521   return SDValue();
2522 }
2523 
2524 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2525   SDValue N0 = N->getOperand(0);
2526   SDValue N1 = N->getOperand(1);
2527   EVT VT = N->getValueType(0);
2528   SDLoc DL(N);
2529 
2530   // fold (mulhu x, 0) -> 0
2531   if (isNullConstant(N1))
2532     return N1;
2533   // fold (mulhu x, 1) -> 0
2534   if (isOneConstant(N1))
2535     return DAG.getConstant(0, DL, N0.getValueType());
2536   // fold (mulhu x, undef) -> 0
2537   if (N0.isUndef() || N1.isUndef())
2538     return DAG.getConstant(0, DL, VT);
2539 
2540   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2541   // plus a shift.
2542   if (VT.isSimple() && !VT.isVector()) {
2543     MVT Simple = VT.getSimpleVT();
2544     unsigned SimpleSize = Simple.getSizeInBits();
2545     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2546     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2547       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2548       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2549       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2550       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2551             DAG.getConstant(SimpleSize, DL,
2552                             getShiftAmountTy(N1.getValueType())));
2553       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2554     }
2555   }
2556 
2557   return SDValue();
2558 }
2559 
2560 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2561 /// give the opcodes for the two computations that are being performed. Return
2562 /// true if a simplification was made.
2563 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2564                                                 unsigned HiOp) {
2565   // If the high half is not needed, just compute the low half.
2566   bool HiExists = N->hasAnyUseOfValue(1);
2567   if (!HiExists &&
2568       (!LegalOperations ||
2569        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2570     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2571     return CombineTo(N, Res, Res);
2572   }
2573 
2574   // If the low half is not needed, just compute the high half.
2575   bool LoExists = N->hasAnyUseOfValue(0);
2576   if (!LoExists &&
2577       (!LegalOperations ||
2578        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2579     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2580     return CombineTo(N, Res, Res);
2581   }
2582 
2583   // If both halves are used, return as it is.
2584   if (LoExists && HiExists)
2585     return SDValue();
2586 
2587   // If the two computed results can be simplified separately, separate them.
2588   if (LoExists) {
2589     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2590     AddToWorklist(Lo.getNode());
2591     SDValue LoOpt = combine(Lo.getNode());
2592     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2593         (!LegalOperations ||
2594          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2595       return CombineTo(N, LoOpt, LoOpt);
2596   }
2597 
2598   if (HiExists) {
2599     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2600     AddToWorklist(Hi.getNode());
2601     SDValue HiOpt = combine(Hi.getNode());
2602     if (HiOpt.getNode() && HiOpt != Hi &&
2603         (!LegalOperations ||
2604          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2605       return CombineTo(N, HiOpt, HiOpt);
2606   }
2607 
2608   return SDValue();
2609 }
2610 
2611 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2612   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2613     return Res;
2614 
2615   EVT VT = N->getValueType(0);
2616   SDLoc DL(N);
2617 
2618   // If the type is twice as wide is legal, transform the mulhu to a wider
2619   // multiply plus a shift.
2620   if (VT.isSimple() && !VT.isVector()) {
2621     MVT Simple = VT.getSimpleVT();
2622     unsigned SimpleSize = Simple.getSizeInBits();
2623     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2624     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2625       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2626       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2627       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2628       // Compute the high part as N1.
2629       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2630             DAG.getConstant(SimpleSize, DL,
2631                             getShiftAmountTy(Lo.getValueType())));
2632       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2633       // Compute the low part as N0.
2634       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2635       return CombineTo(N, Lo, Hi);
2636     }
2637   }
2638 
2639   return SDValue();
2640 }
2641 
2642 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2643   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2644     return Res;
2645 
2646   EVT VT = N->getValueType(0);
2647   SDLoc DL(N);
2648 
2649   // If the type is twice as wide is legal, transform the mulhu to a wider
2650   // multiply plus a shift.
2651   if (VT.isSimple() && !VT.isVector()) {
2652     MVT Simple = VT.getSimpleVT();
2653     unsigned SimpleSize = Simple.getSizeInBits();
2654     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2655     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2656       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2657       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2658       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2659       // Compute the high part as N1.
2660       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2661             DAG.getConstant(SimpleSize, DL,
2662                             getShiftAmountTy(Lo.getValueType())));
2663       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2664       // Compute the low part as N0.
2665       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2666       return CombineTo(N, Lo, Hi);
2667     }
2668   }
2669 
2670   return SDValue();
2671 }
2672 
2673 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2674   // (smulo x, 2) -> (saddo x, x)
2675   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2676     if (C2->getAPIntValue() == 2)
2677       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2678                          N->getOperand(0), N->getOperand(0));
2679 
2680   return SDValue();
2681 }
2682 
2683 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2684   // (umulo x, 2) -> (uaddo x, x)
2685   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2686     if (C2->getAPIntValue() == 2)
2687       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2688                          N->getOperand(0), N->getOperand(0));
2689 
2690   return SDValue();
2691 }
2692 
2693 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2694   SDValue N0 = N->getOperand(0);
2695   SDValue N1 = N->getOperand(1);
2696   EVT VT = N0.getValueType();
2697 
2698   // fold vector ops
2699   if (VT.isVector())
2700     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2701       return FoldedVOp;
2702 
2703   // fold (add c1, c2) -> c1+c2
2704   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2705   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2706   if (N0C && N1C)
2707     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2708 
2709   // canonicalize constant to RHS
2710   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2711      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2712     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2713 
2714   return SDValue();
2715 }
2716 
2717 /// If this is a binary operator with two operands of the same opcode, try to
2718 /// simplify it.
2719 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2720   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2721   EVT VT = N0.getValueType();
2722   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2723 
2724   // Bail early if none of these transforms apply.
2725   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2726 
2727   // For each of OP in AND/OR/XOR:
2728   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2729   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2730   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2731   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2732   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2733   //
2734   // do not sink logical op inside of a vector extend, since it may combine
2735   // into a vsetcc.
2736   EVT Op0VT = N0.getOperand(0).getValueType();
2737   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2738        N0.getOpcode() == ISD::SIGN_EXTEND ||
2739        N0.getOpcode() == ISD::BSWAP ||
2740        // Avoid infinite looping with PromoteIntBinOp.
2741        (N0.getOpcode() == ISD::ANY_EXTEND &&
2742         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2743        (N0.getOpcode() == ISD::TRUNCATE &&
2744         (!TLI.isZExtFree(VT, Op0VT) ||
2745          !TLI.isTruncateFree(Op0VT, VT)) &&
2746         TLI.isTypeLegal(Op0VT))) &&
2747       !VT.isVector() &&
2748       Op0VT == N1.getOperand(0).getValueType() &&
2749       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2750     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2751                                  N0.getOperand(0).getValueType(),
2752                                  N0.getOperand(0), N1.getOperand(0));
2753     AddToWorklist(ORNode.getNode());
2754     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2755   }
2756 
2757   // For each of OP in SHL/SRL/SRA/AND...
2758   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2759   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2760   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2761   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2762        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2763       N0.getOperand(1) == N1.getOperand(1)) {
2764     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2765                                  N0.getOperand(0).getValueType(),
2766                                  N0.getOperand(0), N1.getOperand(0));
2767     AddToWorklist(ORNode.getNode());
2768     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2769                        ORNode, N0.getOperand(1));
2770   }
2771 
2772   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2773   // Only perform this optimization up until type legalization, before
2774   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2775   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2776   // we don't want to undo this promotion.
2777   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2778   // on scalars.
2779   if ((N0.getOpcode() == ISD::BITCAST ||
2780        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2781        Level <= AfterLegalizeTypes) {
2782     SDValue In0 = N0.getOperand(0);
2783     SDValue In1 = N1.getOperand(0);
2784     EVT In0Ty = In0.getValueType();
2785     EVT In1Ty = In1.getValueType();
2786     SDLoc DL(N);
2787     // If both incoming values are integers, and the original types are the
2788     // same.
2789     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2790       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2791       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2792       AddToWorklist(Op.getNode());
2793       return BC;
2794     }
2795   }
2796 
2797   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2798   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2799   // If both shuffles use the same mask, and both shuffle within a single
2800   // vector, then it is worthwhile to move the swizzle after the operation.
2801   // The type-legalizer generates this pattern when loading illegal
2802   // vector types from memory. In many cases this allows additional shuffle
2803   // optimizations.
2804   // There are other cases where moving the shuffle after the xor/and/or
2805   // is profitable even if shuffles don't perform a swizzle.
2806   // If both shuffles use the same mask, and both shuffles have the same first
2807   // or second operand, then it might still be profitable to move the shuffle
2808   // after the xor/and/or operation.
2809   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2810     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2811     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2812 
2813     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2814            "Inputs to shuffles are not the same type");
2815 
2816     // Check that both shuffles use the same mask. The masks are known to be of
2817     // the same length because the result vector type is the same.
2818     // Check also that shuffles have only one use to avoid introducing extra
2819     // instructions.
2820     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2821         SVN0->getMask().equals(SVN1->getMask())) {
2822       SDValue ShOp = N0->getOperand(1);
2823 
2824       // Don't try to fold this node if it requires introducing a
2825       // build vector of all zeros that might be illegal at this stage.
2826       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2827         if (!LegalTypes)
2828           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2829         else
2830           ShOp = SDValue();
2831       }
2832 
2833       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2834       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2835       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2836       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2837         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2838                                       N0->getOperand(0), N1->getOperand(0));
2839         AddToWorklist(NewNode.getNode());
2840         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2841                                     &SVN0->getMask()[0]);
2842       }
2843 
2844       // Don't try to fold this node if it requires introducing a
2845       // build vector of all zeros that might be illegal at this stage.
2846       ShOp = N0->getOperand(0);
2847       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2848         if (!LegalTypes)
2849           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2850         else
2851           ShOp = SDValue();
2852       }
2853 
2854       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2855       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2856       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2857       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2858         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2859                                       N0->getOperand(1), N1->getOperand(1));
2860         AddToWorklist(NewNode.getNode());
2861         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2862                                     &SVN0->getMask()[0]);
2863       }
2864     }
2865   }
2866 
2867   return SDValue();
2868 }
2869 
2870 /// This contains all DAGCombine rules which reduce two values combined by
2871 /// an And operation to a single value. This makes them reusable in the context
2872 /// of visitSELECT(). Rules involving constants are not included as
2873 /// visitSELECT() already handles those cases.
2874 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2875                                   SDNode *LocReference) {
2876   EVT VT = N1.getValueType();
2877 
2878   // fold (and x, undef) -> 0
2879   if (N0.isUndef() || N1.isUndef())
2880     return DAG.getConstant(0, SDLoc(LocReference), VT);
2881   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2882   SDValue LL, LR, RL, RR, CC0, CC1;
2883   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2884     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2885     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2886 
2887     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2888         LL.getValueType().isInteger()) {
2889       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2890       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2891         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2892                                      LR.getValueType(), LL, RL);
2893         AddToWorklist(ORNode.getNode());
2894         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2895       }
2896       if (isAllOnesConstant(LR)) {
2897         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2898         if (Op1 == ISD::SETEQ) {
2899           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2900                                         LR.getValueType(), LL, RL);
2901           AddToWorklist(ANDNode.getNode());
2902           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2903         }
2904         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2905         if (Op1 == ISD::SETGT) {
2906           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2907                                        LR.getValueType(), LL, RL);
2908           AddToWorklist(ORNode.getNode());
2909           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2910         }
2911       }
2912     }
2913     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2914     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2915         Op0 == Op1 && LL.getValueType().isInteger() &&
2916       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2917                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2918       SDLoc DL(N0);
2919       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2920                                     LL, DAG.getConstant(1, DL,
2921                                                         LL.getValueType()));
2922       AddToWorklist(ADDNode.getNode());
2923       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2924                           DAG.getConstant(2, DL, LL.getValueType()),
2925                           ISD::SETUGE);
2926     }
2927     // canonicalize equivalent to ll == rl
2928     if (LL == RR && LR == RL) {
2929       Op1 = ISD::getSetCCSwappedOperands(Op1);
2930       std::swap(RL, RR);
2931     }
2932     if (LL == RL && LR == RR) {
2933       bool isInteger = LL.getValueType().isInteger();
2934       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2935       if (Result != ISD::SETCC_INVALID &&
2936           (!LegalOperations ||
2937            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2938             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2939         EVT CCVT = getSetCCResultType(LL.getValueType());
2940         if (N0.getValueType() == CCVT ||
2941             (!LegalOperations && N0.getValueType() == MVT::i1))
2942           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2943                               LL, LR, Result);
2944       }
2945     }
2946   }
2947 
2948   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2949       VT.getSizeInBits() <= 64) {
2950     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2951       APInt ADDC = ADDI->getAPIntValue();
2952       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2953         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2954         // immediate for an add, but it is legal if its top c2 bits are set,
2955         // transform the ADD so the immediate doesn't need to be materialized
2956         // in a register.
2957         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2958           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2959                                              SRLI->getZExtValue());
2960           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2961             ADDC |= Mask;
2962             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2963               SDLoc DL(N0);
2964               SDValue NewAdd =
2965                 DAG.getNode(ISD::ADD, DL, VT,
2966                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2967               CombineTo(N0.getNode(), NewAdd);
2968               // Return N so it doesn't get rechecked!
2969               return SDValue(LocReference, 0);
2970             }
2971           }
2972         }
2973       }
2974     }
2975   }
2976 
2977   // Reduce bit extract of low half of an integer to the narrower type.
2978   // (and (srl i64:x, K), KMask) ->
2979   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
2980   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2981     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
2982       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2983         unsigned Size = VT.getSizeInBits();
2984         const APInt &AndMask = CAnd->getAPIntValue();
2985         unsigned ShiftBits = CShift->getZExtValue();
2986         unsigned MaskBits = AndMask.countTrailingOnes();
2987         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
2988 
2989         if (APIntOps::isMask(AndMask) &&
2990             // Required bits must not span the two halves of the integer and
2991             // must fit in the half size type.
2992             (ShiftBits + MaskBits <= Size / 2) &&
2993             TLI.isNarrowingProfitable(VT, HalfVT) &&
2994             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
2995             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2996             TLI.isTruncateFree(VT, HalfVT) &&
2997             TLI.isZExtFree(HalfVT, VT)) {
2998           // The isNarrowingProfitable is to avoid regressions on PPC and
2999           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3000           // on downstream users of this. Those patterns could probably be
3001           // extended to handle extensions mixed in.
3002 
3003           SDValue SL(N0);
3004           assert(ShiftBits != 0 && MaskBits <= Size);
3005 
3006           // Extracting the highest bit of the low half.
3007           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3008           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3009                                       N0.getOperand(0));
3010 
3011           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3012           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3013           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3014           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3015           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3016         }
3017       }
3018     }
3019   }
3020 
3021   return SDValue();
3022 }
3023 
3024 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3025                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3026                                    bool &NarrowLoad) {
3027   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3028 
3029   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3030     return false;
3031 
3032   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3033   LoadedVT = LoadN->getMemoryVT();
3034 
3035   if (ExtVT == LoadedVT &&
3036       (!LegalOperations ||
3037        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3038     // ZEXTLOAD will match without needing to change the size of the value being
3039     // loaded.
3040     NarrowLoad = false;
3041     return true;
3042   }
3043 
3044   // Do not change the width of a volatile load.
3045   if (LoadN->isVolatile())
3046     return false;
3047 
3048   // Do not generate loads of non-round integer types since these can
3049   // be expensive (and would be wrong if the type is not byte sized).
3050   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3051     return false;
3052 
3053   if (LegalOperations &&
3054       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3055     return false;
3056 
3057   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3058     return false;
3059 
3060   NarrowLoad = true;
3061   return true;
3062 }
3063 
3064 SDValue DAGCombiner::visitAND(SDNode *N) {
3065   SDValue N0 = N->getOperand(0);
3066   SDValue N1 = N->getOperand(1);
3067   EVT VT = N1.getValueType();
3068 
3069   // fold vector ops
3070   if (VT.isVector()) {
3071     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3072       return FoldedVOp;
3073 
3074     // fold (and x, 0) -> 0, vector edition
3075     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3076       // do not return N0, because undef node may exist in N0
3077       return DAG.getConstant(
3078           APInt::getNullValue(
3079               N0.getValueType().getScalarType().getSizeInBits()),
3080           SDLoc(N), N0.getValueType());
3081     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3082       // do not return N1, because undef node may exist in N1
3083       return DAG.getConstant(
3084           APInt::getNullValue(
3085               N1.getValueType().getScalarType().getSizeInBits()),
3086           SDLoc(N), N1.getValueType());
3087 
3088     // fold (and x, -1) -> x, vector edition
3089     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3090       return N1;
3091     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3092       return N0;
3093   }
3094 
3095   // fold (and c1, c2) -> c1&c2
3096   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3097   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3098   if (N0C && N1C && !N1C->isOpaque())
3099     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3100   // canonicalize constant to RHS
3101   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3102      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3103     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3104   // fold (and x, -1) -> x
3105   if (isAllOnesConstant(N1))
3106     return N0;
3107   // if (and x, c) is known to be zero, return 0
3108   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3109   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3110                                    APInt::getAllOnesValue(BitWidth)))
3111     return DAG.getConstant(0, SDLoc(N), VT);
3112   // reassociate and
3113   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3114     return RAND;
3115   // fold (and (or x, C), D) -> D if (C & D) == D
3116   if (N1C && N0.getOpcode() == ISD::OR)
3117     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3118       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3119         return N1;
3120   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3121   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3122     SDValue N0Op0 = N0.getOperand(0);
3123     APInt Mask = ~N1C->getAPIntValue();
3124     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3125     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3126       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3127                                  N0.getValueType(), N0Op0);
3128 
3129       // Replace uses of the AND with uses of the Zero extend node.
3130       CombineTo(N, Zext);
3131 
3132       // We actually want to replace all uses of the any_extend with the
3133       // zero_extend, to avoid duplicating things.  This will later cause this
3134       // AND to be folded.
3135       CombineTo(N0.getNode(), Zext);
3136       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3137     }
3138   }
3139   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3140   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3141   // already be zero by virtue of the width of the base type of the load.
3142   //
3143   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3144   // more cases.
3145   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3146        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3147        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3148        N0.getOperand(0).getResNo() == 0) ||
3149       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3150     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3151                                          N0 : N0.getOperand(0) );
3152 
3153     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3154     // This can be a pure constant or a vector splat, in which case we treat the
3155     // vector as a scalar and use the splat value.
3156     APInt Constant = APInt::getNullValue(1);
3157     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3158       Constant = C->getAPIntValue();
3159     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3160       APInt SplatValue, SplatUndef;
3161       unsigned SplatBitSize;
3162       bool HasAnyUndefs;
3163       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3164                                              SplatBitSize, HasAnyUndefs);
3165       if (IsSplat) {
3166         // Undef bits can contribute to a possible optimisation if set, so
3167         // set them.
3168         SplatValue |= SplatUndef;
3169 
3170         // The splat value may be something like "0x00FFFFFF", which means 0 for
3171         // the first vector value and FF for the rest, repeating. We need a mask
3172         // that will apply equally to all members of the vector, so AND all the
3173         // lanes of the constant together.
3174         EVT VT = Vector->getValueType(0);
3175         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3176 
3177         // If the splat value has been compressed to a bitlength lower
3178         // than the size of the vector lane, we need to re-expand it to
3179         // the lane size.
3180         if (BitWidth > SplatBitSize)
3181           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3182                SplatBitSize < BitWidth;
3183                SplatBitSize = SplatBitSize * 2)
3184             SplatValue |= SplatValue.shl(SplatBitSize);
3185 
3186         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3187         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3188         if (SplatBitSize % BitWidth == 0) {
3189           Constant = APInt::getAllOnesValue(BitWidth);
3190           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3191             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3192         }
3193       }
3194     }
3195 
3196     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3197     // actually legal and isn't going to get expanded, else this is a false
3198     // optimisation.
3199     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3200                                                     Load->getValueType(0),
3201                                                     Load->getMemoryVT());
3202 
3203     // Resize the constant to the same size as the original memory access before
3204     // extension. If it is still the AllOnesValue then this AND is completely
3205     // unneeded.
3206     Constant =
3207       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3208 
3209     bool B;
3210     switch (Load->getExtensionType()) {
3211     default: B = false; break;
3212     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3213     case ISD::ZEXTLOAD:
3214     case ISD::NON_EXTLOAD: B = true; break;
3215     }
3216 
3217     if (B && Constant.isAllOnesValue()) {
3218       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3219       // preserve semantics once we get rid of the AND.
3220       SDValue NewLoad(Load, 0);
3221       if (Load->getExtensionType() == ISD::EXTLOAD) {
3222         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3223                               Load->getValueType(0), SDLoc(Load),
3224                               Load->getChain(), Load->getBasePtr(),
3225                               Load->getOffset(), Load->getMemoryVT(),
3226                               Load->getMemOperand());
3227         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3228         if (Load->getNumValues() == 3) {
3229           // PRE/POST_INC loads have 3 values.
3230           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3231                            NewLoad.getValue(2) };
3232           CombineTo(Load, To, 3, true);
3233         } else {
3234           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3235         }
3236       }
3237 
3238       // Fold the AND away, taking care not to fold to the old load node if we
3239       // replaced it.
3240       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3241 
3242       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3243     }
3244   }
3245 
3246   // fold (and (load x), 255) -> (zextload x, i8)
3247   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3248   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3249   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3250               (N0.getOpcode() == ISD::ANY_EXTEND &&
3251                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3252     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3253     LoadSDNode *LN0 = HasAnyExt
3254       ? cast<LoadSDNode>(N0.getOperand(0))
3255       : cast<LoadSDNode>(N0);
3256     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3257         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3258       auto NarrowLoad = false;
3259       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3260       EVT ExtVT, LoadedVT;
3261       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3262                            NarrowLoad)) {
3263         if (!NarrowLoad) {
3264           SDValue NewLoad =
3265             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3266                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3267                            LN0->getMemOperand());
3268           AddToWorklist(N);
3269           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3270           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3271         } else {
3272           EVT PtrType = LN0->getOperand(1).getValueType();
3273 
3274           unsigned Alignment = LN0->getAlignment();
3275           SDValue NewPtr = LN0->getBasePtr();
3276 
3277           // For big endian targets, we need to add an offset to the pointer
3278           // to load the correct bytes.  For little endian systems, we merely
3279           // need to read fewer bytes from the same pointer.
3280           if (DAG.getDataLayout().isBigEndian()) {
3281             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3282             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3283             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3284             SDLoc DL(LN0);
3285             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3286                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3287             Alignment = MinAlign(Alignment, PtrOff);
3288           }
3289 
3290           AddToWorklist(NewPtr.getNode());
3291 
3292           SDValue Load =
3293             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3294                            LN0->getChain(), NewPtr,
3295                            LN0->getPointerInfo(),
3296                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3297                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3298           AddToWorklist(N);
3299           CombineTo(LN0, Load, Load.getValue(1));
3300           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3301         }
3302       }
3303     }
3304   }
3305 
3306   if (SDValue Combined = visitANDLike(N0, N1, N))
3307     return Combined;
3308 
3309   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3310   if (N0.getOpcode() == N1.getOpcode())
3311     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3312       return Tmp;
3313 
3314   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3315   // fold (and (sra)) -> (and (srl)) when possible.
3316   if (!VT.isVector() &&
3317       SimplifyDemandedBits(SDValue(N, 0)))
3318     return SDValue(N, 0);
3319 
3320   // fold (zext_inreg (extload x)) -> (zextload x)
3321   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3322     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3323     EVT MemVT = LN0->getMemoryVT();
3324     // If we zero all the possible extended bits, then we can turn this into
3325     // a zextload if we are running before legalize or the operation is legal.
3326     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3327     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3328                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3329         ((!LegalOperations && !LN0->isVolatile()) ||
3330          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3331       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3332                                        LN0->getChain(), LN0->getBasePtr(),
3333                                        MemVT, LN0->getMemOperand());
3334       AddToWorklist(N);
3335       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3336       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3337     }
3338   }
3339   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3340   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3341       N0.hasOneUse()) {
3342     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3343     EVT MemVT = LN0->getMemoryVT();
3344     // If we zero all the possible extended bits, then we can turn this into
3345     // a zextload if we are running before legalize or the operation is legal.
3346     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3347     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3348                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3349         ((!LegalOperations && !LN0->isVolatile()) ||
3350          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3351       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3352                                        LN0->getChain(), LN0->getBasePtr(),
3353                                        MemVT, LN0->getMemOperand());
3354       AddToWorklist(N);
3355       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3356       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3357     }
3358   }
3359   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3360   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3361     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3362                                            N0.getOperand(1), false))
3363       return BSwap;
3364   }
3365 
3366   return SDValue();
3367 }
3368 
3369 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3370 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3371                                         bool DemandHighBits) {
3372   if (!LegalOperations)
3373     return SDValue();
3374 
3375   EVT VT = N->getValueType(0);
3376   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3377     return SDValue();
3378   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3379     return SDValue();
3380 
3381   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3382   bool LookPassAnd0 = false;
3383   bool LookPassAnd1 = false;
3384   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3385       std::swap(N0, N1);
3386   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3387       std::swap(N0, N1);
3388   if (N0.getOpcode() == ISD::AND) {
3389     if (!N0.getNode()->hasOneUse())
3390       return SDValue();
3391     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3392     if (!N01C || N01C->getZExtValue() != 0xFF00)
3393       return SDValue();
3394     N0 = N0.getOperand(0);
3395     LookPassAnd0 = true;
3396   }
3397 
3398   if (N1.getOpcode() == ISD::AND) {
3399     if (!N1.getNode()->hasOneUse())
3400       return SDValue();
3401     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3402     if (!N11C || N11C->getZExtValue() != 0xFF)
3403       return SDValue();
3404     N1 = N1.getOperand(0);
3405     LookPassAnd1 = true;
3406   }
3407 
3408   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3409     std::swap(N0, N1);
3410   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3411     return SDValue();
3412   if (!N0.getNode()->hasOneUse() ||
3413       !N1.getNode()->hasOneUse())
3414     return SDValue();
3415 
3416   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3417   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3418   if (!N01C || !N11C)
3419     return SDValue();
3420   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3421     return SDValue();
3422 
3423   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3424   SDValue N00 = N0->getOperand(0);
3425   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3426     if (!N00.getNode()->hasOneUse())
3427       return SDValue();
3428     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3429     if (!N001C || N001C->getZExtValue() != 0xFF)
3430       return SDValue();
3431     N00 = N00.getOperand(0);
3432     LookPassAnd0 = true;
3433   }
3434 
3435   SDValue N10 = N1->getOperand(0);
3436   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3437     if (!N10.getNode()->hasOneUse())
3438       return SDValue();
3439     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3440     if (!N101C || N101C->getZExtValue() != 0xFF00)
3441       return SDValue();
3442     N10 = N10.getOperand(0);
3443     LookPassAnd1 = true;
3444   }
3445 
3446   if (N00 != N10)
3447     return SDValue();
3448 
3449   // Make sure everything beyond the low halfword gets set to zero since the SRL
3450   // 16 will clear the top bits.
3451   unsigned OpSizeInBits = VT.getSizeInBits();
3452   if (DemandHighBits && OpSizeInBits > 16) {
3453     // If the left-shift isn't masked out then the only way this is a bswap is
3454     // if all bits beyond the low 8 are 0. In that case the entire pattern
3455     // reduces to a left shift anyway: leave it for other parts of the combiner.
3456     if (!LookPassAnd0)
3457       return SDValue();
3458 
3459     // However, if the right shift isn't masked out then it might be because
3460     // it's not needed. See if we can spot that too.
3461     if (!LookPassAnd1 &&
3462         !DAG.MaskedValueIsZero(
3463             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3464       return SDValue();
3465   }
3466 
3467   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3468   if (OpSizeInBits > 16) {
3469     SDLoc DL(N);
3470     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3471                       DAG.getConstant(OpSizeInBits - 16, DL,
3472                                       getShiftAmountTy(VT)));
3473   }
3474   return Res;
3475 }
3476 
3477 /// Return true if the specified node is an element that makes up a 32-bit
3478 /// packed halfword byteswap.
3479 /// ((x & 0x000000ff) << 8) |
3480 /// ((x & 0x0000ff00) >> 8) |
3481 /// ((x & 0x00ff0000) << 8) |
3482 /// ((x & 0xff000000) >> 8)
3483 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3484   if (!N.getNode()->hasOneUse())
3485     return false;
3486 
3487   unsigned Opc = N.getOpcode();
3488   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3489     return false;
3490 
3491   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3492   if (!N1C)
3493     return false;
3494 
3495   unsigned Num;
3496   switch (N1C->getZExtValue()) {
3497   default:
3498     return false;
3499   case 0xFF:       Num = 0; break;
3500   case 0xFF00:     Num = 1; break;
3501   case 0xFF0000:   Num = 2; break;
3502   case 0xFF000000: Num = 3; break;
3503   }
3504 
3505   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3506   SDValue N0 = N.getOperand(0);
3507   if (Opc == ISD::AND) {
3508     if (Num == 0 || Num == 2) {
3509       // (x >> 8) & 0xff
3510       // (x >> 8) & 0xff0000
3511       if (N0.getOpcode() != ISD::SRL)
3512         return false;
3513       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3514       if (!C || C->getZExtValue() != 8)
3515         return false;
3516     } else {
3517       // (x << 8) & 0xff00
3518       // (x << 8) & 0xff000000
3519       if (N0.getOpcode() != ISD::SHL)
3520         return false;
3521       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3522       if (!C || C->getZExtValue() != 8)
3523         return false;
3524     }
3525   } else if (Opc == ISD::SHL) {
3526     // (x & 0xff) << 8
3527     // (x & 0xff0000) << 8
3528     if (Num != 0 && Num != 2)
3529       return false;
3530     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3531     if (!C || C->getZExtValue() != 8)
3532       return false;
3533   } else { // Opc == ISD::SRL
3534     // (x & 0xff00) >> 8
3535     // (x & 0xff000000) >> 8
3536     if (Num != 1 && Num != 3)
3537       return false;
3538     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3539     if (!C || C->getZExtValue() != 8)
3540       return false;
3541   }
3542 
3543   if (Parts[Num])
3544     return false;
3545 
3546   Parts[Num] = N0.getOperand(0).getNode();
3547   return true;
3548 }
3549 
3550 /// Match a 32-bit packed halfword bswap. That is
3551 /// ((x & 0x000000ff) << 8) |
3552 /// ((x & 0x0000ff00) >> 8) |
3553 /// ((x & 0x00ff0000) << 8) |
3554 /// ((x & 0xff000000) >> 8)
3555 /// => (rotl (bswap x), 16)
3556 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3557   if (!LegalOperations)
3558     return SDValue();
3559 
3560   EVT VT = N->getValueType(0);
3561   if (VT != MVT::i32)
3562     return SDValue();
3563   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3564     return SDValue();
3565 
3566   // Look for either
3567   // (or (or (and), (and)), (or (and), (and)))
3568   // (or (or (or (and), (and)), (and)), (and))
3569   if (N0.getOpcode() != ISD::OR)
3570     return SDValue();
3571   SDValue N00 = N0.getOperand(0);
3572   SDValue N01 = N0.getOperand(1);
3573   SDNode *Parts[4] = {};
3574 
3575   if (N1.getOpcode() == ISD::OR &&
3576       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3577     // (or (or (and), (and)), (or (and), (and)))
3578     SDValue N000 = N00.getOperand(0);
3579     if (!isBSwapHWordElement(N000, Parts))
3580       return SDValue();
3581 
3582     SDValue N001 = N00.getOperand(1);
3583     if (!isBSwapHWordElement(N001, Parts))
3584       return SDValue();
3585     SDValue N010 = N01.getOperand(0);
3586     if (!isBSwapHWordElement(N010, Parts))
3587       return SDValue();
3588     SDValue N011 = N01.getOperand(1);
3589     if (!isBSwapHWordElement(N011, Parts))
3590       return SDValue();
3591   } else {
3592     // (or (or (or (and), (and)), (and)), (and))
3593     if (!isBSwapHWordElement(N1, Parts))
3594       return SDValue();
3595     if (!isBSwapHWordElement(N01, Parts))
3596       return SDValue();
3597     if (N00.getOpcode() != ISD::OR)
3598       return SDValue();
3599     SDValue N000 = N00.getOperand(0);
3600     if (!isBSwapHWordElement(N000, Parts))
3601       return SDValue();
3602     SDValue N001 = N00.getOperand(1);
3603     if (!isBSwapHWordElement(N001, Parts))
3604       return SDValue();
3605   }
3606 
3607   // Make sure the parts are all coming from the same node.
3608   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3609     return SDValue();
3610 
3611   SDLoc DL(N);
3612   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3613                               SDValue(Parts[0], 0));
3614 
3615   // Result of the bswap should be rotated by 16. If it's not legal, then
3616   // do  (x << 16) | (x >> 16).
3617   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3618   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3619     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3620   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3621     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3622   return DAG.getNode(ISD::OR, DL, VT,
3623                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3624                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3625 }
3626 
3627 /// This contains all DAGCombine rules which reduce two values combined by
3628 /// an Or operation to a single value \see visitANDLike().
3629 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3630   EVT VT = N1.getValueType();
3631   // fold (or x, undef) -> -1
3632   if (!LegalOperations &&
3633       (N0.isUndef() || N1.isUndef())) {
3634     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3635     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3636                            SDLoc(LocReference), VT);
3637   }
3638   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3639   SDValue LL, LR, RL, RR, CC0, CC1;
3640   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3641     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3642     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3643 
3644     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3645       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3646       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3647       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3648         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3649                                      LR.getValueType(), LL, RL);
3650         AddToWorklist(ORNode.getNode());
3651         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3652       }
3653       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3654       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3655       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3656         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3657                                       LR.getValueType(), LL, RL);
3658         AddToWorklist(ANDNode.getNode());
3659         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3660       }
3661     }
3662     // canonicalize equivalent to ll == rl
3663     if (LL == RR && LR == RL) {
3664       Op1 = ISD::getSetCCSwappedOperands(Op1);
3665       std::swap(RL, RR);
3666     }
3667     if (LL == RL && LR == RR) {
3668       bool isInteger = LL.getValueType().isInteger();
3669       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3670       if (Result != ISD::SETCC_INVALID &&
3671           (!LegalOperations ||
3672            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3673             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3674         EVT CCVT = getSetCCResultType(LL.getValueType());
3675         if (N0.getValueType() == CCVT ||
3676             (!LegalOperations && N0.getValueType() == MVT::i1))
3677           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3678                               LL, LR, Result);
3679       }
3680     }
3681   }
3682 
3683   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3684   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3685       // Don't increase # computations.
3686       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3687     // We can only do this xform if we know that bits from X that are set in C2
3688     // but not in C1 are already zero.  Likewise for Y.
3689     if (const ConstantSDNode *N0O1C =
3690         getAsNonOpaqueConstant(N0.getOperand(1))) {
3691       if (const ConstantSDNode *N1O1C =
3692           getAsNonOpaqueConstant(N1.getOperand(1))) {
3693         // We can only do this xform if we know that bits from X that are set in
3694         // C2 but not in C1 are already zero.  Likewise for Y.
3695         const APInt &LHSMask = N0O1C->getAPIntValue();
3696         const APInt &RHSMask = N1O1C->getAPIntValue();
3697 
3698         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3699             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3700           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3701                                   N0.getOperand(0), N1.getOperand(0));
3702           SDLoc DL(LocReference);
3703           return DAG.getNode(ISD::AND, DL, VT, X,
3704                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3705         }
3706       }
3707     }
3708   }
3709 
3710   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3711   if (N0.getOpcode() == ISD::AND &&
3712       N1.getOpcode() == ISD::AND &&
3713       N0.getOperand(0) == N1.getOperand(0) &&
3714       // Don't increase # computations.
3715       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3716     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3717                             N0.getOperand(1), N1.getOperand(1));
3718     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3719   }
3720 
3721   return SDValue();
3722 }
3723 
3724 SDValue DAGCombiner::visitOR(SDNode *N) {
3725   SDValue N0 = N->getOperand(0);
3726   SDValue N1 = N->getOperand(1);
3727   EVT VT = N1.getValueType();
3728 
3729   // fold vector ops
3730   if (VT.isVector()) {
3731     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3732       return FoldedVOp;
3733 
3734     // fold (or x, 0) -> x, vector edition
3735     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3736       return N1;
3737     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3738       return N0;
3739 
3740     // fold (or x, -1) -> -1, vector edition
3741     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3742       // do not return N0, because undef node may exist in N0
3743       return DAG.getConstant(
3744           APInt::getAllOnesValue(
3745               N0.getValueType().getScalarType().getSizeInBits()),
3746           SDLoc(N), N0.getValueType());
3747     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3748       // do not return N1, because undef node may exist in N1
3749       return DAG.getConstant(
3750           APInt::getAllOnesValue(
3751               N1.getValueType().getScalarType().getSizeInBits()),
3752           SDLoc(N), N1.getValueType());
3753 
3754     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3755     // Do this only if the resulting shuffle is legal.
3756     if (isa<ShuffleVectorSDNode>(N0) &&
3757         isa<ShuffleVectorSDNode>(N1) &&
3758         // Avoid folding a node with illegal type.
3759         TLI.isTypeLegal(VT)) {
3760       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3761       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3762       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3763       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3764       // Ensure both shuffles have a zero input.
3765       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3766         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3767         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3768         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3769         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3770         bool CanFold = true;
3771         int NumElts = VT.getVectorNumElements();
3772         SmallVector<int, 4> Mask(NumElts);
3773 
3774         for (int i = 0; i != NumElts; ++i) {
3775           int M0 = SV0->getMaskElt(i);
3776           int M1 = SV1->getMaskElt(i);
3777 
3778           // Both shuffle indexes are undef. Propagate Undef.
3779           if (M0 < 0 && M1 < 0) {
3780             Mask[i] = -1;
3781             continue;
3782           }
3783 
3784           // Determine if either index is pointing to a zero vector.
3785           bool M0Zero = M0 >= 0 && (ZeroN00 == (M0 < NumElts));
3786           bool M1Zero = M1 >= 0 && (ZeroN10 == (M1 < NumElts));
3787           if (M0Zero == M1Zero) {
3788             CanFold = false;
3789             break;
3790           }
3791 
3792           // We have a zero and non-zero element. If the non-zero came from
3793           // SV0 make the index a LHS index. If it came from SV1, make it
3794           // a RHS index. We need to mod by NumElts because we don't care
3795           // which operand it came from in the original shuffles.
3796           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3797         }
3798 
3799         if (CanFold) {
3800           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3801           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3802 
3803           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3804           if (!LegalMask) {
3805             std::swap(NewLHS, NewRHS);
3806             ShuffleVectorSDNode::commuteMask(Mask);
3807             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3808           }
3809 
3810           if (LegalMask)
3811             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS,
3812                                         NewRHS, &Mask[0]);
3813         }
3814       }
3815     }
3816   }
3817 
3818   // fold (or c1, c2) -> c1|c2
3819   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3820   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3821   if (N0C && N1C && !N1C->isOpaque())
3822     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3823   // canonicalize constant to RHS
3824   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3825      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3826     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3827   // fold (or x, 0) -> x
3828   if (isNullConstant(N1))
3829     return N0;
3830   // fold (or x, -1) -> -1
3831   if (isAllOnesConstant(N1))
3832     return N1;
3833   // fold (or x, c) -> c iff (x & ~c) == 0
3834   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3835     return N1;
3836 
3837   if (SDValue Combined = visitORLike(N0, N1, N))
3838     return Combined;
3839 
3840   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3841   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3842     return BSwap;
3843   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3844     return BSwap;
3845 
3846   // reassociate or
3847   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3848     return ROR;
3849   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3850   // iff (c1 & c2) == 0.
3851   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3852              isa<ConstantSDNode>(N0.getOperand(1))) {
3853     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3854     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3855       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3856                                                    N1C, C1))
3857         return DAG.getNode(
3858             ISD::AND, SDLoc(N), VT,
3859             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3860       return SDValue();
3861     }
3862   }
3863   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3864   if (N0.getOpcode() == N1.getOpcode())
3865     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3866       return Tmp;
3867 
3868   // See if this is some rotate idiom.
3869   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3870     return SDValue(Rot, 0);
3871 
3872   // Simplify the operands using demanded-bits information.
3873   if (!VT.isVector() &&
3874       SimplifyDemandedBits(SDValue(N, 0)))
3875     return SDValue(N, 0);
3876 
3877   return SDValue();
3878 }
3879 
3880 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3881 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3882   if (Op.getOpcode() == ISD::AND) {
3883     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3884       Mask = Op.getOperand(1);
3885       Op = Op.getOperand(0);
3886     } else {
3887       return false;
3888     }
3889   }
3890 
3891   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3892     Shift = Op;
3893     return true;
3894   }
3895 
3896   return false;
3897 }
3898 
3899 // Return true if we can prove that, whenever Neg and Pos are both in the
3900 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3901 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3902 //
3903 //     (or (shift1 X, Neg), (shift2 X, Pos))
3904 //
3905 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3906 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3907 // to consider shift amounts with defined behavior.
3908 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3909   // If EltSize is a power of 2 then:
3910   //
3911   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3912   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3913   //
3914   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3915   // for the stronger condition:
3916   //
3917   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3918   //
3919   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3920   // we can just replace Neg with Neg' for the rest of the function.
3921   //
3922   // In other cases we check for the even stronger condition:
3923   //
3924   //     Neg == EltSize - Pos                                    [B]
3925   //
3926   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3927   // behavior if Pos == 0 (and consequently Neg == EltSize).
3928   //
3929   // We could actually use [A] whenever EltSize is a power of 2, but the
3930   // only extra cases that it would match are those uninteresting ones
3931   // where Neg and Pos are never in range at the same time.  E.g. for
3932   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3933   // as well as (sub 32, Pos), but:
3934   //
3935   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3936   //
3937   // always invokes undefined behavior for 32-bit X.
3938   //
3939   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3940   unsigned MaskLoBits = 0;
3941   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3942     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3943       if (NegC->getAPIntValue() == EltSize - 1) {
3944         Neg = Neg.getOperand(0);
3945         MaskLoBits = Log2_64(EltSize);
3946       }
3947     }
3948   }
3949 
3950   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3951   if (Neg.getOpcode() != ISD::SUB)
3952     return false;
3953   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3954   if (!NegC)
3955     return false;
3956   SDValue NegOp1 = Neg.getOperand(1);
3957 
3958   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3959   // Pos'.  The truncation is redundant for the purpose of the equality.
3960   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3961     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3962       if (PosC->getAPIntValue() == EltSize - 1)
3963         Pos = Pos.getOperand(0);
3964 
3965   // The condition we need is now:
3966   //
3967   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3968   //
3969   // If NegOp1 == Pos then we need:
3970   //
3971   //              EltSize & Mask == NegC & Mask
3972   //
3973   // (because "x & Mask" is a truncation and distributes through subtraction).
3974   APInt Width;
3975   if (Pos == NegOp1)
3976     Width = NegC->getAPIntValue();
3977 
3978   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3979   // Then the condition we want to prove becomes:
3980   //
3981   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3982   //
3983   // which, again because "x & Mask" is a truncation, becomes:
3984   //
3985   //                NegC & Mask == (EltSize - PosC) & Mask
3986   //             EltSize & Mask == (NegC + PosC) & Mask
3987   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3988     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3989       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3990     else
3991       return false;
3992   } else
3993     return false;
3994 
3995   // Now we just need to check that EltSize & Mask == Width & Mask.
3996   if (MaskLoBits)
3997     // EltSize & Mask is 0 since Mask is EltSize - 1.
3998     return Width.getLoBits(MaskLoBits) == 0;
3999   return Width == EltSize;
4000 }
4001 
4002 // A subroutine of MatchRotate used once we have found an OR of two opposite
4003 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4004 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4005 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4006 // Neg with outer conversions stripped away.
4007 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4008                                        SDValue Neg, SDValue InnerPos,
4009                                        SDValue InnerNeg, unsigned PosOpcode,
4010                                        unsigned NegOpcode, const SDLoc &DL) {
4011   // fold (or (shl x, (*ext y)),
4012   //          (srl x, (*ext (sub 32, y)))) ->
4013   //   (rotl x, y) or (rotr x, (sub 32, y))
4014   //
4015   // fold (or (shl x, (*ext (sub 32, y))),
4016   //          (srl x, (*ext y))) ->
4017   //   (rotr x, y) or (rotl x, (sub 32, y))
4018   EVT VT = Shifted.getValueType();
4019   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4020     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4021     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4022                        HasPos ? Pos : Neg).getNode();
4023   }
4024 
4025   return nullptr;
4026 }
4027 
4028 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4029 // idioms for rotate, and if the target supports rotation instructions, generate
4030 // a rot[lr].
4031 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4032   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4033   EVT VT = LHS.getValueType();
4034   if (!TLI.isTypeLegal(VT)) return nullptr;
4035 
4036   // The target must have at least one rotate flavor.
4037   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4038   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4039   if (!HasROTL && !HasROTR) return nullptr;
4040 
4041   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4042   SDValue LHSShift;   // The shift.
4043   SDValue LHSMask;    // AND value if any.
4044   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4045     return nullptr; // Not part of a rotate.
4046 
4047   SDValue RHSShift;   // The shift.
4048   SDValue RHSMask;    // AND value if any.
4049   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4050     return nullptr; // Not part of a rotate.
4051 
4052   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4053     return nullptr;   // Not shifting the same value.
4054 
4055   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4056     return nullptr;   // Shifts must disagree.
4057 
4058   // Canonicalize shl to left side in a shl/srl pair.
4059   if (RHSShift.getOpcode() == ISD::SHL) {
4060     std::swap(LHS, RHS);
4061     std::swap(LHSShift, RHSShift);
4062     std::swap(LHSMask, RHSMask);
4063   }
4064 
4065   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4066   SDValue LHSShiftArg = LHSShift.getOperand(0);
4067   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4068   SDValue RHSShiftArg = RHSShift.getOperand(0);
4069   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4070 
4071   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4072   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4073   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4074     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4075     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4076     if ((LShVal + RShVal) != EltSizeInBits)
4077       return nullptr;
4078 
4079     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4080                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4081 
4082     // If there is an AND of either shifted operand, apply it to the result.
4083     if (LHSMask.getNode() || RHSMask.getNode()) {
4084       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4085       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4086 
4087       if (LHSMask.getNode()) {
4088         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4089         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4090                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4091                                        DAG.getConstant(RHSBits, DL, VT)));
4092       }
4093       if (RHSMask.getNode()) {
4094         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4095         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4096                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4097                                        DAG.getConstant(LHSBits, DL, VT)));
4098       }
4099 
4100       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4101     }
4102 
4103     return Rot.getNode();
4104   }
4105 
4106   // If there is a mask here, and we have a variable shift, we can't be sure
4107   // that we're masking out the right stuff.
4108   if (LHSMask.getNode() || RHSMask.getNode())
4109     return nullptr;
4110 
4111   // If the shift amount is sign/zext/any-extended just peel it off.
4112   SDValue LExtOp0 = LHSShiftAmt;
4113   SDValue RExtOp0 = RHSShiftAmt;
4114   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4115        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4116        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4117        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4118       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4119        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4120        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4121        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4122     LExtOp0 = LHSShiftAmt.getOperand(0);
4123     RExtOp0 = RHSShiftAmt.getOperand(0);
4124   }
4125 
4126   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4127                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4128   if (TryL)
4129     return TryL;
4130 
4131   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4132                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4133   if (TryR)
4134     return TryR;
4135 
4136   return nullptr;
4137 }
4138 
4139 SDValue DAGCombiner::visitXOR(SDNode *N) {
4140   SDValue N0 = N->getOperand(0);
4141   SDValue N1 = N->getOperand(1);
4142   EVT VT = N0.getValueType();
4143 
4144   // fold vector ops
4145   if (VT.isVector()) {
4146     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4147       return FoldedVOp;
4148 
4149     // fold (xor x, 0) -> x, vector edition
4150     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4151       return N1;
4152     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4153       return N0;
4154   }
4155 
4156   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4157   if (N0.isUndef() && N1.isUndef())
4158     return DAG.getConstant(0, SDLoc(N), VT);
4159   // fold (xor x, undef) -> undef
4160   if (N0.isUndef())
4161     return N0;
4162   if (N1.isUndef())
4163     return N1;
4164   // fold (xor c1, c2) -> c1^c2
4165   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4166   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4167   if (N0C && N1C)
4168     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4169   // canonicalize constant to RHS
4170   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4171      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4172     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4173   // fold (xor x, 0) -> x
4174   if (isNullConstant(N1))
4175     return N0;
4176   // reassociate xor
4177   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4178     return RXOR;
4179 
4180   // fold !(x cc y) -> (x !cc y)
4181   SDValue LHS, RHS, CC;
4182   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4183     bool isInt = LHS.getValueType().isInteger();
4184     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4185                                                isInt);
4186 
4187     if (!LegalOperations ||
4188         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4189       switch (N0.getOpcode()) {
4190       default:
4191         llvm_unreachable("Unhandled SetCC Equivalent!");
4192       case ISD::SETCC:
4193         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4194       case ISD::SELECT_CC:
4195         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4196                                N0.getOperand(3), NotCC);
4197       }
4198     }
4199   }
4200 
4201   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4202   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4203       N0.getNode()->hasOneUse() &&
4204       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4205     SDValue V = N0.getOperand(0);
4206     SDLoc DL(N0);
4207     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4208                     DAG.getConstant(1, DL, V.getValueType()));
4209     AddToWorklist(V.getNode());
4210     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4211   }
4212 
4213   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4214   if (isOneConstant(N1) && VT == MVT::i1 &&
4215       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4216     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4217     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4218       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4219       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4220       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4221       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4222       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4223     }
4224   }
4225   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4226   if (isAllOnesConstant(N1) &&
4227       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4228     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4229     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4230       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4231       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4232       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4233       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4234       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4235     }
4236   }
4237   // fold (xor (and x, y), y) -> (and (not x), y)
4238   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4239       N0->getOperand(1) == N1) {
4240     SDValue X = N0->getOperand(0);
4241     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4242     AddToWorklist(NotX.getNode());
4243     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4244   }
4245   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4246   if (N1C && N0.getOpcode() == ISD::XOR) {
4247     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4248       SDLoc DL(N);
4249       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4250                          DAG.getConstant(N1C->getAPIntValue() ^
4251                                          N00C->getAPIntValue(), DL, VT));
4252     }
4253     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4254       SDLoc DL(N);
4255       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4256                          DAG.getConstant(N1C->getAPIntValue() ^
4257                                          N01C->getAPIntValue(), DL, VT));
4258     }
4259   }
4260   // fold (xor x, x) -> 0
4261   if (N0 == N1)
4262     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4263 
4264   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4265   // Here is a concrete example of this equivalence:
4266   // i16   x ==  14
4267   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4268   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4269   //
4270   // =>
4271   //
4272   // i16     ~1      == 0b1111111111111110
4273   // i16 rol(~1, 14) == 0b1011111111111111
4274   //
4275   // Some additional tips to help conceptualize this transform:
4276   // - Try to see the operation as placing a single zero in a value of all ones.
4277   // - There exists no value for x which would allow the result to contain zero.
4278   // - Values of x larger than the bitwidth are undefined and do not require a
4279   //   consistent result.
4280   // - Pushing the zero left requires shifting one bits in from the right.
4281   // A rotate left of ~1 is a nice way of achieving the desired result.
4282   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4283       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4284     SDLoc DL(N);
4285     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4286                        N0.getOperand(1));
4287   }
4288 
4289   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4290   if (N0.getOpcode() == N1.getOpcode())
4291     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4292       return Tmp;
4293 
4294   // Simplify the expression using non-local knowledge.
4295   if (!VT.isVector() &&
4296       SimplifyDemandedBits(SDValue(N, 0)))
4297     return SDValue(N, 0);
4298 
4299   return SDValue();
4300 }
4301 
4302 /// Handle transforms common to the three shifts, when the shift amount is a
4303 /// constant.
4304 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4305   SDNode *LHS = N->getOperand(0).getNode();
4306   if (!LHS->hasOneUse()) return SDValue();
4307 
4308   // We want to pull some binops through shifts, so that we have (and (shift))
4309   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4310   // thing happens with address calculations, so it's important to canonicalize
4311   // it.
4312   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4313 
4314   switch (LHS->getOpcode()) {
4315   default: return SDValue();
4316   case ISD::OR:
4317   case ISD::XOR:
4318     HighBitSet = false; // We can only transform sra if the high bit is clear.
4319     break;
4320   case ISD::AND:
4321     HighBitSet = true;  // We can only transform sra if the high bit is set.
4322     break;
4323   case ISD::ADD:
4324     if (N->getOpcode() != ISD::SHL)
4325       return SDValue(); // only shl(add) not sr[al](add).
4326     HighBitSet = false; // We can only transform sra if the high bit is clear.
4327     break;
4328   }
4329 
4330   // We require the RHS of the binop to be a constant and not opaque as well.
4331   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4332   if (!BinOpCst) return SDValue();
4333 
4334   // FIXME: disable this unless the input to the binop is a shift by a constant.
4335   // If it is not a shift, it pessimizes some common cases like:
4336   //
4337   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4338   //    int bar(int *X, int i) { return X[i & 255]; }
4339   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4340   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4341        BinOpLHSVal->getOpcode() != ISD::SRA &&
4342        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4343       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4344     return SDValue();
4345 
4346   EVT VT = N->getValueType(0);
4347 
4348   // If this is a signed shift right, and the high bit is modified by the
4349   // logical operation, do not perform the transformation. The highBitSet
4350   // boolean indicates the value of the high bit of the constant which would
4351   // cause it to be modified for this operation.
4352   if (N->getOpcode() == ISD::SRA) {
4353     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4354     if (BinOpRHSSignSet != HighBitSet)
4355       return SDValue();
4356   }
4357 
4358   if (!TLI.isDesirableToCommuteWithShift(LHS))
4359     return SDValue();
4360 
4361   // Fold the constants, shifting the binop RHS by the shift amount.
4362   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4363                                N->getValueType(0),
4364                                LHS->getOperand(1), N->getOperand(1));
4365   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4366 
4367   // Create the new shift.
4368   SDValue NewShift = DAG.getNode(N->getOpcode(),
4369                                  SDLoc(LHS->getOperand(0)),
4370                                  VT, LHS->getOperand(0), N->getOperand(1));
4371 
4372   // Create the new binop.
4373   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4374 }
4375 
4376 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4377   assert(N->getOpcode() == ISD::TRUNCATE);
4378   assert(N->getOperand(0).getOpcode() == ISD::AND);
4379 
4380   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4381   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4382     SDValue N01 = N->getOperand(0).getOperand(1);
4383 
4384     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4385       if (!N01C->isOpaque()) {
4386         EVT TruncVT = N->getValueType(0);
4387         SDValue N00 = N->getOperand(0).getOperand(0);
4388         APInt TruncC = N01C->getAPIntValue();
4389         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4390         SDLoc DL(N);
4391 
4392         return DAG.getNode(ISD::AND, DL, TruncVT,
4393                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4394                            DAG.getConstant(TruncC, DL, TruncVT));
4395       }
4396     }
4397   }
4398 
4399   return SDValue();
4400 }
4401 
4402 SDValue DAGCombiner::visitRotate(SDNode *N) {
4403   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4404   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4405       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4406     if (SDValue NewOp1 =
4407             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4408       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4409                          N->getOperand(0), NewOp1);
4410   }
4411   return SDValue();
4412 }
4413 
4414 SDValue DAGCombiner::visitSHL(SDNode *N) {
4415   SDValue N0 = N->getOperand(0);
4416   SDValue N1 = N->getOperand(1);
4417   EVT VT = N0.getValueType();
4418   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4419 
4420   // fold vector ops
4421   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4422   if (VT.isVector()) {
4423     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4424       return FoldedVOp;
4425 
4426     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4427     // If setcc produces all-one true value then:
4428     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4429     if (N1CV && N1CV->isConstant()) {
4430       if (N0.getOpcode() == ISD::AND) {
4431         SDValue N00 = N0->getOperand(0);
4432         SDValue N01 = N0->getOperand(1);
4433         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4434 
4435         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4436             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4437                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4438           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4439                                                      N01CV, N1CV))
4440             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4441         }
4442       } else {
4443         N1C = isConstOrConstSplat(N1);
4444       }
4445     }
4446   }
4447 
4448   // fold (shl c1, c2) -> c1<<c2
4449   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4450   if (N0C && N1C && !N1C->isOpaque())
4451     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4452   // fold (shl 0, x) -> 0
4453   if (isNullConstant(N0))
4454     return N0;
4455   // fold (shl x, c >= size(x)) -> undef
4456   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4457     return DAG.getUNDEF(VT);
4458   // fold (shl x, 0) -> x
4459   if (N1C && N1C->isNullValue())
4460     return N0;
4461   // fold (shl undef, x) -> 0
4462   if (N0.isUndef())
4463     return DAG.getConstant(0, SDLoc(N), VT);
4464   // if (shl x, c) is known to be zero, return 0
4465   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4466                             APInt::getAllOnesValue(OpSizeInBits)))
4467     return DAG.getConstant(0, SDLoc(N), VT);
4468   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4469   if (N1.getOpcode() == ISD::TRUNCATE &&
4470       N1.getOperand(0).getOpcode() == ISD::AND) {
4471     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4472       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4473   }
4474 
4475   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4476     return SDValue(N, 0);
4477 
4478   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4479   if (N1C && N0.getOpcode() == ISD::SHL) {
4480     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4481       uint64_t c1 = N0C1->getZExtValue();
4482       uint64_t c2 = N1C->getZExtValue();
4483       SDLoc DL(N);
4484       if (c1 + c2 >= OpSizeInBits)
4485         return DAG.getConstant(0, DL, VT);
4486       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4487                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4488     }
4489   }
4490 
4491   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4492   // For this to be valid, the second form must not preserve any of the bits
4493   // that are shifted out by the inner shift in the first form.  This means
4494   // the outer shift size must be >= the number of bits added by the ext.
4495   // As a corollary, we don't care what kind of ext it is.
4496   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4497               N0.getOpcode() == ISD::ANY_EXTEND ||
4498               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4499       N0.getOperand(0).getOpcode() == ISD::SHL) {
4500     SDValue N0Op0 = N0.getOperand(0);
4501     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4502       uint64_t c1 = N0Op0C1->getZExtValue();
4503       uint64_t c2 = N1C->getZExtValue();
4504       EVT InnerShiftVT = N0Op0.getValueType();
4505       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4506       if (c2 >= OpSizeInBits - InnerShiftSize) {
4507         SDLoc DL(N0);
4508         if (c1 + c2 >= OpSizeInBits)
4509           return DAG.getConstant(0, DL, VT);
4510         return DAG.getNode(ISD::SHL, DL, VT,
4511                            DAG.getNode(N0.getOpcode(), DL, VT,
4512                                        N0Op0->getOperand(0)),
4513                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4514       }
4515     }
4516   }
4517 
4518   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4519   // Only fold this if the inner zext has no other uses to avoid increasing
4520   // the total number of instructions.
4521   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4522       N0.getOperand(0).getOpcode() == ISD::SRL) {
4523     SDValue N0Op0 = N0.getOperand(0);
4524     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4525       uint64_t c1 = N0Op0C1->getZExtValue();
4526       if (c1 < VT.getScalarSizeInBits()) {
4527         uint64_t c2 = N1C->getZExtValue();
4528         if (c1 == c2) {
4529           SDValue NewOp0 = N0.getOperand(0);
4530           EVT CountVT = NewOp0.getOperand(1).getValueType();
4531           SDLoc DL(N);
4532           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4533                                        NewOp0,
4534                                        DAG.getConstant(c2, DL, CountVT));
4535           AddToWorklist(NewSHL.getNode());
4536           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4537         }
4538       }
4539     }
4540   }
4541 
4542   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4543   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4544   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4545       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4546     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4547       uint64_t C1 = N0C1->getZExtValue();
4548       uint64_t C2 = N1C->getZExtValue();
4549       SDLoc DL(N);
4550       if (C1 <= C2)
4551         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4552                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4553       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4554                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4555     }
4556   }
4557 
4558   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4559   //                               (and (srl x, (sub c1, c2), MASK)
4560   // Only fold this if the inner shift has no other uses -- if it does, folding
4561   // this will increase the total number of instructions.
4562   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4563     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4564       uint64_t c1 = N0C1->getZExtValue();
4565       if (c1 < OpSizeInBits) {
4566         uint64_t c2 = N1C->getZExtValue();
4567         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4568         SDValue Shift;
4569         if (c2 > c1) {
4570           Mask = Mask.shl(c2 - c1);
4571           SDLoc DL(N);
4572           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4573                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4574         } else {
4575           Mask = Mask.lshr(c1 - c2);
4576           SDLoc DL(N);
4577           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4578                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4579         }
4580         SDLoc DL(N0);
4581         return DAG.getNode(ISD::AND, DL, VT, Shift,
4582                            DAG.getConstant(Mask, DL, VT));
4583       }
4584     }
4585   }
4586   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4587   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4588     unsigned BitSize = VT.getScalarSizeInBits();
4589     SDLoc DL(N);
4590     SDValue HiBitsMask =
4591       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4592                                             BitSize - N1C->getZExtValue()),
4593                       DL, VT);
4594     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4595                        HiBitsMask);
4596   }
4597 
4598   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4599   // Variant of version done on multiply, except mul by a power of 2 is turned
4600   // into a shift.
4601   APInt Val;
4602   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4603       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4604        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4605     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4606     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4607     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4608   }
4609 
4610   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4611   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4612     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4613       if (SDValue Folded =
4614               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4615         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4616     }
4617   }
4618 
4619   if (N1C && !N1C->isOpaque())
4620     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4621       return NewSHL;
4622 
4623   return SDValue();
4624 }
4625 
4626 SDValue DAGCombiner::visitSRA(SDNode *N) {
4627   SDValue N0 = N->getOperand(0);
4628   SDValue N1 = N->getOperand(1);
4629   EVT VT = N0.getValueType();
4630   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4631 
4632   // fold vector ops
4633   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4634   if (VT.isVector()) {
4635     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4636       return FoldedVOp;
4637 
4638     N1C = isConstOrConstSplat(N1);
4639   }
4640 
4641   // fold (sra c1, c2) -> (sra c1, c2)
4642   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4643   if (N0C && N1C && !N1C->isOpaque())
4644     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4645   // fold (sra 0, x) -> 0
4646   if (isNullConstant(N0))
4647     return N0;
4648   // fold (sra -1, x) -> -1
4649   if (isAllOnesConstant(N0))
4650     return N0;
4651   // fold (sra x, (setge c, size(x))) -> undef
4652   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4653     return DAG.getUNDEF(VT);
4654   // fold (sra x, 0) -> x
4655   if (N1C && N1C->isNullValue())
4656     return N0;
4657   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4658   // sext_inreg.
4659   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4660     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4661     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4662     if (VT.isVector())
4663       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4664                                ExtVT, VT.getVectorNumElements());
4665     if ((!LegalOperations ||
4666          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4667       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4668                          N0.getOperand(0), DAG.getValueType(ExtVT));
4669   }
4670 
4671   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4672   if (N1C && N0.getOpcode() == ISD::SRA) {
4673     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4674       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4675       if (Sum >= OpSizeInBits)
4676         Sum = OpSizeInBits - 1;
4677       SDLoc DL(N);
4678       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4679                          DAG.getConstant(Sum, DL, N1.getValueType()));
4680     }
4681   }
4682 
4683   // fold (sra (shl X, m), (sub result_size, n))
4684   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4685   // result_size - n != m.
4686   // If truncate is free for the target sext(shl) is likely to result in better
4687   // code.
4688   if (N0.getOpcode() == ISD::SHL && N1C) {
4689     // Get the two constanst of the shifts, CN0 = m, CN = n.
4690     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4691     if (N01C) {
4692       LLVMContext &Ctx = *DAG.getContext();
4693       // Determine what the truncate's result bitsize and type would be.
4694       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4695 
4696       if (VT.isVector())
4697         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4698 
4699       // Determine the residual right-shift amount.
4700       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4701 
4702       // If the shift is not a no-op (in which case this should be just a sign
4703       // extend already), the truncated to type is legal, sign_extend is legal
4704       // on that type, and the truncate to that type is both legal and free,
4705       // perform the transform.
4706       if ((ShiftAmt > 0) &&
4707           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4708           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4709           TLI.isTruncateFree(VT, TruncVT)) {
4710 
4711         SDLoc DL(N);
4712         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4713             getShiftAmountTy(N0.getOperand(0).getValueType()));
4714         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4715                                     N0.getOperand(0), Amt);
4716         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4717                                     Shift);
4718         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4719                            N->getValueType(0), Trunc);
4720       }
4721     }
4722   }
4723 
4724   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4725   if (N1.getOpcode() == ISD::TRUNCATE &&
4726       N1.getOperand(0).getOpcode() == ISD::AND) {
4727     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4728       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4729   }
4730 
4731   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4732   //      if c1 is equal to the number of bits the trunc removes
4733   if (N0.getOpcode() == ISD::TRUNCATE &&
4734       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4735        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4736       N0.getOperand(0).hasOneUse() &&
4737       N0.getOperand(0).getOperand(1).hasOneUse() &&
4738       N1C) {
4739     SDValue N0Op0 = N0.getOperand(0);
4740     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4741       unsigned LargeShiftVal = LargeShift->getZExtValue();
4742       EVT LargeVT = N0Op0.getValueType();
4743 
4744       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4745         SDLoc DL(N);
4746         SDValue Amt =
4747           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4748                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4749         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4750                                   N0Op0.getOperand(0), Amt);
4751         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4752       }
4753     }
4754   }
4755 
4756   // Simplify, based on bits shifted out of the LHS.
4757   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4758     return SDValue(N, 0);
4759 
4760 
4761   // If the sign bit is known to be zero, switch this to a SRL.
4762   if (DAG.SignBitIsZero(N0))
4763     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4764 
4765   if (N1C && !N1C->isOpaque())
4766     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4767       return NewSRA;
4768 
4769   return SDValue();
4770 }
4771 
4772 SDValue DAGCombiner::visitSRL(SDNode *N) {
4773   SDValue N0 = N->getOperand(0);
4774   SDValue N1 = N->getOperand(1);
4775   EVT VT = N0.getValueType();
4776   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4777 
4778   // fold vector ops
4779   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4780   if (VT.isVector()) {
4781     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4782       return FoldedVOp;
4783 
4784     N1C = isConstOrConstSplat(N1);
4785   }
4786 
4787   // fold (srl c1, c2) -> c1 >>u c2
4788   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4789   if (N0C && N1C && !N1C->isOpaque())
4790     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4791   // fold (srl 0, x) -> 0
4792   if (isNullConstant(N0))
4793     return N0;
4794   // fold (srl x, c >= size(x)) -> undef
4795   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4796     return DAG.getUNDEF(VT);
4797   // fold (srl x, 0) -> x
4798   if (N1C && N1C->isNullValue())
4799     return N0;
4800   // if (srl x, c) is known to be zero, return 0
4801   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4802                                    APInt::getAllOnesValue(OpSizeInBits)))
4803     return DAG.getConstant(0, SDLoc(N), VT);
4804 
4805   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4806   if (N1C && N0.getOpcode() == ISD::SRL) {
4807     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4808       uint64_t c1 = N01C->getZExtValue();
4809       uint64_t c2 = N1C->getZExtValue();
4810       SDLoc DL(N);
4811       if (c1 + c2 >= OpSizeInBits)
4812         return DAG.getConstant(0, DL, VT);
4813       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4814                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4815     }
4816   }
4817 
4818   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4819   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4820       N0.getOperand(0).getOpcode() == ISD::SRL &&
4821       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4822     uint64_t c1 =
4823       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4824     uint64_t c2 = N1C->getZExtValue();
4825     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4826     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4827     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4828     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4829     if (c1 + OpSizeInBits == InnerShiftSize) {
4830       SDLoc DL(N0);
4831       if (c1 + c2 >= InnerShiftSize)
4832         return DAG.getConstant(0, DL, VT);
4833       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4834                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4835                                      N0.getOperand(0)->getOperand(0),
4836                                      DAG.getConstant(c1 + c2, DL,
4837                                                      ShiftCountVT)));
4838     }
4839   }
4840 
4841   // fold (srl (shl x, c), c) -> (and x, cst2)
4842   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4843     unsigned BitSize = N0.getScalarValueSizeInBits();
4844     if (BitSize <= 64) {
4845       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4846       SDLoc DL(N);
4847       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4848                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4849     }
4850   }
4851 
4852   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4853   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4854     // Shifting in all undef bits?
4855     EVT SmallVT = N0.getOperand(0).getValueType();
4856     unsigned BitSize = SmallVT.getScalarSizeInBits();
4857     if (N1C->getZExtValue() >= BitSize)
4858       return DAG.getUNDEF(VT);
4859 
4860     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4861       uint64_t ShiftAmt = N1C->getZExtValue();
4862       SDLoc DL0(N0);
4863       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4864                                        N0.getOperand(0),
4865                           DAG.getConstant(ShiftAmt, DL0,
4866                                           getShiftAmountTy(SmallVT)));
4867       AddToWorklist(SmallShift.getNode());
4868       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4869       SDLoc DL(N);
4870       return DAG.getNode(ISD::AND, DL, VT,
4871                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4872                          DAG.getConstant(Mask, DL, VT));
4873     }
4874   }
4875 
4876   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4877   // bit, which is unmodified by sra.
4878   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4879     if (N0.getOpcode() == ISD::SRA)
4880       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4881   }
4882 
4883   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4884   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4885       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4886     APInt KnownZero, KnownOne;
4887     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4888 
4889     // If any of the input bits are KnownOne, then the input couldn't be all
4890     // zeros, thus the result of the srl will always be zero.
4891     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4892 
4893     // If all of the bits input the to ctlz node are known to be zero, then
4894     // the result of the ctlz is "32" and the result of the shift is one.
4895     APInt UnknownBits = ~KnownZero;
4896     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4897 
4898     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4899     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4900       // Okay, we know that only that the single bit specified by UnknownBits
4901       // could be set on input to the CTLZ node. If this bit is set, the SRL
4902       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4903       // to an SRL/XOR pair, which is likely to simplify more.
4904       unsigned ShAmt = UnknownBits.countTrailingZeros();
4905       SDValue Op = N0.getOperand(0);
4906 
4907       if (ShAmt) {
4908         SDLoc DL(N0);
4909         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4910                   DAG.getConstant(ShAmt, DL,
4911                                   getShiftAmountTy(Op.getValueType())));
4912         AddToWorklist(Op.getNode());
4913       }
4914 
4915       SDLoc DL(N);
4916       return DAG.getNode(ISD::XOR, DL, VT,
4917                          Op, DAG.getConstant(1, DL, VT));
4918     }
4919   }
4920 
4921   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4922   if (N1.getOpcode() == ISD::TRUNCATE &&
4923       N1.getOperand(0).getOpcode() == ISD::AND) {
4924     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4925       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4926   }
4927 
4928   // fold operands of srl based on knowledge that the low bits are not
4929   // demanded.
4930   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4931     return SDValue(N, 0);
4932 
4933   if (N1C && !N1C->isOpaque())
4934     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4935       return NewSRL;
4936 
4937   // Attempt to convert a srl of a load into a narrower zero-extending load.
4938   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4939     return NarrowLoad;
4940 
4941   // Here is a common situation. We want to optimize:
4942   //
4943   //   %a = ...
4944   //   %b = and i32 %a, 2
4945   //   %c = srl i32 %b, 1
4946   //   brcond i32 %c ...
4947   //
4948   // into
4949   //
4950   //   %a = ...
4951   //   %b = and %a, 2
4952   //   %c = setcc eq %b, 0
4953   //   brcond %c ...
4954   //
4955   // However when after the source operand of SRL is optimized into AND, the SRL
4956   // itself may not be optimized further. Look for it and add the BRCOND into
4957   // the worklist.
4958   if (N->hasOneUse()) {
4959     SDNode *Use = *N->use_begin();
4960     if (Use->getOpcode() == ISD::BRCOND)
4961       AddToWorklist(Use);
4962     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4963       // Also look pass the truncate.
4964       Use = *Use->use_begin();
4965       if (Use->getOpcode() == ISD::BRCOND)
4966         AddToWorklist(Use);
4967     }
4968   }
4969 
4970   return SDValue();
4971 }
4972 
4973 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4974   SDValue N0 = N->getOperand(0);
4975   EVT VT = N->getValueType(0);
4976 
4977   // fold (bswap c1) -> c2
4978   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4979     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4980   // fold (bswap (bswap x)) -> x
4981   if (N0.getOpcode() == ISD::BSWAP)
4982     return N0->getOperand(0);
4983   return SDValue();
4984 }
4985 
4986 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
4987   SDValue N0 = N->getOperand(0);
4988 
4989   // fold (bitreverse (bitreverse x)) -> x
4990   if (N0.getOpcode() == ISD::BITREVERSE)
4991     return N0.getOperand(0);
4992   return SDValue();
4993 }
4994 
4995 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4996   SDValue N0 = N->getOperand(0);
4997   EVT VT = N->getValueType(0);
4998 
4999   // fold (ctlz c1) -> c2
5000   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5001     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5002   return SDValue();
5003 }
5004 
5005 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5006   SDValue N0 = N->getOperand(0);
5007   EVT VT = N->getValueType(0);
5008 
5009   // fold (ctlz_zero_undef c1) -> c2
5010   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5011     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5012   return SDValue();
5013 }
5014 
5015 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5016   SDValue N0 = N->getOperand(0);
5017   EVT VT = N->getValueType(0);
5018 
5019   // fold (cttz c1) -> c2
5020   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5021     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5022   return SDValue();
5023 }
5024 
5025 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5026   SDValue N0 = N->getOperand(0);
5027   EVT VT = N->getValueType(0);
5028 
5029   // fold (cttz_zero_undef c1) -> c2
5030   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5031     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5032   return SDValue();
5033 }
5034 
5035 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5036   SDValue N0 = N->getOperand(0);
5037   EVT VT = N->getValueType(0);
5038 
5039   // fold (ctpop c1) -> c2
5040   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5041     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5042   return SDValue();
5043 }
5044 
5045 
5046 /// \brief Generate Min/Max node
5047 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5048                                    SDValue RHS, SDValue True, SDValue False,
5049                                    ISD::CondCode CC, const TargetLowering &TLI,
5050                                    SelectionDAG &DAG) {
5051   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5052     return SDValue();
5053 
5054   switch (CC) {
5055   case ISD::SETOLT:
5056   case ISD::SETOLE:
5057   case ISD::SETLT:
5058   case ISD::SETLE:
5059   case ISD::SETULT:
5060   case ISD::SETULE: {
5061     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5062     if (TLI.isOperationLegal(Opcode, VT))
5063       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5064     return SDValue();
5065   }
5066   case ISD::SETOGT:
5067   case ISD::SETOGE:
5068   case ISD::SETGT:
5069   case ISD::SETGE:
5070   case ISD::SETUGT:
5071   case ISD::SETUGE: {
5072     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5073     if (TLI.isOperationLegal(Opcode, VT))
5074       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5075     return SDValue();
5076   }
5077   default:
5078     return SDValue();
5079   }
5080 }
5081 
5082 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5083   SDValue N0 = N->getOperand(0);
5084   SDValue N1 = N->getOperand(1);
5085   SDValue N2 = N->getOperand(2);
5086   EVT VT = N->getValueType(0);
5087   EVT VT0 = N0.getValueType();
5088 
5089   // fold (select C, X, X) -> X
5090   if (N1 == N2)
5091     return N1;
5092   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5093     // fold (select true, X, Y) -> X
5094     // fold (select false, X, Y) -> Y
5095     return !N0C->isNullValue() ? N1 : N2;
5096   }
5097   // fold (select C, 1, X) -> (or C, X)
5098   if (VT == MVT::i1 && isOneConstant(N1))
5099     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5100   // fold (select C, 0, 1) -> (xor C, 1)
5101   // We can't do this reliably if integer based booleans have different contents
5102   // to floating point based booleans. This is because we can't tell whether we
5103   // have an integer-based boolean or a floating-point-based boolean unless we
5104   // can find the SETCC that produced it and inspect its operands. This is
5105   // fairly easy if C is the SETCC node, but it can potentially be
5106   // undiscoverable (or not reasonably discoverable). For example, it could be
5107   // in another basic block or it could require searching a complicated
5108   // expression.
5109   if (VT.isInteger() &&
5110       (VT0 == MVT::i1 || (VT0.isInteger() &&
5111                           TLI.getBooleanContents(false, false) ==
5112                               TLI.getBooleanContents(false, true) &&
5113                           TLI.getBooleanContents(false, false) ==
5114                               TargetLowering::ZeroOrOneBooleanContent)) &&
5115       isNullConstant(N1) && isOneConstant(N2)) {
5116     SDValue XORNode;
5117     if (VT == VT0) {
5118       SDLoc DL(N);
5119       return DAG.getNode(ISD::XOR, DL, VT0,
5120                          N0, DAG.getConstant(1, DL, VT0));
5121     }
5122     SDLoc DL0(N0);
5123     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5124                           N0, DAG.getConstant(1, DL0, VT0));
5125     AddToWorklist(XORNode.getNode());
5126     if (VT.bitsGT(VT0))
5127       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5128     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5129   }
5130   // fold (select C, 0, X) -> (and (not C), X)
5131   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5132     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5133     AddToWorklist(NOTNode.getNode());
5134     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5135   }
5136   // fold (select C, X, 1) -> (or (not C), X)
5137   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5138     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5139     AddToWorklist(NOTNode.getNode());
5140     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5141   }
5142   // fold (select C, X, 0) -> (and C, X)
5143   if (VT == MVT::i1 && isNullConstant(N2))
5144     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5145   // fold (select X, X, Y) -> (or X, Y)
5146   // fold (select X, 1, Y) -> (or X, Y)
5147   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5148     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5149   // fold (select X, Y, X) -> (and X, Y)
5150   // fold (select X, Y, 0) -> (and X, Y)
5151   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5152     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5153 
5154   // If we can fold this based on the true/false value, do so.
5155   if (SimplifySelectOps(N, N1, N2))
5156     return SDValue(N, 0);  // Don't revisit N.
5157 
5158   if (VT0 == MVT::i1) {
5159     // The code in this block deals with the following 2 equivalences:
5160     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5161     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5162     // The target can specify its prefered form with the
5163     // shouldNormalizeToSelectSequence() callback. However we always transform
5164     // to the right anyway if we find the inner select exists in the DAG anyway
5165     // and we always transform to the left side if we know that we can further
5166     // optimize the combination of the conditions.
5167     bool normalizeToSequence
5168       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5169     // select (and Cond0, Cond1), X, Y
5170     //   -> select Cond0, (select Cond1, X, Y), Y
5171     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5172       SDValue Cond0 = N0->getOperand(0);
5173       SDValue Cond1 = N0->getOperand(1);
5174       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5175                                         N1.getValueType(), Cond1, N1, N2);
5176       if (normalizeToSequence || !InnerSelect.use_empty())
5177         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5178                            InnerSelect, N2);
5179     }
5180     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5181     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5182       SDValue Cond0 = N0->getOperand(0);
5183       SDValue Cond1 = N0->getOperand(1);
5184       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5185                                         N1.getValueType(), Cond1, N1, N2);
5186       if (normalizeToSequence || !InnerSelect.use_empty())
5187         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5188                            InnerSelect);
5189     }
5190 
5191     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5192     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5193       SDValue N1_0 = N1->getOperand(0);
5194       SDValue N1_1 = N1->getOperand(1);
5195       SDValue N1_2 = N1->getOperand(2);
5196       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5197         // Create the actual and node if we can generate good code for it.
5198         if (!normalizeToSequence) {
5199           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5200                                     N0, N1_0);
5201           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5202                              N1_1, N2);
5203         }
5204         // Otherwise see if we can optimize the "and" to a better pattern.
5205         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5206           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5207                              N1_1, N2);
5208       }
5209     }
5210     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5211     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5212       SDValue N2_0 = N2->getOperand(0);
5213       SDValue N2_1 = N2->getOperand(1);
5214       SDValue N2_2 = N2->getOperand(2);
5215       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5216         // Create the actual or node if we can generate good code for it.
5217         if (!normalizeToSequence) {
5218           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5219                                    N0, N2_0);
5220           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5221                              N1, N2_2);
5222         }
5223         // Otherwise see if we can optimize to a better pattern.
5224         if (SDValue Combined = visitORLike(N0, N2_0, N))
5225           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5226                              N1, N2_2);
5227       }
5228     }
5229   }
5230 
5231   // fold selects based on a setcc into other things, such as min/max/abs
5232   if (N0.getOpcode() == ISD::SETCC) {
5233     // select x, y (fcmp lt x, y) -> fminnum x, y
5234     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5235     //
5236     // This is OK if we don't care about what happens if either operand is a
5237     // NaN.
5238     //
5239 
5240     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5241     // no signed zeros as well as no nans.
5242     const TargetOptions &Options = DAG.getTarget().Options;
5243     if (Options.UnsafeFPMath &&
5244         VT.isFloatingPoint() && N0.hasOneUse() &&
5245         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5246       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5247 
5248       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5249                                                 N0.getOperand(1), N1, N2, CC,
5250                                                 TLI, DAG))
5251         return FMinMax;
5252     }
5253 
5254     if ((!LegalOperations &&
5255          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5256         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5257       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5258                          N0.getOperand(0), N0.getOperand(1),
5259                          N1, N2, N0.getOperand(2));
5260     return SimplifySelect(SDLoc(N), N0, N1, N2);
5261   }
5262 
5263   return SDValue();
5264 }
5265 
5266 static
5267 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5268   SDLoc DL(N);
5269   EVT LoVT, HiVT;
5270   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5271 
5272   // Split the inputs.
5273   SDValue Lo, Hi, LL, LH, RL, RH;
5274   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5275   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5276 
5277   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5278   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5279 
5280   return std::make_pair(Lo, Hi);
5281 }
5282 
5283 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5284 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5285 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5286   SDLoc dl(N);
5287   SDValue Cond = N->getOperand(0);
5288   SDValue LHS = N->getOperand(1);
5289   SDValue RHS = N->getOperand(2);
5290   EVT VT = N->getValueType(0);
5291   int NumElems = VT.getVectorNumElements();
5292   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5293          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5294          Cond.getOpcode() == ISD::BUILD_VECTOR);
5295 
5296   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5297   // binary ones here.
5298   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5299     return SDValue();
5300 
5301   // We're sure we have an even number of elements due to the
5302   // concat_vectors we have as arguments to vselect.
5303   // Skip BV elements until we find one that's not an UNDEF
5304   // After we find an UNDEF element, keep looping until we get to half the
5305   // length of the BV and see if all the non-undef nodes are the same.
5306   ConstantSDNode *BottomHalf = nullptr;
5307   for (int i = 0; i < NumElems / 2; ++i) {
5308     if (Cond->getOperand(i)->isUndef())
5309       continue;
5310 
5311     if (BottomHalf == nullptr)
5312       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5313     else if (Cond->getOperand(i).getNode() != BottomHalf)
5314       return SDValue();
5315   }
5316 
5317   // Do the same for the second half of the BuildVector
5318   ConstantSDNode *TopHalf = nullptr;
5319   for (int i = NumElems / 2; i < NumElems; ++i) {
5320     if (Cond->getOperand(i)->isUndef())
5321       continue;
5322 
5323     if (TopHalf == nullptr)
5324       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5325     else if (Cond->getOperand(i).getNode() != TopHalf)
5326       return SDValue();
5327   }
5328 
5329   assert(TopHalf && BottomHalf &&
5330          "One half of the selector was all UNDEFs and the other was all the "
5331          "same value. This should have been addressed before this function.");
5332   return DAG.getNode(
5333       ISD::CONCAT_VECTORS, dl, VT,
5334       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5335       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5336 }
5337 
5338 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5339 
5340   if (Level >= AfterLegalizeTypes)
5341     return SDValue();
5342 
5343   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5344   SDValue Mask = MSC->getMask();
5345   SDValue Data  = MSC->getValue();
5346   SDLoc DL(N);
5347 
5348   // If the MSCATTER data type requires splitting and the mask is provided by a
5349   // SETCC, then split both nodes and its operands before legalization. This
5350   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5351   // and enables future optimizations (e.g. min/max pattern matching on X86).
5352   if (Mask.getOpcode() != ISD::SETCC)
5353     return SDValue();
5354 
5355   // Check if any splitting is required.
5356   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5357       TargetLowering::TypeSplitVector)
5358     return SDValue();
5359   SDValue MaskLo, MaskHi, Lo, Hi;
5360   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5361 
5362   EVT LoVT, HiVT;
5363   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5364 
5365   SDValue Chain = MSC->getChain();
5366 
5367   EVT MemoryVT = MSC->getMemoryVT();
5368   unsigned Alignment = MSC->getOriginalAlignment();
5369 
5370   EVT LoMemVT, HiMemVT;
5371   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5372 
5373   SDValue DataLo, DataHi;
5374   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5375 
5376   SDValue BasePtr = MSC->getBasePtr();
5377   SDValue IndexLo, IndexHi;
5378   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5379 
5380   MachineMemOperand *MMO = DAG.getMachineFunction().
5381     getMachineMemOperand(MSC->getPointerInfo(),
5382                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5383                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5384 
5385   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5386   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5387                             DL, OpsLo, MMO);
5388 
5389   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5390   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5391                             DL, OpsHi, MMO);
5392 
5393   AddToWorklist(Lo.getNode());
5394   AddToWorklist(Hi.getNode());
5395 
5396   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5397 }
5398 
5399 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5400 
5401   if (Level >= AfterLegalizeTypes)
5402     return SDValue();
5403 
5404   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5405   SDValue Mask = MST->getMask();
5406   SDValue Data  = MST->getValue();
5407   SDLoc DL(N);
5408 
5409   // If the MSTORE data type requires splitting and the mask is provided by a
5410   // SETCC, then split both nodes and its operands before legalization. This
5411   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5412   // and enables future optimizations (e.g. min/max pattern matching on X86).
5413   if (Mask.getOpcode() == ISD::SETCC) {
5414 
5415     // Check if any splitting is required.
5416     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5417         TargetLowering::TypeSplitVector)
5418       return SDValue();
5419 
5420     SDValue MaskLo, MaskHi, Lo, Hi;
5421     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5422 
5423     EVT LoVT, HiVT;
5424     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5425 
5426     SDValue Chain = MST->getChain();
5427     SDValue Ptr   = MST->getBasePtr();
5428 
5429     EVT MemoryVT = MST->getMemoryVT();
5430     unsigned Alignment = MST->getOriginalAlignment();
5431 
5432     // if Alignment is equal to the vector size,
5433     // take the half of it for the second part
5434     unsigned SecondHalfAlignment =
5435       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5436          Alignment/2 : Alignment;
5437 
5438     EVT LoMemVT, HiMemVT;
5439     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5440 
5441     SDValue DataLo, DataHi;
5442     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5443 
5444     MachineMemOperand *MMO = DAG.getMachineFunction().
5445       getMachineMemOperand(MST->getPointerInfo(),
5446                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5447                            Alignment, MST->getAAInfo(), MST->getRanges());
5448 
5449     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5450                             MST->isTruncatingStore());
5451 
5452     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5453     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5454                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5455 
5456     MMO = DAG.getMachineFunction().
5457       getMachineMemOperand(MST->getPointerInfo(),
5458                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5459                            SecondHalfAlignment, MST->getAAInfo(),
5460                            MST->getRanges());
5461 
5462     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5463                             MST->isTruncatingStore());
5464 
5465     AddToWorklist(Lo.getNode());
5466     AddToWorklist(Hi.getNode());
5467 
5468     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5469   }
5470   return SDValue();
5471 }
5472 
5473 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5474 
5475   if (Level >= AfterLegalizeTypes)
5476     return SDValue();
5477 
5478   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5479   SDValue Mask = MGT->getMask();
5480   SDLoc DL(N);
5481 
5482   // If the MGATHER result requires splitting and the mask is provided by a
5483   // SETCC, then split both nodes and its operands before legalization. This
5484   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5485   // and enables future optimizations (e.g. min/max pattern matching on X86).
5486 
5487   if (Mask.getOpcode() != ISD::SETCC)
5488     return SDValue();
5489 
5490   EVT VT = N->getValueType(0);
5491 
5492   // Check if any splitting is required.
5493   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5494       TargetLowering::TypeSplitVector)
5495     return SDValue();
5496 
5497   SDValue MaskLo, MaskHi, Lo, Hi;
5498   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5499 
5500   SDValue Src0 = MGT->getValue();
5501   SDValue Src0Lo, Src0Hi;
5502   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5503 
5504   EVT LoVT, HiVT;
5505   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5506 
5507   SDValue Chain = MGT->getChain();
5508   EVT MemoryVT = MGT->getMemoryVT();
5509   unsigned Alignment = MGT->getOriginalAlignment();
5510 
5511   EVT LoMemVT, HiMemVT;
5512   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5513 
5514   SDValue BasePtr = MGT->getBasePtr();
5515   SDValue Index = MGT->getIndex();
5516   SDValue IndexLo, IndexHi;
5517   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5518 
5519   MachineMemOperand *MMO = DAG.getMachineFunction().
5520     getMachineMemOperand(MGT->getPointerInfo(),
5521                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5522                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5523 
5524   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5525   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5526                             MMO);
5527 
5528   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5529   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5530                             MMO);
5531 
5532   AddToWorklist(Lo.getNode());
5533   AddToWorklist(Hi.getNode());
5534 
5535   // Build a factor node to remember that this load is independent of the
5536   // other one.
5537   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5538                       Hi.getValue(1));
5539 
5540   // Legalized the chain result - switch anything that used the old chain to
5541   // use the new one.
5542   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5543 
5544   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5545 
5546   SDValue RetOps[] = { GatherRes, Chain };
5547   return DAG.getMergeValues(RetOps, DL);
5548 }
5549 
5550 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5551 
5552   if (Level >= AfterLegalizeTypes)
5553     return SDValue();
5554 
5555   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5556   SDValue Mask = MLD->getMask();
5557   SDLoc DL(N);
5558 
5559   // If the MLOAD result requires splitting and the mask is provided by a
5560   // SETCC, then split both nodes and its operands before legalization. This
5561   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5562   // and enables future optimizations (e.g. min/max pattern matching on X86).
5563 
5564   if (Mask.getOpcode() == ISD::SETCC) {
5565     EVT VT = N->getValueType(0);
5566 
5567     // Check if any splitting is required.
5568     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5569         TargetLowering::TypeSplitVector)
5570       return SDValue();
5571 
5572     SDValue MaskLo, MaskHi, Lo, Hi;
5573     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5574 
5575     SDValue Src0 = MLD->getSrc0();
5576     SDValue Src0Lo, Src0Hi;
5577     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5578 
5579     EVT LoVT, HiVT;
5580     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5581 
5582     SDValue Chain = MLD->getChain();
5583     SDValue Ptr   = MLD->getBasePtr();
5584     EVT MemoryVT = MLD->getMemoryVT();
5585     unsigned Alignment = MLD->getOriginalAlignment();
5586 
5587     // if Alignment is equal to the vector size,
5588     // take the half of it for the second part
5589     unsigned SecondHalfAlignment =
5590       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5591          Alignment/2 : Alignment;
5592 
5593     EVT LoMemVT, HiMemVT;
5594     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5595 
5596     MachineMemOperand *MMO = DAG.getMachineFunction().
5597     getMachineMemOperand(MLD->getPointerInfo(),
5598                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5599                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5600 
5601     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5602                            ISD::NON_EXTLOAD);
5603 
5604     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5605     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5606                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5607 
5608     MMO = DAG.getMachineFunction().
5609     getMachineMemOperand(MLD->getPointerInfo(),
5610                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5611                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5612 
5613     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5614                            ISD::NON_EXTLOAD);
5615 
5616     AddToWorklist(Lo.getNode());
5617     AddToWorklist(Hi.getNode());
5618 
5619     // Build a factor node to remember that this load is independent of the
5620     // other one.
5621     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5622                         Hi.getValue(1));
5623 
5624     // Legalized the chain result - switch anything that used the old chain to
5625     // use the new one.
5626     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5627 
5628     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5629 
5630     SDValue RetOps[] = { LoadRes, Chain };
5631     return DAG.getMergeValues(RetOps, DL);
5632   }
5633   return SDValue();
5634 }
5635 
5636 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5637   SDValue N0 = N->getOperand(0);
5638   SDValue N1 = N->getOperand(1);
5639   SDValue N2 = N->getOperand(2);
5640   SDLoc DL(N);
5641 
5642   // Canonicalize integer abs.
5643   // vselect (setg[te] X,  0),  X, -X ->
5644   // vselect (setgt    X, -1),  X, -X ->
5645   // vselect (setl[te] X,  0), -X,  X ->
5646   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5647   if (N0.getOpcode() == ISD::SETCC) {
5648     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5649     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5650     bool isAbs = false;
5651     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5652 
5653     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5654          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5655         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5656       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5657     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5658              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5659       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5660 
5661     if (isAbs) {
5662       EVT VT = LHS.getValueType();
5663       SDValue Shift = DAG.getNode(
5664           ISD::SRA, DL, VT, LHS,
5665           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5666       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5667       AddToWorklist(Shift.getNode());
5668       AddToWorklist(Add.getNode());
5669       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5670     }
5671   }
5672 
5673   if (SimplifySelectOps(N, N1, N2))
5674     return SDValue(N, 0);  // Don't revisit N.
5675 
5676   // If the VSELECT result requires splitting and the mask is provided by a
5677   // SETCC, then split both nodes and its operands before legalization. This
5678   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5679   // and enables future optimizations (e.g. min/max pattern matching on X86).
5680   if (N0.getOpcode() == ISD::SETCC) {
5681     EVT VT = N->getValueType(0);
5682 
5683     // Check if any splitting is required.
5684     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5685         TargetLowering::TypeSplitVector)
5686       return SDValue();
5687 
5688     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5689     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5690     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5691     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5692 
5693     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5694     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5695 
5696     // Add the new VSELECT nodes to the work list in case they need to be split
5697     // again.
5698     AddToWorklist(Lo.getNode());
5699     AddToWorklist(Hi.getNode());
5700 
5701     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5702   }
5703 
5704   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5705   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5706     return N1;
5707   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5708   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5709     return N2;
5710 
5711   // The ConvertSelectToConcatVector function is assuming both the above
5712   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5713   // and addressed.
5714   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5715       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5716       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5717     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5718       return CV;
5719   }
5720 
5721   return SDValue();
5722 }
5723 
5724 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5725   SDValue N0 = N->getOperand(0);
5726   SDValue N1 = N->getOperand(1);
5727   SDValue N2 = N->getOperand(2);
5728   SDValue N3 = N->getOperand(3);
5729   SDValue N4 = N->getOperand(4);
5730   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5731 
5732   // fold select_cc lhs, rhs, x, x, cc -> x
5733   if (N2 == N3)
5734     return N2;
5735 
5736   // Determine if the condition we're dealing with is constant
5737   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5738                                   CC, SDLoc(N), false)) {
5739     AddToWorklist(SCC.getNode());
5740 
5741     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5742       if (!SCCC->isNullValue())
5743         return N2;    // cond always true -> true val
5744       else
5745         return N3;    // cond always false -> false val
5746     } else if (SCC->isUndef()) {
5747       // When the condition is UNDEF, just return the first operand. This is
5748       // coherent the DAG creation, no setcc node is created in this case
5749       return N2;
5750     } else if (SCC.getOpcode() == ISD::SETCC) {
5751       // Fold to a simpler select_cc
5752       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5753                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5754                          SCC.getOperand(2));
5755     }
5756   }
5757 
5758   // If we can fold this based on the true/false value, do so.
5759   if (SimplifySelectOps(N, N2, N3))
5760     return SDValue(N, 0);  // Don't revisit N.
5761 
5762   // fold select_cc into other things, such as min/max/abs
5763   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5764 }
5765 
5766 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5767   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5768                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5769                        SDLoc(N));
5770 }
5771 
5772 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5773   SDValue LHS = N->getOperand(0);
5774   SDValue RHS = N->getOperand(1);
5775   SDValue Carry = N->getOperand(2);
5776   SDValue Cond = N->getOperand(3);
5777 
5778   // If Carry is false, fold to a regular SETCC.
5779   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5780     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5781 
5782   return SDValue();
5783 }
5784 
5785 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5786 /// a build_vector of constants.
5787 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5788 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5789 /// Vector extends are not folded if operations are legal; this is to
5790 /// avoid introducing illegal build_vector dag nodes.
5791 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5792                                          SelectionDAG &DAG, bool LegalTypes,
5793                                          bool LegalOperations) {
5794   unsigned Opcode = N->getOpcode();
5795   SDValue N0 = N->getOperand(0);
5796   EVT VT = N->getValueType(0);
5797 
5798   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5799          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5800          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5801          && "Expected EXTEND dag node in input!");
5802 
5803   // fold (sext c1) -> c1
5804   // fold (zext c1) -> c1
5805   // fold (aext c1) -> c1
5806   if (isa<ConstantSDNode>(N0))
5807     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5808 
5809   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5810   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5811   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5812   EVT SVT = VT.getScalarType();
5813   if (!(VT.isVector() &&
5814       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5815       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5816     return nullptr;
5817 
5818   // We can fold this node into a build_vector.
5819   unsigned VTBits = SVT.getSizeInBits();
5820   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5821   SmallVector<SDValue, 8> Elts;
5822   unsigned NumElts = VT.getVectorNumElements();
5823   SDLoc DL(N);
5824 
5825   for (unsigned i=0; i != NumElts; ++i) {
5826     SDValue Op = N0->getOperand(i);
5827     if (Op->isUndef()) {
5828       Elts.push_back(DAG.getUNDEF(SVT));
5829       continue;
5830     }
5831 
5832     SDLoc DL(Op);
5833     // Get the constant value and if needed trunc it to the size of the type.
5834     // Nodes like build_vector might have constants wider than the scalar type.
5835     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5836     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5837       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5838     else
5839       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5840   }
5841 
5842   return DAG.getBuildVector(VT, DL, Elts).getNode();
5843 }
5844 
5845 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5846 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5847 // transformation. Returns true if extension are possible and the above
5848 // mentioned transformation is profitable.
5849 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5850                                     unsigned ExtOpc,
5851                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5852                                     const TargetLowering &TLI) {
5853   bool HasCopyToRegUses = false;
5854   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5855   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5856                             UE = N0.getNode()->use_end();
5857        UI != UE; ++UI) {
5858     SDNode *User = *UI;
5859     if (User == N)
5860       continue;
5861     if (UI.getUse().getResNo() != N0.getResNo())
5862       continue;
5863     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5864     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5865       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5866       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5867         // Sign bits will be lost after a zext.
5868         return false;
5869       bool Add = false;
5870       for (unsigned i = 0; i != 2; ++i) {
5871         SDValue UseOp = User->getOperand(i);
5872         if (UseOp == N0)
5873           continue;
5874         if (!isa<ConstantSDNode>(UseOp))
5875           return false;
5876         Add = true;
5877       }
5878       if (Add)
5879         ExtendNodes.push_back(User);
5880       continue;
5881     }
5882     // If truncates aren't free and there are users we can't
5883     // extend, it isn't worthwhile.
5884     if (!isTruncFree)
5885       return false;
5886     // Remember if this value is live-out.
5887     if (User->getOpcode() == ISD::CopyToReg)
5888       HasCopyToRegUses = true;
5889   }
5890 
5891   if (HasCopyToRegUses) {
5892     bool BothLiveOut = false;
5893     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5894          UI != UE; ++UI) {
5895       SDUse &Use = UI.getUse();
5896       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5897         BothLiveOut = true;
5898         break;
5899       }
5900     }
5901     if (BothLiveOut)
5902       // Both unextended and extended values are live out. There had better be
5903       // a good reason for the transformation.
5904       return ExtendNodes.size();
5905   }
5906   return true;
5907 }
5908 
5909 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5910                                   SDValue Trunc, SDValue ExtLoad,
5911                                   const SDLoc &DL, ISD::NodeType ExtType) {
5912   // Extend SetCC uses if necessary.
5913   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5914     SDNode *SetCC = SetCCs[i];
5915     SmallVector<SDValue, 4> Ops;
5916 
5917     for (unsigned j = 0; j != 2; ++j) {
5918       SDValue SOp = SetCC->getOperand(j);
5919       if (SOp == Trunc)
5920         Ops.push_back(ExtLoad);
5921       else
5922         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5923     }
5924 
5925     Ops.push_back(SetCC->getOperand(2));
5926     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5927   }
5928 }
5929 
5930 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5931 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5932   SDValue N0 = N->getOperand(0);
5933   EVT DstVT = N->getValueType(0);
5934   EVT SrcVT = N0.getValueType();
5935 
5936   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5937           N->getOpcode() == ISD::ZERO_EXTEND) &&
5938          "Unexpected node type (not an extend)!");
5939 
5940   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5941   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5942   //   (v8i32 (sext (v8i16 (load x))))
5943   // into:
5944   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5945   //                          (v4i32 (sextload (x + 16)))))
5946   // Where uses of the original load, i.e.:
5947   //   (v8i16 (load x))
5948   // are replaced with:
5949   //   (v8i16 (truncate
5950   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5951   //                            (v4i32 (sextload (x + 16)))))))
5952   //
5953   // This combine is only applicable to illegal, but splittable, vectors.
5954   // All legal types, and illegal non-vector types, are handled elsewhere.
5955   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5956   //
5957   if (N0->getOpcode() != ISD::LOAD)
5958     return SDValue();
5959 
5960   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5961 
5962   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5963       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5964       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5965     return SDValue();
5966 
5967   SmallVector<SDNode *, 4> SetCCs;
5968   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5969     return SDValue();
5970 
5971   ISD::LoadExtType ExtType =
5972       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5973 
5974   // Try to split the vector types to get down to legal types.
5975   EVT SplitSrcVT = SrcVT;
5976   EVT SplitDstVT = DstVT;
5977   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5978          SplitSrcVT.getVectorNumElements() > 1) {
5979     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5980     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5981   }
5982 
5983   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5984     return SDValue();
5985 
5986   SDLoc DL(N);
5987   const unsigned NumSplits =
5988       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5989   const unsigned Stride = SplitSrcVT.getStoreSize();
5990   SmallVector<SDValue, 4> Loads;
5991   SmallVector<SDValue, 4> Chains;
5992 
5993   SDValue BasePtr = LN0->getBasePtr();
5994   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5995     const unsigned Offset = Idx * Stride;
5996     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5997 
5998     SDValue SplitLoad = DAG.getExtLoad(
5999         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6000         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
6001         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
6002         Align, LN0->getAAInfo());
6003 
6004     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6005                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6006 
6007     Loads.push_back(SplitLoad.getValue(0));
6008     Chains.push_back(SplitLoad.getValue(1));
6009   }
6010 
6011   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6012   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6013 
6014   CombineTo(N, NewValue);
6015 
6016   // Replace uses of the original load (before extension)
6017   // with a truncate of the concatenated sextloaded vectors.
6018   SDValue Trunc =
6019       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6020   CombineTo(N0.getNode(), Trunc, NewChain);
6021   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6022                   (ISD::NodeType)N->getOpcode());
6023   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6024 }
6025 
6026 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6027   SDValue N0 = N->getOperand(0);
6028   EVT VT = N->getValueType(0);
6029 
6030   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6031                                               LegalOperations))
6032     return SDValue(Res, 0);
6033 
6034   // fold (sext (sext x)) -> (sext x)
6035   // fold (sext (aext x)) -> (sext x)
6036   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6037     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6038                        N0.getOperand(0));
6039 
6040   if (N0.getOpcode() == ISD::TRUNCATE) {
6041     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6042     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6043     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6044       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6045       if (NarrowLoad.getNode() != N0.getNode()) {
6046         CombineTo(N0.getNode(), NarrowLoad);
6047         // CombineTo deleted the truncate, if needed, but not what's under it.
6048         AddToWorklist(oye);
6049       }
6050       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6051     }
6052 
6053     // See if the value being truncated is already sign extended.  If so, just
6054     // eliminate the trunc/sext pair.
6055     SDValue Op = N0.getOperand(0);
6056     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
6057     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
6058     unsigned DestBits = VT.getScalarType().getSizeInBits();
6059     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6060 
6061     if (OpBits == DestBits) {
6062       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6063       // bits, it is already ready.
6064       if (NumSignBits > DestBits-MidBits)
6065         return Op;
6066     } else if (OpBits < DestBits) {
6067       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6068       // bits, just sext from i32.
6069       if (NumSignBits > OpBits-MidBits)
6070         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6071     } else {
6072       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6073       // bits, just truncate to i32.
6074       if (NumSignBits > OpBits-MidBits)
6075         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6076     }
6077 
6078     // fold (sext (truncate x)) -> (sextinreg x).
6079     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6080                                                  N0.getValueType())) {
6081       if (OpBits < DestBits)
6082         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6083       else if (OpBits > DestBits)
6084         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6085       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6086                          DAG.getValueType(N0.getValueType()));
6087     }
6088   }
6089 
6090   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6091   // Only generate vector extloads when 1) they're legal, and 2) they are
6092   // deemed desirable by the target.
6093   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6094       ((!LegalOperations && !VT.isVector() &&
6095         !cast<LoadSDNode>(N0)->isVolatile()) ||
6096        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6097     bool DoXform = true;
6098     SmallVector<SDNode*, 4> SetCCs;
6099     if (!N0.hasOneUse())
6100       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6101     if (VT.isVector())
6102       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6103     if (DoXform) {
6104       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6105       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6106                                        LN0->getChain(),
6107                                        LN0->getBasePtr(), N0.getValueType(),
6108                                        LN0->getMemOperand());
6109       CombineTo(N, ExtLoad);
6110       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6111                                   N0.getValueType(), ExtLoad);
6112       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6113       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6114                       ISD::SIGN_EXTEND);
6115       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6116     }
6117   }
6118 
6119   // fold (sext (load x)) to multiple smaller sextloads.
6120   // Only on illegal but splittable vectors.
6121   if (SDValue ExtLoad = CombineExtLoad(N))
6122     return ExtLoad;
6123 
6124   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6125   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6126   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6127       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6128     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6129     EVT MemVT = LN0->getMemoryVT();
6130     if ((!LegalOperations && !LN0->isVolatile()) ||
6131         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6132       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6133                                        LN0->getChain(),
6134                                        LN0->getBasePtr(), MemVT,
6135                                        LN0->getMemOperand());
6136       CombineTo(N, ExtLoad);
6137       CombineTo(N0.getNode(),
6138                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6139                             N0.getValueType(), ExtLoad),
6140                 ExtLoad.getValue(1));
6141       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6142     }
6143   }
6144 
6145   // fold (sext (and/or/xor (load x), cst)) ->
6146   //      (and/or/xor (sextload x), (sext cst))
6147   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6148        N0.getOpcode() == ISD::XOR) &&
6149       isa<LoadSDNode>(N0.getOperand(0)) &&
6150       N0.getOperand(1).getOpcode() == ISD::Constant &&
6151       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6152       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6153     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6154     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6155       bool DoXform = true;
6156       SmallVector<SDNode*, 4> SetCCs;
6157       if (!N0.hasOneUse())
6158         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6159                                           SetCCs, TLI);
6160       if (DoXform) {
6161         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6162                                          LN0->getChain(), LN0->getBasePtr(),
6163                                          LN0->getMemoryVT(),
6164                                          LN0->getMemOperand());
6165         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6166         Mask = Mask.sext(VT.getSizeInBits());
6167         SDLoc DL(N);
6168         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6169                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6170         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6171                                     SDLoc(N0.getOperand(0)),
6172                                     N0.getOperand(0).getValueType(), ExtLoad);
6173         CombineTo(N, And);
6174         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6175         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6176                         ISD::SIGN_EXTEND);
6177         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6178       }
6179     }
6180   }
6181 
6182   if (N0.getOpcode() == ISD::SETCC) {
6183     EVT N0VT = N0.getOperand(0).getValueType();
6184     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6185     // Only do this before legalize for now.
6186     if (VT.isVector() && !LegalOperations &&
6187         TLI.getBooleanContents(N0VT) ==
6188             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6189       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6190       // of the same size as the compared operands. Only optimize sext(setcc())
6191       // if this is the case.
6192       EVT SVT = getSetCCResultType(N0VT);
6193 
6194       // We know that the # elements of the results is the same as the
6195       // # elements of the compare (and the # elements of the compare result
6196       // for that matter).  Check to see that they are the same size.  If so,
6197       // we know that the element size of the sext'd result matches the
6198       // element size of the compare operands.
6199       if (VT.getSizeInBits() == SVT.getSizeInBits())
6200         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6201                              N0.getOperand(1),
6202                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6203 
6204       // If the desired elements are smaller or larger than the source
6205       // elements we can use a matching integer vector type and then
6206       // truncate/sign extend
6207       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6208       if (SVT == MatchingVectorType) {
6209         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6210                                N0.getOperand(0), N0.getOperand(1),
6211                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6212         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6213       }
6214     }
6215 
6216     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6217     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6218     SDLoc DL(N);
6219     SDValue NegOne =
6220       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6221     if (SDValue SCC = SimplifySelectCC(
6222             DL, N0.getOperand(0), N0.getOperand(1), NegOne,
6223             DAG.getConstant(0, DL, VT),
6224             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6225       return SCC;
6226 
6227     if (!VT.isVector()) {
6228       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6229       if (!LegalOperations ||
6230           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6231         SDLoc DL(N);
6232         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6233         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6234                                      N0.getOperand(0), N0.getOperand(1), CC);
6235         return DAG.getSelect(DL, VT, SetCC,
6236                              NegOne, DAG.getConstant(0, DL, VT));
6237       }
6238     }
6239   }
6240 
6241   // fold (sext x) -> (zext x) if the sign bit is known zero.
6242   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6243       DAG.SignBitIsZero(N0))
6244     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6245 
6246   return SDValue();
6247 }
6248 
6249 // isTruncateOf - If N is a truncate of some other value, return true, record
6250 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6251 // This function computes KnownZero to avoid a duplicated call to
6252 // computeKnownBits in the caller.
6253 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6254                          APInt &KnownZero) {
6255   APInt KnownOne;
6256   if (N->getOpcode() == ISD::TRUNCATE) {
6257     Op = N->getOperand(0);
6258     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6259     return true;
6260   }
6261 
6262   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6263       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6264     return false;
6265 
6266   SDValue Op0 = N->getOperand(0);
6267   SDValue Op1 = N->getOperand(1);
6268   assert(Op0.getValueType() == Op1.getValueType());
6269 
6270   if (isNullConstant(Op0))
6271     Op = Op1;
6272   else if (isNullConstant(Op1))
6273     Op = Op0;
6274   else
6275     return false;
6276 
6277   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6278 
6279   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6280     return false;
6281 
6282   return true;
6283 }
6284 
6285 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6286   SDValue N0 = N->getOperand(0);
6287   EVT VT = N->getValueType(0);
6288 
6289   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6290                                               LegalOperations))
6291     return SDValue(Res, 0);
6292 
6293   // fold (zext (zext x)) -> (zext x)
6294   // fold (zext (aext x)) -> (zext x)
6295   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6296     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6297                        N0.getOperand(0));
6298 
6299   // fold (zext (truncate x)) -> (zext x) or
6300   //      (zext (truncate x)) -> (truncate x)
6301   // This is valid when the truncated bits of x are already zero.
6302   // FIXME: We should extend this to work for vectors too.
6303   SDValue Op;
6304   APInt KnownZero;
6305   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6306     APInt TruncatedBits =
6307       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6308       APInt(Op.getValueSizeInBits(), 0) :
6309       APInt::getBitsSet(Op.getValueSizeInBits(),
6310                         N0.getValueSizeInBits(),
6311                         std::min(Op.getValueSizeInBits(),
6312                                  VT.getSizeInBits()));
6313     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6314       if (VT.bitsGT(Op.getValueType()))
6315         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6316       if (VT.bitsLT(Op.getValueType()))
6317         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6318 
6319       return Op;
6320     }
6321   }
6322 
6323   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6324   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6325   if (N0.getOpcode() == ISD::TRUNCATE) {
6326     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6327       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6328       if (NarrowLoad.getNode() != N0.getNode()) {
6329         CombineTo(N0.getNode(), NarrowLoad);
6330         // CombineTo deleted the truncate, if needed, but not what's under it.
6331         AddToWorklist(oye);
6332       }
6333       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6334     }
6335   }
6336 
6337   // fold (zext (truncate x)) -> (and x, mask)
6338   if (N0.getOpcode() == ISD::TRUNCATE) {
6339     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6340     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6341     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6342       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6343       if (NarrowLoad.getNode() != N0.getNode()) {
6344         CombineTo(N0.getNode(), NarrowLoad);
6345         // CombineTo deleted the truncate, if needed, but not what's under it.
6346         AddToWorklist(oye);
6347       }
6348       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6349     }
6350 
6351     EVT SrcVT = N0.getOperand(0).getValueType();
6352     EVT MinVT = N0.getValueType();
6353 
6354     // Try to mask before the extension to avoid having to generate a larger mask,
6355     // possibly over several sub-vectors.
6356     if (SrcVT.bitsLT(VT)) {
6357       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6358                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6359         SDValue Op = N0.getOperand(0);
6360         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6361         AddToWorklist(Op.getNode());
6362         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6363       }
6364     }
6365 
6366     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6367       SDValue Op = N0.getOperand(0);
6368       if (SrcVT.bitsLT(VT)) {
6369         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6370         AddToWorklist(Op.getNode());
6371       } else if (SrcVT.bitsGT(VT)) {
6372         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6373         AddToWorklist(Op.getNode());
6374       }
6375       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6376     }
6377   }
6378 
6379   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6380   // if either of the casts is not free.
6381   if (N0.getOpcode() == ISD::AND &&
6382       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6383       N0.getOperand(1).getOpcode() == ISD::Constant &&
6384       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6385                            N0.getValueType()) ||
6386        !TLI.isZExtFree(N0.getValueType(), VT))) {
6387     SDValue X = N0.getOperand(0).getOperand(0);
6388     if (X.getValueType().bitsLT(VT)) {
6389       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6390     } else if (X.getValueType().bitsGT(VT)) {
6391       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6392     }
6393     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6394     Mask = Mask.zext(VT.getSizeInBits());
6395     SDLoc DL(N);
6396     return DAG.getNode(ISD::AND, DL, VT,
6397                        X, DAG.getConstant(Mask, DL, VT));
6398   }
6399 
6400   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6401   // Only generate vector extloads when 1) they're legal, and 2) they are
6402   // deemed desirable by the target.
6403   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6404       ((!LegalOperations && !VT.isVector() &&
6405         !cast<LoadSDNode>(N0)->isVolatile()) ||
6406        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6407     bool DoXform = true;
6408     SmallVector<SDNode*, 4> SetCCs;
6409     if (!N0.hasOneUse())
6410       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6411     if (VT.isVector())
6412       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6413     if (DoXform) {
6414       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6415       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6416                                        LN0->getChain(),
6417                                        LN0->getBasePtr(), N0.getValueType(),
6418                                        LN0->getMemOperand());
6419       CombineTo(N, ExtLoad);
6420       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6421                                   N0.getValueType(), ExtLoad);
6422       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6423 
6424       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6425                       ISD::ZERO_EXTEND);
6426       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6427     }
6428   }
6429 
6430   // fold (zext (load x)) to multiple smaller zextloads.
6431   // Only on illegal but splittable vectors.
6432   if (SDValue ExtLoad = CombineExtLoad(N))
6433     return ExtLoad;
6434 
6435   // fold (zext (and/or/xor (load x), cst)) ->
6436   //      (and/or/xor (zextload x), (zext cst))
6437   // Unless (and (load x) cst) will match as a zextload already and has
6438   // additional users.
6439   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6440        N0.getOpcode() == ISD::XOR) &&
6441       isa<LoadSDNode>(N0.getOperand(0)) &&
6442       N0.getOperand(1).getOpcode() == ISD::Constant &&
6443       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6444       (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) {
6445     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6446     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6447       bool DoXform = true;
6448       SmallVector<SDNode*, 4> SetCCs;
6449       if (!N0.hasOneUse()) {
6450         if (N0.getOpcode() == ISD::AND) {
6451           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6452           auto NarrowLoad = false;
6453           EVT LoadResultTy = AndC->getValueType(0);
6454           EVT ExtVT, LoadedVT;
6455           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6456                                NarrowLoad))
6457             DoXform = false;
6458         }
6459         if (DoXform)
6460           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6461                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6462       }
6463       if (DoXform) {
6464         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6465                                          LN0->getChain(), LN0->getBasePtr(),
6466                                          LN0->getMemoryVT(),
6467                                          LN0->getMemOperand());
6468         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6469         Mask = Mask.zext(VT.getSizeInBits());
6470         SDLoc DL(N);
6471         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6472                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6473         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6474                                     SDLoc(N0.getOperand(0)),
6475                                     N0.getOperand(0).getValueType(), ExtLoad);
6476         CombineTo(N, And);
6477         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6478         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6479                         ISD::ZERO_EXTEND);
6480         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6481       }
6482     }
6483   }
6484 
6485   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6486   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6487   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6488       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6489     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6490     EVT MemVT = LN0->getMemoryVT();
6491     if ((!LegalOperations && !LN0->isVolatile()) ||
6492         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6493       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6494                                        LN0->getChain(),
6495                                        LN0->getBasePtr(), MemVT,
6496                                        LN0->getMemOperand());
6497       CombineTo(N, ExtLoad);
6498       CombineTo(N0.getNode(),
6499                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6500                             ExtLoad),
6501                 ExtLoad.getValue(1));
6502       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6503     }
6504   }
6505 
6506   if (N0.getOpcode() == ISD::SETCC) {
6507     if (!LegalOperations && VT.isVector() &&
6508         N0.getValueType().getVectorElementType() == MVT::i1) {
6509       EVT N0VT = N0.getOperand(0).getValueType();
6510       if (getSetCCResultType(N0VT) == N0.getValueType())
6511         return SDValue();
6512 
6513       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6514       // Only do this before legalize for now.
6515       SDLoc DL(N);
6516       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6517       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6518         // We know that the # elements of the results is the same as the
6519         // # elements of the compare (and the # elements of the compare result
6520         // for that matter).  Check to see that they are the same size.  If so,
6521         // we know that the element size of the sext'd result matches the
6522         // element size of the compare operands.
6523         return DAG.getNode(ISD::AND, DL, VT,
6524                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6525                                          N0.getOperand(1),
6526                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6527                            VecOnes);
6528 
6529       // If the desired elements are smaller or larger than the source
6530       // elements we can use a matching integer vector type and then
6531       // truncate/sign extend
6532       EVT MatchingElementType =
6533         EVT::getIntegerVT(*DAG.getContext(),
6534                           N0VT.getScalarType().getSizeInBits());
6535       EVT MatchingVectorType =
6536         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6537                          N0VT.getVectorNumElements());
6538       SDValue VsetCC =
6539         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6540                       N0.getOperand(1),
6541                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6542       return DAG.getNode(ISD::AND, DL, VT,
6543                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6544                          VecOnes);
6545     }
6546 
6547     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6548     SDLoc DL(N);
6549     if (SDValue SCC = SimplifySelectCC(
6550             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6551             DAG.getConstant(0, DL, VT),
6552             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6553       return SCC;
6554   }
6555 
6556   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6557   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6558       isa<ConstantSDNode>(N0.getOperand(1)) &&
6559       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6560       N0.hasOneUse()) {
6561     SDValue ShAmt = N0.getOperand(1);
6562     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6563     if (N0.getOpcode() == ISD::SHL) {
6564       SDValue InnerZExt = N0.getOperand(0);
6565       // If the original shl may be shifting out bits, do not perform this
6566       // transformation.
6567       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6568         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6569       if (ShAmtVal > KnownZeroBits)
6570         return SDValue();
6571     }
6572 
6573     SDLoc DL(N);
6574 
6575     // Ensure that the shift amount is wide enough for the shifted value.
6576     if (VT.getSizeInBits() >= 256)
6577       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6578 
6579     return DAG.getNode(N0.getOpcode(), DL, VT,
6580                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6581                        ShAmt);
6582   }
6583 
6584   return SDValue();
6585 }
6586 
6587 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6588   SDValue N0 = N->getOperand(0);
6589   EVT VT = N->getValueType(0);
6590 
6591   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6592                                               LegalOperations))
6593     return SDValue(Res, 0);
6594 
6595   // fold (aext (aext x)) -> (aext x)
6596   // fold (aext (zext x)) -> (zext x)
6597   // fold (aext (sext x)) -> (sext x)
6598   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6599       N0.getOpcode() == ISD::ZERO_EXTEND ||
6600       N0.getOpcode() == ISD::SIGN_EXTEND)
6601     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6602 
6603   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6604   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6605   if (N0.getOpcode() == ISD::TRUNCATE) {
6606     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6607       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6608       if (NarrowLoad.getNode() != N0.getNode()) {
6609         CombineTo(N0.getNode(), NarrowLoad);
6610         // CombineTo deleted the truncate, if needed, but not what's under it.
6611         AddToWorklist(oye);
6612       }
6613       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6614     }
6615   }
6616 
6617   // fold (aext (truncate x))
6618   if (N0.getOpcode() == ISD::TRUNCATE) {
6619     SDValue TruncOp = N0.getOperand(0);
6620     if (TruncOp.getValueType() == VT)
6621       return TruncOp; // x iff x size == zext size.
6622     if (TruncOp.getValueType().bitsGT(VT))
6623       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6624     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6625   }
6626 
6627   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6628   // if the trunc is not free.
6629   if (N0.getOpcode() == ISD::AND &&
6630       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6631       N0.getOperand(1).getOpcode() == ISD::Constant &&
6632       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6633                           N0.getValueType())) {
6634     SDValue X = N0.getOperand(0).getOperand(0);
6635     if (X.getValueType().bitsLT(VT)) {
6636       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6637     } else if (X.getValueType().bitsGT(VT)) {
6638       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6639     }
6640     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6641     Mask = Mask.zext(VT.getSizeInBits());
6642     SDLoc DL(N);
6643     return DAG.getNode(ISD::AND, DL, VT,
6644                        X, DAG.getConstant(Mask, DL, VT));
6645   }
6646 
6647   // fold (aext (load x)) -> (aext (truncate (extload x)))
6648   // None of the supported targets knows how to perform load and any_ext
6649   // on vectors in one instruction.  We only perform this transformation on
6650   // scalars.
6651   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6652       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6653       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6654     bool DoXform = true;
6655     SmallVector<SDNode*, 4> SetCCs;
6656     if (!N0.hasOneUse())
6657       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6658     if (DoXform) {
6659       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6660       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6661                                        LN0->getChain(),
6662                                        LN0->getBasePtr(), N0.getValueType(),
6663                                        LN0->getMemOperand());
6664       CombineTo(N, ExtLoad);
6665       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6666                                   N0.getValueType(), ExtLoad);
6667       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6668       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6669                       ISD::ANY_EXTEND);
6670       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6671     }
6672   }
6673 
6674   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6675   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6676   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6677   if (N0.getOpcode() == ISD::LOAD &&
6678       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6679       N0.hasOneUse()) {
6680     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6681     ISD::LoadExtType ExtType = LN0->getExtensionType();
6682     EVT MemVT = LN0->getMemoryVT();
6683     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6684       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6685                                        VT, LN0->getChain(), LN0->getBasePtr(),
6686                                        MemVT, LN0->getMemOperand());
6687       CombineTo(N, ExtLoad);
6688       CombineTo(N0.getNode(),
6689                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6690                             N0.getValueType(), ExtLoad),
6691                 ExtLoad.getValue(1));
6692       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6693     }
6694   }
6695 
6696   if (N0.getOpcode() == ISD::SETCC) {
6697     // For vectors:
6698     // aext(setcc) -> vsetcc
6699     // aext(setcc) -> truncate(vsetcc)
6700     // aext(setcc) -> aext(vsetcc)
6701     // Only do this before legalize for now.
6702     if (VT.isVector() && !LegalOperations) {
6703       EVT N0VT = N0.getOperand(0).getValueType();
6704         // We know that the # elements of the results is the same as the
6705         // # elements of the compare (and the # elements of the compare result
6706         // for that matter).  Check to see that they are the same size.  If so,
6707         // we know that the element size of the sext'd result matches the
6708         // element size of the compare operands.
6709       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6710         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6711                              N0.getOperand(1),
6712                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6713       // If the desired elements are smaller or larger than the source
6714       // elements we can use a matching integer vector type and then
6715       // truncate/any extend
6716       else {
6717         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6718         SDValue VsetCC =
6719           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6720                         N0.getOperand(1),
6721                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6722         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6723       }
6724     }
6725 
6726     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6727     SDLoc DL(N);
6728     if (SDValue SCC = SimplifySelectCC(
6729             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6730             DAG.getConstant(0, DL, VT),
6731             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6732       return SCC;
6733   }
6734 
6735   return SDValue();
6736 }
6737 
6738 /// See if the specified operand can be simplified with the knowledge that only
6739 /// the bits specified by Mask are used.  If so, return the simpler operand,
6740 /// otherwise return a null SDValue.
6741 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6742   switch (V.getOpcode()) {
6743   default: break;
6744   case ISD::Constant: {
6745     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6746     assert(CV && "Const value should be ConstSDNode.");
6747     const APInt &CVal = CV->getAPIntValue();
6748     APInt NewVal = CVal & Mask;
6749     if (NewVal != CVal)
6750       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6751     break;
6752   }
6753   case ISD::OR:
6754   case ISD::XOR:
6755     // If the LHS or RHS don't contribute bits to the or, drop them.
6756     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6757       return V.getOperand(1);
6758     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6759       return V.getOperand(0);
6760     break;
6761   case ISD::SRL:
6762     // Only look at single-use SRLs.
6763     if (!V.getNode()->hasOneUse())
6764       break;
6765     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6766       // See if we can recursively simplify the LHS.
6767       unsigned Amt = RHSC->getZExtValue();
6768 
6769       // Watch out for shift count overflow though.
6770       if (Amt >= Mask.getBitWidth()) break;
6771       APInt NewMask = Mask << Amt;
6772       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6773         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6774                            SimplifyLHS, V.getOperand(1));
6775     }
6776   }
6777   return SDValue();
6778 }
6779 
6780 /// If the result of a wider load is shifted to right of N  bits and then
6781 /// truncated to a narrower type and where N is a multiple of number of bits of
6782 /// the narrower type, transform it to a narrower load from address + N / num of
6783 /// bits of new type. If the result is to be extended, also fold the extension
6784 /// to form a extending load.
6785 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6786   unsigned Opc = N->getOpcode();
6787 
6788   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6789   SDValue N0 = N->getOperand(0);
6790   EVT VT = N->getValueType(0);
6791   EVT ExtVT = VT;
6792 
6793   // This transformation isn't valid for vector loads.
6794   if (VT.isVector())
6795     return SDValue();
6796 
6797   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6798   // extended to VT.
6799   if (Opc == ISD::SIGN_EXTEND_INREG) {
6800     ExtType = ISD::SEXTLOAD;
6801     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6802   } else if (Opc == ISD::SRL) {
6803     // Another special-case: SRL is basically zero-extending a narrower value.
6804     ExtType = ISD::ZEXTLOAD;
6805     N0 = SDValue(N, 0);
6806     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6807     if (!N01) return SDValue();
6808     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6809                               VT.getSizeInBits() - N01->getZExtValue());
6810   }
6811   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6812     return SDValue();
6813 
6814   unsigned EVTBits = ExtVT.getSizeInBits();
6815 
6816   // Do not generate loads of non-round integer types since these can
6817   // be expensive (and would be wrong if the type is not byte sized).
6818   if (!ExtVT.isRound())
6819     return SDValue();
6820 
6821   unsigned ShAmt = 0;
6822   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6823     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6824       ShAmt = N01->getZExtValue();
6825       // Is the shift amount a multiple of size of VT?
6826       if ((ShAmt & (EVTBits-1)) == 0) {
6827         N0 = N0.getOperand(0);
6828         // Is the load width a multiple of size of VT?
6829         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6830           return SDValue();
6831       }
6832 
6833       // At this point, we must have a load or else we can't do the transform.
6834       if (!isa<LoadSDNode>(N0)) return SDValue();
6835 
6836       // Because a SRL must be assumed to *need* to zero-extend the high bits
6837       // (as opposed to anyext the high bits), we can't combine the zextload
6838       // lowering of SRL and an sextload.
6839       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6840         return SDValue();
6841 
6842       // If the shift amount is larger than the input type then we're not
6843       // accessing any of the loaded bytes.  If the load was a zextload/extload
6844       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6845       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6846         return SDValue();
6847     }
6848   }
6849 
6850   // If the load is shifted left (and the result isn't shifted back right),
6851   // we can fold the truncate through the shift.
6852   unsigned ShLeftAmt = 0;
6853   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6854       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6855     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6856       ShLeftAmt = N01->getZExtValue();
6857       N0 = N0.getOperand(0);
6858     }
6859   }
6860 
6861   // If we haven't found a load, we can't narrow it.  Don't transform one with
6862   // multiple uses, this would require adding a new load.
6863   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6864     return SDValue();
6865 
6866   // Don't change the width of a volatile load.
6867   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6868   if (LN0->isVolatile())
6869     return SDValue();
6870 
6871   // Verify that we are actually reducing a load width here.
6872   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6873     return SDValue();
6874 
6875   // For the transform to be legal, the load must produce only two values
6876   // (the value loaded and the chain).  Don't transform a pre-increment
6877   // load, for example, which produces an extra value.  Otherwise the
6878   // transformation is not equivalent, and the downstream logic to replace
6879   // uses gets things wrong.
6880   if (LN0->getNumValues() > 2)
6881     return SDValue();
6882 
6883   // If the load that we're shrinking is an extload and we're not just
6884   // discarding the extension we can't simply shrink the load. Bail.
6885   // TODO: It would be possible to merge the extensions in some cases.
6886   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6887       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6888     return SDValue();
6889 
6890   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6891     return SDValue();
6892 
6893   EVT PtrType = N0.getOperand(1).getValueType();
6894 
6895   if (PtrType == MVT::Untyped || PtrType.isExtended())
6896     // It's not possible to generate a constant of extended or untyped type.
6897     return SDValue();
6898 
6899   // For big endian targets, we need to adjust the offset to the pointer to
6900   // load the correct bytes.
6901   if (DAG.getDataLayout().isBigEndian()) {
6902     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6903     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6904     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6905   }
6906 
6907   uint64_t PtrOff = ShAmt / 8;
6908   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6909   SDLoc DL(LN0);
6910   // The original load itself didn't wrap, so an offset within it doesn't.
6911   SDNodeFlags Flags;
6912   Flags.setNoUnsignedWrap(true);
6913   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6914                                PtrType, LN0->getBasePtr(),
6915                                DAG.getConstant(PtrOff, DL, PtrType),
6916                                &Flags);
6917   AddToWorklist(NewPtr.getNode());
6918 
6919   SDValue Load;
6920   if (ExtType == ISD::NON_EXTLOAD)
6921     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6922                         LN0->getPointerInfo().getWithOffset(PtrOff),
6923                         LN0->isVolatile(), LN0->isNonTemporal(),
6924                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6925   else
6926     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6927                           LN0->getPointerInfo().getWithOffset(PtrOff),
6928                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6929                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6930 
6931   // Replace the old load's chain with the new load's chain.
6932   WorklistRemover DeadNodes(*this);
6933   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6934 
6935   // Shift the result left, if we've swallowed a left shift.
6936   SDValue Result = Load;
6937   if (ShLeftAmt != 0) {
6938     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6939     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6940       ShImmTy = VT;
6941     // If the shift amount is as large as the result size (but, presumably,
6942     // no larger than the source) then the useful bits of the result are
6943     // zero; we can't simply return the shortened shift, because the result
6944     // of that operation is undefined.
6945     SDLoc DL(N0);
6946     if (ShLeftAmt >= VT.getSizeInBits())
6947       Result = DAG.getConstant(0, DL, VT);
6948     else
6949       Result = DAG.getNode(ISD::SHL, DL, VT,
6950                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6951   }
6952 
6953   // Return the new loaded value.
6954   return Result;
6955 }
6956 
6957 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6958   SDValue N0 = N->getOperand(0);
6959   SDValue N1 = N->getOperand(1);
6960   EVT VT = N->getValueType(0);
6961   EVT EVT = cast<VTSDNode>(N1)->getVT();
6962   unsigned VTBits = VT.getScalarType().getSizeInBits();
6963   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6964 
6965   if (N0.isUndef())
6966     return DAG.getUNDEF(VT);
6967 
6968   // fold (sext_in_reg c1) -> c1
6969   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6970     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6971 
6972   // If the input is already sign extended, just drop the extension.
6973   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6974     return N0;
6975 
6976   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6977   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6978       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6979     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6980                        N0.getOperand(0), N1);
6981 
6982   // fold (sext_in_reg (sext x)) -> (sext x)
6983   // fold (sext_in_reg (aext x)) -> (sext x)
6984   // if x is small enough.
6985   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6986     SDValue N00 = N0.getOperand(0);
6987     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6988         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6989       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6990   }
6991 
6992   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6993   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6994     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6995 
6996   // fold operands of sext_in_reg based on knowledge that the top bits are not
6997   // demanded.
6998   if (SimplifyDemandedBits(SDValue(N, 0)))
6999     return SDValue(N, 0);
7000 
7001   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7002   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7003   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7004     return NarrowLoad;
7005 
7006   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7007   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7008   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7009   if (N0.getOpcode() == ISD::SRL) {
7010     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7011       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7012         // We can turn this into an SRA iff the input to the SRL is already sign
7013         // extended enough.
7014         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7015         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7016           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7017                              N0.getOperand(0), N0.getOperand(1));
7018       }
7019   }
7020 
7021   // fold (sext_inreg (extload x)) -> (sextload x)
7022   if (ISD::isEXTLoad(N0.getNode()) &&
7023       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7024       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7025       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7026        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7027     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7028     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7029                                      LN0->getChain(),
7030                                      LN0->getBasePtr(), EVT,
7031                                      LN0->getMemOperand());
7032     CombineTo(N, ExtLoad);
7033     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7034     AddToWorklist(ExtLoad.getNode());
7035     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7036   }
7037   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7038   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7039       N0.hasOneUse() &&
7040       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7041       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7042        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7043     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7044     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7045                                      LN0->getChain(),
7046                                      LN0->getBasePtr(), EVT,
7047                                      LN0->getMemOperand());
7048     CombineTo(N, ExtLoad);
7049     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7050     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7051   }
7052 
7053   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7054   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7055     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7056                                            N0.getOperand(1), false))
7057       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7058                          BSwap, N1);
7059   }
7060 
7061   return SDValue();
7062 }
7063 
7064 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7065   SDValue N0 = N->getOperand(0);
7066   EVT VT = N->getValueType(0);
7067 
7068   if (N0.isUndef())
7069     return DAG.getUNDEF(VT);
7070 
7071   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7072                                               LegalOperations))
7073     return SDValue(Res, 0);
7074 
7075   return SDValue();
7076 }
7077 
7078 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7079   SDValue N0 = N->getOperand(0);
7080   EVT VT = N->getValueType(0);
7081 
7082   if (N0.isUndef())
7083     return DAG.getUNDEF(VT);
7084 
7085   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7086                                               LegalOperations))
7087     return SDValue(Res, 0);
7088 
7089   return SDValue();
7090 }
7091 
7092 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7093   SDValue N0 = N->getOperand(0);
7094   EVT VT = N->getValueType(0);
7095   bool isLE = DAG.getDataLayout().isLittleEndian();
7096 
7097   // noop truncate
7098   if (N0.getValueType() == N->getValueType(0))
7099     return N0;
7100   // fold (truncate c1) -> c1
7101   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7102     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7103   // fold (truncate (truncate x)) -> (truncate x)
7104   if (N0.getOpcode() == ISD::TRUNCATE)
7105     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7106   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7107   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7108       N0.getOpcode() == ISD::SIGN_EXTEND ||
7109       N0.getOpcode() == ISD::ANY_EXTEND) {
7110     // if the source is smaller than the dest, we still need an extend.
7111     if (N0.getOperand(0).getValueType().bitsLT(VT))
7112       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7113     // if the source is larger than the dest, than we just need the truncate.
7114     if (N0.getOperand(0).getValueType().bitsGT(VT))
7115       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7116     // if the source and dest are the same type, we can drop both the extend
7117     // and the truncate.
7118     return N0.getOperand(0);
7119   }
7120 
7121   // Fold extract-and-trunc into a narrow extract. For example:
7122   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7123   //   i32 y = TRUNCATE(i64 x)
7124   //        -- becomes --
7125   //   v16i8 b = BITCAST (v2i64 val)
7126   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7127   //
7128   // Note: We only run this optimization after type legalization (which often
7129   // creates this pattern) and before operation legalization after which
7130   // we need to be more careful about the vector instructions that we generate.
7131   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7132       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7133 
7134     EVT VecTy = N0.getOperand(0).getValueType();
7135     EVT ExTy = N0.getValueType();
7136     EVT TrTy = N->getValueType(0);
7137 
7138     unsigned NumElem = VecTy.getVectorNumElements();
7139     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7140 
7141     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7142     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7143 
7144     SDValue EltNo = N0->getOperand(1);
7145     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7146       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7147       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7148       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7149 
7150       SDLoc DL(N);
7151       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7152                          DAG.getBitcast(NVT, N0.getOperand(0)),
7153                          DAG.getConstant(Index, DL, IndexTy));
7154     }
7155   }
7156 
7157   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7158   if (N0.getOpcode() == ISD::SELECT) {
7159     EVT SrcVT = N0.getValueType();
7160     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7161         TLI.isTruncateFree(SrcVT, VT)) {
7162       SDLoc SL(N0);
7163       SDValue Cond = N0.getOperand(0);
7164       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7165       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7166       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7167     }
7168   }
7169 
7170   // trunc (shl x, K) -> shl (trunc x), K => K < vt.size / 2
7171   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7172       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7173       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7174     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7175       uint64_t Amt = CAmt->getZExtValue();
7176       unsigned Size = VT.getSizeInBits();
7177 
7178       if (Amt < Size / 2) {
7179         SDLoc SL(N);
7180         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7181 
7182         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7183         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7184                            DAG.getConstant(Amt, SL, AmtVT));
7185       }
7186     }
7187   }
7188 
7189   // Fold a series of buildvector, bitcast, and truncate if possible.
7190   // For example fold
7191   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7192   //   (2xi32 (buildvector x, y)).
7193   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7194       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7195       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7196       N0.getOperand(0).hasOneUse()) {
7197 
7198     SDValue BuildVect = N0.getOperand(0);
7199     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7200     EVT TruncVecEltTy = VT.getVectorElementType();
7201 
7202     // Check that the element types match.
7203     if (BuildVectEltTy == TruncVecEltTy) {
7204       // Now we only need to compute the offset of the truncated elements.
7205       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7206       unsigned TruncVecNumElts = VT.getVectorNumElements();
7207       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7208 
7209       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7210              "Invalid number of elements");
7211 
7212       SmallVector<SDValue, 8> Opnds;
7213       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7214         Opnds.push_back(BuildVect.getOperand(i));
7215 
7216       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7217     }
7218   }
7219 
7220   // See if we can simplify the input to this truncate through knowledge that
7221   // only the low bits are being used.
7222   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7223   // Currently we only perform this optimization on scalars because vectors
7224   // may have different active low bits.
7225   if (!VT.isVector()) {
7226     if (SDValue Shorter =
7227             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7228                                                      VT.getSizeInBits())))
7229       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7230   }
7231   // fold (truncate (load x)) -> (smaller load x)
7232   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7233   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7234     if (SDValue Reduced = ReduceLoadWidth(N))
7235       return Reduced;
7236 
7237     // Handle the case where the load remains an extending load even
7238     // after truncation.
7239     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7240       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7241       if (!LN0->isVolatile() &&
7242           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7243         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7244                                          VT, LN0->getChain(), LN0->getBasePtr(),
7245                                          LN0->getMemoryVT(),
7246                                          LN0->getMemOperand());
7247         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7248         return NewLoad;
7249       }
7250     }
7251   }
7252   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7253   // where ... are all 'undef'.
7254   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7255     SmallVector<EVT, 8> VTs;
7256     SDValue V;
7257     unsigned Idx = 0;
7258     unsigned NumDefs = 0;
7259 
7260     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7261       SDValue X = N0.getOperand(i);
7262       if (!X.isUndef()) {
7263         V = X;
7264         Idx = i;
7265         NumDefs++;
7266       }
7267       // Stop if more than one members are non-undef.
7268       if (NumDefs > 1)
7269         break;
7270       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7271                                      VT.getVectorElementType(),
7272                                      X.getValueType().getVectorNumElements()));
7273     }
7274 
7275     if (NumDefs == 0)
7276       return DAG.getUNDEF(VT);
7277 
7278     if (NumDefs == 1) {
7279       assert(V.getNode() && "The single defined operand is empty!");
7280       SmallVector<SDValue, 8> Opnds;
7281       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7282         if (i != Idx) {
7283           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7284           continue;
7285         }
7286         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7287         AddToWorklist(NV.getNode());
7288         Opnds.push_back(NV);
7289       }
7290       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7291     }
7292   }
7293 
7294   // Fold truncate of a bitcast of a vector to an extract of the low vector
7295   // element.
7296   //
7297   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7298   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7299     SDValue VecSrc = N0.getOperand(0);
7300     EVT SrcVT = VecSrc.getValueType();
7301     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7302         (!LegalOperations ||
7303          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7304       SDLoc SL(N);
7305 
7306       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7307       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7308                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7309     }
7310   }
7311 
7312   // Simplify the operands using demanded-bits information.
7313   if (!VT.isVector() &&
7314       SimplifyDemandedBits(SDValue(N, 0)))
7315     return SDValue(N, 0);
7316 
7317   return SDValue();
7318 }
7319 
7320 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7321   SDValue Elt = N->getOperand(i);
7322   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7323     return Elt.getNode();
7324   return Elt.getOperand(Elt.getResNo()).getNode();
7325 }
7326 
7327 /// build_pair (load, load) -> load
7328 /// if load locations are consecutive.
7329 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7330   assert(N->getOpcode() == ISD::BUILD_PAIR);
7331 
7332   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7333   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7334   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7335       LD1->getAddressSpace() != LD2->getAddressSpace())
7336     return SDValue();
7337   EVT LD1VT = LD1->getValueType(0);
7338   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7339   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7340       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7341     unsigned Align = LD1->getAlignment();
7342     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7343         VT.getTypeForEVT(*DAG.getContext()));
7344 
7345     if (NewAlign <= Align &&
7346         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7347       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7348                          LD1->getBasePtr(), LD1->getPointerInfo(),
7349                          false, false, false, Align);
7350   }
7351 
7352   return SDValue();
7353 }
7354 
7355 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7356   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7357   // and Lo parts; on big-endian machines it doesn't.
7358   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7359 }
7360 
7361 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7362                                     const TargetLowering &TLI) {
7363   // If this is not a bitcast to an FP type or if the target doesn't have
7364   // IEEE754-compliant FP logic, we're done.
7365   EVT VT = N->getValueType(0);
7366   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7367     return SDValue();
7368 
7369   // TODO: Use splat values for the constant-checking below and remove this
7370   // restriction.
7371   SDValue N0 = N->getOperand(0);
7372   EVT SourceVT = N0.getValueType();
7373   if (SourceVT.isVector())
7374     return SDValue();
7375 
7376   unsigned FPOpcode;
7377   APInt SignMask;
7378   switch (N0.getOpcode()) {
7379   case ISD::AND:
7380     FPOpcode = ISD::FABS;
7381     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7382     break;
7383   case ISD::XOR:
7384     FPOpcode = ISD::FNEG;
7385     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7386     break;
7387   // TODO: ISD::OR --> ISD::FNABS?
7388   default:
7389     return SDValue();
7390   }
7391 
7392   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7393   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7394   SDValue LogicOp0 = N0.getOperand(0);
7395   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7396   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7397       LogicOp0.getOpcode() == ISD::BITCAST &&
7398       LogicOp0->getOperand(0).getValueType() == VT)
7399     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7400 
7401   return SDValue();
7402 }
7403 
7404 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7405   SDValue N0 = N->getOperand(0);
7406   EVT VT = N->getValueType(0);
7407 
7408   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7409   // Only do this before legalize, since afterward the target may be depending
7410   // on the bitconvert.
7411   // First check to see if this is all constant.
7412   if (!LegalTypes &&
7413       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7414       VT.isVector()) {
7415     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7416 
7417     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7418     assert(!DestEltVT.isVector() &&
7419            "Element type of vector ValueType must not be vector!");
7420     if (isSimple)
7421       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7422   }
7423 
7424   // If the input is a constant, let getNode fold it.
7425   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7426     // If we can't allow illegal operations, we need to check that this is just
7427     // a fp -> int or int -> conversion and that the resulting operation will
7428     // be legal.
7429     if (!LegalOperations ||
7430         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7431          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7432         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7433          TLI.isOperationLegal(ISD::Constant, VT)))
7434       return DAG.getBitcast(VT, N0);
7435   }
7436 
7437   // (conv (conv x, t1), t2) -> (conv x, t2)
7438   if (N0.getOpcode() == ISD::BITCAST)
7439     return DAG.getBitcast(VT, N0.getOperand(0));
7440 
7441   // fold (conv (load x)) -> (load (conv*)x)
7442   // If the resultant load doesn't need a higher alignment than the original!
7443   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7444       // Do not change the width of a volatile load.
7445       !cast<LoadSDNode>(N0)->isVolatile() &&
7446       // Do not remove the cast if the types differ in endian layout.
7447       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7448           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7449       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7450       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7451     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7452     unsigned OrigAlign = LN0->getAlignment();
7453 
7454     bool Fast = false;
7455     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7456                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7457         Fast) {
7458       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7459                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7460                                  LN0->isVolatile(), LN0->isNonTemporal(),
7461                                  LN0->isInvariant(), OrigAlign,
7462                                  LN0->getAAInfo());
7463       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7464       return Load;
7465     }
7466   }
7467 
7468   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7469     return V;
7470 
7471   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7472   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7473   //
7474   // For ppc_fp128:
7475   // fold (bitcast (fneg x)) ->
7476   //     flipbit = signbit
7477   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7478   //
7479   // fold (bitcast (fabs x)) ->
7480   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7481   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7482   // This often reduces constant pool loads.
7483   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7484        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7485       N0.getNode()->hasOneUse() && VT.isInteger() &&
7486       !VT.isVector() && !N0.getValueType().isVector()) {
7487     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7488     AddToWorklist(NewConv.getNode());
7489 
7490     SDLoc DL(N);
7491     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7492       assert(VT.getSizeInBits() == 128);
7493       SDValue SignBit = DAG.getConstant(
7494           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7495       SDValue FlipBit;
7496       if (N0.getOpcode() == ISD::FNEG) {
7497         FlipBit = SignBit;
7498         AddToWorklist(FlipBit.getNode());
7499       } else {
7500         assert(N0.getOpcode() == ISD::FABS);
7501         SDValue Hi =
7502             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7503                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7504                                               SDLoc(NewConv)));
7505         AddToWorklist(Hi.getNode());
7506         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7507         AddToWorklist(FlipBit.getNode());
7508       }
7509       SDValue FlipBits =
7510           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7511       AddToWorklist(FlipBits.getNode());
7512       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7513     }
7514     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7515     if (N0.getOpcode() == ISD::FNEG)
7516       return DAG.getNode(ISD::XOR, DL, VT,
7517                          NewConv, DAG.getConstant(SignBit, DL, VT));
7518     assert(N0.getOpcode() == ISD::FABS);
7519     return DAG.getNode(ISD::AND, DL, VT,
7520                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7521   }
7522 
7523   // fold (bitconvert (fcopysign cst, x)) ->
7524   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7525   // Note that we don't handle (copysign x, cst) because this can always be
7526   // folded to an fneg or fabs.
7527   //
7528   // For ppc_fp128:
7529   // fold (bitcast (fcopysign cst, x)) ->
7530   //     flipbit = (and (extract_element
7531   //                     (xor (bitcast cst), (bitcast x)), 0),
7532   //                    signbit)
7533   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7534   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7535       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7536       VT.isInteger() && !VT.isVector()) {
7537     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7538     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7539     if (isTypeLegal(IntXVT)) {
7540       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7541       AddToWorklist(X.getNode());
7542 
7543       // If X has a different width than the result/lhs, sext it or truncate it.
7544       unsigned VTWidth = VT.getSizeInBits();
7545       if (OrigXWidth < VTWidth) {
7546         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7547         AddToWorklist(X.getNode());
7548       } else if (OrigXWidth > VTWidth) {
7549         // To get the sign bit in the right place, we have to shift it right
7550         // before truncating.
7551         SDLoc DL(X);
7552         X = DAG.getNode(ISD::SRL, DL,
7553                         X.getValueType(), X,
7554                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7555                                         X.getValueType()));
7556         AddToWorklist(X.getNode());
7557         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7558         AddToWorklist(X.getNode());
7559       }
7560 
7561       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7562         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7563         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7564         AddToWorklist(Cst.getNode());
7565         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7566         AddToWorklist(X.getNode());
7567         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7568         AddToWorklist(XorResult.getNode());
7569         SDValue XorResult64 = DAG.getNode(
7570             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7571             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7572                                   SDLoc(XorResult)));
7573         AddToWorklist(XorResult64.getNode());
7574         SDValue FlipBit =
7575             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7576                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7577         AddToWorklist(FlipBit.getNode());
7578         SDValue FlipBits =
7579             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7580         AddToWorklist(FlipBits.getNode());
7581         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7582       }
7583       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7584       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7585                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7586       AddToWorklist(X.getNode());
7587 
7588       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7589       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7590                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7591       AddToWorklist(Cst.getNode());
7592 
7593       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7594     }
7595   }
7596 
7597   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7598   if (N0.getOpcode() == ISD::BUILD_PAIR)
7599     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7600       return CombineLD;
7601 
7602   // Remove double bitcasts from shuffles - this is often a legacy of
7603   // XformToShuffleWithZero being used to combine bitmaskings (of
7604   // float vectors bitcast to integer vectors) into shuffles.
7605   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7606   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7607       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7608       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7609       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7610     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7611 
7612     // If operands are a bitcast, peek through if it casts the original VT.
7613     // If operands are a constant, just bitcast back to original VT.
7614     auto PeekThroughBitcast = [&](SDValue Op) {
7615       if (Op.getOpcode() == ISD::BITCAST &&
7616           Op.getOperand(0).getValueType() == VT)
7617         return SDValue(Op.getOperand(0));
7618       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7619           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7620         return DAG.getBitcast(VT, Op);
7621       return SDValue();
7622     };
7623 
7624     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7625     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7626     if (!(SV0 && SV1))
7627       return SDValue();
7628 
7629     int MaskScale =
7630         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7631     SmallVector<int, 8> NewMask;
7632     for (int M : SVN->getMask())
7633       for (int i = 0; i != MaskScale; ++i)
7634         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7635 
7636     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7637     if (!LegalMask) {
7638       std::swap(SV0, SV1);
7639       ShuffleVectorSDNode::commuteMask(NewMask);
7640       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7641     }
7642 
7643     if (LegalMask)
7644       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7645   }
7646 
7647   return SDValue();
7648 }
7649 
7650 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7651   EVT VT = N->getValueType(0);
7652   return CombineConsecutiveLoads(N, VT);
7653 }
7654 
7655 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7656 /// operands. DstEltVT indicates the destination element value type.
7657 SDValue DAGCombiner::
7658 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7659   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7660 
7661   // If this is already the right type, we're done.
7662   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7663 
7664   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7665   unsigned DstBitSize = DstEltVT.getSizeInBits();
7666 
7667   // If this is a conversion of N elements of one type to N elements of another
7668   // type, convert each element.  This handles FP<->INT cases.
7669   if (SrcBitSize == DstBitSize) {
7670     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7671                               BV->getValueType(0).getVectorNumElements());
7672 
7673     // Due to the FP element handling below calling this routine recursively,
7674     // we can end up with a scalar-to-vector node here.
7675     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7676       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7677                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7678 
7679     SmallVector<SDValue, 8> Ops;
7680     for (SDValue Op : BV->op_values()) {
7681       // If the vector element type is not legal, the BUILD_VECTOR operands
7682       // are promoted and implicitly truncated.  Make that explicit here.
7683       if (Op.getValueType() != SrcEltVT)
7684         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7685       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7686       AddToWorklist(Ops.back().getNode());
7687     }
7688     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7689   }
7690 
7691   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7692   // handle annoying details of growing/shrinking FP values, we convert them to
7693   // int first.
7694   if (SrcEltVT.isFloatingPoint()) {
7695     // Convert the input float vector to a int vector where the elements are the
7696     // same sizes.
7697     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7698     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7699     SrcEltVT = IntVT;
7700   }
7701 
7702   // Now we know the input is an integer vector.  If the output is a FP type,
7703   // convert to integer first, then to FP of the right size.
7704   if (DstEltVT.isFloatingPoint()) {
7705     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7706     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7707 
7708     // Next, convert to FP elements of the same size.
7709     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7710   }
7711 
7712   SDLoc DL(BV);
7713 
7714   // Okay, we know the src/dst types are both integers of differing types.
7715   // Handling growing first.
7716   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7717   if (SrcBitSize < DstBitSize) {
7718     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7719 
7720     SmallVector<SDValue, 8> Ops;
7721     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7722          i += NumInputsPerOutput) {
7723       bool isLE = DAG.getDataLayout().isLittleEndian();
7724       APInt NewBits = APInt(DstBitSize, 0);
7725       bool EltIsUndef = true;
7726       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7727         // Shift the previously computed bits over.
7728         NewBits <<= SrcBitSize;
7729         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7730         if (Op.isUndef()) continue;
7731         EltIsUndef = false;
7732 
7733         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7734                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7735       }
7736 
7737       if (EltIsUndef)
7738         Ops.push_back(DAG.getUNDEF(DstEltVT));
7739       else
7740         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7741     }
7742 
7743     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7744     return DAG.getBuildVector(VT, DL, Ops);
7745   }
7746 
7747   // Finally, this must be the case where we are shrinking elements: each input
7748   // turns into multiple outputs.
7749   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7750   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7751                             NumOutputsPerInput*BV->getNumOperands());
7752   SmallVector<SDValue, 8> Ops;
7753 
7754   for (const SDValue &Op : BV->op_values()) {
7755     if (Op.isUndef()) {
7756       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7757       continue;
7758     }
7759 
7760     APInt OpVal = cast<ConstantSDNode>(Op)->
7761                   getAPIntValue().zextOrTrunc(SrcBitSize);
7762 
7763     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7764       APInt ThisVal = OpVal.trunc(DstBitSize);
7765       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7766       OpVal = OpVal.lshr(DstBitSize);
7767     }
7768 
7769     // For big endian targets, swap the order of the pieces of each element.
7770     if (DAG.getDataLayout().isBigEndian())
7771       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7772   }
7773 
7774   return DAG.getBuildVector(VT, DL, Ops);
7775 }
7776 
7777 /// Try to perform FMA combining on a given FADD node.
7778 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7779   SDValue N0 = N->getOperand(0);
7780   SDValue N1 = N->getOperand(1);
7781   EVT VT = N->getValueType(0);
7782   SDLoc SL(N);
7783 
7784   const TargetOptions &Options = DAG.getTarget().Options;
7785   bool AllowFusion =
7786       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7787 
7788   // Floating-point multiply-add with intermediate rounding.
7789   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7790 
7791   // Floating-point multiply-add without intermediate rounding.
7792   bool HasFMA =
7793       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7794       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7795 
7796   // No valid opcode, do not combine.
7797   if (!HasFMAD && !HasFMA)
7798     return SDValue();
7799 
7800   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7801   ;
7802   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7803     return SDValue();
7804 
7805   // Always prefer FMAD to FMA for precision.
7806   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7807   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7808   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7809 
7810   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7811   // prefer to fold the multiply with fewer uses.
7812   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7813       N1.getOpcode() == ISD::FMUL) {
7814     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7815       std::swap(N0, N1);
7816   }
7817 
7818   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7819   if (N0.getOpcode() == ISD::FMUL &&
7820       (Aggressive || N0->hasOneUse())) {
7821     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7822                        N0.getOperand(0), N0.getOperand(1), N1);
7823   }
7824 
7825   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7826   // Note: Commutes FADD operands.
7827   if (N1.getOpcode() == ISD::FMUL &&
7828       (Aggressive || N1->hasOneUse())) {
7829     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7830                        N1.getOperand(0), N1.getOperand(1), N0);
7831   }
7832 
7833   // Look through FP_EXTEND nodes to do more combining.
7834   if (AllowFusion && LookThroughFPExt) {
7835     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7836     if (N0.getOpcode() == ISD::FP_EXTEND) {
7837       SDValue N00 = N0.getOperand(0);
7838       if (N00.getOpcode() == ISD::FMUL)
7839         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7840                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7841                                        N00.getOperand(0)),
7842                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7843                                        N00.getOperand(1)), N1);
7844     }
7845 
7846     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7847     // Note: Commutes FADD operands.
7848     if (N1.getOpcode() == ISD::FP_EXTEND) {
7849       SDValue N10 = N1.getOperand(0);
7850       if (N10.getOpcode() == ISD::FMUL)
7851         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7852                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7853                                        N10.getOperand(0)),
7854                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7855                                        N10.getOperand(1)), N0);
7856     }
7857   }
7858 
7859   // More folding opportunities when target permits.
7860   if ((AllowFusion || HasFMAD)  && Aggressive) {
7861     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7862     if (N0.getOpcode() == PreferredFusedOpcode &&
7863         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7864       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7865                          N0.getOperand(0), N0.getOperand(1),
7866                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7867                                      N0.getOperand(2).getOperand(0),
7868                                      N0.getOperand(2).getOperand(1),
7869                                      N1));
7870     }
7871 
7872     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7873     if (N1->getOpcode() == PreferredFusedOpcode &&
7874         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7875       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7876                          N1.getOperand(0), N1.getOperand(1),
7877                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7878                                      N1.getOperand(2).getOperand(0),
7879                                      N1.getOperand(2).getOperand(1),
7880                                      N0));
7881     }
7882 
7883     if (AllowFusion && LookThroughFPExt) {
7884       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7885       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7886       auto FoldFAddFMAFPExtFMul = [&] (
7887           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7888         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7889                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7890                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7891                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7892                                        Z));
7893       };
7894       if (N0.getOpcode() == PreferredFusedOpcode) {
7895         SDValue N02 = N0.getOperand(2);
7896         if (N02.getOpcode() == ISD::FP_EXTEND) {
7897           SDValue N020 = N02.getOperand(0);
7898           if (N020.getOpcode() == ISD::FMUL)
7899             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7900                                         N020.getOperand(0), N020.getOperand(1),
7901                                         N1);
7902         }
7903       }
7904 
7905       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7906       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7907       // FIXME: This turns two single-precision and one double-precision
7908       // operation into two double-precision operations, which might not be
7909       // interesting for all targets, especially GPUs.
7910       auto FoldFAddFPExtFMAFMul = [&] (
7911           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7912         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7913                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7914                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7915                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7916                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7917                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7918                                        Z));
7919       };
7920       if (N0.getOpcode() == ISD::FP_EXTEND) {
7921         SDValue N00 = N0.getOperand(0);
7922         if (N00.getOpcode() == PreferredFusedOpcode) {
7923           SDValue N002 = N00.getOperand(2);
7924           if (N002.getOpcode() == ISD::FMUL)
7925             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7926                                         N002.getOperand(0), N002.getOperand(1),
7927                                         N1);
7928         }
7929       }
7930 
7931       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7932       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7933       if (N1.getOpcode() == PreferredFusedOpcode) {
7934         SDValue N12 = N1.getOperand(2);
7935         if (N12.getOpcode() == ISD::FP_EXTEND) {
7936           SDValue N120 = N12.getOperand(0);
7937           if (N120.getOpcode() == ISD::FMUL)
7938             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7939                                         N120.getOperand(0), N120.getOperand(1),
7940                                         N0);
7941         }
7942       }
7943 
7944       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7945       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7946       // FIXME: This turns two single-precision and one double-precision
7947       // operation into two double-precision operations, which might not be
7948       // interesting for all targets, especially GPUs.
7949       if (N1.getOpcode() == ISD::FP_EXTEND) {
7950         SDValue N10 = N1.getOperand(0);
7951         if (N10.getOpcode() == PreferredFusedOpcode) {
7952           SDValue N102 = N10.getOperand(2);
7953           if (N102.getOpcode() == ISD::FMUL)
7954             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7955                                         N102.getOperand(0), N102.getOperand(1),
7956                                         N0);
7957         }
7958       }
7959     }
7960   }
7961 
7962   return SDValue();
7963 }
7964 
7965 /// Try to perform FMA combining on a given FSUB node.
7966 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7967   SDValue N0 = N->getOperand(0);
7968   SDValue N1 = N->getOperand(1);
7969   EVT VT = N->getValueType(0);
7970   SDLoc SL(N);
7971 
7972   const TargetOptions &Options = DAG.getTarget().Options;
7973   bool AllowFusion =
7974       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7975 
7976   // Floating-point multiply-add with intermediate rounding.
7977   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7978 
7979   // Floating-point multiply-add without intermediate rounding.
7980   bool HasFMA =
7981       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7982       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7983 
7984   // No valid opcode, do not combine.
7985   if (!HasFMAD && !HasFMA)
7986     return SDValue();
7987 
7988   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7989   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7990     return SDValue();
7991 
7992   // Always prefer FMAD to FMA for precision.
7993   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7994   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7995   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7996 
7997   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7998   if (N0.getOpcode() == ISD::FMUL &&
7999       (Aggressive || N0->hasOneUse())) {
8000     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8001                        N0.getOperand(0), N0.getOperand(1),
8002                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8003   }
8004 
8005   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8006   // Note: Commutes FSUB operands.
8007   if (N1.getOpcode() == ISD::FMUL &&
8008       (Aggressive || N1->hasOneUse()))
8009     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8010                        DAG.getNode(ISD::FNEG, SL, VT,
8011                                    N1.getOperand(0)),
8012                        N1.getOperand(1), N0);
8013 
8014   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8015   if (N0.getOpcode() == ISD::FNEG &&
8016       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8017       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8018     SDValue N00 = N0.getOperand(0).getOperand(0);
8019     SDValue N01 = N0.getOperand(0).getOperand(1);
8020     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8021                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8022                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8023   }
8024 
8025   // Look through FP_EXTEND nodes to do more combining.
8026   if (AllowFusion && LookThroughFPExt) {
8027     // fold (fsub (fpext (fmul x, y)), z)
8028     //   -> (fma (fpext x), (fpext y), (fneg z))
8029     if (N0.getOpcode() == ISD::FP_EXTEND) {
8030       SDValue N00 = N0.getOperand(0);
8031       if (N00.getOpcode() == ISD::FMUL)
8032         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8033                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8034                                        N00.getOperand(0)),
8035                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8036                                        N00.getOperand(1)),
8037                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8038     }
8039 
8040     // fold (fsub x, (fpext (fmul y, z)))
8041     //   -> (fma (fneg (fpext y)), (fpext z), x)
8042     // Note: Commutes FSUB operands.
8043     if (N1.getOpcode() == ISD::FP_EXTEND) {
8044       SDValue N10 = N1.getOperand(0);
8045       if (N10.getOpcode() == ISD::FMUL)
8046         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8047                            DAG.getNode(ISD::FNEG, SL, VT,
8048                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8049                                                    N10.getOperand(0))),
8050                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8051                                        N10.getOperand(1)),
8052                            N0);
8053     }
8054 
8055     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8056     //   -> (fneg (fma (fpext x), (fpext y), z))
8057     // Note: This could be removed with appropriate canonicalization of the
8058     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8059     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8060     // from implementing the canonicalization in visitFSUB.
8061     if (N0.getOpcode() == ISD::FP_EXTEND) {
8062       SDValue N00 = N0.getOperand(0);
8063       if (N00.getOpcode() == ISD::FNEG) {
8064         SDValue N000 = N00.getOperand(0);
8065         if (N000.getOpcode() == ISD::FMUL) {
8066           return DAG.getNode(ISD::FNEG, SL, VT,
8067                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8068                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8069                                                      N000.getOperand(0)),
8070                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8071                                                      N000.getOperand(1)),
8072                                          N1));
8073         }
8074       }
8075     }
8076 
8077     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8078     //   -> (fneg (fma (fpext x)), (fpext y), z)
8079     // Note: This could be removed with appropriate canonicalization of the
8080     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8081     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8082     // from implementing the canonicalization in visitFSUB.
8083     if (N0.getOpcode() == ISD::FNEG) {
8084       SDValue N00 = N0.getOperand(0);
8085       if (N00.getOpcode() == ISD::FP_EXTEND) {
8086         SDValue N000 = N00.getOperand(0);
8087         if (N000.getOpcode() == ISD::FMUL) {
8088           return DAG.getNode(ISD::FNEG, SL, VT,
8089                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8090                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8091                                                      N000.getOperand(0)),
8092                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8093                                                      N000.getOperand(1)),
8094                                          N1));
8095         }
8096       }
8097     }
8098 
8099   }
8100 
8101   // More folding opportunities when target permits.
8102   if ((AllowFusion || HasFMAD) && Aggressive) {
8103     // fold (fsub (fma x, y, (fmul u, v)), z)
8104     //   -> (fma x, y (fma u, v, (fneg z)))
8105     if (N0.getOpcode() == PreferredFusedOpcode &&
8106         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8107       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8108                          N0.getOperand(0), N0.getOperand(1),
8109                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8110                                      N0.getOperand(2).getOperand(0),
8111                                      N0.getOperand(2).getOperand(1),
8112                                      DAG.getNode(ISD::FNEG, SL, VT,
8113                                                  N1)));
8114     }
8115 
8116     // fold (fsub x, (fma y, z, (fmul u, v)))
8117     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8118     if (N1.getOpcode() == PreferredFusedOpcode &&
8119         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8120       SDValue N20 = N1.getOperand(2).getOperand(0);
8121       SDValue N21 = N1.getOperand(2).getOperand(1);
8122       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8123                          DAG.getNode(ISD::FNEG, SL, VT,
8124                                      N1.getOperand(0)),
8125                          N1.getOperand(1),
8126                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8127                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8128 
8129                                      N21, N0));
8130     }
8131 
8132     if (AllowFusion && LookThroughFPExt) {
8133       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8134       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8135       if (N0.getOpcode() == PreferredFusedOpcode) {
8136         SDValue N02 = N0.getOperand(2);
8137         if (N02.getOpcode() == ISD::FP_EXTEND) {
8138           SDValue N020 = N02.getOperand(0);
8139           if (N020.getOpcode() == ISD::FMUL)
8140             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8141                                N0.getOperand(0), N0.getOperand(1),
8142                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8143                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8144                                                        N020.getOperand(0)),
8145                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8146                                                        N020.getOperand(1)),
8147                                            DAG.getNode(ISD::FNEG, SL, VT,
8148                                                        N1)));
8149         }
8150       }
8151 
8152       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8153       //   -> (fma (fpext x), (fpext y),
8154       //           (fma (fpext u), (fpext v), (fneg z)))
8155       // FIXME: This turns two single-precision and one double-precision
8156       // operation into two double-precision operations, which might not be
8157       // interesting for all targets, especially GPUs.
8158       if (N0.getOpcode() == ISD::FP_EXTEND) {
8159         SDValue N00 = N0.getOperand(0);
8160         if (N00.getOpcode() == PreferredFusedOpcode) {
8161           SDValue N002 = N00.getOperand(2);
8162           if (N002.getOpcode() == ISD::FMUL)
8163             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8164                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8165                                            N00.getOperand(0)),
8166                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8167                                            N00.getOperand(1)),
8168                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8169                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8170                                                        N002.getOperand(0)),
8171                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8172                                                        N002.getOperand(1)),
8173                                            DAG.getNode(ISD::FNEG, SL, VT,
8174                                                        N1)));
8175         }
8176       }
8177 
8178       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8179       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8180       if (N1.getOpcode() == PreferredFusedOpcode &&
8181         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8182         SDValue N120 = N1.getOperand(2).getOperand(0);
8183         if (N120.getOpcode() == ISD::FMUL) {
8184           SDValue N1200 = N120.getOperand(0);
8185           SDValue N1201 = N120.getOperand(1);
8186           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8187                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8188                              N1.getOperand(1),
8189                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8190                                          DAG.getNode(ISD::FNEG, SL, VT,
8191                                              DAG.getNode(ISD::FP_EXTEND, SL,
8192                                                          VT, N1200)),
8193                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8194                                                      N1201),
8195                                          N0));
8196         }
8197       }
8198 
8199       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8200       //   -> (fma (fneg (fpext y)), (fpext z),
8201       //           (fma (fneg (fpext u)), (fpext v), x))
8202       // FIXME: This turns two single-precision and one double-precision
8203       // operation into two double-precision operations, which might not be
8204       // interesting for all targets, especially GPUs.
8205       if (N1.getOpcode() == ISD::FP_EXTEND &&
8206         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8207         SDValue N100 = N1.getOperand(0).getOperand(0);
8208         SDValue N101 = N1.getOperand(0).getOperand(1);
8209         SDValue N102 = N1.getOperand(0).getOperand(2);
8210         if (N102.getOpcode() == ISD::FMUL) {
8211           SDValue N1020 = N102.getOperand(0);
8212           SDValue N1021 = N102.getOperand(1);
8213           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8214                              DAG.getNode(ISD::FNEG, SL, VT,
8215                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8216                                                      N100)),
8217                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8218                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8219                                          DAG.getNode(ISD::FNEG, SL, VT,
8220                                              DAG.getNode(ISD::FP_EXTEND, SL,
8221                                                          VT, N1020)),
8222                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8223                                                      N1021),
8224                                          N0));
8225         }
8226       }
8227     }
8228   }
8229 
8230   return SDValue();
8231 }
8232 
8233 /// Try to perform FMA combining on a given FMUL node.
8234 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8235   SDValue N0 = N->getOperand(0);
8236   SDValue N1 = N->getOperand(1);
8237   EVT VT = N->getValueType(0);
8238   SDLoc SL(N);
8239 
8240   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8241 
8242   const TargetOptions &Options = DAG.getTarget().Options;
8243   bool AllowFusion =
8244       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8245 
8246   // Floating-point multiply-add with intermediate rounding.
8247   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8248 
8249   // Floating-point multiply-add without intermediate rounding.
8250   bool HasFMA =
8251       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8252       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8253 
8254   // No valid opcode, do not combine.
8255   if (!HasFMAD && !HasFMA)
8256     return SDValue();
8257 
8258   // Always prefer FMAD to FMA for precision.
8259   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8260   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8261 
8262   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8263   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8264   auto FuseFADD = [&](SDValue X, SDValue Y) {
8265     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8266       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8267       if (XC1 && XC1->isExactlyValue(+1.0))
8268         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8269       if (XC1 && XC1->isExactlyValue(-1.0))
8270         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8271                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8272     }
8273     return SDValue();
8274   };
8275 
8276   if (SDValue FMA = FuseFADD(N0, N1))
8277     return FMA;
8278   if (SDValue FMA = FuseFADD(N1, N0))
8279     return FMA;
8280 
8281   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8282   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8283   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8284   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8285   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8286     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8287       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8288       if (XC0 && XC0->isExactlyValue(+1.0))
8289         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8290                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8291                            Y);
8292       if (XC0 && XC0->isExactlyValue(-1.0))
8293         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8294                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8295                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8296 
8297       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8298       if (XC1 && XC1->isExactlyValue(+1.0))
8299         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8300                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8301       if (XC1 && XC1->isExactlyValue(-1.0))
8302         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8303     }
8304     return SDValue();
8305   };
8306 
8307   if (SDValue FMA = FuseFSUB(N0, N1))
8308     return FMA;
8309   if (SDValue FMA = FuseFSUB(N1, N0))
8310     return FMA;
8311 
8312   return SDValue();
8313 }
8314 
8315 SDValue DAGCombiner::visitFADD(SDNode *N) {
8316   SDValue N0 = N->getOperand(0);
8317   SDValue N1 = N->getOperand(1);
8318   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8319   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8320   EVT VT = N->getValueType(0);
8321   SDLoc DL(N);
8322   const TargetOptions &Options = DAG.getTarget().Options;
8323   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8324 
8325   // fold vector ops
8326   if (VT.isVector())
8327     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8328       return FoldedVOp;
8329 
8330   // fold (fadd c1, c2) -> c1 + c2
8331   if (N0CFP && N1CFP)
8332     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8333 
8334   // canonicalize constant to RHS
8335   if (N0CFP && !N1CFP)
8336     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8337 
8338   // fold (fadd A, (fneg B)) -> (fsub A, B)
8339   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8340       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8341     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8342                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8343 
8344   // fold (fadd (fneg A), B) -> (fsub B, A)
8345   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8346       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8347     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8348                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8349 
8350   // If 'unsafe math' is enabled, fold lots of things.
8351   if (Options.UnsafeFPMath) {
8352     // No FP constant should be created after legalization as Instruction
8353     // Selection pass has a hard time dealing with FP constants.
8354     bool AllowNewConst = (Level < AfterLegalizeDAG);
8355 
8356     // fold (fadd A, 0) -> A
8357     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8358       if (N1C->isZero())
8359         return N0;
8360 
8361     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8362     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8363         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8364       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8365                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8366                                      Flags),
8367                          Flags);
8368 
8369     // If allowed, fold (fadd (fneg x), x) -> 0.0
8370     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8371       return DAG.getConstantFP(0.0, DL, VT);
8372 
8373     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8374     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8375       return DAG.getConstantFP(0.0, DL, VT);
8376 
8377     // We can fold chains of FADD's of the same value into multiplications.
8378     // This transform is not safe in general because we are reducing the number
8379     // of rounding steps.
8380     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8381       if (N0.getOpcode() == ISD::FMUL) {
8382         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8383         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8384 
8385         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8386         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8387           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8388                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8389           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8390         }
8391 
8392         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8393         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8394             N1.getOperand(0) == N1.getOperand(1) &&
8395             N0.getOperand(0) == N1.getOperand(0)) {
8396           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8397                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8398           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8399         }
8400       }
8401 
8402       if (N1.getOpcode() == ISD::FMUL) {
8403         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8404         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8405 
8406         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8407         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8408           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8409                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8410           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8411         }
8412 
8413         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8414         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8415             N0.getOperand(0) == N0.getOperand(1) &&
8416             N1.getOperand(0) == N0.getOperand(0)) {
8417           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8418                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8419           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8420         }
8421       }
8422 
8423       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8424         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8425         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8426         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8427             (N0.getOperand(0) == N1)) {
8428           return DAG.getNode(ISD::FMUL, DL, VT,
8429                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8430         }
8431       }
8432 
8433       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8434         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8435         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8436         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8437             N1.getOperand(0) == N0) {
8438           return DAG.getNode(ISD::FMUL, DL, VT,
8439                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8440         }
8441       }
8442 
8443       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8444       if (AllowNewConst &&
8445           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8446           N0.getOperand(0) == N0.getOperand(1) &&
8447           N1.getOperand(0) == N1.getOperand(1) &&
8448           N0.getOperand(0) == N1.getOperand(0)) {
8449         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8450                            DAG.getConstantFP(4.0, DL, VT), Flags);
8451       }
8452     }
8453   } // enable-unsafe-fp-math
8454 
8455   // FADD -> FMA combines:
8456   if (SDValue Fused = visitFADDForFMACombine(N)) {
8457     AddToWorklist(Fused.getNode());
8458     return Fused;
8459   }
8460   return SDValue();
8461 }
8462 
8463 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8464   SDValue N0 = N->getOperand(0);
8465   SDValue N1 = N->getOperand(1);
8466   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8467   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8468   EVT VT = N->getValueType(0);
8469   SDLoc dl(N);
8470   const TargetOptions &Options = DAG.getTarget().Options;
8471   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8472 
8473   // fold vector ops
8474   if (VT.isVector())
8475     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8476       return FoldedVOp;
8477 
8478   // fold (fsub c1, c2) -> c1-c2
8479   if (N0CFP && N1CFP)
8480     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8481 
8482   // fold (fsub A, (fneg B)) -> (fadd A, B)
8483   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8484     return DAG.getNode(ISD::FADD, dl, VT, N0,
8485                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8486 
8487   // If 'unsafe math' is enabled, fold lots of things.
8488   if (Options.UnsafeFPMath) {
8489     // (fsub A, 0) -> A
8490     if (N1CFP && N1CFP->isZero())
8491       return N0;
8492 
8493     // (fsub 0, B) -> -B
8494     if (N0CFP && N0CFP->isZero()) {
8495       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8496         return GetNegatedExpression(N1, DAG, LegalOperations);
8497       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8498         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8499     }
8500 
8501     // (fsub x, x) -> 0.0
8502     if (N0 == N1)
8503       return DAG.getConstantFP(0.0f, dl, VT);
8504 
8505     // (fsub x, (fadd x, y)) -> (fneg y)
8506     // (fsub x, (fadd y, x)) -> (fneg y)
8507     if (N1.getOpcode() == ISD::FADD) {
8508       SDValue N10 = N1->getOperand(0);
8509       SDValue N11 = N1->getOperand(1);
8510 
8511       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8512         return GetNegatedExpression(N11, DAG, LegalOperations);
8513 
8514       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8515         return GetNegatedExpression(N10, DAG, LegalOperations);
8516     }
8517   }
8518 
8519   // FSUB -> FMA combines:
8520   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8521     AddToWorklist(Fused.getNode());
8522     return Fused;
8523   }
8524 
8525   return SDValue();
8526 }
8527 
8528 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8529   SDValue N0 = N->getOperand(0);
8530   SDValue N1 = N->getOperand(1);
8531   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8532   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8533   EVT VT = N->getValueType(0);
8534   SDLoc DL(N);
8535   const TargetOptions &Options = DAG.getTarget().Options;
8536   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8537 
8538   // fold vector ops
8539   if (VT.isVector()) {
8540     // This just handles C1 * C2 for vectors. Other vector folds are below.
8541     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8542       return FoldedVOp;
8543   }
8544 
8545   // fold (fmul c1, c2) -> c1*c2
8546   if (N0CFP && N1CFP)
8547     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8548 
8549   // canonicalize constant to RHS
8550   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8551      !isConstantFPBuildVectorOrConstantFP(N1))
8552     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8553 
8554   // fold (fmul A, 1.0) -> A
8555   if (N1CFP && N1CFP->isExactlyValue(1.0))
8556     return N0;
8557 
8558   if (Options.UnsafeFPMath) {
8559     // fold (fmul A, 0) -> 0
8560     if (N1CFP && N1CFP->isZero())
8561       return N1;
8562 
8563     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8564     if (N0.getOpcode() == ISD::FMUL) {
8565       // Fold scalars or any vector constants (not just splats).
8566       // This fold is done in general by InstCombine, but extra fmul insts
8567       // may have been generated during lowering.
8568       SDValue N00 = N0.getOperand(0);
8569       SDValue N01 = N0.getOperand(1);
8570       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8571       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8572       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8573 
8574       // Check 1: Make sure that the first operand of the inner multiply is NOT
8575       // a constant. Otherwise, we may induce infinite looping.
8576       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8577         // Check 2: Make sure that the second operand of the inner multiply and
8578         // the second operand of the outer multiply are constants.
8579         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8580             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8581           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8582           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8583         }
8584       }
8585     }
8586 
8587     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8588     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8589     // during an early run of DAGCombiner can prevent folding with fmuls
8590     // inserted during lowering.
8591     if (N0.getOpcode() == ISD::FADD &&
8592         (N0.getOperand(0) == N0.getOperand(1)) &&
8593         N0.hasOneUse()) {
8594       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8595       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8596       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8597     }
8598   }
8599 
8600   // fold (fmul X, 2.0) -> (fadd X, X)
8601   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8602     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8603 
8604   // fold (fmul X, -1.0) -> (fneg X)
8605   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8606     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8607       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8608 
8609   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8610   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8611     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8612       // Both can be negated for free, check to see if at least one is cheaper
8613       // negated.
8614       if (LHSNeg == 2 || RHSNeg == 2)
8615         return DAG.getNode(ISD::FMUL, DL, VT,
8616                            GetNegatedExpression(N0, DAG, LegalOperations),
8617                            GetNegatedExpression(N1, DAG, LegalOperations),
8618                            Flags);
8619     }
8620   }
8621 
8622   // FMUL -> FMA combines:
8623   if (SDValue Fused = visitFMULForFMACombine(N)) {
8624     AddToWorklist(Fused.getNode());
8625     return Fused;
8626   }
8627 
8628   return SDValue();
8629 }
8630 
8631 SDValue DAGCombiner::visitFMA(SDNode *N) {
8632   SDValue N0 = N->getOperand(0);
8633   SDValue N1 = N->getOperand(1);
8634   SDValue N2 = N->getOperand(2);
8635   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8636   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8637   EVT VT = N->getValueType(0);
8638   SDLoc dl(N);
8639   const TargetOptions &Options = DAG.getTarget().Options;
8640 
8641   // Constant fold FMA.
8642   if (isa<ConstantFPSDNode>(N0) &&
8643       isa<ConstantFPSDNode>(N1) &&
8644       isa<ConstantFPSDNode>(N2)) {
8645     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8646   }
8647 
8648   if (Options.UnsafeFPMath) {
8649     if (N0CFP && N0CFP->isZero())
8650       return N2;
8651     if (N1CFP && N1CFP->isZero())
8652       return N2;
8653   }
8654   // TODO: The FMA node should have flags that propagate to these nodes.
8655   if (N0CFP && N0CFP->isExactlyValue(1.0))
8656     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8657   if (N1CFP && N1CFP->isExactlyValue(1.0))
8658     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8659 
8660   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8661   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8662      !isConstantFPBuildVectorOrConstantFP(N1))
8663     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8664 
8665   // TODO: FMA nodes should have flags that propagate to the created nodes.
8666   // For now, create a Flags object for use with all unsafe math transforms.
8667   SDNodeFlags Flags;
8668   Flags.setUnsafeAlgebra(true);
8669 
8670   if (Options.UnsafeFPMath) {
8671     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8672     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8673         isConstantFPBuildVectorOrConstantFP(N1) &&
8674         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8675       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8676                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8677                                      &Flags), &Flags);
8678     }
8679 
8680     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8681     if (N0.getOpcode() == ISD::FMUL &&
8682         isConstantFPBuildVectorOrConstantFP(N1) &&
8683         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8684       return DAG.getNode(ISD::FMA, dl, VT,
8685                          N0.getOperand(0),
8686                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8687                                      &Flags),
8688                          N2);
8689     }
8690   }
8691 
8692   // (fma x, 1, y) -> (fadd x, y)
8693   // (fma x, -1, y) -> (fadd (fneg x), y)
8694   if (N1CFP) {
8695     if (N1CFP->isExactlyValue(1.0))
8696       // TODO: The FMA node should have flags that propagate to this node.
8697       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8698 
8699     if (N1CFP->isExactlyValue(-1.0) &&
8700         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8701       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8702       AddToWorklist(RHSNeg.getNode());
8703       // TODO: The FMA node should have flags that propagate to this node.
8704       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8705     }
8706   }
8707 
8708   if (Options.UnsafeFPMath) {
8709     // (fma x, c, x) -> (fmul x, (c+1))
8710     if (N1CFP && N0 == N2) {
8711     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8712                          DAG.getNode(ISD::FADD, dl, VT,
8713                                      N1, DAG.getConstantFP(1.0, dl, VT),
8714                                      &Flags), &Flags);
8715     }
8716 
8717     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8718     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8719       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8720                          DAG.getNode(ISD::FADD, dl, VT,
8721                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8722                                      &Flags), &Flags);
8723     }
8724   }
8725 
8726   return SDValue();
8727 }
8728 
8729 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8730 // reciprocal.
8731 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8732 // Notice that this is not always beneficial. One reason is different target
8733 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8734 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8735 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8736 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8737   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8738   const SDNodeFlags *Flags = N->getFlags();
8739   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8740     return SDValue();
8741 
8742   // Skip if current node is a reciprocal.
8743   SDValue N0 = N->getOperand(0);
8744   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8745   if (N0CFP && N0CFP->isExactlyValue(1.0))
8746     return SDValue();
8747 
8748   // Exit early if the target does not want this transform or if there can't
8749   // possibly be enough uses of the divisor to make the transform worthwhile.
8750   SDValue N1 = N->getOperand(1);
8751   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8752   if (!MinUses || N1->use_size() < MinUses)
8753     return SDValue();
8754 
8755   // Find all FDIV users of the same divisor.
8756   // Use a set because duplicates may be present in the user list.
8757   SetVector<SDNode *> Users;
8758   for (auto *U : N1->uses()) {
8759     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8760       // This division is eligible for optimization only if global unsafe math
8761       // is enabled or if this division allows reciprocal formation.
8762       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8763         Users.insert(U);
8764     }
8765   }
8766 
8767   // Now that we have the actual number of divisor uses, make sure it meets
8768   // the minimum threshold specified by the target.
8769   if (Users.size() < MinUses)
8770     return SDValue();
8771 
8772   EVT VT = N->getValueType(0);
8773   SDLoc DL(N);
8774   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8775   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8776 
8777   // Dividend / Divisor -> Dividend * Reciprocal
8778   for (auto *U : Users) {
8779     SDValue Dividend = U->getOperand(0);
8780     if (Dividend != FPOne) {
8781       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8782                                     Reciprocal, Flags);
8783       CombineTo(U, NewNode);
8784     } else if (U != Reciprocal.getNode()) {
8785       // In the absence of fast-math-flags, this user node is always the
8786       // same node as Reciprocal, but with FMF they may be different nodes.
8787       CombineTo(U, Reciprocal);
8788     }
8789   }
8790   return SDValue(N, 0);  // N was replaced.
8791 }
8792 
8793 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8794   SDValue N0 = N->getOperand(0);
8795   SDValue N1 = N->getOperand(1);
8796   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8797   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8798   EVT VT = N->getValueType(0);
8799   SDLoc DL(N);
8800   const TargetOptions &Options = DAG.getTarget().Options;
8801   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8802 
8803   // fold vector ops
8804   if (VT.isVector())
8805     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8806       return FoldedVOp;
8807 
8808   // fold (fdiv c1, c2) -> c1/c2
8809   if (N0CFP && N1CFP)
8810     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8811 
8812   if (Options.UnsafeFPMath) {
8813     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8814     if (N1CFP) {
8815       // Compute the reciprocal 1.0 / c2.
8816       const APFloat &N1APF = N1CFP->getValueAPF();
8817       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8818       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8819       // Only do the transform if the reciprocal is a legal fp immediate that
8820       // isn't too nasty (eg NaN, denormal, ...).
8821       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8822           (!LegalOperations ||
8823            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8824            // backend)... we should handle this gracefully after Legalize.
8825            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8826            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8827            TLI.isFPImmLegal(Recip, VT)))
8828         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8829                            DAG.getConstantFP(Recip, DL, VT), Flags);
8830     }
8831 
8832     // If this FDIV is part of a reciprocal square root, it may be folded
8833     // into a target-specific square root estimate instruction.
8834     if (N1.getOpcode() == ISD::FSQRT) {
8835       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8836         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8837       }
8838     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8839                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8840       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8841                                           Flags)) {
8842         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8843         AddToWorklist(RV.getNode());
8844         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8845       }
8846     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8847                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8848       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8849                                           Flags)) {
8850         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8851         AddToWorklist(RV.getNode());
8852         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8853       }
8854     } else if (N1.getOpcode() == ISD::FMUL) {
8855       // Look through an FMUL. Even though this won't remove the FDIV directly,
8856       // it's still worthwhile to get rid of the FSQRT if possible.
8857       SDValue SqrtOp;
8858       SDValue OtherOp;
8859       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8860         SqrtOp = N1.getOperand(0);
8861         OtherOp = N1.getOperand(1);
8862       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8863         SqrtOp = N1.getOperand(1);
8864         OtherOp = N1.getOperand(0);
8865       }
8866       if (SqrtOp.getNode()) {
8867         // We found a FSQRT, so try to make this fold:
8868         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8869         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8870           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8871           AddToWorklist(RV.getNode());
8872           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8873         }
8874       }
8875     }
8876 
8877     // Fold into a reciprocal estimate and multiply instead of a real divide.
8878     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8879       AddToWorklist(RV.getNode());
8880       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8881     }
8882   }
8883 
8884   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8885   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8886     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8887       // Both can be negated for free, check to see if at least one is cheaper
8888       // negated.
8889       if (LHSNeg == 2 || RHSNeg == 2)
8890         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8891                            GetNegatedExpression(N0, DAG, LegalOperations),
8892                            GetNegatedExpression(N1, DAG, LegalOperations),
8893                            Flags);
8894     }
8895   }
8896 
8897   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8898     return CombineRepeatedDivisors;
8899 
8900   return SDValue();
8901 }
8902 
8903 SDValue DAGCombiner::visitFREM(SDNode *N) {
8904   SDValue N0 = N->getOperand(0);
8905   SDValue N1 = N->getOperand(1);
8906   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8907   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8908   EVT VT = N->getValueType(0);
8909 
8910   // fold (frem c1, c2) -> fmod(c1,c2)
8911   if (N0CFP && N1CFP)
8912     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8913                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8914 
8915   return SDValue();
8916 }
8917 
8918 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8919   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8920     return SDValue();
8921 
8922   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8923   // For now, create a Flags object for use with all unsafe math transforms.
8924   SDNodeFlags Flags;
8925   Flags.setUnsafeAlgebra(true);
8926   return buildSqrtEstimate(N->getOperand(0), &Flags);
8927 }
8928 
8929 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8930 /// copysign(x, fp_round(y)) -> copysign(x, y)
8931 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8932   SDValue N1 = N->getOperand(1);
8933   if ((N1.getOpcode() == ISD::FP_EXTEND ||
8934        N1.getOpcode() == ISD::FP_ROUND)) {
8935     // Do not optimize out type conversion of f128 type yet.
8936     // For some targets like x86_64, configuration is changed to keep one f128
8937     // value in one SSE register, but instruction selection cannot handle
8938     // FCOPYSIGN on SSE registers yet.
8939     EVT N1VT = N1->getValueType(0);
8940     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8941     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8942   }
8943   return false;
8944 }
8945 
8946 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8947   SDValue N0 = N->getOperand(0);
8948   SDValue N1 = N->getOperand(1);
8949   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8950   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8951   EVT VT = N->getValueType(0);
8952 
8953   if (N0CFP && N1CFP)  // Constant fold
8954     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8955 
8956   if (N1CFP) {
8957     const APFloat& V = N1CFP->getValueAPF();
8958     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8959     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8960     if (!V.isNegative()) {
8961       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8962         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8963     } else {
8964       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8965         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8966                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8967     }
8968   }
8969 
8970   // copysign(fabs(x), y) -> copysign(x, y)
8971   // copysign(fneg(x), y) -> copysign(x, y)
8972   // copysign(copysign(x,z), y) -> copysign(x, y)
8973   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8974       N0.getOpcode() == ISD::FCOPYSIGN)
8975     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8976                        N0.getOperand(0), N1);
8977 
8978   // copysign(x, abs(y)) -> abs(x)
8979   if (N1.getOpcode() == ISD::FABS)
8980     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8981 
8982   // copysign(x, copysign(y,z)) -> copysign(x, z)
8983   if (N1.getOpcode() == ISD::FCOPYSIGN)
8984     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8985                        N0, N1.getOperand(1));
8986 
8987   // copysign(x, fp_extend(y)) -> copysign(x, y)
8988   // copysign(x, fp_round(y)) -> copysign(x, y)
8989   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8990     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8991                        N0, N1.getOperand(0));
8992 
8993   return SDValue();
8994 }
8995 
8996 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8997   SDValue N0 = N->getOperand(0);
8998   EVT VT = N->getValueType(0);
8999   EVT OpVT = N0.getValueType();
9000 
9001   // fold (sint_to_fp c1) -> c1fp
9002   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9003       // ...but only if the target supports immediate floating-point values
9004       (!LegalOperations ||
9005        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9006     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9007 
9008   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9009   // but UINT_TO_FP is legal on this target, try to convert.
9010   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9011       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9012     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9013     if (DAG.SignBitIsZero(N0))
9014       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9015   }
9016 
9017   // The next optimizations are desirable only if SELECT_CC can be lowered.
9018   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9019     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9020     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9021         !VT.isVector() &&
9022         (!LegalOperations ||
9023          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9024       SDLoc DL(N);
9025       SDValue Ops[] =
9026         { N0.getOperand(0), N0.getOperand(1),
9027           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9028           N0.getOperand(2) };
9029       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9030     }
9031 
9032     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9033     //      (select_cc x, y, 1.0, 0.0,, cc)
9034     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9035         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9036         (!LegalOperations ||
9037          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9038       SDLoc DL(N);
9039       SDValue Ops[] =
9040         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9041           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9042           N0.getOperand(0).getOperand(2) };
9043       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9044     }
9045   }
9046 
9047   return SDValue();
9048 }
9049 
9050 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9051   SDValue N0 = N->getOperand(0);
9052   EVT VT = N->getValueType(0);
9053   EVT OpVT = N0.getValueType();
9054 
9055   // fold (uint_to_fp c1) -> c1fp
9056   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9057       // ...but only if the target supports immediate floating-point values
9058       (!LegalOperations ||
9059        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9060     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9061 
9062   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9063   // but SINT_TO_FP is legal on this target, try to convert.
9064   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9065       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9066     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9067     if (DAG.SignBitIsZero(N0))
9068       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9069   }
9070 
9071   // The next optimizations are desirable only if SELECT_CC can be lowered.
9072   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9073     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9074 
9075     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9076         (!LegalOperations ||
9077          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9078       SDLoc DL(N);
9079       SDValue Ops[] =
9080         { N0.getOperand(0), N0.getOperand(1),
9081           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9082           N0.getOperand(2) };
9083       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9084     }
9085   }
9086 
9087   return SDValue();
9088 }
9089 
9090 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9091 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9092   SDValue N0 = N->getOperand(0);
9093   EVT VT = N->getValueType(0);
9094 
9095   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9096     return SDValue();
9097 
9098   SDValue Src = N0.getOperand(0);
9099   EVT SrcVT = Src.getValueType();
9100   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9101   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9102 
9103   // We can safely assume the conversion won't overflow the output range,
9104   // because (for example) (uint8_t)18293.f is undefined behavior.
9105 
9106   // Since we can assume the conversion won't overflow, our decision as to
9107   // whether the input will fit in the float should depend on the minimum
9108   // of the input range and output range.
9109 
9110   // This means this is also safe for a signed input and unsigned output, since
9111   // a negative input would lead to undefined behavior.
9112   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9113   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9114   unsigned ActualSize = std::min(InputSize, OutputSize);
9115   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9116 
9117   // We can only fold away the float conversion if the input range can be
9118   // represented exactly in the float range.
9119   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9120     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9121       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9122                                                        : ISD::ZERO_EXTEND;
9123       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9124     }
9125     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9126       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9127     return DAG.getBitcast(VT, Src);
9128   }
9129   return SDValue();
9130 }
9131 
9132 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9133   SDValue N0 = N->getOperand(0);
9134   EVT VT = N->getValueType(0);
9135 
9136   // fold (fp_to_sint c1fp) -> c1
9137   if (isConstantFPBuildVectorOrConstantFP(N0))
9138     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9139 
9140   return FoldIntToFPToInt(N, DAG);
9141 }
9142 
9143 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9144   SDValue N0 = N->getOperand(0);
9145   EVT VT = N->getValueType(0);
9146 
9147   // fold (fp_to_uint c1fp) -> c1
9148   if (isConstantFPBuildVectorOrConstantFP(N0))
9149     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9150 
9151   return FoldIntToFPToInt(N, DAG);
9152 }
9153 
9154 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9155   SDValue N0 = N->getOperand(0);
9156   SDValue N1 = N->getOperand(1);
9157   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9158   EVT VT = N->getValueType(0);
9159 
9160   // fold (fp_round c1fp) -> c1fp
9161   if (N0CFP)
9162     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9163 
9164   // fold (fp_round (fp_extend x)) -> x
9165   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9166     return N0.getOperand(0);
9167 
9168   // fold (fp_round (fp_round x)) -> (fp_round x)
9169   if (N0.getOpcode() == ISD::FP_ROUND) {
9170     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9171     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9172 
9173     // Skip this folding if it results in an fp_round from f80 to f16.
9174     //
9175     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9176     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9177     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9178     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9179     // x86.
9180     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9181       return SDValue();
9182 
9183     // If the first fp_round isn't a value preserving truncation, it might
9184     // introduce a tie in the second fp_round, that wouldn't occur in the
9185     // single-step fp_round we want to fold to.
9186     // In other words, double rounding isn't the same as rounding.
9187     // Also, this is a value preserving truncation iff both fp_round's are.
9188     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9189       SDLoc DL(N);
9190       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9191                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9192     }
9193   }
9194 
9195   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9196   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9197     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9198                               N0.getOperand(0), N1);
9199     AddToWorklist(Tmp.getNode());
9200     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9201                        Tmp, N0.getOperand(1));
9202   }
9203 
9204   return SDValue();
9205 }
9206 
9207 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9208   SDValue N0 = N->getOperand(0);
9209   EVT VT = N->getValueType(0);
9210   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9211   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9212 
9213   // fold (fp_round_inreg c1fp) -> c1fp
9214   if (N0CFP && isTypeLegal(EVT)) {
9215     SDLoc DL(N);
9216     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9217     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9218   }
9219 
9220   return SDValue();
9221 }
9222 
9223 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9224   SDValue N0 = N->getOperand(0);
9225   EVT VT = N->getValueType(0);
9226 
9227   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9228   if (N->hasOneUse() &&
9229       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9230     return SDValue();
9231 
9232   // fold (fp_extend c1fp) -> c1fp
9233   if (isConstantFPBuildVectorOrConstantFP(N0))
9234     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9235 
9236   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9237   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9238       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9239     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9240 
9241   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9242   // value of X.
9243   if (N0.getOpcode() == ISD::FP_ROUND
9244       && N0.getNode()->getConstantOperandVal(1) == 1) {
9245     SDValue In = N0.getOperand(0);
9246     if (In.getValueType() == VT) return In;
9247     if (VT.bitsLT(In.getValueType()))
9248       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9249                          In, N0.getOperand(1));
9250     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9251   }
9252 
9253   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9254   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9255        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9256     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9257     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9258                                      LN0->getChain(),
9259                                      LN0->getBasePtr(), N0.getValueType(),
9260                                      LN0->getMemOperand());
9261     CombineTo(N, ExtLoad);
9262     CombineTo(N0.getNode(),
9263               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9264                           N0.getValueType(), ExtLoad,
9265                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9266               ExtLoad.getValue(1));
9267     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9268   }
9269 
9270   return SDValue();
9271 }
9272 
9273 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9274   SDValue N0 = N->getOperand(0);
9275   EVT VT = N->getValueType(0);
9276 
9277   // fold (fceil c1) -> fceil(c1)
9278   if (isConstantFPBuildVectorOrConstantFP(N0))
9279     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9280 
9281   return SDValue();
9282 }
9283 
9284 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9285   SDValue N0 = N->getOperand(0);
9286   EVT VT = N->getValueType(0);
9287 
9288   // fold (ftrunc c1) -> ftrunc(c1)
9289   if (isConstantFPBuildVectorOrConstantFP(N0))
9290     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9291 
9292   return SDValue();
9293 }
9294 
9295 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9296   SDValue N0 = N->getOperand(0);
9297   EVT VT = N->getValueType(0);
9298 
9299   // fold (ffloor c1) -> ffloor(c1)
9300   if (isConstantFPBuildVectorOrConstantFP(N0))
9301     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9302 
9303   return SDValue();
9304 }
9305 
9306 // FIXME: FNEG and FABS have a lot in common; refactor.
9307 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9308   SDValue N0 = N->getOperand(0);
9309   EVT VT = N->getValueType(0);
9310 
9311   // Constant fold FNEG.
9312   if (isConstantFPBuildVectorOrConstantFP(N0))
9313     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9314 
9315   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9316                          &DAG.getTarget().Options))
9317     return GetNegatedExpression(N0, DAG, LegalOperations);
9318 
9319   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9320   // constant pool values.
9321   if (!TLI.isFNegFree(VT) &&
9322       N0.getOpcode() == ISD::BITCAST &&
9323       N0.getNode()->hasOneUse()) {
9324     SDValue Int = N0.getOperand(0);
9325     EVT IntVT = Int.getValueType();
9326     if (IntVT.isInteger() && !IntVT.isVector()) {
9327       APInt SignMask;
9328       if (N0.getValueType().isVector()) {
9329         // For a vector, get a mask such as 0x80... per scalar element
9330         // and splat it.
9331         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9332         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9333       } else {
9334         // For a scalar, just generate 0x80...
9335         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9336       }
9337       SDLoc DL0(N0);
9338       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9339                         DAG.getConstant(SignMask, DL0, IntVT));
9340       AddToWorklist(Int.getNode());
9341       return DAG.getBitcast(VT, Int);
9342     }
9343   }
9344 
9345   // (fneg (fmul c, x)) -> (fmul -c, x)
9346   if (N0.getOpcode() == ISD::FMUL &&
9347       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9348     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9349     if (CFP1) {
9350       APFloat CVal = CFP1->getValueAPF();
9351       CVal.changeSign();
9352       if (Level >= AfterLegalizeDAG &&
9353           (TLI.isFPImmLegal(CVal, VT) ||
9354            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9355         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9356                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9357                                        N0.getOperand(1)),
9358                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9359     }
9360   }
9361 
9362   return SDValue();
9363 }
9364 
9365 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9366   SDValue N0 = N->getOperand(0);
9367   SDValue N1 = N->getOperand(1);
9368   EVT VT = N->getValueType(0);
9369   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9370   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9371 
9372   if (N0CFP && N1CFP) {
9373     const APFloat &C0 = N0CFP->getValueAPF();
9374     const APFloat &C1 = N1CFP->getValueAPF();
9375     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9376   }
9377 
9378   // Canonicalize to constant on RHS.
9379   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9380      !isConstantFPBuildVectorOrConstantFP(N1))
9381     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9382 
9383   return SDValue();
9384 }
9385 
9386 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9387   SDValue N0 = N->getOperand(0);
9388   SDValue N1 = N->getOperand(1);
9389   EVT VT = N->getValueType(0);
9390   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9391   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9392 
9393   if (N0CFP && N1CFP) {
9394     const APFloat &C0 = N0CFP->getValueAPF();
9395     const APFloat &C1 = N1CFP->getValueAPF();
9396     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9397   }
9398 
9399   // Canonicalize to constant on RHS.
9400   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9401      !isConstantFPBuildVectorOrConstantFP(N1))
9402     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9403 
9404   return SDValue();
9405 }
9406 
9407 SDValue DAGCombiner::visitFABS(SDNode *N) {
9408   SDValue N0 = N->getOperand(0);
9409   EVT VT = N->getValueType(0);
9410 
9411   // fold (fabs c1) -> fabs(c1)
9412   if (isConstantFPBuildVectorOrConstantFP(N0))
9413     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9414 
9415   // fold (fabs (fabs x)) -> (fabs x)
9416   if (N0.getOpcode() == ISD::FABS)
9417     return N->getOperand(0);
9418 
9419   // fold (fabs (fneg x)) -> (fabs x)
9420   // fold (fabs (fcopysign x, y)) -> (fabs x)
9421   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9422     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9423 
9424   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9425   // constant pool values.
9426   if (!TLI.isFAbsFree(VT) &&
9427       N0.getOpcode() == ISD::BITCAST &&
9428       N0.getNode()->hasOneUse()) {
9429     SDValue Int = N0.getOperand(0);
9430     EVT IntVT = Int.getValueType();
9431     if (IntVT.isInteger() && !IntVT.isVector()) {
9432       APInt SignMask;
9433       if (N0.getValueType().isVector()) {
9434         // For a vector, get a mask such as 0x7f... per scalar element
9435         // and splat it.
9436         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9437         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9438       } else {
9439         // For a scalar, just generate 0x7f...
9440         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9441       }
9442       SDLoc DL(N0);
9443       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9444                         DAG.getConstant(SignMask, DL, IntVT));
9445       AddToWorklist(Int.getNode());
9446       return DAG.getBitcast(N->getValueType(0), Int);
9447     }
9448   }
9449 
9450   return SDValue();
9451 }
9452 
9453 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9454   SDValue Chain = N->getOperand(0);
9455   SDValue N1 = N->getOperand(1);
9456   SDValue N2 = N->getOperand(2);
9457 
9458   // If N is a constant we could fold this into a fallthrough or unconditional
9459   // branch. However that doesn't happen very often in normal code, because
9460   // Instcombine/SimplifyCFG should have handled the available opportunities.
9461   // If we did this folding here, it would be necessary to update the
9462   // MachineBasicBlock CFG, which is awkward.
9463 
9464   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9465   // on the target.
9466   if (N1.getOpcode() == ISD::SETCC &&
9467       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9468                                    N1.getOperand(0).getValueType())) {
9469     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9470                        Chain, N1.getOperand(2),
9471                        N1.getOperand(0), N1.getOperand(1), N2);
9472   }
9473 
9474   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9475       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9476        (N1.getOperand(0).hasOneUse() &&
9477         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9478     SDNode *Trunc = nullptr;
9479     if (N1.getOpcode() == ISD::TRUNCATE) {
9480       // Look pass the truncate.
9481       Trunc = N1.getNode();
9482       N1 = N1.getOperand(0);
9483     }
9484 
9485     // Match this pattern so that we can generate simpler code:
9486     //
9487     //   %a = ...
9488     //   %b = and i32 %a, 2
9489     //   %c = srl i32 %b, 1
9490     //   brcond i32 %c ...
9491     //
9492     // into
9493     //
9494     //   %a = ...
9495     //   %b = and i32 %a, 2
9496     //   %c = setcc eq %b, 0
9497     //   brcond %c ...
9498     //
9499     // This applies only when the AND constant value has one bit set and the
9500     // SRL constant is equal to the log2 of the AND constant. The back-end is
9501     // smart enough to convert the result into a TEST/JMP sequence.
9502     SDValue Op0 = N1.getOperand(0);
9503     SDValue Op1 = N1.getOperand(1);
9504 
9505     if (Op0.getOpcode() == ISD::AND &&
9506         Op1.getOpcode() == ISD::Constant) {
9507       SDValue AndOp1 = Op0.getOperand(1);
9508 
9509       if (AndOp1.getOpcode() == ISD::Constant) {
9510         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9511 
9512         if (AndConst.isPowerOf2() &&
9513             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9514           SDLoc DL(N);
9515           SDValue SetCC =
9516             DAG.getSetCC(DL,
9517                          getSetCCResultType(Op0.getValueType()),
9518                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9519                          ISD::SETNE);
9520 
9521           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9522                                           MVT::Other, Chain, SetCC, N2);
9523           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9524           // will convert it back to (X & C1) >> C2.
9525           CombineTo(N, NewBRCond, false);
9526           // Truncate is dead.
9527           if (Trunc)
9528             deleteAndRecombine(Trunc);
9529           // Replace the uses of SRL with SETCC
9530           WorklistRemover DeadNodes(*this);
9531           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9532           deleteAndRecombine(N1.getNode());
9533           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9534         }
9535       }
9536     }
9537 
9538     if (Trunc)
9539       // Restore N1 if the above transformation doesn't match.
9540       N1 = N->getOperand(1);
9541   }
9542 
9543   // Transform br(xor(x, y)) -> br(x != y)
9544   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9545   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9546     SDNode *TheXor = N1.getNode();
9547     SDValue Op0 = TheXor->getOperand(0);
9548     SDValue Op1 = TheXor->getOperand(1);
9549     if (Op0.getOpcode() == Op1.getOpcode()) {
9550       // Avoid missing important xor optimizations.
9551       if (SDValue Tmp = visitXOR(TheXor)) {
9552         if (Tmp.getNode() != TheXor) {
9553           DEBUG(dbgs() << "\nReplacing.8 ";
9554                 TheXor->dump(&DAG);
9555                 dbgs() << "\nWith: ";
9556                 Tmp.getNode()->dump(&DAG);
9557                 dbgs() << '\n');
9558           WorklistRemover DeadNodes(*this);
9559           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9560           deleteAndRecombine(TheXor);
9561           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9562                              MVT::Other, Chain, Tmp, N2);
9563         }
9564 
9565         // visitXOR has changed XOR's operands or replaced the XOR completely,
9566         // bail out.
9567         return SDValue(N, 0);
9568       }
9569     }
9570 
9571     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9572       bool Equal = false;
9573       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9574           Op0.getOpcode() == ISD::XOR) {
9575         TheXor = Op0.getNode();
9576         Equal = true;
9577       }
9578 
9579       EVT SetCCVT = N1.getValueType();
9580       if (LegalTypes)
9581         SetCCVT = getSetCCResultType(SetCCVT);
9582       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9583                                    SetCCVT,
9584                                    Op0, Op1,
9585                                    Equal ? ISD::SETEQ : ISD::SETNE);
9586       // Replace the uses of XOR with SETCC
9587       WorklistRemover DeadNodes(*this);
9588       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9589       deleteAndRecombine(N1.getNode());
9590       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9591                          MVT::Other, Chain, SetCC, N2);
9592     }
9593   }
9594 
9595   return SDValue();
9596 }
9597 
9598 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9599 //
9600 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9601   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9602   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9603 
9604   // If N is a constant we could fold this into a fallthrough or unconditional
9605   // branch. However that doesn't happen very often in normal code, because
9606   // Instcombine/SimplifyCFG should have handled the available opportunities.
9607   // If we did this folding here, it would be necessary to update the
9608   // MachineBasicBlock CFG, which is awkward.
9609 
9610   // Use SimplifySetCC to simplify SETCC's.
9611   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9612                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9613                                false);
9614   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9615 
9616   // fold to a simpler setcc
9617   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9618     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9619                        N->getOperand(0), Simp.getOperand(2),
9620                        Simp.getOperand(0), Simp.getOperand(1),
9621                        N->getOperand(4));
9622 
9623   return SDValue();
9624 }
9625 
9626 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9627 /// and that N may be folded in the load / store addressing mode.
9628 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9629                                     SelectionDAG &DAG,
9630                                     const TargetLowering &TLI) {
9631   EVT VT;
9632   unsigned AS;
9633 
9634   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9635     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9636       return false;
9637     VT = LD->getMemoryVT();
9638     AS = LD->getAddressSpace();
9639   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9640     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9641       return false;
9642     VT = ST->getMemoryVT();
9643     AS = ST->getAddressSpace();
9644   } else
9645     return false;
9646 
9647   TargetLowering::AddrMode AM;
9648   if (N->getOpcode() == ISD::ADD) {
9649     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9650     if (Offset)
9651       // [reg +/- imm]
9652       AM.BaseOffs = Offset->getSExtValue();
9653     else
9654       // [reg +/- reg]
9655       AM.Scale = 1;
9656   } else if (N->getOpcode() == ISD::SUB) {
9657     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9658     if (Offset)
9659       // [reg +/- imm]
9660       AM.BaseOffs = -Offset->getSExtValue();
9661     else
9662       // [reg +/- reg]
9663       AM.Scale = 1;
9664   } else
9665     return false;
9666 
9667   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9668                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9669 }
9670 
9671 /// Try turning a load/store into a pre-indexed load/store when the base
9672 /// pointer is an add or subtract and it has other uses besides the load/store.
9673 /// After the transformation, the new indexed load/store has effectively folded
9674 /// the add/subtract in and all of its other uses are redirected to the
9675 /// new load/store.
9676 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9677   if (Level < AfterLegalizeDAG)
9678     return false;
9679 
9680   bool isLoad = true;
9681   SDValue Ptr;
9682   EVT VT;
9683   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9684     if (LD->isIndexed())
9685       return false;
9686     VT = LD->getMemoryVT();
9687     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9688         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9689       return false;
9690     Ptr = LD->getBasePtr();
9691   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9692     if (ST->isIndexed())
9693       return false;
9694     VT = ST->getMemoryVT();
9695     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9696         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9697       return false;
9698     Ptr = ST->getBasePtr();
9699     isLoad = false;
9700   } else {
9701     return false;
9702   }
9703 
9704   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9705   // out.  There is no reason to make this a preinc/predec.
9706   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9707       Ptr.getNode()->hasOneUse())
9708     return false;
9709 
9710   // Ask the target to do addressing mode selection.
9711   SDValue BasePtr;
9712   SDValue Offset;
9713   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9714   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9715     return false;
9716 
9717   // Backends without true r+i pre-indexed forms may need to pass a
9718   // constant base with a variable offset so that constant coercion
9719   // will work with the patterns in canonical form.
9720   bool Swapped = false;
9721   if (isa<ConstantSDNode>(BasePtr)) {
9722     std::swap(BasePtr, Offset);
9723     Swapped = true;
9724   }
9725 
9726   // Don't create a indexed load / store with zero offset.
9727   if (isNullConstant(Offset))
9728     return false;
9729 
9730   // Try turning it into a pre-indexed load / store except when:
9731   // 1) The new base ptr is a frame index.
9732   // 2) If N is a store and the new base ptr is either the same as or is a
9733   //    predecessor of the value being stored.
9734   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9735   //    that would create a cycle.
9736   // 4) All uses are load / store ops that use it as old base ptr.
9737 
9738   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9739   // (plus the implicit offset) to a register to preinc anyway.
9740   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9741     return false;
9742 
9743   // Check #2.
9744   if (!isLoad) {
9745     SDValue Val = cast<StoreSDNode>(N)->getValue();
9746     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9747       return false;
9748   }
9749 
9750   // Caches for hasPredecessorHelper.
9751   SmallPtrSet<const SDNode *, 32> Visited;
9752   SmallVector<const SDNode *, 16> Worklist;
9753   Worklist.push_back(N);
9754 
9755   // If the offset is a constant, there may be other adds of constants that
9756   // can be folded with this one. We should do this to avoid having to keep
9757   // a copy of the original base pointer.
9758   SmallVector<SDNode *, 16> OtherUses;
9759   if (isa<ConstantSDNode>(Offset))
9760     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9761                               UE = BasePtr.getNode()->use_end();
9762          UI != UE; ++UI) {
9763       SDUse &Use = UI.getUse();
9764       // Skip the use that is Ptr and uses of other results from BasePtr's
9765       // node (important for nodes that return multiple results).
9766       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9767         continue;
9768 
9769       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9770         continue;
9771 
9772       if (Use.getUser()->getOpcode() != ISD::ADD &&
9773           Use.getUser()->getOpcode() != ISD::SUB) {
9774         OtherUses.clear();
9775         break;
9776       }
9777 
9778       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9779       if (!isa<ConstantSDNode>(Op1)) {
9780         OtherUses.clear();
9781         break;
9782       }
9783 
9784       // FIXME: In some cases, we can be smarter about this.
9785       if (Op1.getValueType() != Offset.getValueType()) {
9786         OtherUses.clear();
9787         break;
9788       }
9789 
9790       OtherUses.push_back(Use.getUser());
9791     }
9792 
9793   if (Swapped)
9794     std::swap(BasePtr, Offset);
9795 
9796   // Now check for #3 and #4.
9797   bool RealUse = false;
9798 
9799   for (SDNode *Use : Ptr.getNode()->uses()) {
9800     if (Use == N)
9801       continue;
9802     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9803       return false;
9804 
9805     // If Ptr may be folded in addressing mode of other use, then it's
9806     // not profitable to do this transformation.
9807     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9808       RealUse = true;
9809   }
9810 
9811   if (!RealUse)
9812     return false;
9813 
9814   SDValue Result;
9815   if (isLoad)
9816     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9817                                 BasePtr, Offset, AM);
9818   else
9819     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9820                                  BasePtr, Offset, AM);
9821   ++PreIndexedNodes;
9822   ++NodesCombined;
9823   DEBUG(dbgs() << "\nReplacing.4 ";
9824         N->dump(&DAG);
9825         dbgs() << "\nWith: ";
9826         Result.getNode()->dump(&DAG);
9827         dbgs() << '\n');
9828   WorklistRemover DeadNodes(*this);
9829   if (isLoad) {
9830     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9831     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9832   } else {
9833     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9834   }
9835 
9836   // Finally, since the node is now dead, remove it from the graph.
9837   deleteAndRecombine(N);
9838 
9839   if (Swapped)
9840     std::swap(BasePtr, Offset);
9841 
9842   // Replace other uses of BasePtr that can be updated to use Ptr
9843   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9844     unsigned OffsetIdx = 1;
9845     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9846       OffsetIdx = 0;
9847     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9848            BasePtr.getNode() && "Expected BasePtr operand");
9849 
9850     // We need to replace ptr0 in the following expression:
9851     //   x0 * offset0 + y0 * ptr0 = t0
9852     // knowing that
9853     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9854     //
9855     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9856     // indexed load/store and the expresion that needs to be re-written.
9857     //
9858     // Therefore, we have:
9859     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9860 
9861     ConstantSDNode *CN =
9862       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9863     int X0, X1, Y0, Y1;
9864     const APInt &Offset0 = CN->getAPIntValue();
9865     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9866 
9867     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9868     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9869     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9870     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9871 
9872     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9873 
9874     APInt CNV = Offset0;
9875     if (X0 < 0) CNV = -CNV;
9876     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9877     else CNV = CNV - Offset1;
9878 
9879     SDLoc DL(OtherUses[i]);
9880 
9881     // We can now generate the new expression.
9882     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9883     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9884 
9885     SDValue NewUse = DAG.getNode(Opcode,
9886                                  DL,
9887                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9888     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9889     deleteAndRecombine(OtherUses[i]);
9890   }
9891 
9892   // Replace the uses of Ptr with uses of the updated base value.
9893   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9894   deleteAndRecombine(Ptr.getNode());
9895 
9896   return true;
9897 }
9898 
9899 /// Try to combine a load/store with a add/sub of the base pointer node into a
9900 /// post-indexed load/store. The transformation folded the add/subtract into the
9901 /// new indexed load/store effectively and all of its uses are redirected to the
9902 /// new load/store.
9903 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9904   if (Level < AfterLegalizeDAG)
9905     return false;
9906 
9907   bool isLoad = true;
9908   SDValue Ptr;
9909   EVT VT;
9910   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9911     if (LD->isIndexed())
9912       return false;
9913     VT = LD->getMemoryVT();
9914     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9915         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9916       return false;
9917     Ptr = LD->getBasePtr();
9918   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9919     if (ST->isIndexed())
9920       return false;
9921     VT = ST->getMemoryVT();
9922     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9923         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9924       return false;
9925     Ptr = ST->getBasePtr();
9926     isLoad = false;
9927   } else {
9928     return false;
9929   }
9930 
9931   if (Ptr.getNode()->hasOneUse())
9932     return false;
9933 
9934   for (SDNode *Op : Ptr.getNode()->uses()) {
9935     if (Op == N ||
9936         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9937       continue;
9938 
9939     SDValue BasePtr;
9940     SDValue Offset;
9941     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9942     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9943       // Don't create a indexed load / store with zero offset.
9944       if (isNullConstant(Offset))
9945         continue;
9946 
9947       // Try turning it into a post-indexed load / store except when
9948       // 1) All uses are load / store ops that use it as base ptr (and
9949       //    it may be folded as addressing mmode).
9950       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9951       //    nor a successor of N. Otherwise, if Op is folded that would
9952       //    create a cycle.
9953 
9954       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9955         continue;
9956 
9957       // Check for #1.
9958       bool TryNext = false;
9959       for (SDNode *Use : BasePtr.getNode()->uses()) {
9960         if (Use == Ptr.getNode())
9961           continue;
9962 
9963         // If all the uses are load / store addresses, then don't do the
9964         // transformation.
9965         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9966           bool RealUse = false;
9967           for (SDNode *UseUse : Use->uses()) {
9968             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9969               RealUse = true;
9970           }
9971 
9972           if (!RealUse) {
9973             TryNext = true;
9974             break;
9975           }
9976         }
9977       }
9978 
9979       if (TryNext)
9980         continue;
9981 
9982       // Check for #2
9983       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9984         SDValue Result = isLoad
9985           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9986                                BasePtr, Offset, AM)
9987           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9988                                 BasePtr, Offset, AM);
9989         ++PostIndexedNodes;
9990         ++NodesCombined;
9991         DEBUG(dbgs() << "\nReplacing.5 ";
9992               N->dump(&DAG);
9993               dbgs() << "\nWith: ";
9994               Result.getNode()->dump(&DAG);
9995               dbgs() << '\n');
9996         WorklistRemover DeadNodes(*this);
9997         if (isLoad) {
9998           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9999           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10000         } else {
10001           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10002         }
10003 
10004         // Finally, since the node is now dead, remove it from the graph.
10005         deleteAndRecombine(N);
10006 
10007         // Replace the uses of Use with uses of the updated base value.
10008         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10009                                       Result.getValue(isLoad ? 1 : 0));
10010         deleteAndRecombine(Op);
10011         return true;
10012       }
10013     }
10014   }
10015 
10016   return false;
10017 }
10018 
10019 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10020 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10021   ISD::MemIndexedMode AM = LD->getAddressingMode();
10022   assert(AM != ISD::UNINDEXED);
10023   SDValue BP = LD->getOperand(1);
10024   SDValue Inc = LD->getOperand(2);
10025 
10026   // Some backends use TargetConstants for load offsets, but don't expect
10027   // TargetConstants in general ADD nodes. We can convert these constants into
10028   // regular Constants (if the constant is not opaque).
10029   assert((Inc.getOpcode() != ISD::TargetConstant ||
10030           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10031          "Cannot split out indexing using opaque target constants");
10032   if (Inc.getOpcode() == ISD::TargetConstant) {
10033     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10034     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10035                           ConstInc->getValueType(0));
10036   }
10037 
10038   unsigned Opc =
10039       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10040   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10041 }
10042 
10043 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10044   LoadSDNode *LD  = cast<LoadSDNode>(N);
10045   SDValue Chain = LD->getChain();
10046   SDValue Ptr   = LD->getBasePtr();
10047 
10048   // If load is not volatile and there are no uses of the loaded value (and
10049   // the updated indexed value in case of indexed loads), change uses of the
10050   // chain value into uses of the chain input (i.e. delete the dead load).
10051   if (!LD->isVolatile()) {
10052     if (N->getValueType(1) == MVT::Other) {
10053       // Unindexed loads.
10054       if (!N->hasAnyUseOfValue(0)) {
10055         // It's not safe to use the two value CombineTo variant here. e.g.
10056         // v1, chain2 = load chain1, loc
10057         // v2, chain3 = load chain2, loc
10058         // v3         = add v2, c
10059         // Now we replace use of chain2 with chain1.  This makes the second load
10060         // isomorphic to the one we are deleting, and thus makes this load live.
10061         DEBUG(dbgs() << "\nReplacing.6 ";
10062               N->dump(&DAG);
10063               dbgs() << "\nWith chain: ";
10064               Chain.getNode()->dump(&DAG);
10065               dbgs() << "\n");
10066         WorklistRemover DeadNodes(*this);
10067         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10068 
10069         if (N->use_empty())
10070           deleteAndRecombine(N);
10071 
10072         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10073       }
10074     } else {
10075       // Indexed loads.
10076       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10077 
10078       // If this load has an opaque TargetConstant offset, then we cannot split
10079       // the indexing into an add/sub directly (that TargetConstant may not be
10080       // valid for a different type of node, and we cannot convert an opaque
10081       // target constant into a regular constant).
10082       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10083                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10084 
10085       if (!N->hasAnyUseOfValue(0) &&
10086           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10087         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10088         SDValue Index;
10089         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10090           Index = SplitIndexingFromLoad(LD);
10091           // Try to fold the base pointer arithmetic into subsequent loads and
10092           // stores.
10093           AddUsersToWorklist(N);
10094         } else
10095           Index = DAG.getUNDEF(N->getValueType(1));
10096         DEBUG(dbgs() << "\nReplacing.7 ";
10097               N->dump(&DAG);
10098               dbgs() << "\nWith: ";
10099               Undef.getNode()->dump(&DAG);
10100               dbgs() << " and 2 other values\n");
10101         WorklistRemover DeadNodes(*this);
10102         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10103         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10104         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10105         deleteAndRecombine(N);
10106         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10107       }
10108     }
10109   }
10110 
10111   // If this load is directly stored, replace the load value with the stored
10112   // value.
10113   // TODO: Handle store large -> read small portion.
10114   // TODO: Handle TRUNCSTORE/LOADEXT
10115   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10116     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10117       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10118       if (PrevST->getBasePtr() == Ptr &&
10119           PrevST->getValue().getValueType() == N->getValueType(0))
10120       return CombineTo(N, Chain.getOperand(1), Chain);
10121     }
10122   }
10123 
10124   // Try to infer better alignment information than the load already has.
10125   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10126     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10127       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10128         SDValue NewLoad =
10129                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
10130                               LD->getValueType(0),
10131                               Chain, Ptr, LD->getPointerInfo(),
10132                               LD->getMemoryVT(),
10133                               LD->isVolatile(), LD->isNonTemporal(),
10134                               LD->isInvariant(), Align, LD->getAAInfo());
10135         if (NewLoad.getNode() != N)
10136           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10137       }
10138     }
10139   }
10140 
10141   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10142                                                   : DAG.getSubtarget().useAA();
10143 #ifndef NDEBUG
10144   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10145       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10146     UseAA = false;
10147 #endif
10148   if (UseAA && LD->isUnindexed()) {
10149     // Walk up chain skipping non-aliasing memory nodes.
10150     SDValue BetterChain = FindBetterChain(N, Chain);
10151 
10152     // If there is a better chain.
10153     if (Chain != BetterChain) {
10154       SDValue ReplLoad;
10155 
10156       // Replace the chain to void dependency.
10157       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10158         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10159                                BetterChain, Ptr, LD->getMemOperand());
10160       } else {
10161         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10162                                   LD->getValueType(0),
10163                                   BetterChain, Ptr, LD->getMemoryVT(),
10164                                   LD->getMemOperand());
10165       }
10166 
10167       // Create token factor to keep old chain connected.
10168       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10169                                   MVT::Other, Chain, ReplLoad.getValue(1));
10170 
10171       // Make sure the new and old chains are cleaned up.
10172       AddToWorklist(Token.getNode());
10173 
10174       // Replace uses with load result and token factor. Don't add users
10175       // to work list.
10176       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10177     }
10178   }
10179 
10180   // Try transforming N to an indexed load.
10181   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10182     return SDValue(N, 0);
10183 
10184   // Try to slice up N to more direct loads if the slices are mapped to
10185   // different register banks or pairing can take place.
10186   if (SliceUpLoad(N))
10187     return SDValue(N, 0);
10188 
10189   return SDValue();
10190 }
10191 
10192 namespace {
10193 /// \brief Helper structure used to slice a load in smaller loads.
10194 /// Basically a slice is obtained from the following sequence:
10195 /// Origin = load Ty1, Base
10196 /// Shift = srl Ty1 Origin, CstTy Amount
10197 /// Inst = trunc Shift to Ty2
10198 ///
10199 /// Then, it will be rewriten into:
10200 /// Slice = load SliceTy, Base + SliceOffset
10201 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10202 ///
10203 /// SliceTy is deduced from the number of bits that are actually used to
10204 /// build Inst.
10205 struct LoadedSlice {
10206   /// \brief Helper structure used to compute the cost of a slice.
10207   struct Cost {
10208     /// Are we optimizing for code size.
10209     bool ForCodeSize;
10210     /// Various cost.
10211     unsigned Loads;
10212     unsigned Truncates;
10213     unsigned CrossRegisterBanksCopies;
10214     unsigned ZExts;
10215     unsigned Shift;
10216 
10217     Cost(bool ForCodeSize = false)
10218         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10219           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10220 
10221     /// \brief Get the cost of one isolated slice.
10222     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10223         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10224           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10225       EVT TruncType = LS.Inst->getValueType(0);
10226       EVT LoadedType = LS.getLoadedType();
10227       if (TruncType != LoadedType &&
10228           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10229         ZExts = 1;
10230     }
10231 
10232     /// \brief Account for slicing gain in the current cost.
10233     /// Slicing provide a few gains like removing a shift or a
10234     /// truncate. This method allows to grow the cost of the original
10235     /// load with the gain from this slice.
10236     void addSliceGain(const LoadedSlice &LS) {
10237       // Each slice saves a truncate.
10238       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10239       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10240                               LS.Inst->getValueType(0)))
10241         ++Truncates;
10242       // If there is a shift amount, this slice gets rid of it.
10243       if (LS.Shift)
10244         ++Shift;
10245       // If this slice can merge a cross register bank copy, account for it.
10246       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10247         ++CrossRegisterBanksCopies;
10248     }
10249 
10250     Cost &operator+=(const Cost &RHS) {
10251       Loads += RHS.Loads;
10252       Truncates += RHS.Truncates;
10253       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10254       ZExts += RHS.ZExts;
10255       Shift += RHS.Shift;
10256       return *this;
10257     }
10258 
10259     bool operator==(const Cost &RHS) const {
10260       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10261              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10262              ZExts == RHS.ZExts && Shift == RHS.Shift;
10263     }
10264 
10265     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10266 
10267     bool operator<(const Cost &RHS) const {
10268       // Assume cross register banks copies are as expensive as loads.
10269       // FIXME: Do we want some more target hooks?
10270       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10271       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10272       // Unless we are optimizing for code size, consider the
10273       // expensive operation first.
10274       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10275         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10276       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10277              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10278     }
10279 
10280     bool operator>(const Cost &RHS) const { return RHS < *this; }
10281 
10282     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10283 
10284     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10285   };
10286   // The last instruction that represent the slice. This should be a
10287   // truncate instruction.
10288   SDNode *Inst;
10289   // The original load instruction.
10290   LoadSDNode *Origin;
10291   // The right shift amount in bits from the original load.
10292   unsigned Shift;
10293   // The DAG from which Origin came from.
10294   // This is used to get some contextual information about legal types, etc.
10295   SelectionDAG *DAG;
10296 
10297   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10298               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10299       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10300 
10301   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10302   /// \return Result is \p BitWidth and has used bits set to 1 and
10303   ///         not used bits set to 0.
10304   APInt getUsedBits() const {
10305     // Reproduce the trunc(lshr) sequence:
10306     // - Start from the truncated value.
10307     // - Zero extend to the desired bit width.
10308     // - Shift left.
10309     assert(Origin && "No original load to compare against.");
10310     unsigned BitWidth = Origin->getValueSizeInBits(0);
10311     assert(Inst && "This slice is not bound to an instruction");
10312     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10313            "Extracted slice is bigger than the whole type!");
10314     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10315     UsedBits.setAllBits();
10316     UsedBits = UsedBits.zext(BitWidth);
10317     UsedBits <<= Shift;
10318     return UsedBits;
10319   }
10320 
10321   /// \brief Get the size of the slice to be loaded in bytes.
10322   unsigned getLoadedSize() const {
10323     unsigned SliceSize = getUsedBits().countPopulation();
10324     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10325     return SliceSize / 8;
10326   }
10327 
10328   /// \brief Get the type that will be loaded for this slice.
10329   /// Note: This may not be the final type for the slice.
10330   EVT getLoadedType() const {
10331     assert(DAG && "Missing context");
10332     LLVMContext &Ctxt = *DAG->getContext();
10333     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10334   }
10335 
10336   /// \brief Get the alignment of the load used for this slice.
10337   unsigned getAlignment() const {
10338     unsigned Alignment = Origin->getAlignment();
10339     unsigned Offset = getOffsetFromBase();
10340     if (Offset != 0)
10341       Alignment = MinAlign(Alignment, Alignment + Offset);
10342     return Alignment;
10343   }
10344 
10345   /// \brief Check if this slice can be rewritten with legal operations.
10346   bool isLegal() const {
10347     // An invalid slice is not legal.
10348     if (!Origin || !Inst || !DAG)
10349       return false;
10350 
10351     // Offsets are for indexed load only, we do not handle that.
10352     if (!Origin->getOffset().isUndef())
10353       return false;
10354 
10355     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10356 
10357     // Check that the type is legal.
10358     EVT SliceType = getLoadedType();
10359     if (!TLI.isTypeLegal(SliceType))
10360       return false;
10361 
10362     // Check that the load is legal for this type.
10363     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10364       return false;
10365 
10366     // Check that the offset can be computed.
10367     // 1. Check its type.
10368     EVT PtrType = Origin->getBasePtr().getValueType();
10369     if (PtrType == MVT::Untyped || PtrType.isExtended())
10370       return false;
10371 
10372     // 2. Check that it fits in the immediate.
10373     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10374       return false;
10375 
10376     // 3. Check that the computation is legal.
10377     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10378       return false;
10379 
10380     // Check that the zext is legal if it needs one.
10381     EVT TruncateType = Inst->getValueType(0);
10382     if (TruncateType != SliceType &&
10383         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10384       return false;
10385 
10386     return true;
10387   }
10388 
10389   /// \brief Get the offset in bytes of this slice in the original chunk of
10390   /// bits.
10391   /// \pre DAG != nullptr.
10392   uint64_t getOffsetFromBase() const {
10393     assert(DAG && "Missing context.");
10394     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10395     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10396     uint64_t Offset = Shift / 8;
10397     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10398     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10399            "The size of the original loaded type is not a multiple of a"
10400            " byte.");
10401     // If Offset is bigger than TySizeInBytes, it means we are loading all
10402     // zeros. This should have been optimized before in the process.
10403     assert(TySizeInBytes > Offset &&
10404            "Invalid shift amount for given loaded size");
10405     if (IsBigEndian)
10406       Offset = TySizeInBytes - Offset - getLoadedSize();
10407     return Offset;
10408   }
10409 
10410   /// \brief Generate the sequence of instructions to load the slice
10411   /// represented by this object and redirect the uses of this slice to
10412   /// this new sequence of instructions.
10413   /// \pre this->Inst && this->Origin are valid Instructions and this
10414   /// object passed the legal check: LoadedSlice::isLegal returned true.
10415   /// \return The last instruction of the sequence used to load the slice.
10416   SDValue loadSlice() const {
10417     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10418     const SDValue &OldBaseAddr = Origin->getBasePtr();
10419     SDValue BaseAddr = OldBaseAddr;
10420     // Get the offset in that chunk of bytes w.r.t. the endianess.
10421     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10422     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10423     if (Offset) {
10424       // BaseAddr = BaseAddr + Offset.
10425       EVT ArithType = BaseAddr.getValueType();
10426       SDLoc DL(Origin);
10427       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10428                               DAG->getConstant(Offset, DL, ArithType));
10429     }
10430 
10431     // Create the type of the loaded slice according to its size.
10432     EVT SliceType = getLoadedType();
10433 
10434     // Create the load for the slice.
10435     SDValue LastInst = DAG->getLoad(
10436         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10437         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10438         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10439     // If the final type is not the same as the loaded type, this means that
10440     // we have to pad with zero. Create a zero extend for that.
10441     EVT FinalType = Inst->getValueType(0);
10442     if (SliceType != FinalType)
10443       LastInst =
10444           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10445     return LastInst;
10446   }
10447 
10448   /// \brief Check if this slice can be merged with an expensive cross register
10449   /// bank copy. E.g.,
10450   /// i = load i32
10451   /// f = bitcast i32 i to float
10452   bool canMergeExpensiveCrossRegisterBankCopy() const {
10453     if (!Inst || !Inst->hasOneUse())
10454       return false;
10455     SDNode *Use = *Inst->use_begin();
10456     if (Use->getOpcode() != ISD::BITCAST)
10457       return false;
10458     assert(DAG && "Missing context");
10459     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10460     EVT ResVT = Use->getValueType(0);
10461     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10462     const TargetRegisterClass *ArgRC =
10463         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10464     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10465       return false;
10466 
10467     // At this point, we know that we perform a cross-register-bank copy.
10468     // Check if it is expensive.
10469     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10470     // Assume bitcasts are cheap, unless both register classes do not
10471     // explicitly share a common sub class.
10472     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10473       return false;
10474 
10475     // Check if it will be merged with the load.
10476     // 1. Check the alignment constraint.
10477     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10478         ResVT.getTypeForEVT(*DAG->getContext()));
10479 
10480     if (RequiredAlignment > getAlignment())
10481       return false;
10482 
10483     // 2. Check that the load is a legal operation for that type.
10484     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10485       return false;
10486 
10487     // 3. Check that we do not have a zext in the way.
10488     if (Inst->getValueType(0) != getLoadedType())
10489       return false;
10490 
10491     return true;
10492   }
10493 };
10494 }
10495 
10496 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10497 /// \p UsedBits looks like 0..0 1..1 0..0.
10498 static bool areUsedBitsDense(const APInt &UsedBits) {
10499   // If all the bits are one, this is dense!
10500   if (UsedBits.isAllOnesValue())
10501     return true;
10502 
10503   // Get rid of the unused bits on the right.
10504   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10505   // Get rid of the unused bits on the left.
10506   if (NarrowedUsedBits.countLeadingZeros())
10507     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10508   // Check that the chunk of bits is completely used.
10509   return NarrowedUsedBits.isAllOnesValue();
10510 }
10511 
10512 /// \brief Check whether or not \p First and \p Second are next to each other
10513 /// in memory. This means that there is no hole between the bits loaded
10514 /// by \p First and the bits loaded by \p Second.
10515 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10516                                      const LoadedSlice &Second) {
10517   assert(First.Origin == Second.Origin && First.Origin &&
10518          "Unable to match different memory origins.");
10519   APInt UsedBits = First.getUsedBits();
10520   assert((UsedBits & Second.getUsedBits()) == 0 &&
10521          "Slices are not supposed to overlap.");
10522   UsedBits |= Second.getUsedBits();
10523   return areUsedBitsDense(UsedBits);
10524 }
10525 
10526 /// \brief Adjust the \p GlobalLSCost according to the target
10527 /// paring capabilities and the layout of the slices.
10528 /// \pre \p GlobalLSCost should account for at least as many loads as
10529 /// there is in the slices in \p LoadedSlices.
10530 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10531                                  LoadedSlice::Cost &GlobalLSCost) {
10532   unsigned NumberOfSlices = LoadedSlices.size();
10533   // If there is less than 2 elements, no pairing is possible.
10534   if (NumberOfSlices < 2)
10535     return;
10536 
10537   // Sort the slices so that elements that are likely to be next to each
10538   // other in memory are next to each other in the list.
10539   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10540             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10541     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10542     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10543   });
10544   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10545   // First (resp. Second) is the first (resp. Second) potentially candidate
10546   // to be placed in a paired load.
10547   const LoadedSlice *First = nullptr;
10548   const LoadedSlice *Second = nullptr;
10549   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10550                 // Set the beginning of the pair.
10551                                                            First = Second) {
10552 
10553     Second = &LoadedSlices[CurrSlice];
10554 
10555     // If First is NULL, it means we start a new pair.
10556     // Get to the next slice.
10557     if (!First)
10558       continue;
10559 
10560     EVT LoadedType = First->getLoadedType();
10561 
10562     // If the types of the slices are different, we cannot pair them.
10563     if (LoadedType != Second->getLoadedType())
10564       continue;
10565 
10566     // Check if the target supplies paired loads for this type.
10567     unsigned RequiredAlignment = 0;
10568     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10569       // move to the next pair, this type is hopeless.
10570       Second = nullptr;
10571       continue;
10572     }
10573     // Check if we meet the alignment requirement.
10574     if (RequiredAlignment > First->getAlignment())
10575       continue;
10576 
10577     // Check that both loads are next to each other in memory.
10578     if (!areSlicesNextToEachOther(*First, *Second))
10579       continue;
10580 
10581     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10582     --GlobalLSCost.Loads;
10583     // Move to the next pair.
10584     Second = nullptr;
10585   }
10586 }
10587 
10588 /// \brief Check the profitability of all involved LoadedSlice.
10589 /// Currently, it is considered profitable if there is exactly two
10590 /// involved slices (1) which are (2) next to each other in memory, and
10591 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10592 ///
10593 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10594 /// the elements themselves.
10595 ///
10596 /// FIXME: When the cost model will be mature enough, we can relax
10597 /// constraints (1) and (2).
10598 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10599                                 const APInt &UsedBits, bool ForCodeSize) {
10600   unsigned NumberOfSlices = LoadedSlices.size();
10601   if (StressLoadSlicing)
10602     return NumberOfSlices > 1;
10603 
10604   // Check (1).
10605   if (NumberOfSlices != 2)
10606     return false;
10607 
10608   // Check (2).
10609   if (!areUsedBitsDense(UsedBits))
10610     return false;
10611 
10612   // Check (3).
10613   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10614   // The original code has one big load.
10615   OrigCost.Loads = 1;
10616   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10617     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10618     // Accumulate the cost of all the slices.
10619     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10620     GlobalSlicingCost += SliceCost;
10621 
10622     // Account as cost in the original configuration the gain obtained
10623     // with the current slices.
10624     OrigCost.addSliceGain(LS);
10625   }
10626 
10627   // If the target supports paired load, adjust the cost accordingly.
10628   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10629   return OrigCost > GlobalSlicingCost;
10630 }
10631 
10632 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10633 /// operations, split it in the various pieces being extracted.
10634 ///
10635 /// This sort of thing is introduced by SROA.
10636 /// This slicing takes care not to insert overlapping loads.
10637 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10638 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10639   if (Level < AfterLegalizeDAG)
10640     return false;
10641 
10642   LoadSDNode *LD = cast<LoadSDNode>(N);
10643   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10644       !LD->getValueType(0).isInteger())
10645     return false;
10646 
10647   // Keep track of already used bits to detect overlapping values.
10648   // In that case, we will just abort the transformation.
10649   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10650 
10651   SmallVector<LoadedSlice, 4> LoadedSlices;
10652 
10653   // Check if this load is used as several smaller chunks of bits.
10654   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10655   // of computation for each trunc.
10656   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10657        UI != UIEnd; ++UI) {
10658     // Skip the uses of the chain.
10659     if (UI.getUse().getResNo() != 0)
10660       continue;
10661 
10662     SDNode *User = *UI;
10663     unsigned Shift = 0;
10664 
10665     // Check if this is a trunc(lshr).
10666     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10667         isa<ConstantSDNode>(User->getOperand(1))) {
10668       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10669       User = *User->use_begin();
10670     }
10671 
10672     // At this point, User is a Truncate, iff we encountered, trunc or
10673     // trunc(lshr).
10674     if (User->getOpcode() != ISD::TRUNCATE)
10675       return false;
10676 
10677     // The width of the type must be a power of 2 and greater than 8-bits.
10678     // Otherwise the load cannot be represented in LLVM IR.
10679     // Moreover, if we shifted with a non-8-bits multiple, the slice
10680     // will be across several bytes. We do not support that.
10681     unsigned Width = User->getValueSizeInBits(0);
10682     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10683       return 0;
10684 
10685     // Build the slice for this chain of computations.
10686     LoadedSlice LS(User, LD, Shift, &DAG);
10687     APInt CurrentUsedBits = LS.getUsedBits();
10688 
10689     // Check if this slice overlaps with another.
10690     if ((CurrentUsedBits & UsedBits) != 0)
10691       return false;
10692     // Update the bits used globally.
10693     UsedBits |= CurrentUsedBits;
10694 
10695     // Check if the new slice would be legal.
10696     if (!LS.isLegal())
10697       return false;
10698 
10699     // Record the slice.
10700     LoadedSlices.push_back(LS);
10701   }
10702 
10703   // Abort slicing if it does not seem to be profitable.
10704   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10705     return false;
10706 
10707   ++SlicedLoads;
10708 
10709   // Rewrite each chain to use an independent load.
10710   // By construction, each chain can be represented by a unique load.
10711 
10712   // Prepare the argument for the new token factor for all the slices.
10713   SmallVector<SDValue, 8> ArgChains;
10714   for (SmallVectorImpl<LoadedSlice>::const_iterator
10715            LSIt = LoadedSlices.begin(),
10716            LSItEnd = LoadedSlices.end();
10717        LSIt != LSItEnd; ++LSIt) {
10718     SDValue SliceInst = LSIt->loadSlice();
10719     CombineTo(LSIt->Inst, SliceInst, true);
10720     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10721       SliceInst = SliceInst.getOperand(0);
10722     assert(SliceInst->getOpcode() == ISD::LOAD &&
10723            "It takes more than a zext to get to the loaded slice!!");
10724     ArgChains.push_back(SliceInst.getValue(1));
10725   }
10726 
10727   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10728                               ArgChains);
10729   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10730   return true;
10731 }
10732 
10733 /// Check to see if V is (and load (ptr), imm), where the load is having
10734 /// specific bytes cleared out.  If so, return the byte size being masked out
10735 /// and the shift amount.
10736 static std::pair<unsigned, unsigned>
10737 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10738   std::pair<unsigned, unsigned> Result(0, 0);
10739 
10740   // Check for the structure we're looking for.
10741   if (V->getOpcode() != ISD::AND ||
10742       !isa<ConstantSDNode>(V->getOperand(1)) ||
10743       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10744     return Result;
10745 
10746   // Check the chain and pointer.
10747   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10748   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10749 
10750   // The store should be chained directly to the load or be an operand of a
10751   // tokenfactor.
10752   if (LD == Chain.getNode())
10753     ; // ok.
10754   else if (Chain->getOpcode() != ISD::TokenFactor)
10755     return Result; // Fail.
10756   else {
10757     bool isOk = false;
10758     for (const SDValue &ChainOp : Chain->op_values())
10759       if (ChainOp.getNode() == LD) {
10760         isOk = true;
10761         break;
10762       }
10763     if (!isOk) return Result;
10764   }
10765 
10766   // This only handles simple types.
10767   if (V.getValueType() != MVT::i16 &&
10768       V.getValueType() != MVT::i32 &&
10769       V.getValueType() != MVT::i64)
10770     return Result;
10771 
10772   // Check the constant mask.  Invert it so that the bits being masked out are
10773   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10774   // follow the sign bit for uniformity.
10775   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10776   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10777   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10778   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10779   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10780   if (NotMaskLZ == 64) return Result;  // All zero mask.
10781 
10782   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10783   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10784     return Result;
10785 
10786   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10787   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10788     NotMaskLZ -= 64-V.getValueSizeInBits();
10789 
10790   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10791   switch (MaskedBytes) {
10792   case 1:
10793   case 2:
10794   case 4: break;
10795   default: return Result; // All one mask, or 5-byte mask.
10796   }
10797 
10798   // Verify that the first bit starts at a multiple of mask so that the access
10799   // is aligned the same as the access width.
10800   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10801 
10802   Result.first = MaskedBytes;
10803   Result.second = NotMaskTZ/8;
10804   return Result;
10805 }
10806 
10807 
10808 /// Check to see if IVal is something that provides a value as specified by
10809 /// MaskInfo. If so, replace the specified store with a narrower store of
10810 /// truncated IVal.
10811 static SDNode *
10812 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10813                                 SDValue IVal, StoreSDNode *St,
10814                                 DAGCombiner *DC) {
10815   unsigned NumBytes = MaskInfo.first;
10816   unsigned ByteShift = MaskInfo.second;
10817   SelectionDAG &DAG = DC->getDAG();
10818 
10819   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10820   // that uses this.  If not, this is not a replacement.
10821   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10822                                   ByteShift*8, (ByteShift+NumBytes)*8);
10823   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10824 
10825   // Check that it is legal on the target to do this.  It is legal if the new
10826   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10827   // legalization.
10828   MVT VT = MVT::getIntegerVT(NumBytes*8);
10829   if (!DC->isTypeLegal(VT))
10830     return nullptr;
10831 
10832   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10833   // shifted by ByteShift and truncated down to NumBytes.
10834   if (ByteShift) {
10835     SDLoc DL(IVal);
10836     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10837                        DAG.getConstant(ByteShift*8, DL,
10838                                     DC->getShiftAmountTy(IVal.getValueType())));
10839   }
10840 
10841   // Figure out the offset for the store and the alignment of the access.
10842   unsigned StOffset;
10843   unsigned NewAlign = St->getAlignment();
10844 
10845   if (DAG.getDataLayout().isLittleEndian())
10846     StOffset = ByteShift;
10847   else
10848     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10849 
10850   SDValue Ptr = St->getBasePtr();
10851   if (StOffset) {
10852     SDLoc DL(IVal);
10853     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10854                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10855     NewAlign = MinAlign(NewAlign, StOffset);
10856   }
10857 
10858   // Truncate down to the new size.
10859   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10860 
10861   ++OpsNarrowed;
10862   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10863                       St->getPointerInfo().getWithOffset(StOffset),
10864                       false, false, NewAlign).getNode();
10865 }
10866 
10867 
10868 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10869 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10870 /// narrowing the load and store if it would end up being a win for performance
10871 /// or code size.
10872 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10873   StoreSDNode *ST  = cast<StoreSDNode>(N);
10874   if (ST->isVolatile())
10875     return SDValue();
10876 
10877   SDValue Chain = ST->getChain();
10878   SDValue Value = ST->getValue();
10879   SDValue Ptr   = ST->getBasePtr();
10880   EVT VT = Value.getValueType();
10881 
10882   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10883     return SDValue();
10884 
10885   unsigned Opc = Value.getOpcode();
10886 
10887   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10888   // is a byte mask indicating a consecutive number of bytes, check to see if
10889   // Y is known to provide just those bytes.  If so, we try to replace the
10890   // load + replace + store sequence with a single (narrower) store, which makes
10891   // the load dead.
10892   if (Opc == ISD::OR) {
10893     std::pair<unsigned, unsigned> MaskedLoad;
10894     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10895     if (MaskedLoad.first)
10896       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10897                                                   Value.getOperand(1), ST,this))
10898         return SDValue(NewST, 0);
10899 
10900     // Or is commutative, so try swapping X and Y.
10901     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10902     if (MaskedLoad.first)
10903       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10904                                                   Value.getOperand(0), ST,this))
10905         return SDValue(NewST, 0);
10906   }
10907 
10908   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10909       Value.getOperand(1).getOpcode() != ISD::Constant)
10910     return SDValue();
10911 
10912   SDValue N0 = Value.getOperand(0);
10913   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10914       Chain == SDValue(N0.getNode(), 1)) {
10915     LoadSDNode *LD = cast<LoadSDNode>(N0);
10916     if (LD->getBasePtr() != Ptr ||
10917         LD->getPointerInfo().getAddrSpace() !=
10918         ST->getPointerInfo().getAddrSpace())
10919       return SDValue();
10920 
10921     // Find the type to narrow it the load / op / store to.
10922     SDValue N1 = Value.getOperand(1);
10923     unsigned BitWidth = N1.getValueSizeInBits();
10924     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10925     if (Opc == ISD::AND)
10926       Imm ^= APInt::getAllOnesValue(BitWidth);
10927     if (Imm == 0 || Imm.isAllOnesValue())
10928       return SDValue();
10929     unsigned ShAmt = Imm.countTrailingZeros();
10930     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10931     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10932     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10933     // The narrowing should be profitable, the load/store operation should be
10934     // legal (or custom) and the store size should be equal to the NewVT width.
10935     while (NewBW < BitWidth &&
10936            (NewVT.getStoreSizeInBits() != NewBW ||
10937             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10938             !TLI.isNarrowingProfitable(VT, NewVT))) {
10939       NewBW = NextPowerOf2(NewBW);
10940       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10941     }
10942     if (NewBW >= BitWidth)
10943       return SDValue();
10944 
10945     // If the lsb changed does not start at the type bitwidth boundary,
10946     // start at the previous one.
10947     if (ShAmt % NewBW)
10948       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10949     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10950                                    std::min(BitWidth, ShAmt + NewBW));
10951     if ((Imm & Mask) == Imm) {
10952       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10953       if (Opc == ISD::AND)
10954         NewImm ^= APInt::getAllOnesValue(NewBW);
10955       uint64_t PtrOff = ShAmt / 8;
10956       // For big endian targets, we need to adjust the offset to the pointer to
10957       // load the correct bytes.
10958       if (DAG.getDataLayout().isBigEndian())
10959         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10960 
10961       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10962       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10963       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10964         return SDValue();
10965 
10966       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10967                                    Ptr.getValueType(), Ptr,
10968                                    DAG.getConstant(PtrOff, SDLoc(LD),
10969                                                    Ptr.getValueType()));
10970       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10971                                   LD->getChain(), NewPtr,
10972                                   LD->getPointerInfo().getWithOffset(PtrOff),
10973                                   LD->isVolatile(), LD->isNonTemporal(),
10974                                   LD->isInvariant(), NewAlign,
10975                                   LD->getAAInfo());
10976       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10977                                    DAG.getConstant(NewImm, SDLoc(Value),
10978                                                    NewVT));
10979       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10980                                    NewVal, NewPtr,
10981                                    ST->getPointerInfo().getWithOffset(PtrOff),
10982                                    false, false, NewAlign);
10983 
10984       AddToWorklist(NewPtr.getNode());
10985       AddToWorklist(NewLD.getNode());
10986       AddToWorklist(NewVal.getNode());
10987       WorklistRemover DeadNodes(*this);
10988       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10989       ++OpsNarrowed;
10990       return NewST;
10991     }
10992   }
10993 
10994   return SDValue();
10995 }
10996 
10997 /// For a given floating point load / store pair, if the load value isn't used
10998 /// by any other operations, then consider transforming the pair to integer
10999 /// load / store operations if the target deems the transformation profitable.
11000 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11001   StoreSDNode *ST  = cast<StoreSDNode>(N);
11002   SDValue Chain = ST->getChain();
11003   SDValue Value = ST->getValue();
11004   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11005       Value.hasOneUse() &&
11006       Chain == SDValue(Value.getNode(), 1)) {
11007     LoadSDNode *LD = cast<LoadSDNode>(Value);
11008     EVT VT = LD->getMemoryVT();
11009     if (!VT.isFloatingPoint() ||
11010         VT != ST->getMemoryVT() ||
11011         LD->isNonTemporal() ||
11012         ST->isNonTemporal() ||
11013         LD->getPointerInfo().getAddrSpace() != 0 ||
11014         ST->getPointerInfo().getAddrSpace() != 0)
11015       return SDValue();
11016 
11017     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11018     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11019         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11020         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11021         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11022       return SDValue();
11023 
11024     unsigned LDAlign = LD->getAlignment();
11025     unsigned STAlign = ST->getAlignment();
11026     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11027     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11028     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11029       return SDValue();
11030 
11031     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
11032                                 LD->getChain(), LD->getBasePtr(),
11033                                 LD->getPointerInfo(),
11034                                 false, false, false, LDAlign);
11035 
11036     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
11037                                  NewLD, ST->getBasePtr(),
11038                                  ST->getPointerInfo(),
11039                                  false, false, STAlign);
11040 
11041     AddToWorklist(NewLD.getNode());
11042     AddToWorklist(NewST.getNode());
11043     WorklistRemover DeadNodes(*this);
11044     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11045     ++LdStFP2Int;
11046     return NewST;
11047   }
11048 
11049   return SDValue();
11050 }
11051 
11052 namespace {
11053 /// Helper struct to parse and store a memory address as base + index + offset.
11054 /// We ignore sign extensions when it is safe to do so.
11055 /// The following two expressions are not equivalent. To differentiate we need
11056 /// to store whether there was a sign extension involved in the index
11057 /// computation.
11058 ///  (load (i64 add (i64 copyfromreg %c)
11059 ///                 (i64 signextend (add (i8 load %index)
11060 ///                                      (i8 1))))
11061 /// vs
11062 ///
11063 /// (load (i64 add (i64 copyfromreg %c)
11064 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11065 ///                                         (i32 1)))))
11066 struct BaseIndexOffset {
11067   SDValue Base;
11068   SDValue Index;
11069   int64_t Offset;
11070   bool IsIndexSignExt;
11071 
11072   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11073 
11074   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11075                   bool IsIndexSignExt) :
11076     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11077 
11078   bool equalBaseIndex(const BaseIndexOffset &Other) {
11079     return Other.Base == Base && Other.Index == Index &&
11080       Other.IsIndexSignExt == IsIndexSignExt;
11081   }
11082 
11083   /// Parses tree in Ptr for base, index, offset addresses.
11084   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11085     bool IsIndexSignExt = false;
11086 
11087     // Split up a folded GlobalAddress+Offset into its component parts.
11088     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11089       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11090         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11091                                                     SDLoc(GA),
11092                                                     GA->getValueType(0),
11093                                                     /*Offset=*/0,
11094                                                     /*isTargetGA=*/false,
11095                                                     GA->getTargetFlags()),
11096                                SDValue(),
11097                                GA->getOffset(),
11098                                IsIndexSignExt);
11099       }
11100 
11101     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11102     // instruction, then it could be just the BASE or everything else we don't
11103     // know how to handle. Just use Ptr as BASE and give up.
11104     if (Ptr->getOpcode() != ISD::ADD)
11105       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11106 
11107     // We know that we have at least an ADD instruction. Try to pattern match
11108     // the simple case of BASE + OFFSET.
11109     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11110       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11111       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11112                               IsIndexSignExt);
11113     }
11114 
11115     // Inside a loop the current BASE pointer is calculated using an ADD and a
11116     // MUL instruction. In this case Ptr is the actual BASE pointer.
11117     // (i64 add (i64 %array_ptr)
11118     //          (i64 mul (i64 %induction_var)
11119     //                   (i64 %element_size)))
11120     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11121       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11122 
11123     // Look at Base + Index + Offset cases.
11124     SDValue Base = Ptr->getOperand(0);
11125     SDValue IndexOffset = Ptr->getOperand(1);
11126 
11127     // Skip signextends.
11128     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11129       IndexOffset = IndexOffset->getOperand(0);
11130       IsIndexSignExt = true;
11131     }
11132 
11133     // Either the case of Base + Index (no offset) or something else.
11134     if (IndexOffset->getOpcode() != ISD::ADD)
11135       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11136 
11137     // Now we have the case of Base + Index + offset.
11138     SDValue Index = IndexOffset->getOperand(0);
11139     SDValue Offset = IndexOffset->getOperand(1);
11140 
11141     if (!isa<ConstantSDNode>(Offset))
11142       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11143 
11144     // Ignore signextends.
11145     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11146       Index = Index->getOperand(0);
11147       IsIndexSignExt = true;
11148     } else IsIndexSignExt = false;
11149 
11150     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11151     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11152   }
11153 };
11154 } // namespace
11155 
11156 // This is a helper function for visitMUL to check the profitability
11157 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11158 // MulNode is the original multiply, AddNode is (add x, c1),
11159 // and ConstNode is c2.
11160 //
11161 // If the (add x, c1) has multiple uses, we could increase
11162 // the number of adds if we make this transformation.
11163 // It would only be worth doing this if we can remove a
11164 // multiply in the process. Check for that here.
11165 // To illustrate:
11166 //     (A + c1) * c3
11167 //     (A + c2) * c3
11168 // We're checking for cases where we have common "c3 * A" expressions.
11169 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11170                                               SDValue &AddNode,
11171                                               SDValue &ConstNode) {
11172   APInt Val;
11173 
11174   // If the add only has one use, this would be OK to do.
11175   if (AddNode.getNode()->hasOneUse())
11176     return true;
11177 
11178   // Walk all the users of the constant with which we're multiplying.
11179   for (SDNode *Use : ConstNode->uses()) {
11180 
11181     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11182       continue;
11183 
11184     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11185       SDNode *OtherOp;
11186       SDNode *MulVar = AddNode.getOperand(0).getNode();
11187 
11188       // OtherOp is what we're multiplying against the constant.
11189       if (Use->getOperand(0) == ConstNode)
11190         OtherOp = Use->getOperand(1).getNode();
11191       else
11192         OtherOp = Use->getOperand(0).getNode();
11193 
11194       // Check to see if multiply is with the same operand of our "add".
11195       //
11196       //     ConstNode  = CONST
11197       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11198       //     ...
11199       //     AddNode  = (A + c1)  <-- MulVar is A.
11200       //         = AddNode * ConstNode   <-- current visiting instruction.
11201       //
11202       // If we make this transformation, we will have a common
11203       // multiply (ConstNode * A) that we can save.
11204       if (OtherOp == MulVar)
11205         return true;
11206 
11207       // Now check to see if a future expansion will give us a common
11208       // multiply.
11209       //
11210       //     ConstNode  = CONST
11211       //     AddNode    = (A + c1)
11212       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11213       //     ...
11214       //     OtherOp = (A + c2)
11215       //     Use     = OtherOp * ConstNode <-- visiting Use.
11216       //
11217       // If we make this transformation, we will have a common
11218       // multiply (CONST * A) after we also do the same transformation
11219       // to the "t2" instruction.
11220       if (OtherOp->getOpcode() == ISD::ADD &&
11221           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11222           OtherOp->getOperand(0).getNode() == MulVar)
11223         return true;
11224     }
11225   }
11226 
11227   // Didn't find a case where this would be profitable.
11228   return false;
11229 }
11230 
11231 SDValue DAGCombiner::getMergedConstantVectorStore(
11232     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11233     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11234   SmallVector<SDValue, 8> BuildVector;
11235 
11236   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11237     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11238     Chains.push_back(St->getChain());
11239     BuildVector.push_back(St->getValue());
11240   }
11241 
11242   return DAG.getBuildVector(Ty, SL, BuildVector);
11243 }
11244 
11245 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11246                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11247                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11248   // Make sure we have something to merge.
11249   if (NumStores < 2)
11250     return false;
11251 
11252   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11253   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11254   unsigned LatestNodeUsed = 0;
11255 
11256   for (unsigned i=0; i < NumStores; ++i) {
11257     // Find a chain for the new wide-store operand. Notice that some
11258     // of the store nodes that we found may not be selected for inclusion
11259     // in the wide store. The chain we use needs to be the chain of the
11260     // latest store node which is *used* and replaced by the wide store.
11261     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11262       LatestNodeUsed = i;
11263   }
11264 
11265   SmallVector<SDValue, 8> Chains;
11266 
11267   // The latest Node in the DAG.
11268   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11269   SDLoc DL(StoreNodes[0].MemNode);
11270 
11271   SDValue StoredVal;
11272   if (UseVector) {
11273     bool IsVec = MemVT.isVector();
11274     unsigned Elts = NumStores;
11275     if (IsVec) {
11276       // When merging vector stores, get the total number of elements.
11277       Elts *= MemVT.getVectorNumElements();
11278     }
11279     // Get the type for the merged vector store.
11280     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11281     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11282 
11283     if (IsConstantSrc) {
11284       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11285     } else {
11286       SmallVector<SDValue, 8> Ops;
11287       for (unsigned i = 0; i < NumStores; ++i) {
11288         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11289         SDValue Val = St->getValue();
11290         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11291         if (Val.getValueType() != MemVT)
11292           return false;
11293         Ops.push_back(Val);
11294         Chains.push_back(St->getChain());
11295       }
11296 
11297       // Build the extracted vector elements back into a vector.
11298       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11299                               DL, Ty, Ops);    }
11300   } else {
11301     // We should always use a vector store when merging extracted vector
11302     // elements, so this path implies a store of constants.
11303     assert(IsConstantSrc && "Merged vector elements should use vector store");
11304 
11305     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11306     APInt StoreInt(SizeInBits, 0);
11307 
11308     // Construct a single integer constant which is made of the smaller
11309     // constant inputs.
11310     bool IsLE = DAG.getDataLayout().isLittleEndian();
11311     for (unsigned i = 0; i < NumStores; ++i) {
11312       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11313       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11314       Chains.push_back(St->getChain());
11315 
11316       SDValue Val = St->getValue();
11317       StoreInt <<= ElementSizeBytes * 8;
11318       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11319         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11320       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11321         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11322       } else {
11323         llvm_unreachable("Invalid constant element type");
11324       }
11325     }
11326 
11327     // Create the new Load and Store operations.
11328     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11329     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11330   }
11331 
11332   assert(!Chains.empty());
11333 
11334   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11335   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11336                                   FirstInChain->getBasePtr(),
11337                                   FirstInChain->getPointerInfo(),
11338                                   false, false,
11339                                   FirstInChain->getAlignment());
11340 
11341   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11342                                                   : DAG.getSubtarget().useAA();
11343   if (UseAA) {
11344     // Replace all merged stores with the new store.
11345     for (unsigned i = 0; i < NumStores; ++i)
11346       CombineTo(StoreNodes[i].MemNode, NewStore);
11347   } else {
11348     // Replace the last store with the new store.
11349     CombineTo(LatestOp, NewStore);
11350     // Erase all other stores.
11351     for (unsigned i = 0; i < NumStores; ++i) {
11352       if (StoreNodes[i].MemNode == LatestOp)
11353         continue;
11354       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11355       // ReplaceAllUsesWith will replace all uses that existed when it was
11356       // called, but graph optimizations may cause new ones to appear. For
11357       // example, the case in pr14333 looks like
11358       //
11359       //  St's chain -> St -> another store -> X
11360       //
11361       // And the only difference from St to the other store is the chain.
11362       // When we change it's chain to be St's chain they become identical,
11363       // get CSEed and the net result is that X is now a use of St.
11364       // Since we know that St is redundant, just iterate.
11365       while (!St->use_empty())
11366         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11367       deleteAndRecombine(St);
11368     }
11369   }
11370 
11371   return true;
11372 }
11373 
11374 void DAGCombiner::getStoreMergeAndAliasCandidates(
11375     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11376     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11377   // This holds the base pointer, index, and the offset in bytes from the base
11378   // pointer.
11379   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11380 
11381   // We must have a base and an offset.
11382   if (!BasePtr.Base.getNode())
11383     return;
11384 
11385   // Do not handle stores to undef base pointers.
11386   if (BasePtr.Base.isUndef())
11387     return;
11388 
11389   // Walk up the chain and look for nodes with offsets from the same
11390   // base pointer. Stop when reaching an instruction with a different kind
11391   // or instruction which has a different base pointer.
11392   EVT MemVT = St->getMemoryVT();
11393   unsigned Seq = 0;
11394   StoreSDNode *Index = St;
11395 
11396 
11397   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11398                                                   : DAG.getSubtarget().useAA();
11399 
11400   if (UseAA) {
11401     // Look at other users of the same chain. Stores on the same chain do not
11402     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11403     // to be on the same chain, so don't bother looking at adjacent chains.
11404 
11405     SDValue Chain = St->getChain();
11406     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11407       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11408         if (I.getOperandNo() != 0)
11409           continue;
11410 
11411         if (OtherST->isVolatile() || OtherST->isIndexed())
11412           continue;
11413 
11414         if (OtherST->getMemoryVT() != MemVT)
11415           continue;
11416 
11417         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11418 
11419         if (Ptr.equalBaseIndex(BasePtr))
11420           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11421       }
11422     }
11423 
11424     return;
11425   }
11426 
11427   while (Index) {
11428     // If the chain has more than one use, then we can't reorder the mem ops.
11429     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11430       break;
11431 
11432     // Find the base pointer and offset for this memory node.
11433     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11434 
11435     // Check that the base pointer is the same as the original one.
11436     if (!Ptr.equalBaseIndex(BasePtr))
11437       break;
11438 
11439     // The memory operands must not be volatile.
11440     if (Index->isVolatile() || Index->isIndexed())
11441       break;
11442 
11443     // No truncation.
11444     if (Index->isTruncatingStore())
11445       break;
11446 
11447     // The stored memory type must be the same.
11448     if (Index->getMemoryVT() != MemVT)
11449       break;
11450 
11451     // We do not allow under-aligned stores in order to prevent
11452     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11453     // be irrelevant here; what MATTERS is that we not move memory
11454     // operations that potentially overlap past each-other.
11455     if (Index->getAlignment() < MemVT.getStoreSize())
11456       break;
11457 
11458     // We found a potential memory operand to merge.
11459     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11460 
11461     // Find the next memory operand in the chain. If the next operand in the
11462     // chain is a store then move up and continue the scan with the next
11463     // memory operand. If the next operand is a load save it and use alias
11464     // information to check if it interferes with anything.
11465     SDNode *NextInChain = Index->getChain().getNode();
11466     while (1) {
11467       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11468         // We found a store node. Use it for the next iteration.
11469         Index = STn;
11470         break;
11471       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11472         if (Ldn->isVolatile()) {
11473           Index = nullptr;
11474           break;
11475         }
11476 
11477         // Save the load node for later. Continue the scan.
11478         AliasLoadNodes.push_back(Ldn);
11479         NextInChain = Ldn->getChain().getNode();
11480         continue;
11481       } else {
11482         Index = nullptr;
11483         break;
11484       }
11485     }
11486   }
11487 }
11488 
11489 // We need to check that merging these stores does not cause a loop
11490 // in the DAG. Any store candidate may depend on another candidate
11491 // indirectly through its operand (we already consider dependencies
11492 // through the chain). Check in parallel by searching up from
11493 // non-chain operands of candidates.
11494 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11495     SmallVectorImpl<MemOpLink> &StoreNodes) {
11496   SmallPtrSet<const SDNode *, 16> Visited;
11497   SmallVector<const SDNode *, 8> Worklist;
11498   // search ops of store candidates
11499   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11500     SDNode *n = StoreNodes[i].MemNode;
11501     // Potential loops may happen only through non-chain operands
11502     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11503       Worklist.push_back(n->getOperand(j).getNode());
11504   }
11505   // search through DAG. We can stop early if we find a storenode
11506   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11507     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11508       return false;
11509   }
11510   return true;
11511 }
11512 
11513 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11514   if (OptLevel == CodeGenOpt::None)
11515     return false;
11516 
11517   EVT MemVT = St->getMemoryVT();
11518   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11519   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11520       Attribute::NoImplicitFloat);
11521 
11522   // This function cannot currently deal with non-byte-sized memory sizes.
11523   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11524     return false;
11525 
11526   if (!MemVT.isSimple())
11527     return false;
11528 
11529   // Perform an early exit check. Do not bother looking at stored values that
11530   // are not constants, loads, or extracted vector elements.
11531   SDValue StoredVal = St->getValue();
11532   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11533   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11534                        isa<ConstantFPSDNode>(StoredVal);
11535   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11536                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11537 
11538   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11539     return false;
11540 
11541   // Don't merge vectors into wider vectors if the source data comes from loads.
11542   // TODO: This restriction can be lifted by using logic similar to the
11543   // ExtractVecSrc case.
11544   if (MemVT.isVector() && IsLoadSrc)
11545     return false;
11546 
11547   // Only look at ends of store sequences.
11548   SDValue Chain = SDValue(St, 0);
11549   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11550     return false;
11551 
11552   // Save the LoadSDNodes that we find in the chain.
11553   // We need to make sure that these nodes do not interfere with
11554   // any of the store nodes.
11555   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11556 
11557   // Save the StoreSDNodes that we find in the chain.
11558   SmallVector<MemOpLink, 8> StoreNodes;
11559 
11560   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11561 
11562   // Check if there is anything to merge.
11563   if (StoreNodes.size() < 2)
11564     return false;
11565 
11566   // only do dep endence check in AA case
11567   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11568                                                   : DAG.getSubtarget().useAA();
11569   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11570     return false;
11571 
11572   // Sort the memory operands according to their distance from the
11573   // base pointer.  As a secondary criteria: make sure stores coming
11574   // later in the code come first in the list. This is important for
11575   // the non-UseAA case, because we're merging stores into the FINAL
11576   // store along a chain which potentially contains aliasing stores.
11577   // Thus, if there are multiple stores to the same address, the last
11578   // one can be considered for merging but not the others.
11579   std::sort(StoreNodes.begin(), StoreNodes.end(),
11580             [](MemOpLink LHS, MemOpLink RHS) {
11581     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11582            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11583             LHS.SequenceNum < RHS.SequenceNum);
11584   });
11585 
11586   // Scan the memory operations on the chain and find the first non-consecutive
11587   // store memory address.
11588   unsigned LastConsecutiveStore = 0;
11589   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11590   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11591 
11592     // Check that the addresses are consecutive starting from the second
11593     // element in the list of stores.
11594     if (i > 0) {
11595       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11596       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11597         break;
11598     }
11599 
11600     // Check if this store interferes with any of the loads that we found.
11601     // If we find a load that alias with this store. Stop the sequence.
11602     if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11603                     [&](LSBaseSDNode* Ldn) {
11604                       return isAlias(Ldn, StoreNodes[i].MemNode);
11605                     }))
11606       break;
11607 
11608     // Mark this node as useful.
11609     LastConsecutiveStore = i;
11610   }
11611 
11612   // The node with the lowest store address.
11613   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11614   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11615   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11616   LLVMContext &Context = *DAG.getContext();
11617   const DataLayout &DL = DAG.getDataLayout();
11618 
11619   // Store the constants into memory as one consecutive store.
11620   if (IsConstantSrc) {
11621     unsigned LastLegalType = 0;
11622     unsigned LastLegalVectorType = 0;
11623     bool NonZero = false;
11624     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11625       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11626       SDValue StoredVal = St->getValue();
11627 
11628       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11629         NonZero |= !C->isNullValue();
11630       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11631         NonZero |= !C->getConstantFPValue()->isNullValue();
11632       } else {
11633         // Non-constant.
11634         break;
11635       }
11636 
11637       // Find a legal type for the constant store.
11638       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11639       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11640       bool IsFast;
11641       if (TLI.isTypeLegal(StoreTy) &&
11642           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11643                                  FirstStoreAlign, &IsFast) && IsFast) {
11644         LastLegalType = i+1;
11645       // Or check whether a truncstore is legal.
11646       } else if (TLI.getTypeAction(Context, StoreTy) ==
11647                  TargetLowering::TypePromoteInteger) {
11648         EVT LegalizedStoredValueTy =
11649           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11650         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11651             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11652                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11653             IsFast) {
11654           LastLegalType = i + 1;
11655         }
11656       }
11657 
11658       // We only use vectors if the constant is known to be zero or the target
11659       // allows it and the function is not marked with the noimplicitfloat
11660       // attribute.
11661       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11662                                                         FirstStoreAS)) &&
11663           !NoVectors) {
11664         // Find a legal type for the vector store.
11665         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11666         if (TLI.isTypeLegal(Ty) &&
11667             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11668                                    FirstStoreAlign, &IsFast) && IsFast)
11669           LastLegalVectorType = i + 1;
11670       }
11671     }
11672 
11673     // Check if we found a legal integer type to store.
11674     if (LastLegalType == 0 && LastLegalVectorType == 0)
11675       return false;
11676 
11677     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11678     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11679 
11680     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11681                                            true, UseVector);
11682   }
11683 
11684   // When extracting multiple vector elements, try to store them
11685   // in one vector store rather than a sequence of scalar stores.
11686   if (IsExtractVecSrc) {
11687     unsigned NumStoresToMerge = 0;
11688     bool IsVec = MemVT.isVector();
11689     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11690       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11691       unsigned StoreValOpcode = St->getValue().getOpcode();
11692       // This restriction could be loosened.
11693       // Bail out if any stored values are not elements extracted from a vector.
11694       // It should be possible to handle mixed sources, but load sources need
11695       // more careful handling (see the block of code below that handles
11696       // consecutive loads).
11697       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11698           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11699         return false;
11700 
11701       // Find a legal type for the vector store.
11702       unsigned Elts = i + 1;
11703       if (IsVec) {
11704         // When merging vector stores, get the total number of elements.
11705         Elts *= MemVT.getVectorNumElements();
11706       }
11707       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11708       bool IsFast;
11709       if (TLI.isTypeLegal(Ty) &&
11710           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11711                                  FirstStoreAlign, &IsFast) && IsFast)
11712         NumStoresToMerge = i + 1;
11713     }
11714 
11715     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11716                                            false, true);
11717   }
11718 
11719   // Below we handle the case of multiple consecutive stores that
11720   // come from multiple consecutive loads. We merge them into a single
11721   // wide load and a single wide store.
11722 
11723   // Look for load nodes which are used by the stored values.
11724   SmallVector<MemOpLink, 8> LoadNodes;
11725 
11726   // Find acceptable loads. Loads need to have the same chain (token factor),
11727   // must not be zext, volatile, indexed, and they must be consecutive.
11728   BaseIndexOffset LdBasePtr;
11729   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11730     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11731     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11732     if (!Ld) break;
11733 
11734     // Loads must only have one use.
11735     if (!Ld->hasNUsesOfValue(1, 0))
11736       break;
11737 
11738     // The memory operands must not be volatile.
11739     if (Ld->isVolatile() || Ld->isIndexed())
11740       break;
11741 
11742     // We do not accept ext loads.
11743     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11744       break;
11745 
11746     // The stored memory type must be the same.
11747     if (Ld->getMemoryVT() != MemVT)
11748       break;
11749 
11750     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11751     // If this is not the first ptr that we check.
11752     if (LdBasePtr.Base.getNode()) {
11753       // The base ptr must be the same.
11754       if (!LdPtr.equalBaseIndex(LdBasePtr))
11755         break;
11756     } else {
11757       // Check that all other base pointers are the same as this one.
11758       LdBasePtr = LdPtr;
11759     }
11760 
11761     // We found a potential memory operand to merge.
11762     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11763   }
11764 
11765   if (LoadNodes.size() < 2)
11766     return false;
11767 
11768   // If we have load/store pair instructions and we only have two values,
11769   // don't bother.
11770   unsigned RequiredAlignment;
11771   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11772       St->getAlignment() >= RequiredAlignment)
11773     return false;
11774 
11775   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11776   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11777   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11778 
11779   // Scan the memory operations on the chain and find the first non-consecutive
11780   // load memory address. These variables hold the index in the store node
11781   // array.
11782   unsigned LastConsecutiveLoad = 0;
11783   // This variable refers to the size and not index in the array.
11784   unsigned LastLegalVectorType = 0;
11785   unsigned LastLegalIntegerType = 0;
11786   StartAddress = LoadNodes[0].OffsetFromBase;
11787   SDValue FirstChain = FirstLoad->getChain();
11788   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11789     // All loads must share the same chain.
11790     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11791       break;
11792 
11793     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11794     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11795       break;
11796     LastConsecutiveLoad = i;
11797     // Find a legal type for the vector store.
11798     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11799     bool IsFastSt, IsFastLd;
11800     if (TLI.isTypeLegal(StoreTy) &&
11801         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11802                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11803         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11804                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11805       LastLegalVectorType = i + 1;
11806     }
11807 
11808     // Find a legal type for the integer store.
11809     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11810     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11811     if (TLI.isTypeLegal(StoreTy) &&
11812         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11813                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11814         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11815                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11816       LastLegalIntegerType = i + 1;
11817     // Or check whether a truncstore and extload is legal.
11818     else if (TLI.getTypeAction(Context, StoreTy) ==
11819              TargetLowering::TypePromoteInteger) {
11820       EVT LegalizedStoredValueTy =
11821         TLI.getTypeToTransformTo(Context, StoreTy);
11822       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11823           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11824           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11825           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11826           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11827                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11828           IsFastSt &&
11829           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11830                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11831           IsFastLd)
11832         LastLegalIntegerType = i+1;
11833     }
11834   }
11835 
11836   // Only use vector types if the vector type is larger than the integer type.
11837   // If they are the same, use integers.
11838   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11839   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11840 
11841   // We add +1 here because the LastXXX variables refer to location while
11842   // the NumElem refers to array/index size.
11843   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11844   NumElem = std::min(LastLegalType, NumElem);
11845 
11846   if (NumElem < 2)
11847     return false;
11848 
11849   // Collect the chains from all merged stores.
11850   SmallVector<SDValue, 8> MergeStoreChains;
11851   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11852 
11853   // The latest Node in the DAG.
11854   unsigned LatestNodeUsed = 0;
11855   for (unsigned i=1; i<NumElem; ++i) {
11856     // Find a chain for the new wide-store operand. Notice that some
11857     // of the store nodes that we found may not be selected for inclusion
11858     // in the wide store. The chain we use needs to be the chain of the
11859     // latest store node which is *used* and replaced by the wide store.
11860     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11861       LatestNodeUsed = i;
11862 
11863     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11864   }
11865 
11866   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11867 
11868   // Find if it is better to use vectors or integers to load and store
11869   // to memory.
11870   EVT JointMemOpVT;
11871   if (UseVectorTy) {
11872     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11873   } else {
11874     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11875     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11876   }
11877 
11878   SDLoc LoadDL(LoadNodes[0].MemNode);
11879   SDLoc StoreDL(StoreNodes[0].MemNode);
11880 
11881   // The merged loads are required to have the same incoming chain, so
11882   // using the first's chain is acceptable.
11883   SDValue NewLoad = DAG.getLoad(
11884       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11885       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11886 
11887   SDValue NewStoreChain =
11888     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11889 
11890   SDValue NewStore = DAG.getStore(
11891     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11892       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11893 
11894   // Transfer chain users from old loads to the new load.
11895   for (unsigned i = 0; i < NumElem; ++i) {
11896     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11897     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11898                                   SDValue(NewLoad.getNode(), 1));
11899   }
11900 
11901   if (UseAA) {
11902     // Replace the all stores with the new store.
11903     for (unsigned i = 0; i < NumElem; ++i)
11904       CombineTo(StoreNodes[i].MemNode, NewStore);
11905   } else {
11906     // Replace the last store with the new store.
11907     CombineTo(LatestOp, NewStore);
11908     // Erase all other stores.
11909     for (unsigned i = 0; i < NumElem; ++i) {
11910       // Remove all Store nodes.
11911       if (StoreNodes[i].MemNode == LatestOp)
11912         continue;
11913       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11914       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11915       deleteAndRecombine(St);
11916     }
11917   }
11918 
11919   return true;
11920 }
11921 
11922 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11923   SDLoc SL(ST);
11924   SDValue ReplStore;
11925 
11926   // Replace the chain to avoid dependency.
11927   if (ST->isTruncatingStore()) {
11928     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11929                                   ST->getBasePtr(), ST->getMemoryVT(),
11930                                   ST->getMemOperand());
11931   } else {
11932     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11933                              ST->getMemOperand());
11934   }
11935 
11936   // Create token to keep both nodes around.
11937   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11938                               MVT::Other, ST->getChain(), ReplStore);
11939 
11940   // Make sure the new and old chains are cleaned up.
11941   AddToWorklist(Token.getNode());
11942 
11943   // Don't add users to work list.
11944   return CombineTo(ST, Token, false);
11945 }
11946 
11947 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11948   SDValue Value = ST->getValue();
11949   if (Value.getOpcode() == ISD::TargetConstantFP)
11950     return SDValue();
11951 
11952   SDLoc DL(ST);
11953 
11954   SDValue Chain = ST->getChain();
11955   SDValue Ptr = ST->getBasePtr();
11956 
11957   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11958 
11959   // NOTE: If the original store is volatile, this transform must not increase
11960   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11961   // processor operation but an i64 (which is not legal) requires two.  So the
11962   // transform should not be done in this case.
11963 
11964   SDValue Tmp;
11965   switch (CFP->getSimpleValueType(0).SimpleTy) {
11966   default:
11967     llvm_unreachable("Unknown FP type");
11968   case MVT::f16:    // We don't do this for these yet.
11969   case MVT::f80:
11970   case MVT::f128:
11971   case MVT::ppcf128:
11972     return SDValue();
11973   case MVT::f32:
11974     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11975         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11976       ;
11977       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11978                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11979                             MVT::i32);
11980       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11981     }
11982 
11983     return SDValue();
11984   case MVT::f64:
11985     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11986          !ST->isVolatile()) ||
11987         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11988       ;
11989       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11990                             getZExtValue(), SDLoc(CFP), MVT::i64);
11991       return DAG.getStore(Chain, DL, Tmp,
11992                           Ptr, ST->getMemOperand());
11993     }
11994 
11995     if (!ST->isVolatile() &&
11996         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11997       // Many FP stores are not made apparent until after legalize, e.g. for
11998       // argument passing.  Since this is so common, custom legalize the
11999       // 64-bit integer store into two 32-bit stores.
12000       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12001       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12002       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12003       if (DAG.getDataLayout().isBigEndian())
12004         std::swap(Lo, Hi);
12005 
12006       unsigned Alignment = ST->getAlignment();
12007       bool isVolatile = ST->isVolatile();
12008       bool isNonTemporal = ST->isNonTemporal();
12009       AAMDNodes AAInfo = ST->getAAInfo();
12010 
12011       SDValue St0 = DAG.getStore(Chain, DL, Lo,
12012                                  Ptr, ST->getPointerInfo(),
12013                                  isVolatile, isNonTemporal,
12014                                  ST->getAlignment(), AAInfo);
12015       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12016                         DAG.getConstant(4, DL, Ptr.getValueType()));
12017       Alignment = MinAlign(Alignment, 4U);
12018       SDValue St1 = DAG.getStore(Chain, DL, Hi,
12019                                  Ptr, ST->getPointerInfo().getWithOffset(4),
12020                                  isVolatile, isNonTemporal,
12021                                  Alignment, AAInfo);
12022       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12023                          St0, St1);
12024     }
12025 
12026     return SDValue();
12027   }
12028 }
12029 
12030 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12031   StoreSDNode *ST  = cast<StoreSDNode>(N);
12032   SDValue Chain = ST->getChain();
12033   SDValue Value = ST->getValue();
12034   SDValue Ptr   = ST->getBasePtr();
12035 
12036   // If this is a store of a bit convert, store the input value if the
12037   // resultant store does not need a higher alignment than the original.
12038   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12039       ST->isUnindexed()) {
12040     EVT SVT = Value.getOperand(0).getValueType();
12041     if (((!LegalOperations && !ST->isVolatile()) ||
12042          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12043         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12044       unsigned OrigAlign = ST->getAlignment();
12045       bool Fast = false;
12046       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12047                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12048           Fast) {
12049         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
12050                             Ptr, ST->getPointerInfo(), ST->isVolatile(),
12051                             ST->isNonTemporal(), OrigAlign,
12052                             ST->getAAInfo());
12053       }
12054     }
12055   }
12056 
12057   // Turn 'store undef, Ptr' -> nothing.
12058   if (Value.isUndef() && ST->isUnindexed())
12059     return Chain;
12060 
12061   // Try to infer better alignment information than the store already has.
12062   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12063     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12064       if (Align > ST->getAlignment()) {
12065         SDValue NewStore =
12066                DAG.getTruncStore(Chain, SDLoc(N), Value,
12067                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
12068                                  ST->isVolatile(), ST->isNonTemporal(), Align,
12069                                  ST->getAAInfo());
12070         if (NewStore.getNode() != N)
12071           return CombineTo(ST, NewStore, true);
12072       }
12073     }
12074   }
12075 
12076   // Try transforming a pair floating point load / store ops to integer
12077   // load / store ops.
12078   if (SDValue NewST = TransformFPLoadStorePair(N))
12079     return NewST;
12080 
12081   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12082                                                   : DAG.getSubtarget().useAA();
12083 #ifndef NDEBUG
12084   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12085       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12086     UseAA = false;
12087 #endif
12088   if (UseAA && ST->isUnindexed()) {
12089     // FIXME: We should do this even without AA enabled. AA will just allow
12090     // FindBetterChain to work in more situations. The problem with this is that
12091     // any combine that expects memory operations to be on consecutive chains
12092     // first needs to be updated to look for users of the same chain.
12093 
12094     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12095     // adjacent stores.
12096     if (findBetterNeighborChains(ST)) {
12097       // replaceStoreChain uses CombineTo, which handled all of the worklist
12098       // manipulation. Return the original node to not do anything else.
12099       return SDValue(ST, 0);
12100     }
12101   }
12102 
12103   // Try transforming N to an indexed store.
12104   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12105     return SDValue(N, 0);
12106 
12107   // FIXME: is there such a thing as a truncating indexed store?
12108   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12109       Value.getValueType().isInteger()) {
12110     // See if we can simplify the input to this truncstore with knowledge that
12111     // only the low bits are being used.  For example:
12112     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12113     SDValue Shorter =
12114       GetDemandedBits(Value,
12115                       APInt::getLowBitsSet(
12116                         Value.getValueType().getScalarType().getSizeInBits(),
12117                         ST->getMemoryVT().getScalarType().getSizeInBits()));
12118     AddToWorklist(Value.getNode());
12119     if (Shorter.getNode())
12120       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12121                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12122 
12123     // Otherwise, see if we can simplify the operation with
12124     // SimplifyDemandedBits, which only works if the value has a single use.
12125     if (SimplifyDemandedBits(Value,
12126                         APInt::getLowBitsSet(
12127                           Value.getValueType().getScalarType().getSizeInBits(),
12128                           ST->getMemoryVT().getScalarType().getSizeInBits())))
12129       return SDValue(N, 0);
12130   }
12131 
12132   // If this is a load followed by a store to the same location, then the store
12133   // is dead/noop.
12134   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12135     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12136         ST->isUnindexed() && !ST->isVolatile() &&
12137         // There can't be any side effects between the load and store, such as
12138         // a call or store.
12139         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12140       // The store is dead, remove it.
12141       return Chain;
12142     }
12143   }
12144 
12145   // If this is a store followed by a store with the same value to the same
12146   // location, then the store is dead/noop.
12147   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12148     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12149         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12150         ST1->isUnindexed() && !ST1->isVolatile()) {
12151       // The store is dead, remove it.
12152       return Chain;
12153     }
12154   }
12155 
12156   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12157   // truncating store.  We can do this even if this is already a truncstore.
12158   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12159       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12160       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12161                             ST->getMemoryVT())) {
12162     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12163                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12164   }
12165 
12166   // Only perform this optimization before the types are legal, because we
12167   // don't want to perform this optimization on every DAGCombine invocation.
12168   if (!LegalTypes) {
12169     bool EverChanged = false;
12170 
12171     do {
12172       // There can be multiple store sequences on the same chain.
12173       // Keep trying to merge store sequences until we are unable to do so
12174       // or until we merge the last store on the chain.
12175       bool Changed = MergeConsecutiveStores(ST);
12176       EverChanged |= Changed;
12177       if (!Changed) break;
12178     } while (ST->getOpcode() != ISD::DELETED_NODE);
12179 
12180     if (EverChanged)
12181       return SDValue(N, 0);
12182   }
12183 
12184   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12185   //
12186   // Make sure to do this only after attempting to merge stores in order to
12187   //  avoid changing the types of some subset of stores due to visit order,
12188   //  preventing their merging.
12189   if (isa<ConstantFPSDNode>(Value)) {
12190     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12191       return NewSt;
12192   }
12193 
12194   return ReduceLoadOpStoreWidth(N);
12195 }
12196 
12197 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12198   SDValue InVec = N->getOperand(0);
12199   SDValue InVal = N->getOperand(1);
12200   SDValue EltNo = N->getOperand(2);
12201   SDLoc dl(N);
12202 
12203   // If the inserted element is an UNDEF, just use the input vector.
12204   if (InVal.isUndef())
12205     return InVec;
12206 
12207   EVT VT = InVec.getValueType();
12208 
12209   // If we can't generate a legal BUILD_VECTOR, exit
12210   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12211     return SDValue();
12212 
12213   // Check that we know which element is being inserted
12214   if (!isa<ConstantSDNode>(EltNo))
12215     return SDValue();
12216   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12217 
12218   // Canonicalize insert_vector_elt dag nodes.
12219   // Example:
12220   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12221   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12222   //
12223   // Do this only if the child insert_vector node has one use; also
12224   // do this only if indices are both constants and Idx1 < Idx0.
12225   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12226       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12227     unsigned OtherElt =
12228       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12229     if (Elt < OtherElt) {
12230       // Swap nodes.
12231       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12232                                   InVec.getOperand(0), InVal, EltNo);
12233       AddToWorklist(NewOp.getNode());
12234       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12235                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12236     }
12237   }
12238 
12239   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12240   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12241   // vector elements.
12242   SmallVector<SDValue, 8> Ops;
12243   // Do not combine these two vectors if the output vector will not replace
12244   // the input vector.
12245   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12246     Ops.append(InVec.getNode()->op_begin(),
12247                InVec.getNode()->op_end());
12248   } else if (InVec.isUndef()) {
12249     unsigned NElts = VT.getVectorNumElements();
12250     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12251   } else {
12252     return SDValue();
12253   }
12254 
12255   // Insert the element
12256   if (Elt < Ops.size()) {
12257     // All the operands of BUILD_VECTOR must have the same type;
12258     // we enforce that here.
12259     EVT OpVT = Ops[0].getValueType();
12260     if (InVal.getValueType() != OpVT)
12261       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12262                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12263                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12264     Ops[Elt] = InVal;
12265   }
12266 
12267   // Return the new vector
12268   return DAG.getBuildVector(VT, dl, Ops);
12269 }
12270 
12271 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12272     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12273   assert(!OriginalLoad->isVolatile());
12274 
12275   EVT ResultVT = EVE->getValueType(0);
12276   EVT VecEltVT = InVecVT.getVectorElementType();
12277   unsigned Align = OriginalLoad->getAlignment();
12278   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12279       VecEltVT.getTypeForEVT(*DAG.getContext()));
12280 
12281   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12282     return SDValue();
12283 
12284   Align = NewAlign;
12285 
12286   SDValue NewPtr = OriginalLoad->getBasePtr();
12287   SDValue Offset;
12288   EVT PtrType = NewPtr.getValueType();
12289   MachinePointerInfo MPI;
12290   SDLoc DL(EVE);
12291   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12292     int Elt = ConstEltNo->getZExtValue();
12293     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12294     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12295     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12296   } else {
12297     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12298     Offset = DAG.getNode(
12299         ISD::MUL, DL, PtrType, Offset,
12300         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12301     MPI = OriginalLoad->getPointerInfo();
12302   }
12303   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12304 
12305   // The replacement we need to do here is a little tricky: we need to
12306   // replace an extractelement of a load with a load.
12307   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12308   // Note that this replacement assumes that the extractvalue is the only
12309   // use of the load; that's okay because we don't want to perform this
12310   // transformation in other cases anyway.
12311   SDValue Load;
12312   SDValue Chain;
12313   if (ResultVT.bitsGT(VecEltVT)) {
12314     // If the result type of vextract is wider than the load, then issue an
12315     // extending load instead.
12316     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12317                                                   VecEltVT)
12318                                    ? ISD::ZEXTLOAD
12319                                    : ISD::EXTLOAD;
12320     Load = DAG.getExtLoad(
12321         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12322         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12323         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12324     Chain = Load.getValue(1);
12325   } else {
12326     Load = DAG.getLoad(
12327         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12328         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12329         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12330     Chain = Load.getValue(1);
12331     if (ResultVT.bitsLT(VecEltVT))
12332       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12333     else
12334       Load = DAG.getBitcast(ResultVT, Load);
12335   }
12336   WorklistRemover DeadNodes(*this);
12337   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12338   SDValue To[] = { Load, Chain };
12339   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12340   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12341   // worklist explicitly as well.
12342   AddToWorklist(Load.getNode());
12343   AddUsersToWorklist(Load.getNode()); // Add users too
12344   // Make sure to revisit this node to clean it up; it will usually be dead.
12345   AddToWorklist(EVE);
12346   ++OpsNarrowed;
12347   return SDValue(EVE, 0);
12348 }
12349 
12350 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12351   // (vextract (scalar_to_vector val, 0) -> val
12352   SDValue InVec = N->getOperand(0);
12353   EVT VT = InVec.getValueType();
12354   EVT NVT = N->getValueType(0);
12355 
12356   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12357     // Check if the result type doesn't match the inserted element type. A
12358     // SCALAR_TO_VECTOR may truncate the inserted element and the
12359     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12360     SDValue InOp = InVec.getOperand(0);
12361     if (InOp.getValueType() != NVT) {
12362       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12363       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12364     }
12365     return InOp;
12366   }
12367 
12368   SDValue EltNo = N->getOperand(1);
12369   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12370 
12371   // extract_vector_elt (build_vector x, y), 1 -> y
12372   if (ConstEltNo &&
12373       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12374       TLI.isTypeLegal(VT) &&
12375       (InVec.hasOneUse() ||
12376        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12377     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12378     EVT InEltVT = Elt.getValueType();
12379 
12380     // Sometimes build_vector's scalar input types do not match result type.
12381     if (NVT == InEltVT)
12382       return Elt;
12383 
12384     // TODO: It may be useful to truncate if free if the build_vector implicitly
12385     // converts.
12386   }
12387 
12388   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12389   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12390       ConstEltNo->isNullValue() && VT.isInteger()) {
12391     SDValue BCSrc = InVec.getOperand(0);
12392     if (BCSrc.getValueType().isScalarInteger())
12393       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12394   }
12395 
12396   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12397   // We only perform this optimization before the op legalization phase because
12398   // we may introduce new vector instructions which are not backed by TD
12399   // patterns. For example on AVX, extracting elements from a wide vector
12400   // without using extract_subvector. However, if we can find an underlying
12401   // scalar value, then we can always use that.
12402   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12403     int NumElem = VT.getVectorNumElements();
12404     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12405     // Find the new index to extract from.
12406     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12407 
12408     // Extracting an undef index is undef.
12409     if (OrigElt == -1)
12410       return DAG.getUNDEF(NVT);
12411 
12412     // Select the right vector half to extract from.
12413     SDValue SVInVec;
12414     if (OrigElt < NumElem) {
12415       SVInVec = InVec->getOperand(0);
12416     } else {
12417       SVInVec = InVec->getOperand(1);
12418       OrigElt -= NumElem;
12419     }
12420 
12421     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12422       SDValue InOp = SVInVec.getOperand(OrigElt);
12423       if (InOp.getValueType() != NVT) {
12424         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12425         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12426       }
12427 
12428       return InOp;
12429     }
12430 
12431     // FIXME: We should handle recursing on other vector shuffles and
12432     // scalar_to_vector here as well.
12433 
12434     if (!LegalOperations) {
12435       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12436       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12437                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12438     }
12439   }
12440 
12441   bool BCNumEltsChanged = false;
12442   EVT ExtVT = VT.getVectorElementType();
12443   EVT LVT = ExtVT;
12444 
12445   // If the result of load has to be truncated, then it's not necessarily
12446   // profitable.
12447   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12448     return SDValue();
12449 
12450   if (InVec.getOpcode() == ISD::BITCAST) {
12451     // Don't duplicate a load with other uses.
12452     if (!InVec.hasOneUse())
12453       return SDValue();
12454 
12455     EVT BCVT = InVec.getOperand(0).getValueType();
12456     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12457       return SDValue();
12458     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12459       BCNumEltsChanged = true;
12460     InVec = InVec.getOperand(0);
12461     ExtVT = BCVT.getVectorElementType();
12462   }
12463 
12464   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12465   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12466       ISD::isNormalLoad(InVec.getNode()) &&
12467       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12468     SDValue Index = N->getOperand(1);
12469     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12470       if (!OrigLoad->isVolatile()) {
12471         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12472                                                              OrigLoad);
12473       }
12474     }
12475   }
12476 
12477   // Perform only after legalization to ensure build_vector / vector_shuffle
12478   // optimizations have already been done.
12479   if (!LegalOperations) return SDValue();
12480 
12481   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12482   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12483   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12484 
12485   if (ConstEltNo) {
12486     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12487 
12488     LoadSDNode *LN0 = nullptr;
12489     const ShuffleVectorSDNode *SVN = nullptr;
12490     if (ISD::isNormalLoad(InVec.getNode())) {
12491       LN0 = cast<LoadSDNode>(InVec);
12492     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12493                InVec.getOperand(0).getValueType() == ExtVT &&
12494                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12495       // Don't duplicate a load with other uses.
12496       if (!InVec.hasOneUse())
12497         return SDValue();
12498 
12499       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12500     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12501       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12502       // =>
12503       // (load $addr+1*size)
12504 
12505       // Don't duplicate a load with other uses.
12506       if (!InVec.hasOneUse())
12507         return SDValue();
12508 
12509       // If the bit convert changed the number of elements, it is unsafe
12510       // to examine the mask.
12511       if (BCNumEltsChanged)
12512         return SDValue();
12513 
12514       // Select the input vector, guarding against out of range extract vector.
12515       unsigned NumElems = VT.getVectorNumElements();
12516       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12517       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12518 
12519       if (InVec.getOpcode() == ISD::BITCAST) {
12520         // Don't duplicate a load with other uses.
12521         if (!InVec.hasOneUse())
12522           return SDValue();
12523 
12524         InVec = InVec.getOperand(0);
12525       }
12526       if (ISD::isNormalLoad(InVec.getNode())) {
12527         LN0 = cast<LoadSDNode>(InVec);
12528         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12529         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12530       }
12531     }
12532 
12533     // Make sure we found a non-volatile load and the extractelement is
12534     // the only use.
12535     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12536       return SDValue();
12537 
12538     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12539     if (Elt == -1)
12540       return DAG.getUNDEF(LVT);
12541 
12542     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12543   }
12544 
12545   return SDValue();
12546 }
12547 
12548 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12549 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12550   // We perform this optimization post type-legalization because
12551   // the type-legalizer often scalarizes integer-promoted vectors.
12552   // Performing this optimization before may create bit-casts which
12553   // will be type-legalized to complex code sequences.
12554   // We perform this optimization only before the operation legalizer because we
12555   // may introduce illegal operations.
12556   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12557     return SDValue();
12558 
12559   unsigned NumInScalars = N->getNumOperands();
12560   SDLoc dl(N);
12561   EVT VT = N->getValueType(0);
12562 
12563   // Check to see if this is a BUILD_VECTOR of a bunch of values
12564   // which come from any_extend or zero_extend nodes. If so, we can create
12565   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12566   // optimizations. We do not handle sign-extend because we can't fill the sign
12567   // using shuffles.
12568   EVT SourceType = MVT::Other;
12569   bool AllAnyExt = true;
12570 
12571   for (unsigned i = 0; i != NumInScalars; ++i) {
12572     SDValue In = N->getOperand(i);
12573     // Ignore undef inputs.
12574     if (In.isUndef()) continue;
12575 
12576     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12577     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12578 
12579     // Abort if the element is not an extension.
12580     if (!ZeroExt && !AnyExt) {
12581       SourceType = MVT::Other;
12582       break;
12583     }
12584 
12585     // The input is a ZeroExt or AnyExt. Check the original type.
12586     EVT InTy = In.getOperand(0).getValueType();
12587 
12588     // Check that all of the widened source types are the same.
12589     if (SourceType == MVT::Other)
12590       // First time.
12591       SourceType = InTy;
12592     else if (InTy != SourceType) {
12593       // Multiple income types. Abort.
12594       SourceType = MVT::Other;
12595       break;
12596     }
12597 
12598     // Check if all of the extends are ANY_EXTENDs.
12599     AllAnyExt &= AnyExt;
12600   }
12601 
12602   // In order to have valid types, all of the inputs must be extended from the
12603   // same source type and all of the inputs must be any or zero extend.
12604   // Scalar sizes must be a power of two.
12605   EVT OutScalarTy = VT.getScalarType();
12606   bool ValidTypes = SourceType != MVT::Other &&
12607                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12608                  isPowerOf2_32(SourceType.getSizeInBits());
12609 
12610   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12611   // turn into a single shuffle instruction.
12612   if (!ValidTypes)
12613     return SDValue();
12614 
12615   bool isLE = DAG.getDataLayout().isLittleEndian();
12616   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12617   assert(ElemRatio > 1 && "Invalid element size ratio");
12618   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12619                                DAG.getConstant(0, SDLoc(N), SourceType);
12620 
12621   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12622   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12623 
12624   // Populate the new build_vector
12625   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12626     SDValue Cast = N->getOperand(i);
12627     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12628             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12629             Cast.isUndef()) && "Invalid cast opcode");
12630     SDValue In;
12631     if (Cast.isUndef())
12632       In = DAG.getUNDEF(SourceType);
12633     else
12634       In = Cast->getOperand(0);
12635     unsigned Index = isLE ? (i * ElemRatio) :
12636                             (i * ElemRatio + (ElemRatio - 1));
12637 
12638     assert(Index < Ops.size() && "Invalid index");
12639     Ops[Index] = In;
12640   }
12641 
12642   // The type of the new BUILD_VECTOR node.
12643   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12644   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12645          "Invalid vector size");
12646   // Check if the new vector type is legal.
12647   if (!isTypeLegal(VecVT)) return SDValue();
12648 
12649   // Make the new BUILD_VECTOR.
12650   SDValue BV = DAG.getBuildVector(VecVT, dl, Ops);
12651 
12652   // The new BUILD_VECTOR node has the potential to be further optimized.
12653   AddToWorklist(BV.getNode());
12654   // Bitcast to the desired type.
12655   return DAG.getBitcast(VT, BV);
12656 }
12657 
12658 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12659   EVT VT = N->getValueType(0);
12660 
12661   unsigned NumInScalars = N->getNumOperands();
12662   SDLoc dl(N);
12663 
12664   EVT SrcVT = MVT::Other;
12665   unsigned Opcode = ISD::DELETED_NODE;
12666   unsigned NumDefs = 0;
12667 
12668   for (unsigned i = 0; i != NumInScalars; ++i) {
12669     SDValue In = N->getOperand(i);
12670     unsigned Opc = In.getOpcode();
12671 
12672     if (Opc == ISD::UNDEF)
12673       continue;
12674 
12675     // If all scalar values are floats and converted from integers.
12676     if (Opcode == ISD::DELETED_NODE &&
12677         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12678       Opcode = Opc;
12679     }
12680 
12681     if (Opc != Opcode)
12682       return SDValue();
12683 
12684     EVT InVT = In.getOperand(0).getValueType();
12685 
12686     // If all scalar values are typed differently, bail out. It's chosen to
12687     // simplify BUILD_VECTOR of integer types.
12688     if (SrcVT == MVT::Other)
12689       SrcVT = InVT;
12690     if (SrcVT != InVT)
12691       return SDValue();
12692     NumDefs++;
12693   }
12694 
12695   // If the vector has just one element defined, it's not worth to fold it into
12696   // a vectorized one.
12697   if (NumDefs < 2)
12698     return SDValue();
12699 
12700   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12701          && "Should only handle conversion from integer to float.");
12702   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12703 
12704   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12705 
12706   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12707     return SDValue();
12708 
12709   // Just because the floating-point vector type is legal does not necessarily
12710   // mean that the corresponding integer vector type is.
12711   if (!isTypeLegal(NVT))
12712     return SDValue();
12713 
12714   SmallVector<SDValue, 8> Opnds;
12715   for (unsigned i = 0; i != NumInScalars; ++i) {
12716     SDValue In = N->getOperand(i);
12717 
12718     if (In.isUndef())
12719       Opnds.push_back(DAG.getUNDEF(SrcVT));
12720     else
12721       Opnds.push_back(In.getOperand(0));
12722   }
12723   SDValue BV = DAG.getBuildVector(NVT, dl, Opnds);
12724   AddToWorklist(BV.getNode());
12725 
12726   return DAG.getNode(Opcode, dl, VT, BV);
12727 }
12728 
12729 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12730   unsigned NumInScalars = N->getNumOperands();
12731   SDLoc dl(N);
12732   EVT VT = N->getValueType(0);
12733 
12734   // A vector built entirely of undefs is undef.
12735   if (ISD::allOperandsUndef(N))
12736     return DAG.getUNDEF(VT);
12737 
12738   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12739     return V;
12740 
12741   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12742     return V;
12743 
12744   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12745   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12746   // at most two distinct vectors, turn this into a shuffle node.
12747 
12748   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12749   if (!isTypeLegal(VT))
12750     return SDValue();
12751 
12752   // May only combine to shuffle after legalize if shuffle is legal.
12753   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12754     return SDValue();
12755 
12756   SDValue VecIn1, VecIn2;
12757   bool UsesZeroVector = false;
12758   for (unsigned i = 0; i != NumInScalars; ++i) {
12759     SDValue Op = N->getOperand(i);
12760     // Ignore undef inputs.
12761     if (Op.isUndef()) continue;
12762 
12763     // See if we can combine this build_vector into a blend with a zero vector.
12764     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12765       UsesZeroVector = true;
12766       continue;
12767     }
12768 
12769     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12770     // constant index, bail out.
12771     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12772         !isa<ConstantSDNode>(Op.getOperand(1))) {
12773       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12774       break;
12775     }
12776 
12777     // We allow up to two distinct input vectors.
12778     SDValue ExtractedFromVec = Op.getOperand(0);
12779     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12780       continue;
12781 
12782     if (!VecIn1.getNode()) {
12783       VecIn1 = ExtractedFromVec;
12784     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12785       VecIn2 = ExtractedFromVec;
12786     } else {
12787       // Too many inputs.
12788       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12789       break;
12790     }
12791   }
12792 
12793   // If everything is good, we can make a shuffle operation.
12794   if (VecIn1.getNode()) {
12795     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12796     SmallVector<int, 8> Mask;
12797     for (unsigned i = 0; i != NumInScalars; ++i) {
12798       unsigned Opcode = N->getOperand(i).getOpcode();
12799       if (Opcode == ISD::UNDEF) {
12800         Mask.push_back(-1);
12801         continue;
12802       }
12803 
12804       // Operands can also be zero.
12805       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12806         assert(UsesZeroVector &&
12807                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12808                "Unexpected node found!");
12809         Mask.push_back(NumInScalars+i);
12810         continue;
12811       }
12812 
12813       // If extracting from the first vector, just use the index directly.
12814       SDValue Extract = N->getOperand(i);
12815       SDValue ExtVal = Extract.getOperand(1);
12816       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12817       if (Extract.getOperand(0) == VecIn1) {
12818         Mask.push_back(ExtIndex);
12819         continue;
12820       }
12821 
12822       // Otherwise, use InIdx + InputVecSize
12823       Mask.push_back(InNumElements + ExtIndex);
12824     }
12825 
12826     // Avoid introducing illegal shuffles with zero.
12827     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12828       return SDValue();
12829 
12830     // We can't generate a shuffle node with mismatched input and output types.
12831     // Attempt to transform a single input vector to the correct type.
12832     if ((VT != VecIn1.getValueType())) {
12833       // If the input vector type has a different base type to the output
12834       // vector type, bail out.
12835       EVT VTElemType = VT.getVectorElementType();
12836       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12837           (VecIn2.getNode() &&
12838            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12839         return SDValue();
12840 
12841       // If the input vector is too small, widen it.
12842       // We only support widening of vectors which are half the size of the
12843       // output registers. For example XMM->YMM widening on X86 with AVX.
12844       EVT VecInT = VecIn1.getValueType();
12845       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12846         // If we only have one small input, widen it by adding undef values.
12847         if (!VecIn2.getNode())
12848           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12849                                DAG.getUNDEF(VecIn1.getValueType()));
12850         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12851           // If we have two small inputs of the same type, try to concat them.
12852           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12853           VecIn2 = SDValue(nullptr, 0);
12854         } else
12855           return SDValue();
12856       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12857         // If the input vector is too large, try to split it.
12858         // We don't support having two input vectors that are too large.
12859         // If the zero vector was used, we can not split the vector,
12860         // since we'd need 3 inputs.
12861         if (UsesZeroVector || VecIn2.getNode())
12862           return SDValue();
12863 
12864         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12865           return SDValue();
12866 
12867         // Try to replace VecIn1 with two extract_subvectors
12868         // No need to update the masks, they should still be correct.
12869         VecIn2 = DAG.getNode(
12870             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12871             DAG.getConstant(VT.getVectorNumElements(), dl,
12872                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12873         VecIn1 = DAG.getNode(
12874             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12875             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12876       } else
12877         return SDValue();
12878     }
12879 
12880     if (UsesZeroVector)
12881       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12882                                 DAG.getConstantFP(0.0, dl, VT);
12883     else
12884       // If VecIn2 is unused then change it to undef.
12885       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12886 
12887     // Check that we were able to transform all incoming values to the same
12888     // type.
12889     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12890         VecIn1.getValueType() != VT)
12891           return SDValue();
12892 
12893     // Return the new VECTOR_SHUFFLE node.
12894     SDValue Ops[2];
12895     Ops[0] = VecIn1;
12896     Ops[1] = VecIn2;
12897     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12898   }
12899 
12900   return SDValue();
12901 }
12902 
12903 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12904   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12905   EVT OpVT = N->getOperand(0).getValueType();
12906 
12907   // If the operands are legal vectors, leave them alone.
12908   if (TLI.isTypeLegal(OpVT))
12909     return SDValue();
12910 
12911   SDLoc DL(N);
12912   EVT VT = N->getValueType(0);
12913   SmallVector<SDValue, 8> Ops;
12914 
12915   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12916   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12917 
12918   // Keep track of what we encounter.
12919   bool AnyInteger = false;
12920   bool AnyFP = false;
12921   for (const SDValue &Op : N->ops()) {
12922     if (ISD::BITCAST == Op.getOpcode() &&
12923         !Op.getOperand(0).getValueType().isVector())
12924       Ops.push_back(Op.getOperand(0));
12925     else if (ISD::UNDEF == Op.getOpcode())
12926       Ops.push_back(ScalarUndef);
12927     else
12928       return SDValue();
12929 
12930     // Note whether we encounter an integer or floating point scalar.
12931     // If it's neither, bail out, it could be something weird like x86mmx.
12932     EVT LastOpVT = Ops.back().getValueType();
12933     if (LastOpVT.isFloatingPoint())
12934       AnyFP = true;
12935     else if (LastOpVT.isInteger())
12936       AnyInteger = true;
12937     else
12938       return SDValue();
12939   }
12940 
12941   // If any of the operands is a floating point scalar bitcast to a vector,
12942   // use floating point types throughout, and bitcast everything.
12943   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12944   if (AnyFP) {
12945     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12946     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12947     if (AnyInteger) {
12948       for (SDValue &Op : Ops) {
12949         if (Op.getValueType() == SVT)
12950           continue;
12951         if (Op.isUndef())
12952           Op = ScalarUndef;
12953         else
12954           Op = DAG.getBitcast(SVT, Op);
12955       }
12956     }
12957   }
12958 
12959   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12960                                VT.getSizeInBits() / SVT.getSizeInBits());
12961   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
12962 }
12963 
12964 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12965 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12966 // most two distinct vectors the same size as the result, attempt to turn this
12967 // into a legal shuffle.
12968 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12969   EVT VT = N->getValueType(0);
12970   EVT OpVT = N->getOperand(0).getValueType();
12971   int NumElts = VT.getVectorNumElements();
12972   int NumOpElts = OpVT.getVectorNumElements();
12973 
12974   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12975   SmallVector<int, 8> Mask;
12976 
12977   for (SDValue Op : N->ops()) {
12978     // Peek through any bitcast.
12979     while (Op.getOpcode() == ISD::BITCAST)
12980       Op = Op.getOperand(0);
12981 
12982     // UNDEF nodes convert to UNDEF shuffle mask values.
12983     if (Op.isUndef()) {
12984       Mask.append((unsigned)NumOpElts, -1);
12985       continue;
12986     }
12987 
12988     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12989       return SDValue();
12990 
12991     // What vector are we extracting the subvector from and at what index?
12992     SDValue ExtVec = Op.getOperand(0);
12993 
12994     // We want the EVT of the original extraction to correctly scale the
12995     // extraction index.
12996     EVT ExtVT = ExtVec.getValueType();
12997 
12998     // Peek through any bitcast.
12999     while (ExtVec.getOpcode() == ISD::BITCAST)
13000       ExtVec = ExtVec.getOperand(0);
13001 
13002     // UNDEF nodes convert to UNDEF shuffle mask values.
13003     if (ExtVec.isUndef()) {
13004       Mask.append((unsigned)NumOpElts, -1);
13005       continue;
13006     }
13007 
13008     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13009       return SDValue();
13010     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13011 
13012     // Ensure that we are extracting a subvector from a vector the same
13013     // size as the result.
13014     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13015       return SDValue();
13016 
13017     // Scale the subvector index to account for any bitcast.
13018     int NumExtElts = ExtVT.getVectorNumElements();
13019     if (0 == (NumExtElts % NumElts))
13020       ExtIdx /= (NumExtElts / NumElts);
13021     else if (0 == (NumElts % NumExtElts))
13022       ExtIdx *= (NumElts / NumExtElts);
13023     else
13024       return SDValue();
13025 
13026     // At most we can reference 2 inputs in the final shuffle.
13027     if (SV0.isUndef() || SV0 == ExtVec) {
13028       SV0 = ExtVec;
13029       for (int i = 0; i != NumOpElts; ++i)
13030         Mask.push_back(i + ExtIdx);
13031     } else if (SV1.isUndef() || SV1 == ExtVec) {
13032       SV1 = ExtVec;
13033       for (int i = 0; i != NumOpElts; ++i)
13034         Mask.push_back(i + ExtIdx + NumElts);
13035     } else {
13036       return SDValue();
13037     }
13038   }
13039 
13040   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13041     return SDValue();
13042 
13043   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13044                               DAG.getBitcast(VT, SV1), Mask);
13045 }
13046 
13047 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13048   // If we only have one input vector, we don't need to do any concatenation.
13049   if (N->getNumOperands() == 1)
13050     return N->getOperand(0);
13051 
13052   // Check if all of the operands are undefs.
13053   EVT VT = N->getValueType(0);
13054   if (ISD::allOperandsUndef(N))
13055     return DAG.getUNDEF(VT);
13056 
13057   // Optimize concat_vectors where all but the first of the vectors are undef.
13058   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13059         return Op.isUndef();
13060       })) {
13061     SDValue In = N->getOperand(0);
13062     assert(In.getValueType().isVector() && "Must concat vectors");
13063 
13064     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13065     if (In->getOpcode() == ISD::BITCAST &&
13066         !In->getOperand(0)->getValueType(0).isVector()) {
13067       SDValue Scalar = In->getOperand(0);
13068 
13069       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13070       // look through the trunc so we can still do the transform:
13071       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13072       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13073           !TLI.isTypeLegal(Scalar.getValueType()) &&
13074           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13075         Scalar = Scalar->getOperand(0);
13076 
13077       EVT SclTy = Scalar->getValueType(0);
13078 
13079       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13080         return SDValue();
13081 
13082       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13083                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13084       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13085         return SDValue();
13086 
13087       SDLoc dl = SDLoc(N);
13088       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
13089       return DAG.getBitcast(VT, Res);
13090     }
13091   }
13092 
13093   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13094   // We have already tested above for an UNDEF only concatenation.
13095   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13096   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13097   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13098     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13099   };
13100   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13101     SmallVector<SDValue, 8> Opnds;
13102     EVT SVT = VT.getScalarType();
13103 
13104     EVT MinVT = SVT;
13105     if (!SVT.isFloatingPoint()) {
13106       // If BUILD_VECTOR are from built from integer, they may have different
13107       // operand types. Get the smallest type and truncate all operands to it.
13108       bool FoundMinVT = false;
13109       for (const SDValue &Op : N->ops())
13110         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13111           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13112           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13113           FoundMinVT = true;
13114         }
13115       assert(FoundMinVT && "Concat vector type mismatch");
13116     }
13117 
13118     for (const SDValue &Op : N->ops()) {
13119       EVT OpVT = Op.getValueType();
13120       unsigned NumElts = OpVT.getVectorNumElements();
13121 
13122       if (ISD::UNDEF == Op.getOpcode())
13123         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13124 
13125       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13126         if (SVT.isFloatingPoint()) {
13127           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13128           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13129         } else {
13130           for (unsigned i = 0; i != NumElts; ++i)
13131             Opnds.push_back(
13132                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13133         }
13134       }
13135     }
13136 
13137     assert(VT.getVectorNumElements() == Opnds.size() &&
13138            "Concat vector type mismatch");
13139     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13140   }
13141 
13142   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13143   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13144     return V;
13145 
13146   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13147   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13148     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13149       return V;
13150 
13151   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13152   // nodes often generate nop CONCAT_VECTOR nodes.
13153   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13154   // place the incoming vectors at the exact same location.
13155   SDValue SingleSource = SDValue();
13156   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13157 
13158   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13159     SDValue Op = N->getOperand(i);
13160 
13161     if (Op.isUndef())
13162       continue;
13163 
13164     // Check if this is the identity extract:
13165     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13166       return SDValue();
13167 
13168     // Find the single incoming vector for the extract_subvector.
13169     if (SingleSource.getNode()) {
13170       if (Op.getOperand(0) != SingleSource)
13171         return SDValue();
13172     } else {
13173       SingleSource = Op.getOperand(0);
13174 
13175       // Check the source type is the same as the type of the result.
13176       // If not, this concat may extend the vector, so we can not
13177       // optimize it away.
13178       if (SingleSource.getValueType() != N->getValueType(0))
13179         return SDValue();
13180     }
13181 
13182     unsigned IdentityIndex = i * PartNumElem;
13183     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13184     // The extract index must be constant.
13185     if (!CS)
13186       return SDValue();
13187 
13188     // Check that we are reading from the identity index.
13189     if (CS->getZExtValue() != IdentityIndex)
13190       return SDValue();
13191   }
13192 
13193   if (SingleSource.getNode())
13194     return SingleSource;
13195 
13196   return SDValue();
13197 }
13198 
13199 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13200   EVT NVT = N->getValueType(0);
13201   SDValue V = N->getOperand(0);
13202 
13203   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13204     // Combine:
13205     //    (extract_subvec (concat V1, V2, ...), i)
13206     // Into:
13207     //    Vi if possible
13208     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13209     // type.
13210     if (V->getOperand(0).getValueType() != NVT)
13211       return SDValue();
13212     unsigned Idx = N->getConstantOperandVal(1);
13213     unsigned NumElems = NVT.getVectorNumElements();
13214     assert((Idx % NumElems) == 0 &&
13215            "IDX in concat is not a multiple of the result vector length.");
13216     return V->getOperand(Idx / NumElems);
13217   }
13218 
13219   // Skip bitcasting
13220   if (V->getOpcode() == ISD::BITCAST)
13221     V = V.getOperand(0);
13222 
13223   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13224     SDLoc dl(N);
13225     // Handle only simple case where vector being inserted and vector
13226     // being extracted are of same type, and are half size of larger vectors.
13227     EVT BigVT = V->getOperand(0).getValueType();
13228     EVT SmallVT = V->getOperand(1).getValueType();
13229     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13230       return SDValue();
13231 
13232     // Only handle cases where both indexes are constants with the same type.
13233     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13234     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13235 
13236     if (InsIdx && ExtIdx &&
13237         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13238         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13239       // Combine:
13240       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13241       // Into:
13242       //    indices are equal or bit offsets are equal => V1
13243       //    otherwise => (extract_subvec V1, ExtIdx)
13244       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13245           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13246         return DAG.getBitcast(NVT, V->getOperand(1));
13247       return DAG.getNode(
13248           ISD::EXTRACT_SUBVECTOR, dl, NVT,
13249           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13250           N->getOperand(1));
13251     }
13252   }
13253 
13254   return SDValue();
13255 }
13256 
13257 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13258                                                  SDValue V, SelectionDAG &DAG) {
13259   SDLoc DL(V);
13260   EVT VT = V.getValueType();
13261 
13262   switch (V.getOpcode()) {
13263   default:
13264     return V;
13265 
13266   case ISD::CONCAT_VECTORS: {
13267     EVT OpVT = V->getOperand(0).getValueType();
13268     int OpSize = OpVT.getVectorNumElements();
13269     SmallBitVector OpUsedElements(OpSize, false);
13270     bool FoundSimplification = false;
13271     SmallVector<SDValue, 4> NewOps;
13272     NewOps.reserve(V->getNumOperands());
13273     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13274       SDValue Op = V->getOperand(i);
13275       bool OpUsed = false;
13276       for (int j = 0; j < OpSize; ++j)
13277         if (UsedElements[i * OpSize + j]) {
13278           OpUsedElements[j] = true;
13279           OpUsed = true;
13280         }
13281       NewOps.push_back(
13282           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13283                  : DAG.getUNDEF(OpVT));
13284       FoundSimplification |= Op == NewOps.back();
13285       OpUsedElements.reset();
13286     }
13287     if (FoundSimplification)
13288       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13289     return V;
13290   }
13291 
13292   case ISD::INSERT_SUBVECTOR: {
13293     SDValue BaseV = V->getOperand(0);
13294     SDValue SubV = V->getOperand(1);
13295     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13296     if (!IdxN)
13297       return V;
13298 
13299     int SubSize = SubV.getValueType().getVectorNumElements();
13300     int Idx = IdxN->getZExtValue();
13301     bool SubVectorUsed = false;
13302     SmallBitVector SubUsedElements(SubSize, false);
13303     for (int i = 0; i < SubSize; ++i)
13304       if (UsedElements[i + Idx]) {
13305         SubVectorUsed = true;
13306         SubUsedElements[i] = true;
13307         UsedElements[i + Idx] = false;
13308       }
13309 
13310     // Now recurse on both the base and sub vectors.
13311     SDValue SimplifiedSubV =
13312         SubVectorUsed
13313             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13314             : DAG.getUNDEF(SubV.getValueType());
13315     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13316     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13317       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13318                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13319     return V;
13320   }
13321   }
13322 }
13323 
13324 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13325                                        SDValue N1, SelectionDAG &DAG) {
13326   EVT VT = SVN->getValueType(0);
13327   int NumElts = VT.getVectorNumElements();
13328   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13329   for (int M : SVN->getMask())
13330     if (M >= 0 && M < NumElts)
13331       N0UsedElements[M] = true;
13332     else if (M >= NumElts)
13333       N1UsedElements[M - NumElts] = true;
13334 
13335   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13336   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13337   if (S0 == N0 && S1 == N1)
13338     return SDValue();
13339 
13340   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13341 }
13342 
13343 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13344 // or turn a shuffle of a single concat into simpler shuffle then concat.
13345 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13346   EVT VT = N->getValueType(0);
13347   unsigned NumElts = VT.getVectorNumElements();
13348 
13349   SDValue N0 = N->getOperand(0);
13350   SDValue N1 = N->getOperand(1);
13351   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13352 
13353   SmallVector<SDValue, 4> Ops;
13354   EVT ConcatVT = N0.getOperand(0).getValueType();
13355   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13356   unsigned NumConcats = NumElts / NumElemsPerConcat;
13357 
13358   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13359   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13360   // half vector elements.
13361   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13362       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13363                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13364     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13365                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13366     N1 = DAG.getUNDEF(ConcatVT);
13367     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13368   }
13369 
13370   // Look at every vector that's inserted. We're looking for exact
13371   // subvector-sized copies from a concatenated vector
13372   for (unsigned I = 0; I != NumConcats; ++I) {
13373     // Make sure we're dealing with a copy.
13374     unsigned Begin = I * NumElemsPerConcat;
13375     bool AllUndef = true, NoUndef = true;
13376     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13377       if (SVN->getMaskElt(J) >= 0)
13378         AllUndef = false;
13379       else
13380         NoUndef = false;
13381     }
13382 
13383     if (NoUndef) {
13384       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13385         return SDValue();
13386 
13387       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13388         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13389           return SDValue();
13390 
13391       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13392       if (FirstElt < N0.getNumOperands())
13393         Ops.push_back(N0.getOperand(FirstElt));
13394       else
13395         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13396 
13397     } else if (AllUndef) {
13398       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13399     } else { // Mixed with general masks and undefs, can't do optimization.
13400       return SDValue();
13401     }
13402   }
13403 
13404   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13405 }
13406 
13407 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13408   EVT VT = N->getValueType(0);
13409   unsigned NumElts = VT.getVectorNumElements();
13410 
13411   SDValue N0 = N->getOperand(0);
13412   SDValue N1 = N->getOperand(1);
13413 
13414   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13415 
13416   // Canonicalize shuffle undef, undef -> undef
13417   if (N0.isUndef() && N1.isUndef())
13418     return DAG.getUNDEF(VT);
13419 
13420   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13421 
13422   // Canonicalize shuffle v, v -> v, undef
13423   if (N0 == N1) {
13424     SmallVector<int, 8> NewMask;
13425     for (unsigned i = 0; i != NumElts; ++i) {
13426       int Idx = SVN->getMaskElt(i);
13427       if (Idx >= (int)NumElts) Idx -= NumElts;
13428       NewMask.push_back(Idx);
13429     }
13430     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13431                                 &NewMask[0]);
13432   }
13433 
13434   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13435   if (N0.isUndef())
13436     return DAG.getCommutedVectorShuffle(*SVN);
13437 
13438   // Remove references to rhs if it is undef
13439   if (N1.isUndef()) {
13440     bool Changed = false;
13441     SmallVector<int, 8> NewMask;
13442     for (unsigned i = 0; i != NumElts; ++i) {
13443       int Idx = SVN->getMaskElt(i);
13444       if (Idx >= (int)NumElts) {
13445         Idx = -1;
13446         Changed = true;
13447       }
13448       NewMask.push_back(Idx);
13449     }
13450     if (Changed)
13451       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13452   }
13453 
13454   // If it is a splat, check if the argument vector is another splat or a
13455   // build_vector.
13456   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13457     SDNode *V = N0.getNode();
13458 
13459     // If this is a bit convert that changes the element type of the vector but
13460     // not the number of vector elements, look through it.  Be careful not to
13461     // look though conversions that change things like v4f32 to v2f64.
13462     if (V->getOpcode() == ISD::BITCAST) {
13463       SDValue ConvInput = V->getOperand(0);
13464       if (ConvInput.getValueType().isVector() &&
13465           ConvInput.getValueType().getVectorNumElements() == NumElts)
13466         V = ConvInput.getNode();
13467     }
13468 
13469     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13470       assert(V->getNumOperands() == NumElts &&
13471              "BUILD_VECTOR has wrong number of operands");
13472       SDValue Base;
13473       bool AllSame = true;
13474       for (unsigned i = 0; i != NumElts; ++i) {
13475         if (!V->getOperand(i).isUndef()) {
13476           Base = V->getOperand(i);
13477           break;
13478         }
13479       }
13480       // Splat of <u, u, u, u>, return <u, u, u, u>
13481       if (!Base.getNode())
13482         return N0;
13483       for (unsigned i = 0; i != NumElts; ++i) {
13484         if (V->getOperand(i) != Base) {
13485           AllSame = false;
13486           break;
13487         }
13488       }
13489       // Splat of <x, x, x, x>, return <x, x, x, x>
13490       if (AllSame)
13491         return N0;
13492 
13493       // Canonicalize any other splat as a build_vector.
13494       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13495       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13496       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13497 
13498       // We may have jumped through bitcasts, so the type of the
13499       // BUILD_VECTOR may not match the type of the shuffle.
13500       if (V->getValueType(0) != VT)
13501         NewBV = DAG.getBitcast(VT, NewBV);
13502       return NewBV;
13503     }
13504   }
13505 
13506   // There are various patterns used to build up a vector from smaller vectors,
13507   // subvectors, or elements. Scan chains of these and replace unused insertions
13508   // or components with undef.
13509   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13510     return S;
13511 
13512   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13513       Level < AfterLegalizeVectorOps &&
13514       (N1.isUndef() ||
13515       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13516        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13517     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13518       return V;
13519   }
13520 
13521   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13522   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13523   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13524     SmallVector<SDValue, 8> Ops;
13525     for (int M : SVN->getMask()) {
13526       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13527       if (M >= 0) {
13528         int Idx = M % NumElts;
13529         SDValue &S = (M < (int)NumElts ? N0 : N1);
13530         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13531           Op = S.getOperand(Idx);
13532         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13533           if (Idx == 0)
13534             Op = S.getOperand(0);
13535         } else {
13536           // Operand can't be combined - bail out.
13537           break;
13538         }
13539       }
13540       Ops.push_back(Op);
13541     }
13542     if (Ops.size() == VT.getVectorNumElements()) {
13543       // BUILD_VECTOR requires all inputs to be of the same type, find the
13544       // maximum type and extend them all.
13545       EVT SVT = VT.getScalarType();
13546       if (SVT.isInteger())
13547         for (SDValue &Op : Ops)
13548           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13549       if (SVT != VT.getScalarType())
13550         for (SDValue &Op : Ops)
13551           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13552                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13553                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13554       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13555     }
13556   }
13557 
13558   // If this shuffle only has a single input that is a bitcasted shuffle,
13559   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13560   // back to their original types.
13561   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13562       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13563       TLI.isTypeLegal(VT)) {
13564 
13565     // Peek through the bitcast only if there is one user.
13566     SDValue BC0 = N0;
13567     while (BC0.getOpcode() == ISD::BITCAST) {
13568       if (!BC0.hasOneUse())
13569         break;
13570       BC0 = BC0.getOperand(0);
13571     }
13572 
13573     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13574       if (Scale == 1)
13575         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13576 
13577       SmallVector<int, 8> NewMask;
13578       for (int M : Mask)
13579         for (int s = 0; s != Scale; ++s)
13580           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13581       return NewMask;
13582     };
13583 
13584     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13585       EVT SVT = VT.getScalarType();
13586       EVT InnerVT = BC0->getValueType(0);
13587       EVT InnerSVT = InnerVT.getScalarType();
13588 
13589       // Determine which shuffle works with the smaller scalar type.
13590       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13591       EVT ScaleSVT = ScaleVT.getScalarType();
13592 
13593       if (TLI.isTypeLegal(ScaleVT) &&
13594           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13595           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13596 
13597         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13598         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13599 
13600         // Scale the shuffle masks to the smaller scalar type.
13601         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13602         SmallVector<int, 8> InnerMask =
13603             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13604         SmallVector<int, 8> OuterMask =
13605             ScaleShuffleMask(SVN->getMask(), OuterScale);
13606 
13607         // Merge the shuffle masks.
13608         SmallVector<int, 8> NewMask;
13609         for (int M : OuterMask)
13610           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13611 
13612         // Test for shuffle mask legality over both commutations.
13613         SDValue SV0 = BC0->getOperand(0);
13614         SDValue SV1 = BC0->getOperand(1);
13615         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13616         if (!LegalMask) {
13617           std::swap(SV0, SV1);
13618           ShuffleVectorSDNode::commuteMask(NewMask);
13619           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13620         }
13621 
13622         if (LegalMask) {
13623           SV0 = DAG.getBitcast(ScaleVT, SV0);
13624           SV1 = DAG.getBitcast(ScaleVT, SV1);
13625           return DAG.getBitcast(
13626               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13627         }
13628       }
13629     }
13630   }
13631 
13632   // Canonicalize shuffles according to rules:
13633   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13634   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13635   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13636   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13637       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13638       TLI.isTypeLegal(VT)) {
13639     // The incoming shuffle must be of the same type as the result of the
13640     // current shuffle.
13641     assert(N1->getOperand(0).getValueType() == VT &&
13642            "Shuffle types don't match");
13643 
13644     SDValue SV0 = N1->getOperand(0);
13645     SDValue SV1 = N1->getOperand(1);
13646     bool HasSameOp0 = N0 == SV0;
13647     bool IsSV1Undef = SV1.isUndef();
13648     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13649       // Commute the operands of this shuffle so that next rule
13650       // will trigger.
13651       return DAG.getCommutedVectorShuffle(*SVN);
13652   }
13653 
13654   // Try to fold according to rules:
13655   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13656   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13657   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13658   // Don't try to fold shuffles with illegal type.
13659   // Only fold if this shuffle is the only user of the other shuffle.
13660   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13661       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13662     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13663 
13664     // The incoming shuffle must be of the same type as the result of the
13665     // current shuffle.
13666     assert(OtherSV->getOperand(0).getValueType() == VT &&
13667            "Shuffle types don't match");
13668 
13669     SDValue SV0, SV1;
13670     SmallVector<int, 4> Mask;
13671     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13672     // operand, and SV1 as the second operand.
13673     for (unsigned i = 0; i != NumElts; ++i) {
13674       int Idx = SVN->getMaskElt(i);
13675       if (Idx < 0) {
13676         // Propagate Undef.
13677         Mask.push_back(Idx);
13678         continue;
13679       }
13680 
13681       SDValue CurrentVec;
13682       if (Idx < (int)NumElts) {
13683         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13684         // shuffle mask to identify which vector is actually referenced.
13685         Idx = OtherSV->getMaskElt(Idx);
13686         if (Idx < 0) {
13687           // Propagate Undef.
13688           Mask.push_back(Idx);
13689           continue;
13690         }
13691 
13692         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13693                                            : OtherSV->getOperand(1);
13694       } else {
13695         // This shuffle index references an element within N1.
13696         CurrentVec = N1;
13697       }
13698 
13699       // Simple case where 'CurrentVec' is UNDEF.
13700       if (CurrentVec.isUndef()) {
13701         Mask.push_back(-1);
13702         continue;
13703       }
13704 
13705       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13706       // will be the first or second operand of the combined shuffle.
13707       Idx = Idx % NumElts;
13708       if (!SV0.getNode() || SV0 == CurrentVec) {
13709         // Ok. CurrentVec is the left hand side.
13710         // Update the mask accordingly.
13711         SV0 = CurrentVec;
13712         Mask.push_back(Idx);
13713         continue;
13714       }
13715 
13716       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13717       if (SV1.getNode() && SV1 != CurrentVec)
13718         return SDValue();
13719 
13720       // Ok. CurrentVec is the right hand side.
13721       // Update the mask accordingly.
13722       SV1 = CurrentVec;
13723       Mask.push_back(Idx + NumElts);
13724     }
13725 
13726     // Check if all indices in Mask are Undef. In case, propagate Undef.
13727     bool isUndefMask = true;
13728     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13729       isUndefMask &= Mask[i] < 0;
13730 
13731     if (isUndefMask)
13732       return DAG.getUNDEF(VT);
13733 
13734     if (!SV0.getNode())
13735       SV0 = DAG.getUNDEF(VT);
13736     if (!SV1.getNode())
13737       SV1 = DAG.getUNDEF(VT);
13738 
13739     // Avoid introducing shuffles with illegal mask.
13740     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13741       ShuffleVectorSDNode::commuteMask(Mask);
13742 
13743       if (!TLI.isShuffleMaskLegal(Mask, VT))
13744         return SDValue();
13745 
13746       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13747       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13748       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13749       std::swap(SV0, SV1);
13750     }
13751 
13752     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13753     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13754     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13755     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13756   }
13757 
13758   return SDValue();
13759 }
13760 
13761 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13762   SDValue InVal = N->getOperand(0);
13763   EVT VT = N->getValueType(0);
13764 
13765   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13766   // with a VECTOR_SHUFFLE.
13767   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13768     SDValue InVec = InVal->getOperand(0);
13769     SDValue EltNo = InVal->getOperand(1);
13770 
13771     // FIXME: We could support implicit truncation if the shuffle can be
13772     // scaled to a smaller vector scalar type.
13773     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13774     if (C0 && VT == InVec.getValueType() &&
13775         VT.getScalarType() == InVal.getValueType()) {
13776       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13777       int Elt = C0->getZExtValue();
13778       NewMask[0] = Elt;
13779 
13780       if (TLI.isShuffleMaskLegal(NewMask, VT))
13781         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13782                                     NewMask);
13783     }
13784   }
13785 
13786   return SDValue();
13787 }
13788 
13789 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13790   SDValue N0 = N->getOperand(0);
13791   SDValue N1 = N->getOperand(1);
13792   SDValue N2 = N->getOperand(2);
13793 
13794   if (N0.getValueType() != N1.getValueType())
13795     return SDValue();
13796 
13797   // If the input vector is a concatenation, and the insert replaces
13798   // one of the halves, we can optimize into a single concat_vectors.
13799   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
13800       N2.getOpcode() == ISD::Constant) {
13801     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13802     EVT VT = N->getValueType(0);
13803 
13804     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13805     // (concat_vectors Z, Y)
13806     if (InsIdx == 0)
13807       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
13808                          N0.getOperand(1));
13809 
13810     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13811     // (concat_vectors X, Z)
13812     if (InsIdx == VT.getVectorNumElements() / 2)
13813       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
13814                          N1);
13815   }
13816 
13817   return SDValue();
13818 }
13819 
13820 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13821   SDValue N0 = N->getOperand(0);
13822 
13823   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13824   if (N0->getOpcode() == ISD::FP16_TO_FP)
13825     return N0->getOperand(0);
13826 
13827   return SDValue();
13828 }
13829 
13830 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13831   SDValue N0 = N->getOperand(0);
13832 
13833   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13834   if (N0->getOpcode() == ISD::AND) {
13835     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13836     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13837       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13838                          N0.getOperand(0));
13839     }
13840   }
13841 
13842   return SDValue();
13843 }
13844 
13845 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13846 /// with the destination vector and a zero vector.
13847 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13848 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13849 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13850   EVT VT = N->getValueType(0);
13851   SDValue LHS = N->getOperand(0);
13852   SDValue RHS = N->getOperand(1);
13853   SDLoc dl(N);
13854 
13855   // Make sure we're not running after operation legalization where it
13856   // may have custom lowered the vector shuffles.
13857   if (LegalOperations)
13858     return SDValue();
13859 
13860   if (N->getOpcode() != ISD::AND)
13861     return SDValue();
13862 
13863   if (RHS.getOpcode() == ISD::BITCAST)
13864     RHS = RHS.getOperand(0);
13865 
13866   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13867     return SDValue();
13868 
13869   EVT RVT = RHS.getValueType();
13870   unsigned NumElts = RHS.getNumOperands();
13871 
13872   // Attempt to create a valid clear mask, splitting the mask into
13873   // sub elements and checking to see if each is
13874   // all zeros or all ones - suitable for shuffle masking.
13875   auto BuildClearMask = [&](int Split) {
13876     int NumSubElts = NumElts * Split;
13877     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13878 
13879     SmallVector<int, 8> Indices;
13880     for (int i = 0; i != NumSubElts; ++i) {
13881       int EltIdx = i / Split;
13882       int SubIdx = i % Split;
13883       SDValue Elt = RHS.getOperand(EltIdx);
13884       if (Elt.isUndef()) {
13885         Indices.push_back(-1);
13886         continue;
13887       }
13888 
13889       APInt Bits;
13890       if (isa<ConstantSDNode>(Elt))
13891         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13892       else if (isa<ConstantFPSDNode>(Elt))
13893         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13894       else
13895         return SDValue();
13896 
13897       // Extract the sub element from the constant bit mask.
13898       if (DAG.getDataLayout().isBigEndian()) {
13899         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13900       } else {
13901         Bits = Bits.lshr(SubIdx * NumSubBits);
13902       }
13903 
13904       if (Split > 1)
13905         Bits = Bits.trunc(NumSubBits);
13906 
13907       if (Bits.isAllOnesValue())
13908         Indices.push_back(i);
13909       else if (Bits == 0)
13910         Indices.push_back(i + NumSubElts);
13911       else
13912         return SDValue();
13913     }
13914 
13915     // Let's see if the target supports this vector_shuffle.
13916     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13917     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13918     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13919       return SDValue();
13920 
13921     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13922     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13923                                                    DAG.getBitcast(ClearVT, LHS),
13924                                                    Zero, &Indices[0]));
13925   };
13926 
13927   // Determine maximum split level (byte level masking).
13928   int MaxSplit = 1;
13929   if (RVT.getScalarSizeInBits() % 8 == 0)
13930     MaxSplit = RVT.getScalarSizeInBits() / 8;
13931 
13932   for (int Split = 1; Split <= MaxSplit; ++Split)
13933     if (RVT.getScalarSizeInBits() % Split == 0)
13934       if (SDValue S = BuildClearMask(Split))
13935         return S;
13936 
13937   return SDValue();
13938 }
13939 
13940 /// Visit a binary vector operation, like ADD.
13941 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13942   assert(N->getValueType(0).isVector() &&
13943          "SimplifyVBinOp only works on vectors!");
13944 
13945   SDValue LHS = N->getOperand(0);
13946   SDValue RHS = N->getOperand(1);
13947   SDValue Ops[] = {LHS, RHS};
13948 
13949   // See if we can constant fold the vector operation.
13950   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13951           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13952     return Fold;
13953 
13954   // Try to convert a constant mask AND into a shuffle clear mask.
13955   if (SDValue Shuffle = XformToShuffleWithZero(N))
13956     return Shuffle;
13957 
13958   // Type legalization might introduce new shuffles in the DAG.
13959   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13960   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13961   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13962       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13963       LHS.getOperand(1).isUndef() &&
13964       RHS.getOperand(1).isUndef()) {
13965     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13966     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13967 
13968     if (SVN0->getMask().equals(SVN1->getMask())) {
13969       EVT VT = N->getValueType(0);
13970       SDValue UndefVector = LHS.getOperand(1);
13971       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13972                                      LHS.getOperand(0), RHS.getOperand(0),
13973                                      N->getFlags());
13974       AddUsersToWorklist(N);
13975       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13976                                   &SVN0->getMask()[0]);
13977     }
13978   }
13979 
13980   return SDValue();
13981 }
13982 
13983 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
13984                                     SDValue N2) {
13985   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13986 
13987   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13988                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13989 
13990   // If we got a simplified select_cc node back from SimplifySelectCC, then
13991   // break it down into a new SETCC node, and a new SELECT node, and then return
13992   // the SELECT node, since we were called with a SELECT node.
13993   if (SCC.getNode()) {
13994     // Check to see if we got a select_cc back (to turn into setcc/select).
13995     // Otherwise, just return whatever node we got back, like fabs.
13996     if (SCC.getOpcode() == ISD::SELECT_CC) {
13997       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13998                                   N0.getValueType(),
13999                                   SCC.getOperand(0), SCC.getOperand(1),
14000                                   SCC.getOperand(4));
14001       AddToWorklist(SETCC.getNode());
14002       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14003                            SCC.getOperand(2), SCC.getOperand(3));
14004     }
14005 
14006     return SCC;
14007   }
14008   return SDValue();
14009 }
14010 
14011 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14012 /// being selected between, see if we can simplify the select.  Callers of this
14013 /// should assume that TheSelect is deleted if this returns true.  As such, they
14014 /// should return the appropriate thing (e.g. the node) back to the top-level of
14015 /// the DAG combiner loop to avoid it being looked at.
14016 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14017                                     SDValue RHS) {
14018 
14019   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14020   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14021   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14022     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14023       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14024       SDValue Sqrt = RHS;
14025       ISD::CondCode CC;
14026       SDValue CmpLHS;
14027       const ConstantFPSDNode *Zero = nullptr;
14028 
14029       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14030         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14031         CmpLHS = TheSelect->getOperand(0);
14032         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14033       } else {
14034         // SELECT or VSELECT
14035         SDValue Cmp = TheSelect->getOperand(0);
14036         if (Cmp.getOpcode() == ISD::SETCC) {
14037           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14038           CmpLHS = Cmp.getOperand(0);
14039           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14040         }
14041       }
14042       if (Zero && Zero->isZero() &&
14043           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14044           CC == ISD::SETULT || CC == ISD::SETLT)) {
14045         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14046         CombineTo(TheSelect, Sqrt);
14047         return true;
14048       }
14049     }
14050   }
14051   // Cannot simplify select with vector condition
14052   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14053 
14054   // If this is a select from two identical things, try to pull the operation
14055   // through the select.
14056   if (LHS.getOpcode() != RHS.getOpcode() ||
14057       !LHS.hasOneUse() || !RHS.hasOneUse())
14058     return false;
14059 
14060   // If this is a load and the token chain is identical, replace the select
14061   // of two loads with a load through a select of the address to load from.
14062   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14063   // constants have been dropped into the constant pool.
14064   if (LHS.getOpcode() == ISD::LOAD) {
14065     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14066     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14067 
14068     // Token chains must be identical.
14069     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14070         // Do not let this transformation reduce the number of volatile loads.
14071         LLD->isVolatile() || RLD->isVolatile() ||
14072         // FIXME: If either is a pre/post inc/dec load,
14073         // we'd need to split out the address adjustment.
14074         LLD->isIndexed() || RLD->isIndexed() ||
14075         // If this is an EXTLOAD, the VT's must match.
14076         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14077         // If this is an EXTLOAD, the kind of extension must match.
14078         (LLD->getExtensionType() != RLD->getExtensionType() &&
14079          // The only exception is if one of the extensions is anyext.
14080          LLD->getExtensionType() != ISD::EXTLOAD &&
14081          RLD->getExtensionType() != ISD::EXTLOAD) ||
14082         // FIXME: this discards src value information.  This is
14083         // over-conservative. It would be beneficial to be able to remember
14084         // both potential memory locations.  Since we are discarding
14085         // src value info, don't do the transformation if the memory
14086         // locations are not in the default address space.
14087         LLD->getPointerInfo().getAddrSpace() != 0 ||
14088         RLD->getPointerInfo().getAddrSpace() != 0 ||
14089         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14090                                       LLD->getBasePtr().getValueType()))
14091       return false;
14092 
14093     // Check that the select condition doesn't reach either load.  If so,
14094     // folding this will induce a cycle into the DAG.  If not, this is safe to
14095     // xform, so create a select of the addresses.
14096     SDValue Addr;
14097     if (TheSelect->getOpcode() == ISD::SELECT) {
14098       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14099       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14100           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14101         return false;
14102       // The loads must not depend on one another.
14103       if (LLD->isPredecessorOf(RLD) ||
14104           RLD->isPredecessorOf(LLD))
14105         return false;
14106       Addr = DAG.getSelect(SDLoc(TheSelect),
14107                            LLD->getBasePtr().getValueType(),
14108                            TheSelect->getOperand(0), LLD->getBasePtr(),
14109                            RLD->getBasePtr());
14110     } else {  // Otherwise SELECT_CC
14111       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14112       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14113 
14114       if ((LLD->hasAnyUseOfValue(1) &&
14115            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14116           (RLD->hasAnyUseOfValue(1) &&
14117            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14118         return false;
14119 
14120       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14121                          LLD->getBasePtr().getValueType(),
14122                          TheSelect->getOperand(0),
14123                          TheSelect->getOperand(1),
14124                          LLD->getBasePtr(), RLD->getBasePtr(),
14125                          TheSelect->getOperand(4));
14126     }
14127 
14128     SDValue Load;
14129     // It is safe to replace the two loads if they have different alignments,
14130     // but the new load must be the minimum (most restrictive) alignment of the
14131     // inputs.
14132     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
14133     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14134     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14135       Load = DAG.getLoad(TheSelect->getValueType(0),
14136                          SDLoc(TheSelect),
14137                          // FIXME: Discards pointer and AA info.
14138                          LLD->getChain(), Addr, MachinePointerInfo(),
14139                          LLD->isVolatile(), LLD->isNonTemporal(),
14140                          isInvariant, Alignment);
14141     } else {
14142       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
14143                             RLD->getExtensionType() : LLD->getExtensionType(),
14144                             SDLoc(TheSelect),
14145                             TheSelect->getValueType(0),
14146                             // FIXME: Discards pointer and AA info.
14147                             LLD->getChain(), Addr, MachinePointerInfo(),
14148                             LLD->getMemoryVT(), LLD->isVolatile(),
14149                             LLD->isNonTemporal(), isInvariant, Alignment);
14150     }
14151 
14152     // Users of the select now use the result of the load.
14153     CombineTo(TheSelect, Load);
14154 
14155     // Users of the old loads now use the new load's chain.  We know the
14156     // old-load value is dead now.
14157     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14158     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14159     return true;
14160   }
14161 
14162   return false;
14163 }
14164 
14165 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14166 /// where 'cond' is the comparison specified by CC.
14167 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14168                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14169                                       bool NotExtCompare) {
14170   // (x ? y : y) -> y.
14171   if (N2 == N3) return N2;
14172 
14173   EVT VT = N2.getValueType();
14174   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14175   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14176 
14177   // Determine if the condition we're dealing with is constant
14178   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14179                               N0, N1, CC, DL, false);
14180   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14181 
14182   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14183     // fold select_cc true, x, y -> x
14184     // fold select_cc false, x, y -> y
14185     return !SCCC->isNullValue() ? N2 : N3;
14186   }
14187 
14188   // Check to see if we can simplify the select into an fabs node
14189   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14190     // Allow either -0.0 or 0.0
14191     if (CFP->isZero()) {
14192       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14193       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14194           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14195           N2 == N3.getOperand(0))
14196         return DAG.getNode(ISD::FABS, DL, VT, N0);
14197 
14198       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14199       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14200           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14201           N2.getOperand(0) == N3)
14202         return DAG.getNode(ISD::FABS, DL, VT, N3);
14203     }
14204   }
14205 
14206   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14207   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14208   // in it.  This is a win when the constant is not otherwise available because
14209   // it replaces two constant pool loads with one.  We only do this if the FP
14210   // type is known to be legal, because if it isn't, then we are before legalize
14211   // types an we want the other legalization to happen first (e.g. to avoid
14212   // messing with soft float) and if the ConstantFP is not legal, because if
14213   // it is legal, we may not need to store the FP constant in a constant pool.
14214   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14215     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14216       if (TLI.isTypeLegal(N2.getValueType()) &&
14217           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14218                TargetLowering::Legal &&
14219            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14220            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14221           // If both constants have multiple uses, then we won't need to do an
14222           // extra load, they are likely around in registers for other users.
14223           (TV->hasOneUse() || FV->hasOneUse())) {
14224         Constant *Elts[] = {
14225           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14226           const_cast<ConstantFP*>(TV->getConstantFPValue())
14227         };
14228         Type *FPTy = Elts[0]->getType();
14229         const DataLayout &TD = DAG.getDataLayout();
14230 
14231         // Create a ConstantArray of the two constants.
14232         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14233         SDValue CPIdx =
14234             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14235                                 TD.getPrefTypeAlignment(FPTy));
14236         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14237 
14238         // Get the offsets to the 0 and 1 element of the array so that we can
14239         // select between them.
14240         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14241         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14242         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14243 
14244         SDValue Cond = DAG.getSetCC(DL,
14245                                     getSetCCResultType(N0.getValueType()),
14246                                     N0, N1, CC);
14247         AddToWorklist(Cond.getNode());
14248         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14249                                           Cond, One, Zero);
14250         AddToWorklist(CstOffset.getNode());
14251         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14252                             CstOffset);
14253         AddToWorklist(CPIdx.getNode());
14254         return DAG.getLoad(
14255             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14256             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14257             false, false, false, Alignment);
14258       }
14259     }
14260 
14261   // Check to see if we can perform the "gzip trick", transforming
14262   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14263   if (isNullConstant(N3) && CC == ISD::SETLT &&
14264       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14265        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14266     EVT XType = N0.getValueType();
14267     EVT AType = N2.getValueType();
14268     if (XType.bitsGE(AType)) {
14269       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14270       // single-bit constant.
14271       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14272         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14273         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14274         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14275                                        getShiftAmountTy(N0.getValueType()));
14276         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14277                                     XType, N0, ShCt);
14278         AddToWorklist(Shift.getNode());
14279 
14280         if (XType.bitsGT(AType)) {
14281           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14282           AddToWorklist(Shift.getNode());
14283         }
14284 
14285         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14286       }
14287 
14288       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14289                                   XType, N0,
14290                                   DAG.getConstant(XType.getSizeInBits() - 1,
14291                                                   SDLoc(N0),
14292                                          getShiftAmountTy(N0.getValueType())));
14293       AddToWorklist(Shift.getNode());
14294 
14295       if (XType.bitsGT(AType)) {
14296         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14297         AddToWorklist(Shift.getNode());
14298       }
14299 
14300       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14301     }
14302   }
14303 
14304   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14305   // where y is has a single bit set.
14306   // A plaintext description would be, we can turn the SELECT_CC into an AND
14307   // when the condition can be materialized as an all-ones register.  Any
14308   // single bit-test can be materialized as an all-ones register with
14309   // shift-left and shift-right-arith.
14310   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14311       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14312     SDValue AndLHS = N0->getOperand(0);
14313     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14314     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14315       // Shift the tested bit over the sign bit.
14316       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14317       SDValue ShlAmt =
14318         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14319                         getShiftAmountTy(AndLHS.getValueType()));
14320       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14321 
14322       // Now arithmetic right shift it all the way over, so the result is either
14323       // all-ones, or zero.
14324       SDValue ShrAmt =
14325         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14326                         getShiftAmountTy(Shl.getValueType()));
14327       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14328 
14329       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14330     }
14331   }
14332 
14333   // fold select C, 16, 0 -> shl C, 4
14334   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14335       TLI.getBooleanContents(N0.getValueType()) ==
14336           TargetLowering::ZeroOrOneBooleanContent) {
14337 
14338     // If the caller doesn't want us to simplify this into a zext of a compare,
14339     // don't do it.
14340     if (NotExtCompare && N2C->isOne())
14341       return SDValue();
14342 
14343     // Get a SetCC of the condition
14344     // NOTE: Don't create a SETCC if it's not legal on this target.
14345     if (!LegalOperations ||
14346         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14347       SDValue Temp, SCC;
14348       // cast from setcc result type to select result type
14349       if (LegalTypes) {
14350         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14351                             N0, N1, CC);
14352         if (N2.getValueType().bitsLT(SCC.getValueType()))
14353           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14354                                         N2.getValueType());
14355         else
14356           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14357                              N2.getValueType(), SCC);
14358       } else {
14359         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14360         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14361                            N2.getValueType(), SCC);
14362       }
14363 
14364       AddToWorklist(SCC.getNode());
14365       AddToWorklist(Temp.getNode());
14366 
14367       if (N2C->isOne())
14368         return Temp;
14369 
14370       // shl setcc result by log2 n2c
14371       return DAG.getNode(
14372           ISD::SHL, DL, N2.getValueType(), Temp,
14373           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14374                           getShiftAmountTy(Temp.getValueType())));
14375     }
14376   }
14377 
14378   // Check to see if this is an integer abs.
14379   // select_cc setg[te] X,  0,  X, -X ->
14380   // select_cc setgt    X, -1,  X, -X ->
14381   // select_cc setl[te] X,  0, -X,  X ->
14382   // select_cc setlt    X,  1, -X,  X ->
14383   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14384   if (N1C) {
14385     ConstantSDNode *SubC = nullptr;
14386     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14387          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14388         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14389       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14390     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14391               (N1C->isOne() && CC == ISD::SETLT)) &&
14392              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14393       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14394 
14395     EVT XType = N0.getValueType();
14396     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14397       SDLoc DL(N0);
14398       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14399                                   N0,
14400                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14401                                          getShiftAmountTy(N0.getValueType())));
14402       SDValue Add = DAG.getNode(ISD::ADD, DL,
14403                                 XType, N0, Shift);
14404       AddToWorklist(Shift.getNode());
14405       AddToWorklist(Add.getNode());
14406       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14407     }
14408   }
14409 
14410   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14411   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14412   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14413   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14414   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14415   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14416   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14417   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14418   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14419     SDValue ValueOnZero = N2;
14420     SDValue Count = N3;
14421     // If the condition is NE instead of E, swap the operands.
14422     if (CC == ISD::SETNE)
14423       std::swap(ValueOnZero, Count);
14424     // Check if the value on zero is a constant equal to the bits in the type.
14425     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14426       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14427         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14428         // legal, combine to just cttz.
14429         if ((Count.getOpcode() == ISD::CTTZ ||
14430              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14431             N0 == Count.getOperand(0) &&
14432             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14433           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14434         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14435         // legal, combine to just ctlz.
14436         if ((Count.getOpcode() == ISD::CTLZ ||
14437              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14438             N0 == Count.getOperand(0) &&
14439             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14440           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14441       }
14442     }
14443   }
14444 
14445   return SDValue();
14446 }
14447 
14448 /// This is a stub for TargetLowering::SimplifySetCC.
14449 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14450                                    ISD::CondCode Cond, const SDLoc &DL,
14451                                    bool foldBooleans) {
14452   TargetLowering::DAGCombinerInfo
14453     DagCombineInfo(DAG, Level, false, this);
14454   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14455 }
14456 
14457 /// Given an ISD::SDIV node expressing a divide by constant, return
14458 /// a DAG expression to select that will generate the same value by multiplying
14459 /// by a magic number.
14460 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14461 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14462   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14463   if (!C)
14464     return SDValue();
14465 
14466   // Avoid division by zero.
14467   if (C->isNullValue())
14468     return SDValue();
14469 
14470   std::vector<SDNode*> Built;
14471   SDValue S =
14472       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14473 
14474   for (SDNode *N : Built)
14475     AddToWorklist(N);
14476   return S;
14477 }
14478 
14479 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14480 /// DAG expression that will generate the same value by right shifting.
14481 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14482   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14483   if (!C)
14484     return SDValue();
14485 
14486   // Avoid division by zero.
14487   if (C->isNullValue())
14488     return SDValue();
14489 
14490   std::vector<SDNode *> Built;
14491   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14492 
14493   for (SDNode *N : Built)
14494     AddToWorklist(N);
14495   return S;
14496 }
14497 
14498 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14499 /// expression that will generate the same value by multiplying by a magic
14500 /// number.
14501 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14502 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14503   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14504   if (!C)
14505     return SDValue();
14506 
14507   // Avoid division by zero.
14508   if (C->isNullValue())
14509     return SDValue();
14510 
14511   std::vector<SDNode*> Built;
14512   SDValue S =
14513       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14514 
14515   for (SDNode *N : Built)
14516     AddToWorklist(N);
14517   return S;
14518 }
14519 
14520 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14521   if (Level >= AfterLegalizeDAG)
14522     return SDValue();
14523 
14524   // Expose the DAG combiner to the target combiner implementations.
14525   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14526 
14527   unsigned Iterations = 0;
14528   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14529     if (Iterations) {
14530       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14531       // For the reciprocal, we need to find the zero of the function:
14532       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14533       //     =>
14534       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14535       //     does not require additional intermediate precision]
14536       EVT VT = Op.getValueType();
14537       SDLoc DL(Op);
14538       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14539 
14540       AddToWorklist(Est.getNode());
14541 
14542       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14543       for (unsigned i = 0; i < Iterations; ++i) {
14544         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14545         AddToWorklist(NewEst.getNode());
14546 
14547         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14548         AddToWorklist(NewEst.getNode());
14549 
14550         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14551         AddToWorklist(NewEst.getNode());
14552 
14553         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14554         AddToWorklist(Est.getNode());
14555       }
14556     }
14557     return Est;
14558   }
14559 
14560   return SDValue();
14561 }
14562 
14563 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14564 /// For the reciprocal sqrt, we need to find the zero of the function:
14565 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14566 ///     =>
14567 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14568 /// As a result, we precompute A/2 prior to the iteration loop.
14569 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14570                                          unsigned Iterations,
14571                                          SDNodeFlags *Flags, bool Reciprocal) {
14572   EVT VT = Arg.getValueType();
14573   SDLoc DL(Arg);
14574   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14575 
14576   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14577   // this entire sequence requires only one FP constant.
14578   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14579   AddToWorklist(HalfArg.getNode());
14580 
14581   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14582   AddToWorklist(HalfArg.getNode());
14583 
14584   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14585   for (unsigned i = 0; i < Iterations; ++i) {
14586     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14587     AddToWorklist(NewEst.getNode());
14588 
14589     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14590     AddToWorklist(NewEst.getNode());
14591 
14592     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14593     AddToWorklist(NewEst.getNode());
14594 
14595     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14596     AddToWorklist(Est.getNode());
14597   }
14598 
14599   // If non-reciprocal square root is requested, multiply the result by Arg.
14600   if (!Reciprocal) {
14601     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14602     AddToWorklist(Est.getNode());
14603   }
14604 
14605   return Est;
14606 }
14607 
14608 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14609 /// For the reciprocal sqrt, we need to find the zero of the function:
14610 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14611 ///     =>
14612 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14613 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
14614                                          unsigned Iterations,
14615                                          SDNodeFlags *Flags, bool Reciprocal) {
14616   EVT VT = Arg.getValueType();
14617   SDLoc DL(Arg);
14618   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14619   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14620 
14621   // This routine must enter the loop below to work correctly
14622   // when (Reciprocal == false).
14623   assert(Iterations > 0);
14624 
14625   // Newton iterations for reciprocal square root:
14626   // E = (E * -0.5) * ((A * E) * E + -3.0)
14627   for (unsigned i = 0; i < Iterations; ++i) {
14628     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
14629     AddToWorklist(AE.getNode());
14630 
14631     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
14632     AddToWorklist(AEE.getNode());
14633 
14634     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
14635     AddToWorklist(RHS.getNode());
14636 
14637     // When calculating a square root at the last iteration build:
14638     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
14639     // (notice a common subexpression)
14640     SDValue LHS;
14641     if (Reciprocal || (i + 1) < Iterations) {
14642       // RSQRT: LHS = (E * -0.5)
14643       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14644     } else {
14645       // SQRT: LHS = (A * E) * -0.5
14646       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
14647     }
14648     AddToWorklist(LHS.getNode());
14649 
14650     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
14651     AddToWorklist(Est.getNode());
14652   }
14653 
14654   return Est;
14655 }
14656 
14657 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
14658 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
14659 /// Op can be zero.
14660 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
14661                                            bool Reciprocal) {
14662   if (Level >= AfterLegalizeDAG)
14663     return SDValue();
14664 
14665   // Expose the DAG combiner to the target combiner implementations.
14666   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14667   unsigned Iterations = 0;
14668   bool UseOneConstNR = false;
14669   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14670     AddToWorklist(Est.getNode());
14671     if (Iterations) {
14672       Est = UseOneConstNR
14673                 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
14674                 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
14675     }
14676     return Est;
14677   }
14678 
14679   return SDValue();
14680 }
14681 
14682 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14683   return buildSqrtEstimateImpl(Op, Flags, true);
14684 }
14685 
14686 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14687   SDValue Est = buildSqrtEstimateImpl(Op, Flags, false);
14688   if (!Est)
14689     return SDValue();
14690 
14691   // Unfortunately, Est is now NaN if the input was exactly 0.
14692   // Select out this case and force the answer to 0.
14693   EVT VT = Est.getValueType();
14694   SDLoc DL(Op);
14695   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
14696   EVT CCVT = getSetCCResultType(VT);
14697   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ);
14698   AddToWorklist(ZeroCmp.getNode());
14699 
14700   Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp,
14701                     Zero, Est);
14702   AddToWorklist(Est.getNode());
14703   return Est;
14704 }
14705 
14706 /// Return true if base is a frame index, which is known not to alias with
14707 /// anything but itself.  Provides base object and offset as results.
14708 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14709                            const GlobalValue *&GV, const void *&CV) {
14710   // Assume it is a primitive operation.
14711   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14712 
14713   // If it's an adding a simple constant then integrate the offset.
14714   if (Base.getOpcode() == ISD::ADD) {
14715     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14716       Base = Base.getOperand(0);
14717       Offset += C->getZExtValue();
14718     }
14719   }
14720 
14721   // Return the underlying GlobalValue, and update the Offset.  Return false
14722   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14723   // by multiple nodes with different offsets.
14724   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14725     GV = G->getGlobal();
14726     Offset += G->getOffset();
14727     return false;
14728   }
14729 
14730   // Return the underlying Constant value, and update the Offset.  Return false
14731   // for ConstantSDNodes since the same constant pool entry may be represented
14732   // by multiple nodes with different offsets.
14733   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14734     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14735                                          : (const void *)C->getConstVal();
14736     Offset += C->getOffset();
14737     return false;
14738   }
14739   // If it's any of the following then it can't alias with anything but itself.
14740   return isa<FrameIndexSDNode>(Base);
14741 }
14742 
14743 /// Return true if there is any possibility that the two addresses overlap.
14744 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14745   // If they are the same then they must be aliases.
14746   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14747 
14748   // If they are both volatile then they cannot be reordered.
14749   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14750 
14751   // If one operation reads from invariant memory, and the other may store, they
14752   // cannot alias. These should really be checking the equivalent of mayWrite,
14753   // but it only matters for memory nodes other than load /store.
14754   if (Op0->isInvariant() && Op1->writeMem())
14755     return false;
14756 
14757   if (Op1->isInvariant() && Op0->writeMem())
14758     return false;
14759 
14760   // Gather base node and offset information.
14761   SDValue Base1, Base2;
14762   int64_t Offset1, Offset2;
14763   const GlobalValue *GV1, *GV2;
14764   const void *CV1, *CV2;
14765   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14766                                       Base1, Offset1, GV1, CV1);
14767   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14768                                       Base2, Offset2, GV2, CV2);
14769 
14770   // If they have a same base address then check to see if they overlap.
14771   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14772     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14773              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14774 
14775   // It is possible for different frame indices to alias each other, mostly
14776   // when tail call optimization reuses return address slots for arguments.
14777   // To catch this case, look up the actual index of frame indices to compute
14778   // the real alias relationship.
14779   if (isFrameIndex1 && isFrameIndex2) {
14780     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14781     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14782     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14783     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14784              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14785   }
14786 
14787   // Otherwise, if we know what the bases are, and they aren't identical, then
14788   // we know they cannot alias.
14789   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14790     return false;
14791 
14792   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14793   // compared to the size and offset of the access, we may be able to prove they
14794   // do not alias.  This check is conservative for now to catch cases created by
14795   // splitting vector types.
14796   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14797       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14798       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14799        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14800       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
14801     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14802     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14803 
14804     // There is no overlap between these relatively aligned accesses of similar
14805     // size, return no alias.
14806     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14807         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14808       return false;
14809   }
14810 
14811   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14812                    ? CombinerGlobalAA
14813                    : DAG.getSubtarget().useAA();
14814 #ifndef NDEBUG
14815   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14816       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14817     UseAA = false;
14818 #endif
14819   if (UseAA &&
14820       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14821     // Use alias analysis information.
14822     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14823                                  Op1->getSrcValueOffset());
14824     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14825         Op0->getSrcValueOffset() - MinOffset;
14826     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14827         Op1->getSrcValueOffset() - MinOffset;
14828     AliasResult AAResult =
14829         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14830                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14831                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14832                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14833     if (AAResult == NoAlias)
14834       return false;
14835   }
14836 
14837   // Otherwise we have to assume they alias.
14838   return true;
14839 }
14840 
14841 /// Walk up chain skipping non-aliasing memory nodes,
14842 /// looking for aliasing nodes and adding them to the Aliases vector.
14843 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14844                                    SmallVectorImpl<SDValue> &Aliases) {
14845   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14846   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14847 
14848   // Get alias information for node.
14849   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14850 
14851   // Starting off.
14852   Chains.push_back(OriginalChain);
14853   unsigned Depth = 0;
14854 
14855   // Look at each chain and determine if it is an alias.  If so, add it to the
14856   // aliases list.  If not, then continue up the chain looking for the next
14857   // candidate.
14858   while (!Chains.empty()) {
14859     SDValue Chain = Chains.pop_back_val();
14860 
14861     // For TokenFactor nodes, look at each operand and only continue up the
14862     // chain until we reach the depth limit.
14863     //
14864     // FIXME: The depth check could be made to return the last non-aliasing
14865     // chain we found before we hit a tokenfactor rather than the original
14866     // chain.
14867     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14868       Aliases.clear();
14869       Aliases.push_back(OriginalChain);
14870       return;
14871     }
14872 
14873     // Don't bother if we've been before.
14874     if (!Visited.insert(Chain.getNode()).second)
14875       continue;
14876 
14877     switch (Chain.getOpcode()) {
14878     case ISD::EntryToken:
14879       // Entry token is ideal chain operand, but handled in FindBetterChain.
14880       break;
14881 
14882     case ISD::LOAD:
14883     case ISD::STORE: {
14884       // Get alias information for Chain.
14885       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14886           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14887 
14888       // If chain is alias then stop here.
14889       if (!(IsLoad && IsOpLoad) &&
14890           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14891         Aliases.push_back(Chain);
14892       } else {
14893         // Look further up the chain.
14894         Chains.push_back(Chain.getOperand(0));
14895         ++Depth;
14896       }
14897       break;
14898     }
14899 
14900     case ISD::TokenFactor:
14901       // We have to check each of the operands of the token factor for "small"
14902       // token factors, so we queue them up.  Adding the operands to the queue
14903       // (stack) in reverse order maintains the original order and increases the
14904       // likelihood that getNode will find a matching token factor (CSE.)
14905       if (Chain.getNumOperands() > 16) {
14906         Aliases.push_back(Chain);
14907         break;
14908       }
14909       for (unsigned n = Chain.getNumOperands(); n;)
14910         Chains.push_back(Chain.getOperand(--n));
14911       ++Depth;
14912       break;
14913 
14914     default:
14915       // For all other instructions we will just have to take what we can get.
14916       Aliases.push_back(Chain);
14917       break;
14918     }
14919   }
14920 }
14921 
14922 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14923 /// (aliasing node.)
14924 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14925   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14926 
14927   // Accumulate all the aliases to this node.
14928   GatherAllAliases(N, OldChain, Aliases);
14929 
14930   // If no operands then chain to entry token.
14931   if (Aliases.size() == 0)
14932     return DAG.getEntryNode();
14933 
14934   // If a single operand then chain to it.  We don't need to revisit it.
14935   if (Aliases.size() == 1)
14936     return Aliases[0];
14937 
14938   // Construct a custom tailored token factor.
14939   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14940 }
14941 
14942 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14943   // This holds the base pointer, index, and the offset in bytes from the base
14944   // pointer.
14945   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
14946 
14947   // We must have a base and an offset.
14948   if (!BasePtr.Base.getNode())
14949     return false;
14950 
14951   // Do not handle stores to undef base pointers.
14952   if (BasePtr.Base.isUndef())
14953     return false;
14954 
14955   SmallVector<StoreSDNode *, 8> ChainedStores;
14956   ChainedStores.push_back(St);
14957 
14958   // Walk up the chain and look for nodes with offsets from the same
14959   // base pointer. Stop when reaching an instruction with a different kind
14960   // or instruction which has a different base pointer.
14961   StoreSDNode *Index = St;
14962   while (Index) {
14963     // If the chain has more than one use, then we can't reorder the mem ops.
14964     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14965       break;
14966 
14967     if (Index->isVolatile() || Index->isIndexed())
14968       break;
14969 
14970     // Find the base pointer and offset for this memory node.
14971     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
14972 
14973     // Check that the base pointer is the same as the original one.
14974     if (!Ptr.equalBaseIndex(BasePtr))
14975       break;
14976 
14977     // Find the next memory operand in the chain. If the next operand in the
14978     // chain is a store then move up and continue the scan with the next
14979     // memory operand. If the next operand is a load save it and use alias
14980     // information to check if it interferes with anything.
14981     SDNode *NextInChain = Index->getChain().getNode();
14982     while (true) {
14983       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14984         // We found a store node. Use it for the next iteration.
14985         if (STn->isVolatile() || STn->isIndexed()) {
14986           Index = nullptr;
14987           break;
14988         }
14989         ChainedStores.push_back(STn);
14990         Index = STn;
14991         break;
14992       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14993         NextInChain = Ldn->getChain().getNode();
14994         continue;
14995       } else {
14996         Index = nullptr;
14997         break;
14998       }
14999     }
15000   }
15001 
15002   bool MadeChange = false;
15003   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15004 
15005   for (StoreSDNode *ChainedStore : ChainedStores) {
15006     SDValue Chain = ChainedStore->getChain();
15007     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15008 
15009     if (Chain != BetterChain) {
15010       MadeChange = true;
15011       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15012     }
15013   }
15014 
15015   // Do all replacements after finding the replacements to make to avoid making
15016   // the chains more complicated by introducing new TokenFactors.
15017   for (auto Replacement : BetterChains)
15018     replaceStoreChain(Replacement.first, Replacement.second);
15019 
15020   return MadeChange;
15021 }
15022 
15023 /// This is the entry point for the file.
15024 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15025                            CodeGenOpt::Level OptLevel) {
15026   /// This is the main entry point to this class.
15027   DAGCombiner(*this, AA, OptLevel).Run(Level);
15028 }
15029