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,
216                          SDValue Trunc, SDValue ExtLoad, 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, SDLoc DL, SDValue LHS, SDValue RHS);
333 
334     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
335 
336     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
337     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
338     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
339     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
340                              SDValue N3, ISD::CondCode CC,
341                              bool NotExtCompare = false);
342     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
343                           SDLoc DL, bool foldBooleans = true);
344 
345     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
346                            SDValue &CC) const;
347     bool isOneUseSetCC(SDValue N) const;
348 
349     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
350                                          unsigned HiOp);
351     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
352     SDValue CombineExtLoad(SDNode *N);
353     SDValue combineRepeatedFPDivisors(SDNode *N);
354     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
355     SDValue BuildSDIV(SDNode *N);
356     SDValue BuildSDIVPow2(SDNode *N);
357     SDValue BuildUDIV(SDNode *N);
358     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
359     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
360     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
361                                  SDNodeFlags *Flags);
362     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
363                                  SDNodeFlags *Flags);
364     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
365                                bool DemandHighBits = true);
366     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
367     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
368                               SDValue InnerPos, SDValue InnerNeg,
369                               unsigned PosOpcode, unsigned NegOpcode,
370                               SDLoc DL);
371     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
372     SDValue ReduceLoadWidth(SDNode *N);
373     SDValue ReduceLoadOpStoreWidth(SDNode *N);
374     SDValue TransformFPLoadStorePair(SDNode *N);
375     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
376     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
377 
378     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
379 
380     /// Walk up chain skipping non-aliasing memory nodes,
381     /// looking for aliasing nodes and adding them to the Aliases vector.
382     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
383                           SmallVectorImpl<SDValue> &Aliases);
384 
385     /// Return true if there is any possibility that the two addresses overlap.
386     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
387 
388     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
389     /// chain (aliasing node.)
390     SDValue FindBetterChain(SDNode *N, SDValue Chain);
391 
392     /// Do FindBetterChain for a store and any possibly adjacent stores on
393     /// consecutive chains.
394     bool findBetterNeighborChains(StoreSDNode *St);
395 
396     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
397     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
398 
399     /// Holds a pointer to an LSBaseSDNode as well as information on where it
400     /// is located in a sequence of memory operations connected by a chain.
401     struct MemOpLink {
402       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
403       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
404       // Ptr to the mem node.
405       LSBaseSDNode *MemNode;
406       // Offset from the base ptr.
407       int64_t OffsetFromBase;
408       // What is the sequence number of this mem node.
409       // Lowest mem operand in the DAG starts at zero.
410       unsigned SequenceNum;
411     };
412 
413     /// This is a helper function for visitMUL to check the profitability
414     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
415     /// MulNode is the original multiply, AddNode is (add x, c1),
416     /// and ConstNode is c2.
417     bool isMulAddWithConstProfitable(SDNode *MulNode,
418                                      SDValue &AddNode,
419                                      SDValue &ConstNode);
420 
421     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
422     /// constant build_vector of the stored constant values in Stores.
423     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
424                                          SDLoc SL,
425                                          ArrayRef<MemOpLink> Stores,
426                                          SmallVectorImpl<SDValue> &Chains,
427                                          EVT Ty) const;
428 
429     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
430     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
431     /// the type of the loaded value to be extended.  LoadedVT returns the type
432     /// of the original loaded value.  NarrowLoad returns whether the load would
433     /// need to be narrowed in order to match.
434     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
435                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
436                           bool &NarrowLoad);
437 
438     /// This is a helper function for MergeConsecutiveStores. When the source
439     /// elements of the consecutive stores are all constants or all extracted
440     /// vector elements, try to merge them into one larger store.
441     /// \return True if a merged store was created.
442     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
443                                          EVT MemVT, unsigned NumStores,
444                                          bool IsConstantSrc, bool UseVector);
445 
446     /// This is a helper function for MergeConsecutiveStores.
447     /// Stores that may be merged are placed in StoreNodes.
448     /// Loads that may alias with those stores are placed in AliasLoadNodes.
449     void getStoreMergeAndAliasCandidates(
450         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
451         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
452 
453     /// Helper function for MergeConsecutiveStores. Checks if
454     /// Candidate stores have indirect dependency through their
455     /// operands. \return True if safe to merge
456     bool checkMergeStoreCandidatesForDependencies(
457         SmallVectorImpl<MemOpLink> &StoreNodes);
458 
459     /// Merge consecutive store operations into a wide store.
460     /// This optimization uses wide integers or vectors when possible.
461     /// \return True if some memory operations were changed.
462     bool MergeConsecutiveStores(StoreSDNode *N);
463 
464     /// \brief Try to transform a truncation where C is a constant:
465     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
466     ///
467     /// \p N needs to be a truncation and its first operand an AND. Other
468     /// requirements are checked by the function (e.g. that trunc is
469     /// single-use) and if missed an empty SDValue is returned.
470     SDValue distributeTruncateThroughAnd(SDNode *N);
471 
472   public:
473     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
474         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
475           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
476       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
477     }
478 
479     /// Runs the dag combiner on all nodes in the work list
480     void Run(CombineLevel AtLevel);
481 
482     SelectionDAG &getDAG() const { return DAG; }
483 
484     /// Returns a type large enough to hold any valid shift amount - before type
485     /// legalization these can be huge.
486     EVT getShiftAmountTy(EVT LHSTy) {
487       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
488       if (LHSTy.isVector())
489         return LHSTy;
490       auto &DL = DAG.getDataLayout();
491       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
492                         : TLI.getPointerTy(DL);
493     }
494 
495     /// This method returns true if we are running before type legalization or
496     /// if the specified VT is legal.
497     bool isTypeLegal(const EVT &VT) {
498       if (!LegalTypes) return true;
499       return TLI.isTypeLegal(VT);
500     }
501 
502     /// Convenience wrapper around TargetLowering::getSetCCResultType
503     EVT getSetCCResultType(EVT VT) const {
504       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
505     }
506   };
507 }
508 
509 
510 namespace {
511 /// This class is a DAGUpdateListener that removes any deleted
512 /// nodes from the worklist.
513 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
514   DAGCombiner &DC;
515 public:
516   explicit WorklistRemover(DAGCombiner &dc)
517     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
518 
519   void NodeDeleted(SDNode *N, SDNode *E) override {
520     DC.removeFromWorklist(N);
521   }
522 };
523 }
524 
525 //===----------------------------------------------------------------------===//
526 //  TargetLowering::DAGCombinerInfo implementation
527 //===----------------------------------------------------------------------===//
528 
529 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
530   ((DAGCombiner*)DC)->AddToWorklist(N);
531 }
532 
533 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
534   ((DAGCombiner*)DC)->removeFromWorklist(N);
535 }
536 
537 SDValue TargetLowering::DAGCombinerInfo::
538 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
539   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
540 }
541 
542 SDValue TargetLowering::DAGCombinerInfo::
543 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
544   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
545 }
546 
547 
548 SDValue TargetLowering::DAGCombinerInfo::
549 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
550   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
551 }
552 
553 void TargetLowering::DAGCombinerInfo::
554 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
555   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
556 }
557 
558 //===----------------------------------------------------------------------===//
559 // Helper Functions
560 //===----------------------------------------------------------------------===//
561 
562 void DAGCombiner::deleteAndRecombine(SDNode *N) {
563   removeFromWorklist(N);
564 
565   // If the operands of this node are only used by the node, they will now be
566   // dead. Make sure to re-visit them and recursively delete dead nodes.
567   for (const SDValue &Op : N->ops())
568     // For an operand generating multiple values, one of the values may
569     // become dead allowing further simplification (e.g. split index
570     // arithmetic from an indexed load).
571     if (Op->hasOneUse() || Op->getNumValues() > 1)
572       AddToWorklist(Op.getNode());
573 
574   DAG.DeleteNode(N);
575 }
576 
577 /// Return 1 if we can compute the negated form of the specified expression for
578 /// the same cost as the expression itself, or 2 if we can compute the negated
579 /// form more cheaply than the expression itself.
580 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
581                                const TargetLowering &TLI,
582                                const TargetOptions *Options,
583                                unsigned Depth = 0) {
584   // fneg is removable even if it has multiple uses.
585   if (Op.getOpcode() == ISD::FNEG) return 2;
586 
587   // Don't allow anything with multiple uses.
588   if (!Op.hasOneUse()) return 0;
589 
590   // Don't recurse exponentially.
591   if (Depth > 6) return 0;
592 
593   switch (Op.getOpcode()) {
594   default: return false;
595   case ISD::ConstantFP:
596     // Don't invert constant FP values after legalize.  The negated constant
597     // isn't necessarily legal.
598     return LegalOperations ? 0 : 1;
599   case ISD::FADD:
600     // FIXME: determine better conditions for this xform.
601     if (!Options->UnsafeFPMath) return 0;
602 
603     // After operation legalization, it might not be legal to create new FSUBs.
604     if (LegalOperations &&
605         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
606       return 0;
607 
608     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
609     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
610                                     Options, Depth + 1))
611       return V;
612     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
613     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
614                               Depth + 1);
615   case ISD::FSUB:
616     // We can't turn -(A-B) into B-A when we honor signed zeros.
617     if (!Options->UnsafeFPMath) return 0;
618 
619     // fold (fneg (fsub A, B)) -> (fsub B, A)
620     return 1;
621 
622   case ISD::FMUL:
623   case ISD::FDIV:
624     if (Options->HonorSignDependentRoundingFPMath()) return 0;
625 
626     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
627     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
628                                     Options, Depth + 1))
629       return V;
630 
631     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
632                               Depth + 1);
633 
634   case ISD::FP_EXTEND:
635   case ISD::FP_ROUND:
636   case ISD::FSIN:
637     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
638                               Depth + 1);
639   }
640 }
641 
642 /// If isNegatibleForFree returns true, return the newly negated expression.
643 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
644                                     bool LegalOperations, unsigned Depth = 0) {
645   const TargetOptions &Options = DAG.getTarget().Options;
646   // fneg is removable even if it has multiple uses.
647   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
648 
649   // Don't allow anything with multiple uses.
650   assert(Op.hasOneUse() && "Unknown reuse!");
651 
652   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
653 
654   const SDNodeFlags *Flags = Op.getNode()->getFlags();
655 
656   switch (Op.getOpcode()) {
657   default: llvm_unreachable("Unknown code");
658   case ISD::ConstantFP: {
659     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
660     V.changeSign();
661     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
662   }
663   case ISD::FADD:
664     // FIXME: determine better conditions for this xform.
665     assert(Options.UnsafeFPMath);
666 
667     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
668     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
669                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
670       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
671                          GetNegatedExpression(Op.getOperand(0), DAG,
672                                               LegalOperations, Depth+1),
673                          Op.getOperand(1), Flags);
674     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
675     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
676                        GetNegatedExpression(Op.getOperand(1), DAG,
677                                             LegalOperations, Depth+1),
678                        Op.getOperand(0), Flags);
679   case ISD::FSUB:
680     // We can't turn -(A-B) into B-A when we honor signed zeros.
681     assert(Options.UnsafeFPMath);
682 
683     // fold (fneg (fsub 0, B)) -> B
684     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
685       if (N0CFP->isZero())
686         return Op.getOperand(1);
687 
688     // fold (fneg (fsub A, B)) -> (fsub B, A)
689     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
690                        Op.getOperand(1), Op.getOperand(0), Flags);
691 
692   case ISD::FMUL:
693   case ISD::FDIV:
694     assert(!Options.HonorSignDependentRoundingFPMath());
695 
696     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
697     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
698                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
699       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
700                          GetNegatedExpression(Op.getOperand(0), DAG,
701                                               LegalOperations, Depth+1),
702                          Op.getOperand(1), Flags);
703 
704     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
705     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
706                        Op.getOperand(0),
707                        GetNegatedExpression(Op.getOperand(1), DAG,
708                                             LegalOperations, Depth+1), Flags);
709 
710   case ISD::FP_EXTEND:
711   case ISD::FSIN:
712     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
713                        GetNegatedExpression(Op.getOperand(0), DAG,
714                                             LegalOperations, Depth+1));
715   case ISD::FP_ROUND:
716       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
717                          GetNegatedExpression(Op.getOperand(0), DAG,
718                                               LegalOperations, Depth+1),
719                          Op.getOperand(1));
720   }
721 }
722 
723 // Return true if this node is a setcc, or is a select_cc
724 // that selects between the target values used for true and false, making it
725 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
726 // the appropriate nodes based on the type of node we are checking. This
727 // simplifies life a bit for the callers.
728 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
729                                     SDValue &CC) const {
730   if (N.getOpcode() == ISD::SETCC) {
731     LHS = N.getOperand(0);
732     RHS = N.getOperand(1);
733     CC  = N.getOperand(2);
734     return true;
735   }
736 
737   if (N.getOpcode() != ISD::SELECT_CC ||
738       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
739       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
740     return false;
741 
742   if (TLI.getBooleanContents(N.getValueType()) ==
743       TargetLowering::UndefinedBooleanContent)
744     return false;
745 
746   LHS = N.getOperand(0);
747   RHS = N.getOperand(1);
748   CC  = N.getOperand(4);
749   return true;
750 }
751 
752 /// Return true if this is a SetCC-equivalent operation with only one use.
753 /// If this is true, it allows the users to invert the operation for free when
754 /// it is profitable to do so.
755 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
756   SDValue N0, N1, N2;
757   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
758     return true;
759   return false;
760 }
761 
762 /// Returns true if N is a BUILD_VECTOR node whose
763 /// elements are all the same constant or undefined.
764 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
765   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
766   if (!C)
767     return false;
768 
769   APInt SplatUndef;
770   unsigned SplatBitSize;
771   bool HasAnyUndefs;
772   EVT EltVT = N->getValueType(0).getVectorElementType();
773   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
774                              HasAnyUndefs) &&
775           EltVT.getSizeInBits() >= SplatBitSize);
776 }
777 
778 // \brief Returns the SDNode if it is a constant float BuildVector
779 // or constant float.
780 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
781   if (isa<ConstantFPSDNode>(N))
782     return N.getNode();
783   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
784     return N.getNode();
785   return nullptr;
786 }
787 
788 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
789 // int.
790 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
791   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
792     return CN;
793 
794   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
795     BitVector UndefElements;
796     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
797 
798     // BuildVectors can truncate their operands. Ignore that case here.
799     // FIXME: We blindly ignore splats which include undef which is overly
800     // pessimistic.
801     if (CN && UndefElements.none() &&
802         CN->getValueType(0) == N.getValueType().getScalarType())
803       return CN;
804   }
805 
806   return nullptr;
807 }
808 
809 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
810 // float.
811 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
812   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
813     return CN;
814 
815   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
816     BitVector UndefElements;
817     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
818 
819     if (CN && UndefElements.none())
820       return CN;
821   }
822 
823   return nullptr;
824 }
825 
826 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
827                                     SDValue N0, SDValue N1) {
828   EVT VT = N0.getValueType();
829   if (N0.getOpcode() == Opc) {
830     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
831       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
832         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
833         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
834           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
835         return SDValue();
836       }
837       if (N0.hasOneUse()) {
838         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
839         // use
840         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
841         if (!OpNode.getNode())
842           return SDValue();
843         AddToWorklist(OpNode.getNode());
844         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
845       }
846     }
847   }
848 
849   if (N1.getOpcode() == Opc) {
850     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
851       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
852         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
853         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
854           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
855         return SDValue();
856       }
857       if (N1.hasOneUse()) {
858         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
859         // use
860         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
861         if (!OpNode.getNode())
862           return SDValue();
863         AddToWorklist(OpNode.getNode());
864         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
865       }
866     }
867   }
868 
869   return SDValue();
870 }
871 
872 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
873                                bool AddTo) {
874   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
875   ++NodesCombined;
876   DEBUG(dbgs() << "\nReplacing.1 ";
877         N->dump(&DAG);
878         dbgs() << "\nWith: ";
879         To[0].getNode()->dump(&DAG);
880         dbgs() << " and " << NumTo-1 << " other values\n");
881   for (unsigned i = 0, e = NumTo; i != e; ++i)
882     assert((!To[i].getNode() ||
883             N->getValueType(i) == To[i].getValueType()) &&
884            "Cannot combine value to value of different type!");
885 
886   WorklistRemover DeadNodes(*this);
887   DAG.ReplaceAllUsesWith(N, To);
888   if (AddTo) {
889     // Push the new nodes and any users onto the worklist
890     for (unsigned i = 0, e = NumTo; i != e; ++i) {
891       if (To[i].getNode()) {
892         AddToWorklist(To[i].getNode());
893         AddUsersToWorklist(To[i].getNode());
894       }
895     }
896   }
897 
898   // Finally, if the node is now dead, remove it from the graph.  The node
899   // may not be dead if the replacement process recursively simplified to
900   // something else needing this node.
901   if (N->use_empty())
902     deleteAndRecombine(N);
903   return SDValue(N, 0);
904 }
905 
906 void DAGCombiner::
907 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
908   // Replace all uses.  If any nodes become isomorphic to other nodes and
909   // are deleted, make sure to remove them from our worklist.
910   WorklistRemover DeadNodes(*this);
911   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
912 
913   // Push the new node and any (possibly new) users onto the worklist.
914   AddToWorklist(TLO.New.getNode());
915   AddUsersToWorklist(TLO.New.getNode());
916 
917   // Finally, if the node is now dead, remove it from the graph.  The node
918   // may not be dead if the replacement process recursively simplified to
919   // something else needing this node.
920   if (TLO.Old.getNode()->use_empty())
921     deleteAndRecombine(TLO.Old.getNode());
922 }
923 
924 /// Check the specified integer node value to see if it can be simplified or if
925 /// things it uses can be simplified by bit propagation. If so, return true.
926 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
927   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
928   APInt KnownZero, KnownOne;
929   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
930     return false;
931 
932   // Revisit the node.
933   AddToWorklist(Op.getNode());
934 
935   // Replace the old value with the new one.
936   ++NodesCombined;
937   DEBUG(dbgs() << "\nReplacing.2 ";
938         TLO.Old.getNode()->dump(&DAG);
939         dbgs() << "\nWith: ";
940         TLO.New.getNode()->dump(&DAG);
941         dbgs() << '\n');
942 
943   CommitTargetLoweringOpt(TLO);
944   return true;
945 }
946 
947 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
948   SDLoc dl(Load);
949   EVT VT = Load->getValueType(0);
950   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
951 
952   DEBUG(dbgs() << "\nReplacing.9 ";
953         Load->dump(&DAG);
954         dbgs() << "\nWith: ";
955         Trunc.getNode()->dump(&DAG);
956         dbgs() << '\n');
957   WorklistRemover DeadNodes(*this);
958   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
959   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
960   deleteAndRecombine(Load);
961   AddToWorklist(Trunc.getNode());
962 }
963 
964 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
965   Replace = false;
966   SDLoc dl(Op);
967   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
968     LoadSDNode *LD = cast<LoadSDNode>(Op);
969     EVT MemVT = LD->getMemoryVT();
970     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
971       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
972                                                        : ISD::EXTLOAD)
973       : LD->getExtensionType();
974     Replace = true;
975     return DAG.getExtLoad(ExtType, dl, PVT,
976                           LD->getChain(), LD->getBasePtr(),
977                           MemVT, LD->getMemOperand());
978   }
979 
980   unsigned Opc = Op.getOpcode();
981   switch (Opc) {
982   default: break;
983   case ISD::AssertSext:
984     return DAG.getNode(ISD::AssertSext, dl, PVT,
985                        SExtPromoteOperand(Op.getOperand(0), PVT),
986                        Op.getOperand(1));
987   case ISD::AssertZext:
988     return DAG.getNode(ISD::AssertZext, dl, PVT,
989                        ZExtPromoteOperand(Op.getOperand(0), PVT),
990                        Op.getOperand(1));
991   case ISD::Constant: {
992     unsigned ExtOpc =
993       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
994     return DAG.getNode(ExtOpc, dl, PVT, Op);
995   }
996   }
997 
998   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
999     return SDValue();
1000   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
1001 }
1002 
1003 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1004   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1005     return SDValue();
1006   EVT OldVT = Op.getValueType();
1007   SDLoc dl(Op);
1008   bool Replace = false;
1009   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1010   if (!NewOp.getNode())
1011     return SDValue();
1012   AddToWorklist(NewOp.getNode());
1013 
1014   if (Replace)
1015     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1016   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1017                      DAG.getValueType(OldVT));
1018 }
1019 
1020 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1021   EVT OldVT = Op.getValueType();
1022   SDLoc dl(Op);
1023   bool Replace = false;
1024   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1025   if (!NewOp.getNode())
1026     return SDValue();
1027   AddToWorklist(NewOp.getNode());
1028 
1029   if (Replace)
1030     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1031   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1032 }
1033 
1034 /// Promote the specified integer binary operation if the target indicates it is
1035 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1036 /// i32 since i16 instructions are longer.
1037 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1038   if (!LegalOperations)
1039     return SDValue();
1040 
1041   EVT VT = Op.getValueType();
1042   if (VT.isVector() || !VT.isInteger())
1043     return SDValue();
1044 
1045   // If operation type is 'undesirable', e.g. i16 on x86, consider
1046   // promoting it.
1047   unsigned Opc = Op.getOpcode();
1048   if (TLI.isTypeDesirableForOp(Opc, VT))
1049     return SDValue();
1050 
1051   EVT PVT = VT;
1052   // Consult target whether it is a good idea to promote this operation and
1053   // what's the right type to promote it to.
1054   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055     assert(PVT != VT && "Don't know what type to promote to!");
1056 
1057     bool Replace0 = false;
1058     SDValue N0 = Op.getOperand(0);
1059     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1060     if (!NN0.getNode())
1061       return SDValue();
1062 
1063     bool Replace1 = false;
1064     SDValue N1 = Op.getOperand(1);
1065     SDValue NN1;
1066     if (N0 == N1)
1067       NN1 = NN0;
1068     else {
1069       NN1 = PromoteOperand(N1, PVT, Replace1);
1070       if (!NN1.getNode())
1071         return SDValue();
1072     }
1073 
1074     AddToWorklist(NN0.getNode());
1075     if (NN1.getNode())
1076       AddToWorklist(NN1.getNode());
1077 
1078     if (Replace0)
1079       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1080     if (Replace1)
1081       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1082 
1083     DEBUG(dbgs() << "\nPromoting ";
1084           Op.getNode()->dump(&DAG));
1085     SDLoc dl(Op);
1086     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1087                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1088   }
1089   return SDValue();
1090 }
1091 
1092 /// Promote the specified integer shift operation if the target indicates it is
1093 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1094 /// i32 since i16 instructions are longer.
1095 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1096   if (!LegalOperations)
1097     return SDValue();
1098 
1099   EVT VT = Op.getValueType();
1100   if (VT.isVector() || !VT.isInteger())
1101     return SDValue();
1102 
1103   // If operation type is 'undesirable', e.g. i16 on x86, consider
1104   // promoting it.
1105   unsigned Opc = Op.getOpcode();
1106   if (TLI.isTypeDesirableForOp(Opc, VT))
1107     return SDValue();
1108 
1109   EVT PVT = VT;
1110   // Consult target whether it is a good idea to promote this operation and
1111   // what's the right type to promote it to.
1112   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1113     assert(PVT != VT && "Don't know what type to promote to!");
1114 
1115     bool Replace = false;
1116     SDValue N0 = Op.getOperand(0);
1117     if (Opc == ISD::SRA)
1118       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1119     else if (Opc == ISD::SRL)
1120       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1121     else
1122       N0 = PromoteOperand(N0, PVT, Replace);
1123     if (!N0.getNode())
1124       return SDValue();
1125 
1126     AddToWorklist(N0.getNode());
1127     if (Replace)
1128       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1129 
1130     DEBUG(dbgs() << "\nPromoting ";
1131           Op.getNode()->dump(&DAG));
1132     SDLoc dl(Op);
1133     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1134                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1135   }
1136   return SDValue();
1137 }
1138 
1139 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1140   if (!LegalOperations)
1141     return SDValue();
1142 
1143   EVT VT = Op.getValueType();
1144   if (VT.isVector() || !VT.isInteger())
1145     return SDValue();
1146 
1147   // If operation type is 'undesirable', e.g. i16 on x86, consider
1148   // promoting it.
1149   unsigned Opc = Op.getOpcode();
1150   if (TLI.isTypeDesirableForOp(Opc, VT))
1151     return SDValue();
1152 
1153   EVT PVT = VT;
1154   // Consult target whether it is a good idea to promote this operation and
1155   // what's the right type to promote it to.
1156   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1157     assert(PVT != VT && "Don't know what type to promote to!");
1158     // fold (aext (aext x)) -> (aext x)
1159     // fold (aext (zext x)) -> (zext x)
1160     // fold (aext (sext x)) -> (sext x)
1161     DEBUG(dbgs() << "\nPromoting ";
1162           Op.getNode()->dump(&DAG));
1163     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1164   }
1165   return SDValue();
1166 }
1167 
1168 bool DAGCombiner::PromoteLoad(SDValue Op) {
1169   if (!LegalOperations)
1170     return false;
1171 
1172   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1173     return false;
1174 
1175   EVT VT = Op.getValueType();
1176   if (VT.isVector() || !VT.isInteger())
1177     return false;
1178 
1179   // If operation type is 'undesirable', e.g. i16 on x86, consider
1180   // promoting it.
1181   unsigned Opc = Op.getOpcode();
1182   if (TLI.isTypeDesirableForOp(Opc, VT))
1183     return false;
1184 
1185   EVT PVT = VT;
1186   // Consult target whether it is a good idea to promote this operation and
1187   // what's the right type to promote it to.
1188   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1189     assert(PVT != VT && "Don't know what type to promote to!");
1190 
1191     SDLoc dl(Op);
1192     SDNode *N = Op.getNode();
1193     LoadSDNode *LD = cast<LoadSDNode>(N);
1194     EVT MemVT = LD->getMemoryVT();
1195     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1196       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1197                                                        : ISD::EXTLOAD)
1198       : LD->getExtensionType();
1199     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1200                                    LD->getChain(), LD->getBasePtr(),
1201                                    MemVT, LD->getMemOperand());
1202     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1203 
1204     DEBUG(dbgs() << "\nPromoting ";
1205           N->dump(&DAG);
1206           dbgs() << "\nTo: ";
1207           Result.getNode()->dump(&DAG);
1208           dbgs() << '\n');
1209     WorklistRemover DeadNodes(*this);
1210     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1211     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1212     deleteAndRecombine(N);
1213     AddToWorklist(Result.getNode());
1214     return true;
1215   }
1216   return false;
1217 }
1218 
1219 /// \brief Recursively delete a node which has no uses and any operands for
1220 /// which it is the only use.
1221 ///
1222 /// Note that this both deletes the nodes and removes them from the worklist.
1223 /// It also adds any nodes who have had a user deleted to the worklist as they
1224 /// may now have only one use and subject to other combines.
1225 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1226   if (!N->use_empty())
1227     return false;
1228 
1229   SmallSetVector<SDNode *, 16> Nodes;
1230   Nodes.insert(N);
1231   do {
1232     N = Nodes.pop_back_val();
1233     if (!N)
1234       continue;
1235 
1236     if (N->use_empty()) {
1237       for (const SDValue &ChildN : N->op_values())
1238         Nodes.insert(ChildN.getNode());
1239 
1240       removeFromWorklist(N);
1241       DAG.DeleteNode(N);
1242     } else {
1243       AddToWorklist(N);
1244     }
1245   } while (!Nodes.empty());
1246   return true;
1247 }
1248 
1249 //===----------------------------------------------------------------------===//
1250 //  Main DAG Combiner implementation
1251 //===----------------------------------------------------------------------===//
1252 
1253 void DAGCombiner::Run(CombineLevel AtLevel) {
1254   // set the instance variables, so that the various visit routines may use it.
1255   Level = AtLevel;
1256   LegalOperations = Level >= AfterLegalizeVectorOps;
1257   LegalTypes = Level >= AfterLegalizeTypes;
1258 
1259   // Add all the dag nodes to the worklist.
1260   for (SDNode &Node : DAG.allnodes())
1261     AddToWorklist(&Node);
1262 
1263   // Create a dummy node (which is not added to allnodes), that adds a reference
1264   // to the root node, preventing it from being deleted, and tracking any
1265   // changes of the root.
1266   HandleSDNode Dummy(DAG.getRoot());
1267 
1268   // While the worklist isn't empty, find a node and try to combine it.
1269   while (!WorklistMap.empty()) {
1270     SDNode *N;
1271     // The Worklist holds the SDNodes in order, but it may contain null entries.
1272     do {
1273       N = Worklist.pop_back_val();
1274     } while (!N);
1275 
1276     bool GoodWorklistEntry = WorklistMap.erase(N);
1277     (void)GoodWorklistEntry;
1278     assert(GoodWorklistEntry &&
1279            "Found a worklist entry without a corresponding map entry!");
1280 
1281     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1282     // N is deleted from the DAG, since they too may now be dead or may have a
1283     // reduced number of uses, allowing other xforms.
1284     if (recursivelyDeleteUnusedNodes(N))
1285       continue;
1286 
1287     WorklistRemover DeadNodes(*this);
1288 
1289     // If this combine is running after legalizing the DAG, re-legalize any
1290     // nodes pulled off the worklist.
1291     if (Level == AfterLegalizeDAG) {
1292       SmallSetVector<SDNode *, 16> UpdatedNodes;
1293       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1294 
1295       for (SDNode *LN : UpdatedNodes) {
1296         AddToWorklist(LN);
1297         AddUsersToWorklist(LN);
1298       }
1299       if (!NIsValid)
1300         continue;
1301     }
1302 
1303     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1304 
1305     // Add any operands of the new node which have not yet been combined to the
1306     // worklist as well. Because the worklist uniques things already, this
1307     // won't repeatedly process the same operand.
1308     CombinedNodes.insert(N);
1309     for (const SDValue &ChildN : N->op_values())
1310       if (!CombinedNodes.count(ChildN.getNode()))
1311         AddToWorklist(ChildN.getNode());
1312 
1313     SDValue RV = combine(N);
1314 
1315     if (!RV.getNode())
1316       continue;
1317 
1318     ++NodesCombined;
1319 
1320     // If we get back the same node we passed in, rather than a new node or
1321     // zero, we know that the node must have defined multiple values and
1322     // CombineTo was used.  Since CombineTo takes care of the worklist
1323     // mechanics for us, we have no work to do in this case.
1324     if (RV.getNode() == N)
1325       continue;
1326 
1327     assert(N->getOpcode() != ISD::DELETED_NODE &&
1328            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1329            "Node was deleted but visit returned new node!");
1330 
1331     DEBUG(dbgs() << " ... into: ";
1332           RV.getNode()->dump(&DAG));
1333 
1334     // Transfer debug value.
1335     DAG.TransferDbgValues(SDValue(N, 0), RV);
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(SDLoc DL, const TargetLowering &TLI, EVT VT,
1855                              SelectionDAG &DAG,
1856                              bool LegalOperations, 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, Mask1)
3755     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3756     // Do this only if the resulting shuffle is legal.
3757     if (isa<ShuffleVectorSDNode>(N0) &&
3758         isa<ShuffleVectorSDNode>(N1) &&
3759         // Avoid folding a node with illegal type.
3760         TLI.isTypeLegal(VT) &&
3761         N0->getOperand(1) == N1->getOperand(1) &&
3762         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3763       bool CanFold = true;
3764       unsigned NumElts = VT.getVectorNumElements();
3765       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3766       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3767       // We construct two shuffle masks:
3768       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3769       // and N1 as the second operand.
3770       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3771       // and N0 as the second operand.
3772       // We do this because OR is commutable and therefore there might be
3773       // two ways to fold this node into a shuffle.
3774       SmallVector<int,4> Mask1;
3775       SmallVector<int,4> Mask2;
3776 
3777       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3778         int M0 = SV0->getMaskElt(i);
3779         int M1 = SV1->getMaskElt(i);
3780 
3781         // Both shuffle indexes are undef. Propagate Undef.
3782         if (M0 < 0 && M1 < 0) {
3783           Mask1.push_back(M0);
3784           Mask2.push_back(M0);
3785           continue;
3786         }
3787 
3788         if (M0 < 0 || M1 < 0 ||
3789             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3790             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3791           CanFold = false;
3792           break;
3793         }
3794 
3795         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3796         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3797       }
3798 
3799       if (CanFold) {
3800         // Fold this sequence only if the resulting shuffle is 'legal'.
3801         if (TLI.isShuffleMaskLegal(Mask1, VT))
3802           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3803                                       N1->getOperand(0), &Mask1[0]);
3804         if (TLI.isShuffleMaskLegal(Mask2, VT))
3805           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3806                                       N0->getOperand(0), &Mask2[0]);
3807       }
3808     }
3809   }
3810 
3811   // fold (or c1, c2) -> c1|c2
3812   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3813   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3814   if (N0C && N1C && !N1C->isOpaque())
3815     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3816   // canonicalize constant to RHS
3817   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3818      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3819     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3820   // fold (or x, 0) -> x
3821   if (isNullConstant(N1))
3822     return N0;
3823   // fold (or x, -1) -> -1
3824   if (isAllOnesConstant(N1))
3825     return N1;
3826   // fold (or x, c) -> c iff (x & ~c) == 0
3827   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3828     return N1;
3829 
3830   if (SDValue Combined = visitORLike(N0, N1, N))
3831     return Combined;
3832 
3833   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3834   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3835     return BSwap;
3836   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3837     return BSwap;
3838 
3839   // reassociate or
3840   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3841     return ROR;
3842   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3843   // iff (c1 & c2) == 0.
3844   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3845              isa<ConstantSDNode>(N0.getOperand(1))) {
3846     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3847     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3848       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3849                                                    N1C, C1))
3850         return DAG.getNode(
3851             ISD::AND, SDLoc(N), VT,
3852             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3853       return SDValue();
3854     }
3855   }
3856   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3857   if (N0.getOpcode() == N1.getOpcode())
3858     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3859       return Tmp;
3860 
3861   // See if this is some rotate idiom.
3862   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3863     return SDValue(Rot, 0);
3864 
3865   // Simplify the operands using demanded-bits information.
3866   if (!VT.isVector() &&
3867       SimplifyDemandedBits(SDValue(N, 0)))
3868     return SDValue(N, 0);
3869 
3870   return SDValue();
3871 }
3872 
3873 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3874 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3875   if (Op.getOpcode() == ISD::AND) {
3876     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3877       Mask = Op.getOperand(1);
3878       Op = Op.getOperand(0);
3879     } else {
3880       return false;
3881     }
3882   }
3883 
3884   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3885     Shift = Op;
3886     return true;
3887   }
3888 
3889   return false;
3890 }
3891 
3892 // Return true if we can prove that, whenever Neg and Pos are both in the
3893 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3894 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3895 //
3896 //     (or (shift1 X, Neg), (shift2 X, Pos))
3897 //
3898 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3899 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3900 // to consider shift amounts with defined behavior.
3901 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3902   // If EltSize is a power of 2 then:
3903   //
3904   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3905   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3906   //
3907   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3908   // for the stronger condition:
3909   //
3910   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3911   //
3912   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3913   // we can just replace Neg with Neg' for the rest of the function.
3914   //
3915   // In other cases we check for the even stronger condition:
3916   //
3917   //     Neg == EltSize - Pos                                    [B]
3918   //
3919   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3920   // behavior if Pos == 0 (and consequently Neg == EltSize).
3921   //
3922   // We could actually use [A] whenever EltSize is a power of 2, but the
3923   // only extra cases that it would match are those uninteresting ones
3924   // where Neg and Pos are never in range at the same time.  E.g. for
3925   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3926   // as well as (sub 32, Pos), but:
3927   //
3928   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3929   //
3930   // always invokes undefined behavior for 32-bit X.
3931   //
3932   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3933   unsigned MaskLoBits = 0;
3934   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3935     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3936       if (NegC->getAPIntValue() == EltSize - 1) {
3937         Neg = Neg.getOperand(0);
3938         MaskLoBits = Log2_64(EltSize);
3939       }
3940     }
3941   }
3942 
3943   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3944   if (Neg.getOpcode() != ISD::SUB)
3945     return false;
3946   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3947   if (!NegC)
3948     return false;
3949   SDValue NegOp1 = Neg.getOperand(1);
3950 
3951   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3952   // Pos'.  The truncation is redundant for the purpose of the equality.
3953   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3954     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3955       if (PosC->getAPIntValue() == EltSize - 1)
3956         Pos = Pos.getOperand(0);
3957 
3958   // The condition we need is now:
3959   //
3960   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3961   //
3962   // If NegOp1 == Pos then we need:
3963   //
3964   //              EltSize & Mask == NegC & Mask
3965   //
3966   // (because "x & Mask" is a truncation and distributes through subtraction).
3967   APInt Width;
3968   if (Pos == NegOp1)
3969     Width = NegC->getAPIntValue();
3970 
3971   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3972   // Then the condition we want to prove becomes:
3973   //
3974   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3975   //
3976   // which, again because "x & Mask" is a truncation, becomes:
3977   //
3978   //                NegC & Mask == (EltSize - PosC) & Mask
3979   //             EltSize & Mask == (NegC + PosC) & Mask
3980   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3981     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3982       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3983     else
3984       return false;
3985   } else
3986     return false;
3987 
3988   // Now we just need to check that EltSize & Mask == Width & Mask.
3989   if (MaskLoBits)
3990     // EltSize & Mask is 0 since Mask is EltSize - 1.
3991     return Width.getLoBits(MaskLoBits) == 0;
3992   return Width == EltSize;
3993 }
3994 
3995 // A subroutine of MatchRotate used once we have found an OR of two opposite
3996 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3997 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3998 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3999 // Neg with outer conversions stripped away.
4000 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4001                                        SDValue Neg, SDValue InnerPos,
4002                                        SDValue InnerNeg, unsigned PosOpcode,
4003                                        unsigned NegOpcode, SDLoc DL) {
4004   // fold (or (shl x, (*ext y)),
4005   //          (srl x, (*ext (sub 32, y)))) ->
4006   //   (rotl x, y) or (rotr x, (sub 32, y))
4007   //
4008   // fold (or (shl x, (*ext (sub 32, y))),
4009   //          (srl x, (*ext y))) ->
4010   //   (rotr x, y) or (rotl x, (sub 32, y))
4011   EVT VT = Shifted.getValueType();
4012   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4013     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4014     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4015                        HasPos ? Pos : Neg).getNode();
4016   }
4017 
4018   return nullptr;
4019 }
4020 
4021 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4022 // idioms for rotate, and if the target supports rotation instructions, generate
4023 // a rot[lr].
4024 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
4025   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4026   EVT VT = LHS.getValueType();
4027   if (!TLI.isTypeLegal(VT)) return nullptr;
4028 
4029   // The target must have at least one rotate flavor.
4030   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4031   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4032   if (!HasROTL && !HasROTR) return nullptr;
4033 
4034   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4035   SDValue LHSShift;   // The shift.
4036   SDValue LHSMask;    // AND value if any.
4037   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4038     return nullptr; // Not part of a rotate.
4039 
4040   SDValue RHSShift;   // The shift.
4041   SDValue RHSMask;    // AND value if any.
4042   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4043     return nullptr; // Not part of a rotate.
4044 
4045   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4046     return nullptr;   // Not shifting the same value.
4047 
4048   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4049     return nullptr;   // Shifts must disagree.
4050 
4051   // Canonicalize shl to left side in a shl/srl pair.
4052   if (RHSShift.getOpcode() == ISD::SHL) {
4053     std::swap(LHS, RHS);
4054     std::swap(LHSShift, RHSShift);
4055     std::swap(LHSMask, RHSMask);
4056   }
4057 
4058   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4059   SDValue LHSShiftArg = LHSShift.getOperand(0);
4060   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4061   SDValue RHSShiftArg = RHSShift.getOperand(0);
4062   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4063 
4064   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4065   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4066   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4067     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4068     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4069     if ((LShVal + RShVal) != EltSizeInBits)
4070       return nullptr;
4071 
4072     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4073                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4074 
4075     // If there is an AND of either shifted operand, apply it to the result.
4076     if (LHSMask.getNode() || RHSMask.getNode()) {
4077       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4078       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4079 
4080       if (LHSMask.getNode()) {
4081         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4082         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4083                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4084                                        DAG.getConstant(RHSBits, DL, VT)));
4085       }
4086       if (RHSMask.getNode()) {
4087         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4088         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4089                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4090                                        DAG.getConstant(LHSBits, DL, VT)));
4091       }
4092 
4093       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4094     }
4095 
4096     return Rot.getNode();
4097   }
4098 
4099   // If there is a mask here, and we have a variable shift, we can't be sure
4100   // that we're masking out the right stuff.
4101   if (LHSMask.getNode() || RHSMask.getNode())
4102     return nullptr;
4103 
4104   // If the shift amount is sign/zext/any-extended just peel it off.
4105   SDValue LExtOp0 = LHSShiftAmt;
4106   SDValue RExtOp0 = RHSShiftAmt;
4107   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4108        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4109        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4110        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4111       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4112        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4113        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4114        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4115     LExtOp0 = LHSShiftAmt.getOperand(0);
4116     RExtOp0 = RHSShiftAmt.getOperand(0);
4117   }
4118 
4119   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4120                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4121   if (TryL)
4122     return TryL;
4123 
4124   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4125                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4126   if (TryR)
4127     return TryR;
4128 
4129   return nullptr;
4130 }
4131 
4132 SDValue DAGCombiner::visitXOR(SDNode *N) {
4133   SDValue N0 = N->getOperand(0);
4134   SDValue N1 = N->getOperand(1);
4135   EVT VT = N0.getValueType();
4136 
4137   // fold vector ops
4138   if (VT.isVector()) {
4139     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4140       return FoldedVOp;
4141 
4142     // fold (xor x, 0) -> x, vector edition
4143     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4144       return N1;
4145     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4146       return N0;
4147   }
4148 
4149   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4150   if (N0.isUndef() && N1.isUndef())
4151     return DAG.getConstant(0, SDLoc(N), VT);
4152   // fold (xor x, undef) -> undef
4153   if (N0.isUndef())
4154     return N0;
4155   if (N1.isUndef())
4156     return N1;
4157   // fold (xor c1, c2) -> c1^c2
4158   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4159   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4160   if (N0C && N1C)
4161     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4162   // canonicalize constant to RHS
4163   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4164      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4165     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4166   // fold (xor x, 0) -> x
4167   if (isNullConstant(N1))
4168     return N0;
4169   // reassociate xor
4170   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4171     return RXOR;
4172 
4173   // fold !(x cc y) -> (x !cc y)
4174   SDValue LHS, RHS, CC;
4175   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4176     bool isInt = LHS.getValueType().isInteger();
4177     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4178                                                isInt);
4179 
4180     if (!LegalOperations ||
4181         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4182       switch (N0.getOpcode()) {
4183       default:
4184         llvm_unreachable("Unhandled SetCC Equivalent!");
4185       case ISD::SETCC:
4186         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4187       case ISD::SELECT_CC:
4188         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4189                                N0.getOperand(3), NotCC);
4190       }
4191     }
4192   }
4193 
4194   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4195   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4196       N0.getNode()->hasOneUse() &&
4197       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4198     SDValue V = N0.getOperand(0);
4199     SDLoc DL(N0);
4200     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4201                     DAG.getConstant(1, DL, V.getValueType()));
4202     AddToWorklist(V.getNode());
4203     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4204   }
4205 
4206   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4207   if (isOneConstant(N1) && VT == MVT::i1 &&
4208       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4209     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4210     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4211       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4212       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4213       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4214       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4215       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4216     }
4217   }
4218   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4219   if (isAllOnesConstant(N1) &&
4220       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4221     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4222     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4223       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4224       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4225       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4226       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4227       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4228     }
4229   }
4230   // fold (xor (and x, y), y) -> (and (not x), y)
4231   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4232       N0->getOperand(1) == N1) {
4233     SDValue X = N0->getOperand(0);
4234     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4235     AddToWorklist(NotX.getNode());
4236     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4237   }
4238   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4239   if (N1C && N0.getOpcode() == ISD::XOR) {
4240     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4241       SDLoc DL(N);
4242       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4243                          DAG.getConstant(N1C->getAPIntValue() ^
4244                                          N00C->getAPIntValue(), DL, VT));
4245     }
4246     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4247       SDLoc DL(N);
4248       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4249                          DAG.getConstant(N1C->getAPIntValue() ^
4250                                          N01C->getAPIntValue(), DL, VT));
4251     }
4252   }
4253   // fold (xor x, x) -> 0
4254   if (N0 == N1)
4255     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4256 
4257   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4258   // Here is a concrete example of this equivalence:
4259   // i16   x ==  14
4260   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4261   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4262   //
4263   // =>
4264   //
4265   // i16     ~1      == 0b1111111111111110
4266   // i16 rol(~1, 14) == 0b1011111111111111
4267   //
4268   // Some additional tips to help conceptualize this transform:
4269   // - Try to see the operation as placing a single zero in a value of all ones.
4270   // - There exists no value for x which would allow the result to contain zero.
4271   // - Values of x larger than the bitwidth are undefined and do not require a
4272   //   consistent result.
4273   // - Pushing the zero left requires shifting one bits in from the right.
4274   // A rotate left of ~1 is a nice way of achieving the desired result.
4275   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4276       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4277     SDLoc DL(N);
4278     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4279                        N0.getOperand(1));
4280   }
4281 
4282   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4283   if (N0.getOpcode() == N1.getOpcode())
4284     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4285       return Tmp;
4286 
4287   // Simplify the expression using non-local knowledge.
4288   if (!VT.isVector() &&
4289       SimplifyDemandedBits(SDValue(N, 0)))
4290     return SDValue(N, 0);
4291 
4292   return SDValue();
4293 }
4294 
4295 /// Handle transforms common to the three shifts, when the shift amount is a
4296 /// constant.
4297 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4298   SDNode *LHS = N->getOperand(0).getNode();
4299   if (!LHS->hasOneUse()) return SDValue();
4300 
4301   // We want to pull some binops through shifts, so that we have (and (shift))
4302   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4303   // thing happens with address calculations, so it's important to canonicalize
4304   // it.
4305   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4306 
4307   switch (LHS->getOpcode()) {
4308   default: return SDValue();
4309   case ISD::OR:
4310   case ISD::XOR:
4311     HighBitSet = false; // We can only transform sra if the high bit is clear.
4312     break;
4313   case ISD::AND:
4314     HighBitSet = true;  // We can only transform sra if the high bit is set.
4315     break;
4316   case ISD::ADD:
4317     if (N->getOpcode() != ISD::SHL)
4318       return SDValue(); // only shl(add) not sr[al](add).
4319     HighBitSet = false; // We can only transform sra if the high bit is clear.
4320     break;
4321   }
4322 
4323   // We require the RHS of the binop to be a constant and not opaque as well.
4324   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4325   if (!BinOpCst) return SDValue();
4326 
4327   // FIXME: disable this unless the input to the binop is a shift by a constant.
4328   // If it is not a shift, it pessimizes some common cases like:
4329   //
4330   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4331   //    int bar(int *X, int i) { return X[i & 255]; }
4332   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4333   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4334        BinOpLHSVal->getOpcode() != ISD::SRA &&
4335        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4336       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4337     return SDValue();
4338 
4339   EVT VT = N->getValueType(0);
4340 
4341   // If this is a signed shift right, and the high bit is modified by the
4342   // logical operation, do not perform the transformation. The highBitSet
4343   // boolean indicates the value of the high bit of the constant which would
4344   // cause it to be modified for this operation.
4345   if (N->getOpcode() == ISD::SRA) {
4346     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4347     if (BinOpRHSSignSet != HighBitSet)
4348       return SDValue();
4349   }
4350 
4351   if (!TLI.isDesirableToCommuteWithShift(LHS))
4352     return SDValue();
4353 
4354   // Fold the constants, shifting the binop RHS by the shift amount.
4355   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4356                                N->getValueType(0),
4357                                LHS->getOperand(1), N->getOperand(1));
4358   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4359 
4360   // Create the new shift.
4361   SDValue NewShift = DAG.getNode(N->getOpcode(),
4362                                  SDLoc(LHS->getOperand(0)),
4363                                  VT, LHS->getOperand(0), N->getOperand(1));
4364 
4365   // Create the new binop.
4366   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4367 }
4368 
4369 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4370   assert(N->getOpcode() == ISD::TRUNCATE);
4371   assert(N->getOperand(0).getOpcode() == ISD::AND);
4372 
4373   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4374   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4375     SDValue N01 = N->getOperand(0).getOperand(1);
4376 
4377     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4378       if (!N01C->isOpaque()) {
4379         EVT TruncVT = N->getValueType(0);
4380         SDValue N00 = N->getOperand(0).getOperand(0);
4381         APInt TruncC = N01C->getAPIntValue();
4382         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4383         SDLoc DL(N);
4384 
4385         return DAG.getNode(ISD::AND, DL, TruncVT,
4386                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4387                            DAG.getConstant(TruncC, DL, TruncVT));
4388       }
4389     }
4390   }
4391 
4392   return SDValue();
4393 }
4394 
4395 SDValue DAGCombiner::visitRotate(SDNode *N) {
4396   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4397   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4398       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4399     if (SDValue NewOp1 =
4400             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4401       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4402                          N->getOperand(0), NewOp1);
4403   }
4404   return SDValue();
4405 }
4406 
4407 SDValue DAGCombiner::visitSHL(SDNode *N) {
4408   SDValue N0 = N->getOperand(0);
4409   SDValue N1 = N->getOperand(1);
4410   EVT VT = N0.getValueType();
4411   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4412 
4413   // fold vector ops
4414   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4415   if (VT.isVector()) {
4416     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4417       return FoldedVOp;
4418 
4419     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4420     // If setcc produces all-one true value then:
4421     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4422     if (N1CV && N1CV->isConstant()) {
4423       if (N0.getOpcode() == ISD::AND) {
4424         SDValue N00 = N0->getOperand(0);
4425         SDValue N01 = N0->getOperand(1);
4426         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4427 
4428         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4429             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4430                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4431           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4432                                                      N01CV, N1CV))
4433             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4434         }
4435       } else {
4436         N1C = isConstOrConstSplat(N1);
4437       }
4438     }
4439   }
4440 
4441   // fold (shl c1, c2) -> c1<<c2
4442   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4443   if (N0C && N1C && !N1C->isOpaque())
4444     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4445   // fold (shl 0, x) -> 0
4446   if (isNullConstant(N0))
4447     return N0;
4448   // fold (shl x, c >= size(x)) -> undef
4449   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4450     return DAG.getUNDEF(VT);
4451   // fold (shl x, 0) -> x
4452   if (N1C && N1C->isNullValue())
4453     return N0;
4454   // fold (shl undef, x) -> 0
4455   if (N0.isUndef())
4456     return DAG.getConstant(0, SDLoc(N), VT);
4457   // if (shl x, c) is known to be zero, return 0
4458   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4459                             APInt::getAllOnesValue(OpSizeInBits)))
4460     return DAG.getConstant(0, SDLoc(N), VT);
4461   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4462   if (N1.getOpcode() == ISD::TRUNCATE &&
4463       N1.getOperand(0).getOpcode() == ISD::AND) {
4464     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4465       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4466   }
4467 
4468   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4469     return SDValue(N, 0);
4470 
4471   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4472   if (N1C && N0.getOpcode() == ISD::SHL) {
4473     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4474       uint64_t c1 = N0C1->getZExtValue();
4475       uint64_t c2 = N1C->getZExtValue();
4476       SDLoc DL(N);
4477       if (c1 + c2 >= OpSizeInBits)
4478         return DAG.getConstant(0, DL, VT);
4479       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4480                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4481     }
4482   }
4483 
4484   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4485   // For this to be valid, the second form must not preserve any of the bits
4486   // that are shifted out by the inner shift in the first form.  This means
4487   // the outer shift size must be >= the number of bits added by the ext.
4488   // As a corollary, we don't care what kind of ext it is.
4489   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4490               N0.getOpcode() == ISD::ANY_EXTEND ||
4491               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4492       N0.getOperand(0).getOpcode() == ISD::SHL) {
4493     SDValue N0Op0 = N0.getOperand(0);
4494     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4495       uint64_t c1 = N0Op0C1->getZExtValue();
4496       uint64_t c2 = N1C->getZExtValue();
4497       EVT InnerShiftVT = N0Op0.getValueType();
4498       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4499       if (c2 >= OpSizeInBits - InnerShiftSize) {
4500         SDLoc DL(N0);
4501         if (c1 + c2 >= OpSizeInBits)
4502           return DAG.getConstant(0, DL, VT);
4503         return DAG.getNode(ISD::SHL, DL, VT,
4504                            DAG.getNode(N0.getOpcode(), DL, VT,
4505                                        N0Op0->getOperand(0)),
4506                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4507       }
4508     }
4509   }
4510 
4511   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4512   // Only fold this if the inner zext has no other uses to avoid increasing
4513   // the total number of instructions.
4514   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4515       N0.getOperand(0).getOpcode() == ISD::SRL) {
4516     SDValue N0Op0 = N0.getOperand(0);
4517     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4518       uint64_t c1 = N0Op0C1->getZExtValue();
4519       if (c1 < VT.getScalarSizeInBits()) {
4520         uint64_t c2 = N1C->getZExtValue();
4521         if (c1 == c2) {
4522           SDValue NewOp0 = N0.getOperand(0);
4523           EVT CountVT = NewOp0.getOperand(1).getValueType();
4524           SDLoc DL(N);
4525           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4526                                        NewOp0,
4527                                        DAG.getConstant(c2, DL, CountVT));
4528           AddToWorklist(NewSHL.getNode());
4529           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4530         }
4531       }
4532     }
4533   }
4534 
4535   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4536   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4537   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4538       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4539     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4540       uint64_t C1 = N0C1->getZExtValue();
4541       uint64_t C2 = N1C->getZExtValue();
4542       SDLoc DL(N);
4543       if (C1 <= C2)
4544         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4545                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4546       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4547                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4548     }
4549   }
4550 
4551   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4552   //                               (and (srl x, (sub c1, c2), MASK)
4553   // Only fold this if the inner shift has no other uses -- if it does, folding
4554   // this will increase the total number of instructions.
4555   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4556     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4557       uint64_t c1 = N0C1->getZExtValue();
4558       if (c1 < OpSizeInBits) {
4559         uint64_t c2 = N1C->getZExtValue();
4560         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4561         SDValue Shift;
4562         if (c2 > c1) {
4563           Mask = Mask.shl(c2 - c1);
4564           SDLoc DL(N);
4565           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4566                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4567         } else {
4568           Mask = Mask.lshr(c1 - c2);
4569           SDLoc DL(N);
4570           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4571                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4572         }
4573         SDLoc DL(N0);
4574         return DAG.getNode(ISD::AND, DL, VT, Shift,
4575                            DAG.getConstant(Mask, DL, VT));
4576       }
4577     }
4578   }
4579   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4580   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4581     unsigned BitSize = VT.getScalarSizeInBits();
4582     SDLoc DL(N);
4583     SDValue HiBitsMask =
4584       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4585                                             BitSize - N1C->getZExtValue()),
4586                       DL, VT);
4587     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4588                        HiBitsMask);
4589   }
4590 
4591   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4592   // Variant of version done on multiply, except mul by a power of 2 is turned
4593   // into a shift.
4594   APInt Val;
4595   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4596       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4597        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4598     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4599     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4600     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4601   }
4602 
4603   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4604   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4605     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4606       if (SDValue Folded =
4607               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4608         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4609     }
4610   }
4611 
4612   if (N1C && !N1C->isOpaque())
4613     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4614       return NewSHL;
4615 
4616   return SDValue();
4617 }
4618 
4619 SDValue DAGCombiner::visitSRA(SDNode *N) {
4620   SDValue N0 = N->getOperand(0);
4621   SDValue N1 = N->getOperand(1);
4622   EVT VT = N0.getValueType();
4623   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4624 
4625   // fold vector ops
4626   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4627   if (VT.isVector()) {
4628     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4629       return FoldedVOp;
4630 
4631     N1C = isConstOrConstSplat(N1);
4632   }
4633 
4634   // fold (sra c1, c2) -> (sra c1, c2)
4635   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4636   if (N0C && N1C && !N1C->isOpaque())
4637     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4638   // fold (sra 0, x) -> 0
4639   if (isNullConstant(N0))
4640     return N0;
4641   // fold (sra -1, x) -> -1
4642   if (isAllOnesConstant(N0))
4643     return N0;
4644   // fold (sra x, (setge c, size(x))) -> undef
4645   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4646     return DAG.getUNDEF(VT);
4647   // fold (sra x, 0) -> x
4648   if (N1C && N1C->isNullValue())
4649     return N0;
4650   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4651   // sext_inreg.
4652   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4653     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4654     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4655     if (VT.isVector())
4656       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4657                                ExtVT, VT.getVectorNumElements());
4658     if ((!LegalOperations ||
4659          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4660       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4661                          N0.getOperand(0), DAG.getValueType(ExtVT));
4662   }
4663 
4664   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4665   if (N1C && N0.getOpcode() == ISD::SRA) {
4666     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4667       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4668       if (Sum >= OpSizeInBits)
4669         Sum = OpSizeInBits - 1;
4670       SDLoc DL(N);
4671       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4672                          DAG.getConstant(Sum, DL, N1.getValueType()));
4673     }
4674   }
4675 
4676   // fold (sra (shl X, m), (sub result_size, n))
4677   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4678   // result_size - n != m.
4679   // If truncate is free for the target sext(shl) is likely to result in better
4680   // code.
4681   if (N0.getOpcode() == ISD::SHL && N1C) {
4682     // Get the two constanst of the shifts, CN0 = m, CN = n.
4683     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4684     if (N01C) {
4685       LLVMContext &Ctx = *DAG.getContext();
4686       // Determine what the truncate's result bitsize and type would be.
4687       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4688 
4689       if (VT.isVector())
4690         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4691 
4692       // Determine the residual right-shift amount.
4693       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4694 
4695       // If the shift is not a no-op (in which case this should be just a sign
4696       // extend already), the truncated to type is legal, sign_extend is legal
4697       // on that type, and the truncate to that type is both legal and free,
4698       // perform the transform.
4699       if ((ShiftAmt > 0) &&
4700           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4701           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4702           TLI.isTruncateFree(VT, TruncVT)) {
4703 
4704         SDLoc DL(N);
4705         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4706             getShiftAmountTy(N0.getOperand(0).getValueType()));
4707         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4708                                     N0.getOperand(0), Amt);
4709         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4710                                     Shift);
4711         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4712                            N->getValueType(0), Trunc);
4713       }
4714     }
4715   }
4716 
4717   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4718   if (N1.getOpcode() == ISD::TRUNCATE &&
4719       N1.getOperand(0).getOpcode() == ISD::AND) {
4720     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4721       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4722   }
4723 
4724   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4725   //      if c1 is equal to the number of bits the trunc removes
4726   if (N0.getOpcode() == ISD::TRUNCATE &&
4727       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4728        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4729       N0.getOperand(0).hasOneUse() &&
4730       N0.getOperand(0).getOperand(1).hasOneUse() &&
4731       N1C) {
4732     SDValue N0Op0 = N0.getOperand(0);
4733     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4734       unsigned LargeShiftVal = LargeShift->getZExtValue();
4735       EVT LargeVT = N0Op0.getValueType();
4736 
4737       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4738         SDLoc DL(N);
4739         SDValue Amt =
4740           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4741                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4742         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4743                                   N0Op0.getOperand(0), Amt);
4744         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4745       }
4746     }
4747   }
4748 
4749   // Simplify, based on bits shifted out of the LHS.
4750   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4751     return SDValue(N, 0);
4752 
4753 
4754   // If the sign bit is known to be zero, switch this to a SRL.
4755   if (DAG.SignBitIsZero(N0))
4756     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4757 
4758   if (N1C && !N1C->isOpaque())
4759     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4760       return NewSRA;
4761 
4762   return SDValue();
4763 }
4764 
4765 SDValue DAGCombiner::visitSRL(SDNode *N) {
4766   SDValue N0 = N->getOperand(0);
4767   SDValue N1 = N->getOperand(1);
4768   EVT VT = N0.getValueType();
4769   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4770 
4771   // fold vector ops
4772   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4773   if (VT.isVector()) {
4774     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4775       return FoldedVOp;
4776 
4777     N1C = isConstOrConstSplat(N1);
4778   }
4779 
4780   // fold (srl c1, c2) -> c1 >>u c2
4781   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4782   if (N0C && N1C && !N1C->isOpaque())
4783     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4784   // fold (srl 0, x) -> 0
4785   if (isNullConstant(N0))
4786     return N0;
4787   // fold (srl x, c >= size(x)) -> undef
4788   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4789     return DAG.getUNDEF(VT);
4790   // fold (srl x, 0) -> x
4791   if (N1C && N1C->isNullValue())
4792     return N0;
4793   // if (srl x, c) is known to be zero, return 0
4794   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4795                                    APInt::getAllOnesValue(OpSizeInBits)))
4796     return DAG.getConstant(0, SDLoc(N), VT);
4797 
4798   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4799   if (N1C && N0.getOpcode() == ISD::SRL) {
4800     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4801       uint64_t c1 = N01C->getZExtValue();
4802       uint64_t c2 = N1C->getZExtValue();
4803       SDLoc DL(N);
4804       if (c1 + c2 >= OpSizeInBits)
4805         return DAG.getConstant(0, DL, VT);
4806       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4807                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4808     }
4809   }
4810 
4811   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4812   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4813       N0.getOperand(0).getOpcode() == ISD::SRL &&
4814       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4815     uint64_t c1 =
4816       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4817     uint64_t c2 = N1C->getZExtValue();
4818     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4819     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4820     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4821     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4822     if (c1 + OpSizeInBits == InnerShiftSize) {
4823       SDLoc DL(N0);
4824       if (c1 + c2 >= InnerShiftSize)
4825         return DAG.getConstant(0, DL, VT);
4826       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4827                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4828                                      N0.getOperand(0)->getOperand(0),
4829                                      DAG.getConstant(c1 + c2, DL,
4830                                                      ShiftCountVT)));
4831     }
4832   }
4833 
4834   // fold (srl (shl x, c), c) -> (and x, cst2)
4835   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4836     unsigned BitSize = N0.getScalarValueSizeInBits();
4837     if (BitSize <= 64) {
4838       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4839       SDLoc DL(N);
4840       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4841                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4842     }
4843   }
4844 
4845   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4846   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4847     // Shifting in all undef bits?
4848     EVT SmallVT = N0.getOperand(0).getValueType();
4849     unsigned BitSize = SmallVT.getScalarSizeInBits();
4850     if (N1C->getZExtValue() >= BitSize)
4851       return DAG.getUNDEF(VT);
4852 
4853     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4854       uint64_t ShiftAmt = N1C->getZExtValue();
4855       SDLoc DL0(N0);
4856       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4857                                        N0.getOperand(0),
4858                           DAG.getConstant(ShiftAmt, DL0,
4859                                           getShiftAmountTy(SmallVT)));
4860       AddToWorklist(SmallShift.getNode());
4861       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4862       SDLoc DL(N);
4863       return DAG.getNode(ISD::AND, DL, VT,
4864                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4865                          DAG.getConstant(Mask, DL, VT));
4866     }
4867   }
4868 
4869   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4870   // bit, which is unmodified by sra.
4871   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4872     if (N0.getOpcode() == ISD::SRA)
4873       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4874   }
4875 
4876   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4877   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4878       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4879     APInt KnownZero, KnownOne;
4880     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4881 
4882     // If any of the input bits are KnownOne, then the input couldn't be all
4883     // zeros, thus the result of the srl will always be zero.
4884     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4885 
4886     // If all of the bits input the to ctlz node are known to be zero, then
4887     // the result of the ctlz is "32" and the result of the shift is one.
4888     APInt UnknownBits = ~KnownZero;
4889     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4890 
4891     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4892     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4893       // Okay, we know that only that the single bit specified by UnknownBits
4894       // could be set on input to the CTLZ node. If this bit is set, the SRL
4895       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4896       // to an SRL/XOR pair, which is likely to simplify more.
4897       unsigned ShAmt = UnknownBits.countTrailingZeros();
4898       SDValue Op = N0.getOperand(0);
4899 
4900       if (ShAmt) {
4901         SDLoc DL(N0);
4902         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4903                   DAG.getConstant(ShAmt, DL,
4904                                   getShiftAmountTy(Op.getValueType())));
4905         AddToWorklist(Op.getNode());
4906       }
4907 
4908       SDLoc DL(N);
4909       return DAG.getNode(ISD::XOR, DL, VT,
4910                          Op, DAG.getConstant(1, DL, VT));
4911     }
4912   }
4913 
4914   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4915   if (N1.getOpcode() == ISD::TRUNCATE &&
4916       N1.getOperand(0).getOpcode() == ISD::AND) {
4917     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4918       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4919   }
4920 
4921   // fold operands of srl based on knowledge that the low bits are not
4922   // demanded.
4923   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4924     return SDValue(N, 0);
4925 
4926   if (N1C && !N1C->isOpaque())
4927     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4928       return NewSRL;
4929 
4930   // Attempt to convert a srl of a load into a narrower zero-extending load.
4931   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4932     return NarrowLoad;
4933 
4934   // Here is a common situation. We want to optimize:
4935   //
4936   //   %a = ...
4937   //   %b = and i32 %a, 2
4938   //   %c = srl i32 %b, 1
4939   //   brcond i32 %c ...
4940   //
4941   // into
4942   //
4943   //   %a = ...
4944   //   %b = and %a, 2
4945   //   %c = setcc eq %b, 0
4946   //   brcond %c ...
4947   //
4948   // However when after the source operand of SRL is optimized into AND, the SRL
4949   // itself may not be optimized further. Look for it and add the BRCOND into
4950   // the worklist.
4951   if (N->hasOneUse()) {
4952     SDNode *Use = *N->use_begin();
4953     if (Use->getOpcode() == ISD::BRCOND)
4954       AddToWorklist(Use);
4955     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4956       // Also look pass the truncate.
4957       Use = *Use->use_begin();
4958       if (Use->getOpcode() == ISD::BRCOND)
4959         AddToWorklist(Use);
4960     }
4961   }
4962 
4963   return SDValue();
4964 }
4965 
4966 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4967   SDValue N0 = N->getOperand(0);
4968   EVT VT = N->getValueType(0);
4969 
4970   // fold (bswap c1) -> c2
4971   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4972     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4973   // fold (bswap (bswap x)) -> x
4974   if (N0.getOpcode() == ISD::BSWAP)
4975     return N0->getOperand(0);
4976   return SDValue();
4977 }
4978 
4979 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
4980   SDValue N0 = N->getOperand(0);
4981 
4982   // fold (bitreverse (bitreverse x)) -> x
4983   if (N0.getOpcode() == ISD::BITREVERSE)
4984     return N0.getOperand(0);
4985   return SDValue();
4986 }
4987 
4988 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4989   SDValue N0 = N->getOperand(0);
4990   EVT VT = N->getValueType(0);
4991 
4992   // fold (ctlz c1) -> c2
4993   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4994     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4995   return SDValue();
4996 }
4997 
4998 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4999   SDValue N0 = N->getOperand(0);
5000   EVT VT = N->getValueType(0);
5001 
5002   // fold (ctlz_zero_undef c1) -> c2
5003   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5004     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5005   return SDValue();
5006 }
5007 
5008 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5009   SDValue N0 = N->getOperand(0);
5010   EVT VT = N->getValueType(0);
5011 
5012   // fold (cttz c1) -> c2
5013   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5014     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5015   return SDValue();
5016 }
5017 
5018 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5019   SDValue N0 = N->getOperand(0);
5020   EVT VT = N->getValueType(0);
5021 
5022   // fold (cttz_zero_undef c1) -> c2
5023   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5024     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5025   return SDValue();
5026 }
5027 
5028 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5029   SDValue N0 = N->getOperand(0);
5030   EVT VT = N->getValueType(0);
5031 
5032   // fold (ctpop c1) -> c2
5033   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5034     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5035   return SDValue();
5036 }
5037 
5038 
5039 /// \brief Generate Min/Max node
5040 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
5041                                    SDValue True, SDValue False,
5042                                    ISD::CondCode CC, const TargetLowering &TLI,
5043                                    SelectionDAG &DAG) {
5044   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5045     return SDValue();
5046 
5047   switch (CC) {
5048   case ISD::SETOLT:
5049   case ISD::SETOLE:
5050   case ISD::SETLT:
5051   case ISD::SETLE:
5052   case ISD::SETULT:
5053   case ISD::SETULE: {
5054     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5055     if (TLI.isOperationLegal(Opcode, VT))
5056       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5057     return SDValue();
5058   }
5059   case ISD::SETOGT:
5060   case ISD::SETOGE:
5061   case ISD::SETGT:
5062   case ISD::SETGE:
5063   case ISD::SETUGT:
5064   case ISD::SETUGE: {
5065     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5066     if (TLI.isOperationLegal(Opcode, VT))
5067       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5068     return SDValue();
5069   }
5070   default:
5071     return SDValue();
5072   }
5073 }
5074 
5075 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5076   SDValue N0 = N->getOperand(0);
5077   SDValue N1 = N->getOperand(1);
5078   SDValue N2 = N->getOperand(2);
5079   EVT VT = N->getValueType(0);
5080   EVT VT0 = N0.getValueType();
5081 
5082   // fold (select C, X, X) -> X
5083   if (N1 == N2)
5084     return N1;
5085   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5086     // fold (select true, X, Y) -> X
5087     // fold (select false, X, Y) -> Y
5088     return !N0C->isNullValue() ? N1 : N2;
5089   }
5090   // fold (select C, 1, X) -> (or C, X)
5091   if (VT == MVT::i1 && isOneConstant(N1))
5092     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5093   // fold (select C, 0, 1) -> (xor C, 1)
5094   // We can't do this reliably if integer based booleans have different contents
5095   // to floating point based booleans. This is because we can't tell whether we
5096   // have an integer-based boolean or a floating-point-based boolean unless we
5097   // can find the SETCC that produced it and inspect its operands. This is
5098   // fairly easy if C is the SETCC node, but it can potentially be
5099   // undiscoverable (or not reasonably discoverable). For example, it could be
5100   // in another basic block or it could require searching a complicated
5101   // expression.
5102   if (VT.isInteger() &&
5103       (VT0 == MVT::i1 || (VT0.isInteger() &&
5104                           TLI.getBooleanContents(false, false) ==
5105                               TLI.getBooleanContents(false, true) &&
5106                           TLI.getBooleanContents(false, false) ==
5107                               TargetLowering::ZeroOrOneBooleanContent)) &&
5108       isNullConstant(N1) && isOneConstant(N2)) {
5109     SDValue XORNode;
5110     if (VT == VT0) {
5111       SDLoc DL(N);
5112       return DAG.getNode(ISD::XOR, DL, VT0,
5113                          N0, DAG.getConstant(1, DL, VT0));
5114     }
5115     SDLoc DL0(N0);
5116     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5117                           N0, DAG.getConstant(1, DL0, VT0));
5118     AddToWorklist(XORNode.getNode());
5119     if (VT.bitsGT(VT0))
5120       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5121     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5122   }
5123   // fold (select C, 0, X) -> (and (not C), X)
5124   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5125     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5126     AddToWorklist(NOTNode.getNode());
5127     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5128   }
5129   // fold (select C, X, 1) -> (or (not C), X)
5130   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5131     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5132     AddToWorklist(NOTNode.getNode());
5133     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5134   }
5135   // fold (select C, X, 0) -> (and C, X)
5136   if (VT == MVT::i1 && isNullConstant(N2))
5137     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5138   // fold (select X, X, Y) -> (or X, Y)
5139   // fold (select X, 1, Y) -> (or X, Y)
5140   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5141     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5142   // fold (select X, Y, X) -> (and X, Y)
5143   // fold (select X, Y, 0) -> (and X, Y)
5144   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5145     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5146 
5147   // If we can fold this based on the true/false value, do so.
5148   if (SimplifySelectOps(N, N1, N2))
5149     return SDValue(N, 0);  // Don't revisit N.
5150 
5151   if (VT0 == MVT::i1) {
5152     // The code in this block deals with the following 2 equivalences:
5153     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5154     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5155     // The target can specify its prefered form with the
5156     // shouldNormalizeToSelectSequence() callback. However we always transform
5157     // to the right anyway if we find the inner select exists in the DAG anyway
5158     // and we always transform to the left side if we know that we can further
5159     // optimize the combination of the conditions.
5160     bool normalizeToSequence
5161       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5162     // select (and Cond0, Cond1), X, Y
5163     //   -> select Cond0, (select Cond1, X, Y), Y
5164     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5165       SDValue Cond0 = N0->getOperand(0);
5166       SDValue Cond1 = N0->getOperand(1);
5167       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5168                                         N1.getValueType(), Cond1, N1, N2);
5169       if (normalizeToSequence || !InnerSelect.use_empty())
5170         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5171                            InnerSelect, N2);
5172     }
5173     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5174     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5175       SDValue Cond0 = N0->getOperand(0);
5176       SDValue Cond1 = N0->getOperand(1);
5177       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5178                                         N1.getValueType(), Cond1, N1, N2);
5179       if (normalizeToSequence || !InnerSelect.use_empty())
5180         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5181                            InnerSelect);
5182     }
5183 
5184     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5185     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5186       SDValue N1_0 = N1->getOperand(0);
5187       SDValue N1_1 = N1->getOperand(1);
5188       SDValue N1_2 = N1->getOperand(2);
5189       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5190         // Create the actual and node if we can generate good code for it.
5191         if (!normalizeToSequence) {
5192           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5193                                     N0, N1_0);
5194           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5195                              N1_1, N2);
5196         }
5197         // Otherwise see if we can optimize the "and" to a better pattern.
5198         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5199           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5200                              N1_1, N2);
5201       }
5202     }
5203     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5204     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5205       SDValue N2_0 = N2->getOperand(0);
5206       SDValue N2_1 = N2->getOperand(1);
5207       SDValue N2_2 = N2->getOperand(2);
5208       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5209         // Create the actual or node if we can generate good code for it.
5210         if (!normalizeToSequence) {
5211           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5212                                    N0, N2_0);
5213           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5214                              N1, N2_2);
5215         }
5216         // Otherwise see if we can optimize to a better pattern.
5217         if (SDValue Combined = visitORLike(N0, N2_0, N))
5218           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5219                              N1, N2_2);
5220       }
5221     }
5222   }
5223 
5224   // fold selects based on a setcc into other things, such as min/max/abs
5225   if (N0.getOpcode() == ISD::SETCC) {
5226     // select x, y (fcmp lt x, y) -> fminnum x, y
5227     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5228     //
5229     // This is OK if we don't care about what happens if either operand is a
5230     // NaN.
5231     //
5232 
5233     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5234     // no signed zeros as well as no nans.
5235     const TargetOptions &Options = DAG.getTarget().Options;
5236     if (Options.UnsafeFPMath &&
5237         VT.isFloatingPoint() && N0.hasOneUse() &&
5238         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5239       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5240 
5241       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5242                                                 N0.getOperand(1), N1, N2, CC,
5243                                                 TLI, DAG))
5244         return FMinMax;
5245     }
5246 
5247     if ((!LegalOperations &&
5248          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5249         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5250       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5251                          N0.getOperand(0), N0.getOperand(1),
5252                          N1, N2, N0.getOperand(2));
5253     return SimplifySelect(SDLoc(N), N0, N1, N2);
5254   }
5255 
5256   return SDValue();
5257 }
5258 
5259 static
5260 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5261   SDLoc DL(N);
5262   EVT LoVT, HiVT;
5263   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5264 
5265   // Split the inputs.
5266   SDValue Lo, Hi, LL, LH, RL, RH;
5267   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5268   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5269 
5270   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5271   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5272 
5273   return std::make_pair(Lo, Hi);
5274 }
5275 
5276 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5277 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5278 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5279   SDLoc dl(N);
5280   SDValue Cond = N->getOperand(0);
5281   SDValue LHS = N->getOperand(1);
5282   SDValue RHS = N->getOperand(2);
5283   EVT VT = N->getValueType(0);
5284   int NumElems = VT.getVectorNumElements();
5285   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5286          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5287          Cond.getOpcode() == ISD::BUILD_VECTOR);
5288 
5289   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5290   // binary ones here.
5291   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5292     return SDValue();
5293 
5294   // We're sure we have an even number of elements due to the
5295   // concat_vectors we have as arguments to vselect.
5296   // Skip BV elements until we find one that's not an UNDEF
5297   // After we find an UNDEF element, keep looping until we get to half the
5298   // length of the BV and see if all the non-undef nodes are the same.
5299   ConstantSDNode *BottomHalf = nullptr;
5300   for (int i = 0; i < NumElems / 2; ++i) {
5301     if (Cond->getOperand(i)->isUndef())
5302       continue;
5303 
5304     if (BottomHalf == nullptr)
5305       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5306     else if (Cond->getOperand(i).getNode() != BottomHalf)
5307       return SDValue();
5308   }
5309 
5310   // Do the same for the second half of the BuildVector
5311   ConstantSDNode *TopHalf = nullptr;
5312   for (int i = NumElems / 2; i < NumElems; ++i) {
5313     if (Cond->getOperand(i)->isUndef())
5314       continue;
5315 
5316     if (TopHalf == nullptr)
5317       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5318     else if (Cond->getOperand(i).getNode() != TopHalf)
5319       return SDValue();
5320   }
5321 
5322   assert(TopHalf && BottomHalf &&
5323          "One half of the selector was all UNDEFs and the other was all the "
5324          "same value. This should have been addressed before this function.");
5325   return DAG.getNode(
5326       ISD::CONCAT_VECTORS, dl, VT,
5327       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5328       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5329 }
5330 
5331 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5332 
5333   if (Level >= AfterLegalizeTypes)
5334     return SDValue();
5335 
5336   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5337   SDValue Mask = MSC->getMask();
5338   SDValue Data  = MSC->getValue();
5339   SDLoc DL(N);
5340 
5341   // If the MSCATTER data type requires splitting and the mask is provided by a
5342   // SETCC, then split both nodes and its operands before legalization. This
5343   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5344   // and enables future optimizations (e.g. min/max pattern matching on X86).
5345   if (Mask.getOpcode() != ISD::SETCC)
5346     return SDValue();
5347 
5348   // Check if any splitting is required.
5349   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5350       TargetLowering::TypeSplitVector)
5351     return SDValue();
5352   SDValue MaskLo, MaskHi, Lo, Hi;
5353   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5354 
5355   EVT LoVT, HiVT;
5356   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5357 
5358   SDValue Chain = MSC->getChain();
5359 
5360   EVT MemoryVT = MSC->getMemoryVT();
5361   unsigned Alignment = MSC->getOriginalAlignment();
5362 
5363   EVT LoMemVT, HiMemVT;
5364   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5365 
5366   SDValue DataLo, DataHi;
5367   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5368 
5369   SDValue BasePtr = MSC->getBasePtr();
5370   SDValue IndexLo, IndexHi;
5371   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5372 
5373   MachineMemOperand *MMO = DAG.getMachineFunction().
5374     getMachineMemOperand(MSC->getPointerInfo(),
5375                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5376                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5377 
5378   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5379   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5380                             DL, OpsLo, MMO);
5381 
5382   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5383   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5384                             DL, OpsHi, MMO);
5385 
5386   AddToWorklist(Lo.getNode());
5387   AddToWorklist(Hi.getNode());
5388 
5389   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5390 }
5391 
5392 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5393 
5394   if (Level >= AfterLegalizeTypes)
5395     return SDValue();
5396 
5397   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5398   SDValue Mask = MST->getMask();
5399   SDValue Data  = MST->getValue();
5400   SDLoc DL(N);
5401 
5402   // If the MSTORE data type requires splitting and the mask is provided by a
5403   // SETCC, then split both nodes and its operands before legalization. This
5404   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5405   // and enables future optimizations (e.g. min/max pattern matching on X86).
5406   if (Mask.getOpcode() == ISD::SETCC) {
5407 
5408     // Check if any splitting is required.
5409     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5410         TargetLowering::TypeSplitVector)
5411       return SDValue();
5412 
5413     SDValue MaskLo, MaskHi, Lo, Hi;
5414     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5415 
5416     EVT LoVT, HiVT;
5417     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5418 
5419     SDValue Chain = MST->getChain();
5420     SDValue Ptr   = MST->getBasePtr();
5421 
5422     EVT MemoryVT = MST->getMemoryVT();
5423     unsigned Alignment = MST->getOriginalAlignment();
5424 
5425     // if Alignment is equal to the vector size,
5426     // take the half of it for the second part
5427     unsigned SecondHalfAlignment =
5428       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5429          Alignment/2 : Alignment;
5430 
5431     EVT LoMemVT, HiMemVT;
5432     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5433 
5434     SDValue DataLo, DataHi;
5435     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5436 
5437     MachineMemOperand *MMO = DAG.getMachineFunction().
5438       getMachineMemOperand(MST->getPointerInfo(),
5439                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5440                            Alignment, MST->getAAInfo(), MST->getRanges());
5441 
5442     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5443                             MST->isTruncatingStore());
5444 
5445     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5446     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5447                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5448 
5449     MMO = DAG.getMachineFunction().
5450       getMachineMemOperand(MST->getPointerInfo(),
5451                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5452                            SecondHalfAlignment, MST->getAAInfo(),
5453                            MST->getRanges());
5454 
5455     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5456                             MST->isTruncatingStore());
5457 
5458     AddToWorklist(Lo.getNode());
5459     AddToWorklist(Hi.getNode());
5460 
5461     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5462   }
5463   return SDValue();
5464 }
5465 
5466 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5467 
5468   if (Level >= AfterLegalizeTypes)
5469     return SDValue();
5470 
5471   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5472   SDValue Mask = MGT->getMask();
5473   SDLoc DL(N);
5474 
5475   // If the MGATHER result requires splitting and the mask is provided by a
5476   // SETCC, then split both nodes and its operands before legalization. This
5477   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5478   // and enables future optimizations (e.g. min/max pattern matching on X86).
5479 
5480   if (Mask.getOpcode() != ISD::SETCC)
5481     return SDValue();
5482 
5483   EVT VT = N->getValueType(0);
5484 
5485   // Check if any splitting is required.
5486   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5487       TargetLowering::TypeSplitVector)
5488     return SDValue();
5489 
5490   SDValue MaskLo, MaskHi, Lo, Hi;
5491   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5492 
5493   SDValue Src0 = MGT->getValue();
5494   SDValue Src0Lo, Src0Hi;
5495   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5496 
5497   EVT LoVT, HiVT;
5498   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5499 
5500   SDValue Chain = MGT->getChain();
5501   EVT MemoryVT = MGT->getMemoryVT();
5502   unsigned Alignment = MGT->getOriginalAlignment();
5503 
5504   EVT LoMemVT, HiMemVT;
5505   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5506 
5507   SDValue BasePtr = MGT->getBasePtr();
5508   SDValue Index = MGT->getIndex();
5509   SDValue IndexLo, IndexHi;
5510   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5511 
5512   MachineMemOperand *MMO = DAG.getMachineFunction().
5513     getMachineMemOperand(MGT->getPointerInfo(),
5514                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5515                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5516 
5517   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5518   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5519                             MMO);
5520 
5521   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5522   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5523                             MMO);
5524 
5525   AddToWorklist(Lo.getNode());
5526   AddToWorklist(Hi.getNode());
5527 
5528   // Build a factor node to remember that this load is independent of the
5529   // other one.
5530   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5531                       Hi.getValue(1));
5532 
5533   // Legalized the chain result - switch anything that used the old chain to
5534   // use the new one.
5535   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5536 
5537   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5538 
5539   SDValue RetOps[] = { GatherRes, Chain };
5540   return DAG.getMergeValues(RetOps, DL);
5541 }
5542 
5543 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5544 
5545   if (Level >= AfterLegalizeTypes)
5546     return SDValue();
5547 
5548   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5549   SDValue Mask = MLD->getMask();
5550   SDLoc DL(N);
5551 
5552   // If the MLOAD result requires splitting and the mask is provided by a
5553   // SETCC, then split both nodes and its operands before legalization. This
5554   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5555   // and enables future optimizations (e.g. min/max pattern matching on X86).
5556 
5557   if (Mask.getOpcode() == ISD::SETCC) {
5558     EVT VT = N->getValueType(0);
5559 
5560     // Check if any splitting is required.
5561     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5562         TargetLowering::TypeSplitVector)
5563       return SDValue();
5564 
5565     SDValue MaskLo, MaskHi, Lo, Hi;
5566     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5567 
5568     SDValue Src0 = MLD->getSrc0();
5569     SDValue Src0Lo, Src0Hi;
5570     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5571 
5572     EVT LoVT, HiVT;
5573     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5574 
5575     SDValue Chain = MLD->getChain();
5576     SDValue Ptr   = MLD->getBasePtr();
5577     EVT MemoryVT = MLD->getMemoryVT();
5578     unsigned Alignment = MLD->getOriginalAlignment();
5579 
5580     // if Alignment is equal to the vector size,
5581     // take the half of it for the second part
5582     unsigned SecondHalfAlignment =
5583       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5584          Alignment/2 : Alignment;
5585 
5586     EVT LoMemVT, HiMemVT;
5587     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5588 
5589     MachineMemOperand *MMO = DAG.getMachineFunction().
5590     getMachineMemOperand(MLD->getPointerInfo(),
5591                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5592                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5593 
5594     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5595                            ISD::NON_EXTLOAD);
5596 
5597     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5598     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5599                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5600 
5601     MMO = DAG.getMachineFunction().
5602     getMachineMemOperand(MLD->getPointerInfo(),
5603                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5604                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5605 
5606     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5607                            ISD::NON_EXTLOAD);
5608 
5609     AddToWorklist(Lo.getNode());
5610     AddToWorklist(Hi.getNode());
5611 
5612     // Build a factor node to remember that this load is independent of the
5613     // other one.
5614     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5615                         Hi.getValue(1));
5616 
5617     // Legalized the chain result - switch anything that used the old chain to
5618     // use the new one.
5619     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5620 
5621     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5622 
5623     SDValue RetOps[] = { LoadRes, Chain };
5624     return DAG.getMergeValues(RetOps, DL);
5625   }
5626   return SDValue();
5627 }
5628 
5629 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5630   SDValue N0 = N->getOperand(0);
5631   SDValue N1 = N->getOperand(1);
5632   SDValue N2 = N->getOperand(2);
5633   SDLoc DL(N);
5634 
5635   // Canonicalize integer abs.
5636   // vselect (setg[te] X,  0),  X, -X ->
5637   // vselect (setgt    X, -1),  X, -X ->
5638   // vselect (setl[te] X,  0), -X,  X ->
5639   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5640   if (N0.getOpcode() == ISD::SETCC) {
5641     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5642     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5643     bool isAbs = false;
5644     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5645 
5646     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5647          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5648         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5649       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5650     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5651              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5652       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5653 
5654     if (isAbs) {
5655       EVT VT = LHS.getValueType();
5656       SDValue Shift = DAG.getNode(
5657           ISD::SRA, DL, VT, LHS,
5658           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5659       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5660       AddToWorklist(Shift.getNode());
5661       AddToWorklist(Add.getNode());
5662       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5663     }
5664   }
5665 
5666   if (SimplifySelectOps(N, N1, N2))
5667     return SDValue(N, 0);  // Don't revisit N.
5668 
5669   // If the VSELECT result requires splitting and the mask is provided by a
5670   // SETCC, then split both nodes and its operands before legalization. This
5671   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5672   // and enables future optimizations (e.g. min/max pattern matching on X86).
5673   if (N0.getOpcode() == ISD::SETCC) {
5674     EVT VT = N->getValueType(0);
5675 
5676     // Check if any splitting is required.
5677     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5678         TargetLowering::TypeSplitVector)
5679       return SDValue();
5680 
5681     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5682     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5683     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5684     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5685 
5686     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5687     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5688 
5689     // Add the new VSELECT nodes to the work list in case they need to be split
5690     // again.
5691     AddToWorklist(Lo.getNode());
5692     AddToWorklist(Hi.getNode());
5693 
5694     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5695   }
5696 
5697   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5698   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5699     return N1;
5700   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5701   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5702     return N2;
5703 
5704   // The ConvertSelectToConcatVector function is assuming both the above
5705   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5706   // and addressed.
5707   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5708       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5709       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5710     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5711       return CV;
5712   }
5713 
5714   return SDValue();
5715 }
5716 
5717 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5718   SDValue N0 = N->getOperand(0);
5719   SDValue N1 = N->getOperand(1);
5720   SDValue N2 = N->getOperand(2);
5721   SDValue N3 = N->getOperand(3);
5722   SDValue N4 = N->getOperand(4);
5723   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5724 
5725   // fold select_cc lhs, rhs, x, x, cc -> x
5726   if (N2 == N3)
5727     return N2;
5728 
5729   // Determine if the condition we're dealing with is constant
5730   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5731                                   CC, SDLoc(N), false)) {
5732     AddToWorklist(SCC.getNode());
5733 
5734     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5735       if (!SCCC->isNullValue())
5736         return N2;    // cond always true -> true val
5737       else
5738         return N3;    // cond always false -> false val
5739     } else if (SCC->isUndef()) {
5740       // When the condition is UNDEF, just return the first operand. This is
5741       // coherent the DAG creation, no setcc node is created in this case
5742       return N2;
5743     } else if (SCC.getOpcode() == ISD::SETCC) {
5744       // Fold to a simpler select_cc
5745       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5746                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5747                          SCC.getOperand(2));
5748     }
5749   }
5750 
5751   // If we can fold this based on the true/false value, do so.
5752   if (SimplifySelectOps(N, N2, N3))
5753     return SDValue(N, 0);  // Don't revisit N.
5754 
5755   // fold select_cc into other things, such as min/max/abs
5756   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5757 }
5758 
5759 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5760   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5761                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5762                        SDLoc(N));
5763 }
5764 
5765 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5766   SDValue LHS = N->getOperand(0);
5767   SDValue RHS = N->getOperand(1);
5768   SDValue Carry = N->getOperand(2);
5769   SDValue Cond = N->getOperand(3);
5770 
5771   // If Carry is false, fold to a regular SETCC.
5772   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5773     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5774 
5775   return SDValue();
5776 }
5777 
5778 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5779 /// a build_vector of constants.
5780 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5781 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5782 /// Vector extends are not folded if operations are legal; this is to
5783 /// avoid introducing illegal build_vector dag nodes.
5784 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5785                                          SelectionDAG &DAG, bool LegalTypes,
5786                                          bool LegalOperations) {
5787   unsigned Opcode = N->getOpcode();
5788   SDValue N0 = N->getOperand(0);
5789   EVT VT = N->getValueType(0);
5790 
5791   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5792          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5793          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5794          && "Expected EXTEND dag node in input!");
5795 
5796   // fold (sext c1) -> c1
5797   // fold (zext c1) -> c1
5798   // fold (aext c1) -> c1
5799   if (isa<ConstantSDNode>(N0))
5800     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5801 
5802   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5803   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5804   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5805   EVT SVT = VT.getScalarType();
5806   if (!(VT.isVector() &&
5807       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5808       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5809     return nullptr;
5810 
5811   // We can fold this node into a build_vector.
5812   unsigned VTBits = SVT.getSizeInBits();
5813   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5814   SmallVector<SDValue, 8> Elts;
5815   unsigned NumElts = VT.getVectorNumElements();
5816   SDLoc DL(N);
5817 
5818   for (unsigned i=0; i != NumElts; ++i) {
5819     SDValue Op = N0->getOperand(i);
5820     if (Op->isUndef()) {
5821       Elts.push_back(DAG.getUNDEF(SVT));
5822       continue;
5823     }
5824 
5825     SDLoc DL(Op);
5826     // Get the constant value and if needed trunc it to the size of the type.
5827     // Nodes like build_vector might have constants wider than the scalar type.
5828     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5829     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5830       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5831     else
5832       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5833   }
5834 
5835   return DAG.getBuildVector(VT, DL, Elts).getNode();
5836 }
5837 
5838 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5839 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5840 // transformation. Returns true if extension are possible and the above
5841 // mentioned transformation is profitable.
5842 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5843                                     unsigned ExtOpc,
5844                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5845                                     const TargetLowering &TLI) {
5846   bool HasCopyToRegUses = false;
5847   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5848   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5849                             UE = N0.getNode()->use_end();
5850        UI != UE; ++UI) {
5851     SDNode *User = *UI;
5852     if (User == N)
5853       continue;
5854     if (UI.getUse().getResNo() != N0.getResNo())
5855       continue;
5856     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5857     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5858       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5859       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5860         // Sign bits will be lost after a zext.
5861         return false;
5862       bool Add = false;
5863       for (unsigned i = 0; i != 2; ++i) {
5864         SDValue UseOp = User->getOperand(i);
5865         if (UseOp == N0)
5866           continue;
5867         if (!isa<ConstantSDNode>(UseOp))
5868           return false;
5869         Add = true;
5870       }
5871       if (Add)
5872         ExtendNodes.push_back(User);
5873       continue;
5874     }
5875     // If truncates aren't free and there are users we can't
5876     // extend, it isn't worthwhile.
5877     if (!isTruncFree)
5878       return false;
5879     // Remember if this value is live-out.
5880     if (User->getOpcode() == ISD::CopyToReg)
5881       HasCopyToRegUses = true;
5882   }
5883 
5884   if (HasCopyToRegUses) {
5885     bool BothLiveOut = false;
5886     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5887          UI != UE; ++UI) {
5888       SDUse &Use = UI.getUse();
5889       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5890         BothLiveOut = true;
5891         break;
5892       }
5893     }
5894     if (BothLiveOut)
5895       // Both unextended and extended values are live out. There had better be
5896       // a good reason for the transformation.
5897       return ExtendNodes.size();
5898   }
5899   return true;
5900 }
5901 
5902 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5903                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5904                                   ISD::NodeType ExtType) {
5905   // Extend SetCC uses if necessary.
5906   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5907     SDNode *SetCC = SetCCs[i];
5908     SmallVector<SDValue, 4> Ops;
5909 
5910     for (unsigned j = 0; j != 2; ++j) {
5911       SDValue SOp = SetCC->getOperand(j);
5912       if (SOp == Trunc)
5913         Ops.push_back(ExtLoad);
5914       else
5915         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5916     }
5917 
5918     Ops.push_back(SetCC->getOperand(2));
5919     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5920   }
5921 }
5922 
5923 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5924 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5925   SDValue N0 = N->getOperand(0);
5926   EVT DstVT = N->getValueType(0);
5927   EVT SrcVT = N0.getValueType();
5928 
5929   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5930           N->getOpcode() == ISD::ZERO_EXTEND) &&
5931          "Unexpected node type (not an extend)!");
5932 
5933   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5934   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5935   //   (v8i32 (sext (v8i16 (load x))))
5936   // into:
5937   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5938   //                          (v4i32 (sextload (x + 16)))))
5939   // Where uses of the original load, i.e.:
5940   //   (v8i16 (load x))
5941   // are replaced with:
5942   //   (v8i16 (truncate
5943   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5944   //                            (v4i32 (sextload (x + 16)))))))
5945   //
5946   // This combine is only applicable to illegal, but splittable, vectors.
5947   // All legal types, and illegal non-vector types, are handled elsewhere.
5948   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5949   //
5950   if (N0->getOpcode() != ISD::LOAD)
5951     return SDValue();
5952 
5953   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5954 
5955   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5956       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5957       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5958     return SDValue();
5959 
5960   SmallVector<SDNode *, 4> SetCCs;
5961   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5962     return SDValue();
5963 
5964   ISD::LoadExtType ExtType =
5965       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5966 
5967   // Try to split the vector types to get down to legal types.
5968   EVT SplitSrcVT = SrcVT;
5969   EVT SplitDstVT = DstVT;
5970   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5971          SplitSrcVT.getVectorNumElements() > 1) {
5972     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5973     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5974   }
5975 
5976   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5977     return SDValue();
5978 
5979   SDLoc DL(N);
5980   const unsigned NumSplits =
5981       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5982   const unsigned Stride = SplitSrcVT.getStoreSize();
5983   SmallVector<SDValue, 4> Loads;
5984   SmallVector<SDValue, 4> Chains;
5985 
5986   SDValue BasePtr = LN0->getBasePtr();
5987   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5988     const unsigned Offset = Idx * Stride;
5989     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5990 
5991     SDValue SplitLoad = DAG.getExtLoad(
5992         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5993         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5994         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5995         Align, LN0->getAAInfo());
5996 
5997     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5998                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5999 
6000     Loads.push_back(SplitLoad.getValue(0));
6001     Chains.push_back(SplitLoad.getValue(1));
6002   }
6003 
6004   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6005   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6006 
6007   CombineTo(N, NewValue);
6008 
6009   // Replace uses of the original load (before extension)
6010   // with a truncate of the concatenated sextloaded vectors.
6011   SDValue Trunc =
6012       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6013   CombineTo(N0.getNode(), Trunc, NewChain);
6014   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6015                   (ISD::NodeType)N->getOpcode());
6016   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6017 }
6018 
6019 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6020   SDValue N0 = N->getOperand(0);
6021   EVT VT = N->getValueType(0);
6022 
6023   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6024                                               LegalOperations))
6025     return SDValue(Res, 0);
6026 
6027   // fold (sext (sext x)) -> (sext x)
6028   // fold (sext (aext x)) -> (sext x)
6029   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6030     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6031                        N0.getOperand(0));
6032 
6033   if (N0.getOpcode() == ISD::TRUNCATE) {
6034     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6035     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6036     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6037       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6038       if (NarrowLoad.getNode() != N0.getNode()) {
6039         CombineTo(N0.getNode(), NarrowLoad);
6040         // CombineTo deleted the truncate, if needed, but not what's under it.
6041         AddToWorklist(oye);
6042       }
6043       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6044     }
6045 
6046     // See if the value being truncated is already sign extended.  If so, just
6047     // eliminate the trunc/sext pair.
6048     SDValue Op = N0.getOperand(0);
6049     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
6050     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
6051     unsigned DestBits = VT.getScalarType().getSizeInBits();
6052     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6053 
6054     if (OpBits == DestBits) {
6055       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6056       // bits, it is already ready.
6057       if (NumSignBits > DestBits-MidBits)
6058         return Op;
6059     } else if (OpBits < DestBits) {
6060       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6061       // bits, just sext from i32.
6062       if (NumSignBits > OpBits-MidBits)
6063         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6064     } else {
6065       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6066       // bits, just truncate to i32.
6067       if (NumSignBits > OpBits-MidBits)
6068         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6069     }
6070 
6071     // fold (sext (truncate x)) -> (sextinreg x).
6072     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6073                                                  N0.getValueType())) {
6074       if (OpBits < DestBits)
6075         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6076       else if (OpBits > DestBits)
6077         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6078       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6079                          DAG.getValueType(N0.getValueType()));
6080     }
6081   }
6082 
6083   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6084   // Only generate vector extloads when 1) they're legal, and 2) they are
6085   // deemed desirable by the target.
6086   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6087       ((!LegalOperations && !VT.isVector() &&
6088         !cast<LoadSDNode>(N0)->isVolatile()) ||
6089        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6090     bool DoXform = true;
6091     SmallVector<SDNode*, 4> SetCCs;
6092     if (!N0.hasOneUse())
6093       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6094     if (VT.isVector())
6095       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6096     if (DoXform) {
6097       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6098       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6099                                        LN0->getChain(),
6100                                        LN0->getBasePtr(), N0.getValueType(),
6101                                        LN0->getMemOperand());
6102       CombineTo(N, ExtLoad);
6103       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6104                                   N0.getValueType(), ExtLoad);
6105       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6106       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6107                       ISD::SIGN_EXTEND);
6108       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6109     }
6110   }
6111 
6112   // fold (sext (load x)) to multiple smaller sextloads.
6113   // Only on illegal but splittable vectors.
6114   if (SDValue ExtLoad = CombineExtLoad(N))
6115     return ExtLoad;
6116 
6117   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6118   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6119   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6120       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6121     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6122     EVT MemVT = LN0->getMemoryVT();
6123     if ((!LegalOperations && !LN0->isVolatile()) ||
6124         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6125       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6126                                        LN0->getChain(),
6127                                        LN0->getBasePtr(), MemVT,
6128                                        LN0->getMemOperand());
6129       CombineTo(N, ExtLoad);
6130       CombineTo(N0.getNode(),
6131                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6132                             N0.getValueType(), ExtLoad),
6133                 ExtLoad.getValue(1));
6134       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6135     }
6136   }
6137 
6138   // fold (sext (and/or/xor (load x), cst)) ->
6139   //      (and/or/xor (sextload x), (sext cst))
6140   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6141        N0.getOpcode() == ISD::XOR) &&
6142       isa<LoadSDNode>(N0.getOperand(0)) &&
6143       N0.getOperand(1).getOpcode() == ISD::Constant &&
6144       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6145       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6146     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6147     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6148       bool DoXform = true;
6149       SmallVector<SDNode*, 4> SetCCs;
6150       if (!N0.hasOneUse())
6151         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6152                                           SetCCs, TLI);
6153       if (DoXform) {
6154         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6155                                          LN0->getChain(), LN0->getBasePtr(),
6156                                          LN0->getMemoryVT(),
6157                                          LN0->getMemOperand());
6158         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6159         Mask = Mask.sext(VT.getSizeInBits());
6160         SDLoc DL(N);
6161         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6162                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6163         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6164                                     SDLoc(N0.getOperand(0)),
6165                                     N0.getOperand(0).getValueType(), ExtLoad);
6166         CombineTo(N, And);
6167         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6168         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6169                         ISD::SIGN_EXTEND);
6170         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6171       }
6172     }
6173   }
6174 
6175   if (N0.getOpcode() == ISD::SETCC) {
6176     EVT N0VT = N0.getOperand(0).getValueType();
6177     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6178     // Only do this before legalize for now.
6179     if (VT.isVector() && !LegalOperations &&
6180         TLI.getBooleanContents(N0VT) ==
6181             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6182       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6183       // of the same size as the compared operands. Only optimize sext(setcc())
6184       // if this is the case.
6185       EVT SVT = getSetCCResultType(N0VT);
6186 
6187       // We know that the # elements of the results is the same as the
6188       // # elements of the compare (and the # elements of the compare result
6189       // for that matter).  Check to see that they are the same size.  If so,
6190       // we know that the element size of the sext'd result matches the
6191       // element size of the compare operands.
6192       if (VT.getSizeInBits() == SVT.getSizeInBits())
6193         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6194                              N0.getOperand(1),
6195                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6196 
6197       // If the desired elements are smaller or larger than the source
6198       // elements we can use a matching integer vector type and then
6199       // truncate/sign extend
6200       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6201       if (SVT == MatchingVectorType) {
6202         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6203                                N0.getOperand(0), N0.getOperand(1),
6204                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6205         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6206       }
6207     }
6208 
6209     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6210     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6211     SDLoc DL(N);
6212     SDValue NegOne =
6213       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6214     if (SDValue SCC = SimplifySelectCC(
6215             DL, N0.getOperand(0), N0.getOperand(1), NegOne,
6216             DAG.getConstant(0, DL, VT),
6217             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6218       return SCC;
6219 
6220     if (!VT.isVector()) {
6221       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6222       if (!LegalOperations ||
6223           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6224         SDLoc DL(N);
6225         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6226         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6227                                      N0.getOperand(0), N0.getOperand(1), CC);
6228         return DAG.getSelect(DL, VT, SetCC,
6229                              NegOne, DAG.getConstant(0, DL, VT));
6230       }
6231     }
6232   }
6233 
6234   // fold (sext x) -> (zext x) if the sign bit is known zero.
6235   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6236       DAG.SignBitIsZero(N0))
6237     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6238 
6239   return SDValue();
6240 }
6241 
6242 // isTruncateOf - If N is a truncate of some other value, return true, record
6243 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6244 // This function computes KnownZero to avoid a duplicated call to
6245 // computeKnownBits in the caller.
6246 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6247                          APInt &KnownZero) {
6248   APInt KnownOne;
6249   if (N->getOpcode() == ISD::TRUNCATE) {
6250     Op = N->getOperand(0);
6251     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6252     return true;
6253   }
6254 
6255   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6256       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6257     return false;
6258 
6259   SDValue Op0 = N->getOperand(0);
6260   SDValue Op1 = N->getOperand(1);
6261   assert(Op0.getValueType() == Op1.getValueType());
6262 
6263   if (isNullConstant(Op0))
6264     Op = Op1;
6265   else if (isNullConstant(Op1))
6266     Op = Op0;
6267   else
6268     return false;
6269 
6270   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6271 
6272   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6273     return false;
6274 
6275   return true;
6276 }
6277 
6278 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6279   SDValue N0 = N->getOperand(0);
6280   EVT VT = N->getValueType(0);
6281 
6282   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6283                                               LegalOperations))
6284     return SDValue(Res, 0);
6285 
6286   // fold (zext (zext x)) -> (zext x)
6287   // fold (zext (aext x)) -> (zext x)
6288   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6289     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6290                        N0.getOperand(0));
6291 
6292   // fold (zext (truncate x)) -> (zext x) or
6293   //      (zext (truncate x)) -> (truncate x)
6294   // This is valid when the truncated bits of x are already zero.
6295   // FIXME: We should extend this to work for vectors too.
6296   SDValue Op;
6297   APInt KnownZero;
6298   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6299     APInt TruncatedBits =
6300       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6301       APInt(Op.getValueSizeInBits(), 0) :
6302       APInt::getBitsSet(Op.getValueSizeInBits(),
6303                         N0.getValueSizeInBits(),
6304                         std::min(Op.getValueSizeInBits(),
6305                                  VT.getSizeInBits()));
6306     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6307       if (VT.bitsGT(Op.getValueType()))
6308         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6309       if (VT.bitsLT(Op.getValueType()))
6310         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6311 
6312       return Op;
6313     }
6314   }
6315 
6316   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6317   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6318   if (N0.getOpcode() == ISD::TRUNCATE) {
6319     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6320       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6321       if (NarrowLoad.getNode() != N0.getNode()) {
6322         CombineTo(N0.getNode(), NarrowLoad);
6323         // CombineTo deleted the truncate, if needed, but not what's under it.
6324         AddToWorklist(oye);
6325       }
6326       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6327     }
6328   }
6329 
6330   // fold (zext (truncate x)) -> (and x, mask)
6331   if (N0.getOpcode() == ISD::TRUNCATE) {
6332     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6333     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6334     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6335       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6336       if (NarrowLoad.getNode() != N0.getNode()) {
6337         CombineTo(N0.getNode(), NarrowLoad);
6338         // CombineTo deleted the truncate, if needed, but not what's under it.
6339         AddToWorklist(oye);
6340       }
6341       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6342     }
6343 
6344     EVT SrcVT = N0.getOperand(0).getValueType();
6345     EVT MinVT = N0.getValueType();
6346 
6347     // Try to mask before the extension to avoid having to generate a larger mask,
6348     // possibly over several sub-vectors.
6349     if (SrcVT.bitsLT(VT)) {
6350       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6351                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6352         SDValue Op = N0.getOperand(0);
6353         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6354         AddToWorklist(Op.getNode());
6355         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6356       }
6357     }
6358 
6359     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6360       SDValue Op = N0.getOperand(0);
6361       if (SrcVT.bitsLT(VT)) {
6362         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6363         AddToWorklist(Op.getNode());
6364       } else if (SrcVT.bitsGT(VT)) {
6365         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6366         AddToWorklist(Op.getNode());
6367       }
6368       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6369     }
6370   }
6371 
6372   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6373   // if either of the casts is not free.
6374   if (N0.getOpcode() == ISD::AND &&
6375       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6376       N0.getOperand(1).getOpcode() == ISD::Constant &&
6377       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6378                            N0.getValueType()) ||
6379        !TLI.isZExtFree(N0.getValueType(), VT))) {
6380     SDValue X = N0.getOperand(0).getOperand(0);
6381     if (X.getValueType().bitsLT(VT)) {
6382       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6383     } else if (X.getValueType().bitsGT(VT)) {
6384       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6385     }
6386     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6387     Mask = Mask.zext(VT.getSizeInBits());
6388     SDLoc DL(N);
6389     return DAG.getNode(ISD::AND, DL, VT,
6390                        X, DAG.getConstant(Mask, DL, VT));
6391   }
6392 
6393   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6394   // Only generate vector extloads when 1) they're legal, and 2) they are
6395   // deemed desirable by the target.
6396   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6397       ((!LegalOperations && !VT.isVector() &&
6398         !cast<LoadSDNode>(N0)->isVolatile()) ||
6399        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6400     bool DoXform = true;
6401     SmallVector<SDNode*, 4> SetCCs;
6402     if (!N0.hasOneUse())
6403       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6404     if (VT.isVector())
6405       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6406     if (DoXform) {
6407       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6408       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6409                                        LN0->getChain(),
6410                                        LN0->getBasePtr(), N0.getValueType(),
6411                                        LN0->getMemOperand());
6412       CombineTo(N, ExtLoad);
6413       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6414                                   N0.getValueType(), ExtLoad);
6415       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6416 
6417       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6418                       ISD::ZERO_EXTEND);
6419       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6420     }
6421   }
6422 
6423   // fold (zext (load x)) to multiple smaller zextloads.
6424   // Only on illegal but splittable vectors.
6425   if (SDValue ExtLoad = CombineExtLoad(N))
6426     return ExtLoad;
6427 
6428   // fold (zext (and/or/xor (load x), cst)) ->
6429   //      (and/or/xor (zextload x), (zext cst))
6430   // Unless (and (load x) cst) will match as a zextload already and has
6431   // additional users.
6432   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6433        N0.getOpcode() == ISD::XOR) &&
6434       isa<LoadSDNode>(N0.getOperand(0)) &&
6435       N0.getOperand(1).getOpcode() == ISD::Constant &&
6436       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6437       (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) {
6438     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6439     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6440       bool DoXform = true;
6441       SmallVector<SDNode*, 4> SetCCs;
6442       if (!N0.hasOneUse()) {
6443         if (N0.getOpcode() == ISD::AND) {
6444           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6445           auto NarrowLoad = false;
6446           EVT LoadResultTy = AndC->getValueType(0);
6447           EVT ExtVT, LoadedVT;
6448           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6449                                NarrowLoad))
6450             DoXform = false;
6451         }
6452         if (DoXform)
6453           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6454                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6455       }
6456       if (DoXform) {
6457         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6458                                          LN0->getChain(), LN0->getBasePtr(),
6459                                          LN0->getMemoryVT(),
6460                                          LN0->getMemOperand());
6461         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6462         Mask = Mask.zext(VT.getSizeInBits());
6463         SDLoc DL(N);
6464         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6465                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6466         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6467                                     SDLoc(N0.getOperand(0)),
6468                                     N0.getOperand(0).getValueType(), ExtLoad);
6469         CombineTo(N, And);
6470         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6471         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6472                         ISD::ZERO_EXTEND);
6473         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6474       }
6475     }
6476   }
6477 
6478   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6479   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6480   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6481       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6482     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6483     EVT MemVT = LN0->getMemoryVT();
6484     if ((!LegalOperations && !LN0->isVolatile()) ||
6485         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6486       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6487                                        LN0->getChain(),
6488                                        LN0->getBasePtr(), MemVT,
6489                                        LN0->getMemOperand());
6490       CombineTo(N, ExtLoad);
6491       CombineTo(N0.getNode(),
6492                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6493                             ExtLoad),
6494                 ExtLoad.getValue(1));
6495       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6496     }
6497   }
6498 
6499   if (N0.getOpcode() == ISD::SETCC) {
6500     if (!LegalOperations && VT.isVector() &&
6501         N0.getValueType().getVectorElementType() == MVT::i1) {
6502       EVT N0VT = N0.getOperand(0).getValueType();
6503       if (getSetCCResultType(N0VT) == N0.getValueType())
6504         return SDValue();
6505 
6506       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6507       // Only do this before legalize for now.
6508       SDLoc DL(N);
6509       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6510       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6511         // We know that the # elements of the results is the same as the
6512         // # elements of the compare (and the # elements of the compare result
6513         // for that matter).  Check to see that they are the same size.  If so,
6514         // we know that the element size of the sext'd result matches the
6515         // element size of the compare operands.
6516         return DAG.getNode(ISD::AND, DL, VT,
6517                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6518                                          N0.getOperand(1),
6519                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6520                            VecOnes);
6521 
6522       // If the desired elements are smaller or larger than the source
6523       // elements we can use a matching integer vector type and then
6524       // truncate/sign extend
6525       EVT MatchingElementType =
6526         EVT::getIntegerVT(*DAG.getContext(),
6527                           N0VT.getScalarType().getSizeInBits());
6528       EVT MatchingVectorType =
6529         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6530                          N0VT.getVectorNumElements());
6531       SDValue VsetCC =
6532         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6533                       N0.getOperand(1),
6534                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6535       return DAG.getNode(ISD::AND, DL, VT,
6536                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6537                          VecOnes);
6538     }
6539 
6540     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6541     SDLoc DL(N);
6542     if (SDValue SCC = SimplifySelectCC(
6543             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6544             DAG.getConstant(0, DL, VT),
6545             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6546       return SCC;
6547   }
6548 
6549   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6550   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6551       isa<ConstantSDNode>(N0.getOperand(1)) &&
6552       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6553       N0.hasOneUse()) {
6554     SDValue ShAmt = N0.getOperand(1);
6555     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6556     if (N0.getOpcode() == ISD::SHL) {
6557       SDValue InnerZExt = N0.getOperand(0);
6558       // If the original shl may be shifting out bits, do not perform this
6559       // transformation.
6560       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6561         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6562       if (ShAmtVal > KnownZeroBits)
6563         return SDValue();
6564     }
6565 
6566     SDLoc DL(N);
6567 
6568     // Ensure that the shift amount is wide enough for the shifted value.
6569     if (VT.getSizeInBits() >= 256)
6570       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6571 
6572     return DAG.getNode(N0.getOpcode(), DL, VT,
6573                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6574                        ShAmt);
6575   }
6576 
6577   return SDValue();
6578 }
6579 
6580 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6581   SDValue N0 = N->getOperand(0);
6582   EVT VT = N->getValueType(0);
6583 
6584   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6585                                               LegalOperations))
6586     return SDValue(Res, 0);
6587 
6588   // fold (aext (aext x)) -> (aext x)
6589   // fold (aext (zext x)) -> (zext x)
6590   // fold (aext (sext x)) -> (sext x)
6591   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6592       N0.getOpcode() == ISD::ZERO_EXTEND ||
6593       N0.getOpcode() == ISD::SIGN_EXTEND)
6594     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6595 
6596   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6597   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6598   if (N0.getOpcode() == ISD::TRUNCATE) {
6599     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6600       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6601       if (NarrowLoad.getNode() != N0.getNode()) {
6602         CombineTo(N0.getNode(), NarrowLoad);
6603         // CombineTo deleted the truncate, if needed, but not what's under it.
6604         AddToWorklist(oye);
6605       }
6606       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6607     }
6608   }
6609 
6610   // fold (aext (truncate x))
6611   if (N0.getOpcode() == ISD::TRUNCATE) {
6612     SDValue TruncOp = N0.getOperand(0);
6613     if (TruncOp.getValueType() == VT)
6614       return TruncOp; // x iff x size == zext size.
6615     if (TruncOp.getValueType().bitsGT(VT))
6616       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6617     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6618   }
6619 
6620   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6621   // if the trunc is not free.
6622   if (N0.getOpcode() == ISD::AND &&
6623       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6624       N0.getOperand(1).getOpcode() == ISD::Constant &&
6625       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6626                           N0.getValueType())) {
6627     SDValue X = N0.getOperand(0).getOperand(0);
6628     if (X.getValueType().bitsLT(VT)) {
6629       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6630     } else if (X.getValueType().bitsGT(VT)) {
6631       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6632     }
6633     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6634     Mask = Mask.zext(VT.getSizeInBits());
6635     SDLoc DL(N);
6636     return DAG.getNode(ISD::AND, DL, VT,
6637                        X, DAG.getConstant(Mask, DL, VT));
6638   }
6639 
6640   // fold (aext (load x)) -> (aext (truncate (extload x)))
6641   // None of the supported targets knows how to perform load and any_ext
6642   // on vectors in one instruction.  We only perform this transformation on
6643   // scalars.
6644   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6645       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6646       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6647     bool DoXform = true;
6648     SmallVector<SDNode*, 4> SetCCs;
6649     if (!N0.hasOneUse())
6650       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6651     if (DoXform) {
6652       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6653       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6654                                        LN0->getChain(),
6655                                        LN0->getBasePtr(), N0.getValueType(),
6656                                        LN0->getMemOperand());
6657       CombineTo(N, ExtLoad);
6658       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6659                                   N0.getValueType(), ExtLoad);
6660       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6661       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6662                       ISD::ANY_EXTEND);
6663       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6664     }
6665   }
6666 
6667   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6668   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6669   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6670   if (N0.getOpcode() == ISD::LOAD &&
6671       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6672       N0.hasOneUse()) {
6673     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6674     ISD::LoadExtType ExtType = LN0->getExtensionType();
6675     EVT MemVT = LN0->getMemoryVT();
6676     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6677       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6678                                        VT, LN0->getChain(), LN0->getBasePtr(),
6679                                        MemVT, LN0->getMemOperand());
6680       CombineTo(N, ExtLoad);
6681       CombineTo(N0.getNode(),
6682                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6683                             N0.getValueType(), ExtLoad),
6684                 ExtLoad.getValue(1));
6685       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6686     }
6687   }
6688 
6689   if (N0.getOpcode() == ISD::SETCC) {
6690     // For vectors:
6691     // aext(setcc) -> vsetcc
6692     // aext(setcc) -> truncate(vsetcc)
6693     // aext(setcc) -> aext(vsetcc)
6694     // Only do this before legalize for now.
6695     if (VT.isVector() && !LegalOperations) {
6696       EVT N0VT = N0.getOperand(0).getValueType();
6697         // We know that the # elements of the results is the same as the
6698         // # elements of the compare (and the # elements of the compare result
6699         // for that matter).  Check to see that they are the same size.  If so,
6700         // we know that the element size of the sext'd result matches the
6701         // element size of the compare operands.
6702       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6703         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6704                              N0.getOperand(1),
6705                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6706       // If the desired elements are smaller or larger than the source
6707       // elements we can use a matching integer vector type and then
6708       // truncate/any extend
6709       else {
6710         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6711         SDValue VsetCC =
6712           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6713                         N0.getOperand(1),
6714                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6715         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6716       }
6717     }
6718 
6719     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6720     SDLoc DL(N);
6721     if (SDValue SCC = SimplifySelectCC(
6722             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6723             DAG.getConstant(0, DL, VT),
6724             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6725       return SCC;
6726   }
6727 
6728   return SDValue();
6729 }
6730 
6731 /// See if the specified operand can be simplified with the knowledge that only
6732 /// the bits specified by Mask are used.  If so, return the simpler operand,
6733 /// otherwise return a null SDValue.
6734 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6735   switch (V.getOpcode()) {
6736   default: break;
6737   case ISD::Constant: {
6738     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6739     assert(CV && "Const value should be ConstSDNode.");
6740     const APInt &CVal = CV->getAPIntValue();
6741     APInt NewVal = CVal & Mask;
6742     if (NewVal != CVal)
6743       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6744     break;
6745   }
6746   case ISD::OR:
6747   case ISD::XOR:
6748     // If the LHS or RHS don't contribute bits to the or, drop them.
6749     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6750       return V.getOperand(1);
6751     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6752       return V.getOperand(0);
6753     break;
6754   case ISD::SRL:
6755     // Only look at single-use SRLs.
6756     if (!V.getNode()->hasOneUse())
6757       break;
6758     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6759       // See if we can recursively simplify the LHS.
6760       unsigned Amt = RHSC->getZExtValue();
6761 
6762       // Watch out for shift count overflow though.
6763       if (Amt >= Mask.getBitWidth()) break;
6764       APInt NewMask = Mask << Amt;
6765       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6766         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6767                            SimplifyLHS, V.getOperand(1));
6768     }
6769   }
6770   return SDValue();
6771 }
6772 
6773 /// If the result of a wider load is shifted to right of N  bits and then
6774 /// truncated to a narrower type and where N is a multiple of number of bits of
6775 /// the narrower type, transform it to a narrower load from address + N / num of
6776 /// bits of new type. If the result is to be extended, also fold the extension
6777 /// to form a extending load.
6778 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6779   unsigned Opc = N->getOpcode();
6780 
6781   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6782   SDValue N0 = N->getOperand(0);
6783   EVT VT = N->getValueType(0);
6784   EVT ExtVT = VT;
6785 
6786   // This transformation isn't valid for vector loads.
6787   if (VT.isVector())
6788     return SDValue();
6789 
6790   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6791   // extended to VT.
6792   if (Opc == ISD::SIGN_EXTEND_INREG) {
6793     ExtType = ISD::SEXTLOAD;
6794     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6795   } else if (Opc == ISD::SRL) {
6796     // Another special-case: SRL is basically zero-extending a narrower value.
6797     ExtType = ISD::ZEXTLOAD;
6798     N0 = SDValue(N, 0);
6799     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6800     if (!N01) return SDValue();
6801     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6802                               VT.getSizeInBits() - N01->getZExtValue());
6803   }
6804   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6805     return SDValue();
6806 
6807   unsigned EVTBits = ExtVT.getSizeInBits();
6808 
6809   // Do not generate loads of non-round integer types since these can
6810   // be expensive (and would be wrong if the type is not byte sized).
6811   if (!ExtVT.isRound())
6812     return SDValue();
6813 
6814   unsigned ShAmt = 0;
6815   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6816     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6817       ShAmt = N01->getZExtValue();
6818       // Is the shift amount a multiple of size of VT?
6819       if ((ShAmt & (EVTBits-1)) == 0) {
6820         N0 = N0.getOperand(0);
6821         // Is the load width a multiple of size of VT?
6822         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6823           return SDValue();
6824       }
6825 
6826       // At this point, we must have a load or else we can't do the transform.
6827       if (!isa<LoadSDNode>(N0)) return SDValue();
6828 
6829       // Because a SRL must be assumed to *need* to zero-extend the high bits
6830       // (as opposed to anyext the high bits), we can't combine the zextload
6831       // lowering of SRL and an sextload.
6832       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6833         return SDValue();
6834 
6835       // If the shift amount is larger than the input type then we're not
6836       // accessing any of the loaded bytes.  If the load was a zextload/extload
6837       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6838       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6839         return SDValue();
6840     }
6841   }
6842 
6843   // If the load is shifted left (and the result isn't shifted back right),
6844   // we can fold the truncate through the shift.
6845   unsigned ShLeftAmt = 0;
6846   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6847       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6848     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6849       ShLeftAmt = N01->getZExtValue();
6850       N0 = N0.getOperand(0);
6851     }
6852   }
6853 
6854   // If we haven't found a load, we can't narrow it.  Don't transform one with
6855   // multiple uses, this would require adding a new load.
6856   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6857     return SDValue();
6858 
6859   // Don't change the width of a volatile load.
6860   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6861   if (LN0->isVolatile())
6862     return SDValue();
6863 
6864   // Verify that we are actually reducing a load width here.
6865   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6866     return SDValue();
6867 
6868   // For the transform to be legal, the load must produce only two values
6869   // (the value loaded and the chain).  Don't transform a pre-increment
6870   // load, for example, which produces an extra value.  Otherwise the
6871   // transformation is not equivalent, and the downstream logic to replace
6872   // uses gets things wrong.
6873   if (LN0->getNumValues() > 2)
6874     return SDValue();
6875 
6876   // If the load that we're shrinking is an extload and we're not just
6877   // discarding the extension we can't simply shrink the load. Bail.
6878   // TODO: It would be possible to merge the extensions in some cases.
6879   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6880       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6881     return SDValue();
6882 
6883   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6884     return SDValue();
6885 
6886   EVT PtrType = N0.getOperand(1).getValueType();
6887 
6888   if (PtrType == MVT::Untyped || PtrType.isExtended())
6889     // It's not possible to generate a constant of extended or untyped type.
6890     return SDValue();
6891 
6892   // For big endian targets, we need to adjust the offset to the pointer to
6893   // load the correct bytes.
6894   if (DAG.getDataLayout().isBigEndian()) {
6895     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6896     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6897     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6898   }
6899 
6900   uint64_t PtrOff = ShAmt / 8;
6901   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6902   SDLoc DL(LN0);
6903   // The original load itself didn't wrap, so an offset within it doesn't.
6904   SDNodeFlags Flags;
6905   Flags.setNoUnsignedWrap(true);
6906   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6907                                PtrType, LN0->getBasePtr(),
6908                                DAG.getConstant(PtrOff, DL, PtrType),
6909                                &Flags);
6910   AddToWorklist(NewPtr.getNode());
6911 
6912   SDValue Load;
6913   if (ExtType == ISD::NON_EXTLOAD)
6914     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6915                         LN0->getPointerInfo().getWithOffset(PtrOff),
6916                         LN0->isVolatile(), LN0->isNonTemporal(),
6917                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6918   else
6919     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6920                           LN0->getPointerInfo().getWithOffset(PtrOff),
6921                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6922                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6923 
6924   // Replace the old load's chain with the new load's chain.
6925   WorklistRemover DeadNodes(*this);
6926   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6927 
6928   // Shift the result left, if we've swallowed a left shift.
6929   SDValue Result = Load;
6930   if (ShLeftAmt != 0) {
6931     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6932     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6933       ShImmTy = VT;
6934     // If the shift amount is as large as the result size (but, presumably,
6935     // no larger than the source) then the useful bits of the result are
6936     // zero; we can't simply return the shortened shift, because the result
6937     // of that operation is undefined.
6938     SDLoc DL(N0);
6939     if (ShLeftAmt >= VT.getSizeInBits())
6940       Result = DAG.getConstant(0, DL, VT);
6941     else
6942       Result = DAG.getNode(ISD::SHL, DL, VT,
6943                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6944   }
6945 
6946   // Return the new loaded value.
6947   return Result;
6948 }
6949 
6950 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6951   SDValue N0 = N->getOperand(0);
6952   SDValue N1 = N->getOperand(1);
6953   EVT VT = N->getValueType(0);
6954   EVT EVT = cast<VTSDNode>(N1)->getVT();
6955   unsigned VTBits = VT.getScalarType().getSizeInBits();
6956   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6957 
6958   if (N0.isUndef())
6959     return DAG.getUNDEF(VT);
6960 
6961   // fold (sext_in_reg c1) -> c1
6962   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6963     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6964 
6965   // If the input is already sign extended, just drop the extension.
6966   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6967     return N0;
6968 
6969   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6970   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6971       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6972     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6973                        N0.getOperand(0), N1);
6974 
6975   // fold (sext_in_reg (sext x)) -> (sext x)
6976   // fold (sext_in_reg (aext x)) -> (sext x)
6977   // if x is small enough.
6978   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6979     SDValue N00 = N0.getOperand(0);
6980     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6981         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6982       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6983   }
6984 
6985   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6986   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6987     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6988 
6989   // fold operands of sext_in_reg based on knowledge that the top bits are not
6990   // demanded.
6991   if (SimplifyDemandedBits(SDValue(N, 0)))
6992     return SDValue(N, 0);
6993 
6994   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6995   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6996   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6997     return NarrowLoad;
6998 
6999   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7000   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7001   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7002   if (N0.getOpcode() == ISD::SRL) {
7003     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7004       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7005         // We can turn this into an SRA iff the input to the SRL is already sign
7006         // extended enough.
7007         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7008         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7009           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7010                              N0.getOperand(0), N0.getOperand(1));
7011       }
7012   }
7013 
7014   // fold (sext_inreg (extload x)) -> (sextload x)
7015   if (ISD::isEXTLoad(N0.getNode()) &&
7016       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7017       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7018       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7019        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7020     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7021     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7022                                      LN0->getChain(),
7023                                      LN0->getBasePtr(), EVT,
7024                                      LN0->getMemOperand());
7025     CombineTo(N, ExtLoad);
7026     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7027     AddToWorklist(ExtLoad.getNode());
7028     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7029   }
7030   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7031   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7032       N0.hasOneUse() &&
7033       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7034       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7035        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7036     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7037     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7038                                      LN0->getChain(),
7039                                      LN0->getBasePtr(), EVT,
7040                                      LN0->getMemOperand());
7041     CombineTo(N, ExtLoad);
7042     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7043     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7044   }
7045 
7046   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7047   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7048     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7049                                            N0.getOperand(1), false))
7050       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7051                          BSwap, N1);
7052   }
7053 
7054   return SDValue();
7055 }
7056 
7057 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7058   SDValue N0 = N->getOperand(0);
7059   EVT VT = N->getValueType(0);
7060 
7061   if (N0.isUndef())
7062     return DAG.getUNDEF(VT);
7063 
7064   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7065                                               LegalOperations))
7066     return SDValue(Res, 0);
7067 
7068   return SDValue();
7069 }
7070 
7071 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7072   SDValue N0 = N->getOperand(0);
7073   EVT VT = N->getValueType(0);
7074 
7075   if (N0.isUndef())
7076     return DAG.getUNDEF(VT);
7077 
7078   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7079                                               LegalOperations))
7080     return SDValue(Res, 0);
7081 
7082   return SDValue();
7083 }
7084 
7085 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7086   SDValue N0 = N->getOperand(0);
7087   EVT VT = N->getValueType(0);
7088   bool isLE = DAG.getDataLayout().isLittleEndian();
7089 
7090   // noop truncate
7091   if (N0.getValueType() == N->getValueType(0))
7092     return N0;
7093   // fold (truncate c1) -> c1
7094   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7095     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7096   // fold (truncate (truncate x)) -> (truncate x)
7097   if (N0.getOpcode() == ISD::TRUNCATE)
7098     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7099   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7100   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7101       N0.getOpcode() == ISD::SIGN_EXTEND ||
7102       N0.getOpcode() == ISD::ANY_EXTEND) {
7103     // if the source is smaller than the dest, we still need an extend.
7104     if (N0.getOperand(0).getValueType().bitsLT(VT))
7105       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7106     // if the source is larger than the dest, than we just need the truncate.
7107     if (N0.getOperand(0).getValueType().bitsGT(VT))
7108       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7109     // if the source and dest are the same type, we can drop both the extend
7110     // and the truncate.
7111     return N0.getOperand(0);
7112   }
7113 
7114   // Fold extract-and-trunc into a narrow extract. For example:
7115   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7116   //   i32 y = TRUNCATE(i64 x)
7117   //        -- becomes --
7118   //   v16i8 b = BITCAST (v2i64 val)
7119   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7120   //
7121   // Note: We only run this optimization after type legalization (which often
7122   // creates this pattern) and before operation legalization after which
7123   // we need to be more careful about the vector instructions that we generate.
7124   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7125       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7126 
7127     EVT VecTy = N0.getOperand(0).getValueType();
7128     EVT ExTy = N0.getValueType();
7129     EVT TrTy = N->getValueType(0);
7130 
7131     unsigned NumElem = VecTy.getVectorNumElements();
7132     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7133 
7134     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7135     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7136 
7137     SDValue EltNo = N0->getOperand(1);
7138     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7139       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7140       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7141       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7142 
7143       SDLoc DL(N);
7144       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7145                          DAG.getBitcast(NVT, N0.getOperand(0)),
7146                          DAG.getConstant(Index, DL, IndexTy));
7147     }
7148   }
7149 
7150   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7151   if (N0.getOpcode() == ISD::SELECT) {
7152     EVT SrcVT = N0.getValueType();
7153     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7154         TLI.isTruncateFree(SrcVT, VT)) {
7155       SDLoc SL(N0);
7156       SDValue Cond = N0.getOperand(0);
7157       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7158       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7159       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7160     }
7161   }
7162 
7163   // trunc (shl x, K) -> shl (trunc x), K => K < vt.size / 2
7164   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7165       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7166       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7167     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7168       uint64_t Amt = CAmt->getZExtValue();
7169       unsigned Size = VT.getSizeInBits();
7170 
7171       if (Amt < Size / 2) {
7172         SDLoc SL(N);
7173         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7174 
7175         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7176         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7177                            DAG.getConstant(Amt, SL, AmtVT));
7178       }
7179     }
7180   }
7181 
7182   // Fold a series of buildvector, bitcast, and truncate if possible.
7183   // For example fold
7184   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7185   //   (2xi32 (buildvector x, y)).
7186   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7187       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7188       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7189       N0.getOperand(0).hasOneUse()) {
7190 
7191     SDValue BuildVect = N0.getOperand(0);
7192     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7193     EVT TruncVecEltTy = VT.getVectorElementType();
7194 
7195     // Check that the element types match.
7196     if (BuildVectEltTy == TruncVecEltTy) {
7197       // Now we only need to compute the offset of the truncated elements.
7198       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7199       unsigned TruncVecNumElts = VT.getVectorNumElements();
7200       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7201 
7202       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7203              "Invalid number of elements");
7204 
7205       SmallVector<SDValue, 8> Opnds;
7206       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7207         Opnds.push_back(BuildVect.getOperand(i));
7208 
7209       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7210     }
7211   }
7212 
7213   // See if we can simplify the input to this truncate through knowledge that
7214   // only the low bits are being used.
7215   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7216   // Currently we only perform this optimization on scalars because vectors
7217   // may have different active low bits.
7218   if (!VT.isVector()) {
7219     if (SDValue Shorter =
7220             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7221                                                      VT.getSizeInBits())))
7222       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7223   }
7224   // fold (truncate (load x)) -> (smaller load x)
7225   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7226   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7227     if (SDValue Reduced = ReduceLoadWidth(N))
7228       return Reduced;
7229 
7230     // Handle the case where the load remains an extending load even
7231     // after truncation.
7232     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7233       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7234       if (!LN0->isVolatile() &&
7235           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7236         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7237                                          VT, LN0->getChain(), LN0->getBasePtr(),
7238                                          LN0->getMemoryVT(),
7239                                          LN0->getMemOperand());
7240         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7241         return NewLoad;
7242       }
7243     }
7244   }
7245   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7246   // where ... are all 'undef'.
7247   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7248     SmallVector<EVT, 8> VTs;
7249     SDValue V;
7250     unsigned Idx = 0;
7251     unsigned NumDefs = 0;
7252 
7253     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7254       SDValue X = N0.getOperand(i);
7255       if (!X.isUndef()) {
7256         V = X;
7257         Idx = i;
7258         NumDefs++;
7259       }
7260       // Stop if more than one members are non-undef.
7261       if (NumDefs > 1)
7262         break;
7263       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7264                                      VT.getVectorElementType(),
7265                                      X.getValueType().getVectorNumElements()));
7266     }
7267 
7268     if (NumDefs == 0)
7269       return DAG.getUNDEF(VT);
7270 
7271     if (NumDefs == 1) {
7272       assert(V.getNode() && "The single defined operand is empty!");
7273       SmallVector<SDValue, 8> Opnds;
7274       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7275         if (i != Idx) {
7276           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7277           continue;
7278         }
7279         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7280         AddToWorklist(NV.getNode());
7281         Opnds.push_back(NV);
7282       }
7283       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7284     }
7285   }
7286 
7287   // Fold truncate of a bitcast of a vector to an extract of the low vector
7288   // element.
7289   //
7290   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7291   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7292     SDValue VecSrc = N0.getOperand(0);
7293     EVT SrcVT = VecSrc.getValueType();
7294     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7295         (!LegalOperations ||
7296          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7297       SDLoc SL(N);
7298 
7299       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7300       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7301                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7302     }
7303   }
7304 
7305   // Simplify the operands using demanded-bits information.
7306   if (!VT.isVector() &&
7307       SimplifyDemandedBits(SDValue(N, 0)))
7308     return SDValue(N, 0);
7309 
7310   return SDValue();
7311 }
7312 
7313 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7314   SDValue Elt = N->getOperand(i);
7315   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7316     return Elt.getNode();
7317   return Elt.getOperand(Elt.getResNo()).getNode();
7318 }
7319 
7320 /// build_pair (load, load) -> load
7321 /// if load locations are consecutive.
7322 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7323   assert(N->getOpcode() == ISD::BUILD_PAIR);
7324 
7325   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7326   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7327   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7328       LD1->getAddressSpace() != LD2->getAddressSpace())
7329     return SDValue();
7330   EVT LD1VT = LD1->getValueType(0);
7331   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7332   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7333       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7334     unsigned Align = LD1->getAlignment();
7335     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7336         VT.getTypeForEVT(*DAG.getContext()));
7337 
7338     if (NewAlign <= Align &&
7339         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7340       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7341                          LD1->getBasePtr(), LD1->getPointerInfo(),
7342                          false, false, false, Align);
7343   }
7344 
7345   return SDValue();
7346 }
7347 
7348 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7349   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7350   // and Lo parts; on big-endian machines it doesn't.
7351   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7352 }
7353 
7354 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7355   SDValue N0 = N->getOperand(0);
7356   EVT VT = N->getValueType(0);
7357 
7358   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7359   // Only do this before legalize, since afterward the target may be depending
7360   // on the bitconvert.
7361   // First check to see if this is all constant.
7362   if (!LegalTypes &&
7363       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7364       VT.isVector()) {
7365     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7366 
7367     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7368     assert(!DestEltVT.isVector() &&
7369            "Element type of vector ValueType must not be vector!");
7370     if (isSimple)
7371       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7372   }
7373 
7374   // If the input is a constant, let getNode fold it.
7375   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7376     // If we can't allow illegal operations, we need to check that this is just
7377     // a fp -> int or int -> conversion and that the resulting operation will
7378     // be legal.
7379     if (!LegalOperations ||
7380         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7381          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7382         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7383          TLI.isOperationLegal(ISD::Constant, VT)))
7384       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7385   }
7386 
7387   // (conv (conv x, t1), t2) -> (conv x, t2)
7388   if (N0.getOpcode() == ISD::BITCAST)
7389     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7390                        N0.getOperand(0));
7391 
7392   // fold (conv (load x)) -> (load (conv*)x)
7393   // If the resultant load doesn't need a higher alignment than the original!
7394   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7395       // Do not change the width of a volatile load.
7396       !cast<LoadSDNode>(N0)->isVolatile() &&
7397       // Do not remove the cast if the types differ in endian layout.
7398       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7399           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7400       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7401       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7402     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7403     unsigned OrigAlign = LN0->getAlignment();
7404 
7405     bool Fast = false;
7406     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7407                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7408         Fast) {
7409       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7410                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7411                                  LN0->isVolatile(), LN0->isNonTemporal(),
7412                                  LN0->isInvariant(), OrigAlign,
7413                                  LN0->getAAInfo());
7414       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7415       return Load;
7416     }
7417   }
7418 
7419   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7420   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7421   //
7422   // For ppc_fp128:
7423   // fold (bitcast (fneg x)) ->
7424   //     flipbit = signbit
7425   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7426   //
7427   // fold (bitcast (fabs x)) ->
7428   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7429   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7430   // This often reduces constant pool loads.
7431   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7432        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7433       N0.getNode()->hasOneUse() && VT.isInteger() &&
7434       !VT.isVector() && !N0.getValueType().isVector()) {
7435     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7436                                   N0.getOperand(0));
7437     AddToWorklist(NewConv.getNode());
7438 
7439     SDLoc DL(N);
7440     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7441       assert(VT.getSizeInBits() == 128);
7442       SDValue SignBit = DAG.getConstant(
7443           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7444       SDValue FlipBit;
7445       if (N0.getOpcode() == ISD::FNEG) {
7446         FlipBit = SignBit;
7447         AddToWorklist(FlipBit.getNode());
7448       } else {
7449         assert(N0.getOpcode() == ISD::FABS);
7450         SDValue Hi =
7451             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7452                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7453                                               SDLoc(NewConv)));
7454         AddToWorklist(Hi.getNode());
7455         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7456         AddToWorklist(FlipBit.getNode());
7457       }
7458       SDValue FlipBits =
7459           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7460       AddToWorklist(FlipBits.getNode());
7461       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7462     }
7463     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7464     if (N0.getOpcode() == ISD::FNEG)
7465       return DAG.getNode(ISD::XOR, DL, VT,
7466                          NewConv, DAG.getConstant(SignBit, DL, VT));
7467     assert(N0.getOpcode() == ISD::FABS);
7468     return DAG.getNode(ISD::AND, DL, VT,
7469                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7470   }
7471 
7472   // fold (bitconvert (fcopysign cst, x)) ->
7473   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7474   // Note that we don't handle (copysign x, cst) because this can always be
7475   // folded to an fneg or fabs.
7476   //
7477   // For ppc_fp128:
7478   // fold (bitcast (fcopysign cst, x)) ->
7479   //     flipbit = (and (extract_element
7480   //                     (xor (bitcast cst), (bitcast x)), 0),
7481   //                    signbit)
7482   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7483   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7484       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7485       VT.isInteger() && !VT.isVector()) {
7486     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7487     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7488     if (isTypeLegal(IntXVT)) {
7489       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7490                               IntXVT, N0.getOperand(1));
7491       AddToWorklist(X.getNode());
7492 
7493       // If X has a different width than the result/lhs, sext it or truncate it.
7494       unsigned VTWidth = VT.getSizeInBits();
7495       if (OrigXWidth < VTWidth) {
7496         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7497         AddToWorklist(X.getNode());
7498       } else if (OrigXWidth > VTWidth) {
7499         // To get the sign bit in the right place, we have to shift it right
7500         // before truncating.
7501         SDLoc DL(X);
7502         X = DAG.getNode(ISD::SRL, DL,
7503                         X.getValueType(), X,
7504                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7505                                         X.getValueType()));
7506         AddToWorklist(X.getNode());
7507         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7508         AddToWorklist(X.getNode());
7509       }
7510 
7511       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7512         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7513         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7514         AddToWorklist(Cst.getNode());
7515         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7516         AddToWorklist(X.getNode());
7517         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7518         AddToWorklist(XorResult.getNode());
7519         SDValue XorResult64 = DAG.getNode(
7520             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7521             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7522                                   SDLoc(XorResult)));
7523         AddToWorklist(XorResult64.getNode());
7524         SDValue FlipBit =
7525             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7526                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7527         AddToWorklist(FlipBit.getNode());
7528         SDValue FlipBits =
7529             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7530         AddToWorklist(FlipBits.getNode());
7531         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7532       }
7533       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7534       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7535                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7536       AddToWorklist(X.getNode());
7537 
7538       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7539                                 VT, N0.getOperand(0));
7540       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7541                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7542       AddToWorklist(Cst.getNode());
7543 
7544       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7545     }
7546   }
7547 
7548   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7549   if (N0.getOpcode() == ISD::BUILD_PAIR)
7550     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7551       return CombineLD;
7552 
7553   // Remove double bitcasts from shuffles - this is often a legacy of
7554   // XformToShuffleWithZero being used to combine bitmaskings (of
7555   // float vectors bitcast to integer vectors) into shuffles.
7556   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7557   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7558       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7559       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7560       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7561     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7562 
7563     // If operands are a bitcast, peek through if it casts the original VT.
7564     // If operands are a constant, just bitcast back to original VT.
7565     auto PeekThroughBitcast = [&](SDValue Op) {
7566       if (Op.getOpcode() == ISD::BITCAST &&
7567           Op.getOperand(0).getValueType() == VT)
7568         return SDValue(Op.getOperand(0));
7569       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7570           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7571         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7572       return SDValue();
7573     };
7574 
7575     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7576     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7577     if (!(SV0 && SV1))
7578       return SDValue();
7579 
7580     int MaskScale =
7581         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7582     SmallVector<int, 8> NewMask;
7583     for (int M : SVN->getMask())
7584       for (int i = 0; i != MaskScale; ++i)
7585         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7586 
7587     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7588     if (!LegalMask) {
7589       std::swap(SV0, SV1);
7590       ShuffleVectorSDNode::commuteMask(NewMask);
7591       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7592     }
7593 
7594     if (LegalMask)
7595       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7596   }
7597 
7598   return SDValue();
7599 }
7600 
7601 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7602   EVT VT = N->getValueType(0);
7603   return CombineConsecutiveLoads(N, VT);
7604 }
7605 
7606 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7607 /// operands. DstEltVT indicates the destination element value type.
7608 SDValue DAGCombiner::
7609 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7610   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7611 
7612   // If this is already the right type, we're done.
7613   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7614 
7615   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7616   unsigned DstBitSize = DstEltVT.getSizeInBits();
7617 
7618   // If this is a conversion of N elements of one type to N elements of another
7619   // type, convert each element.  This handles FP<->INT cases.
7620   if (SrcBitSize == DstBitSize) {
7621     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7622                               BV->getValueType(0).getVectorNumElements());
7623 
7624     // Due to the FP element handling below calling this routine recursively,
7625     // we can end up with a scalar-to-vector node here.
7626     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7627       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7628                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7629                                      DstEltVT, BV->getOperand(0)));
7630 
7631     SmallVector<SDValue, 8> Ops;
7632     for (SDValue Op : BV->op_values()) {
7633       // If the vector element type is not legal, the BUILD_VECTOR operands
7634       // are promoted and implicitly truncated.  Make that explicit here.
7635       if (Op.getValueType() != SrcEltVT)
7636         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7637       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7638                                 DstEltVT, Op));
7639       AddToWorklist(Ops.back().getNode());
7640     }
7641     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7642   }
7643 
7644   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7645   // handle annoying details of growing/shrinking FP values, we convert them to
7646   // int first.
7647   if (SrcEltVT.isFloatingPoint()) {
7648     // Convert the input float vector to a int vector where the elements are the
7649     // same sizes.
7650     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7651     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7652     SrcEltVT = IntVT;
7653   }
7654 
7655   // Now we know the input is an integer vector.  If the output is a FP type,
7656   // convert to integer first, then to FP of the right size.
7657   if (DstEltVT.isFloatingPoint()) {
7658     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7659     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7660 
7661     // Next, convert to FP elements of the same size.
7662     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7663   }
7664 
7665   SDLoc DL(BV);
7666 
7667   // Okay, we know the src/dst types are both integers of differing types.
7668   // Handling growing first.
7669   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7670   if (SrcBitSize < DstBitSize) {
7671     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7672 
7673     SmallVector<SDValue, 8> Ops;
7674     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7675          i += NumInputsPerOutput) {
7676       bool isLE = DAG.getDataLayout().isLittleEndian();
7677       APInt NewBits = APInt(DstBitSize, 0);
7678       bool EltIsUndef = true;
7679       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7680         // Shift the previously computed bits over.
7681         NewBits <<= SrcBitSize;
7682         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7683         if (Op.isUndef()) continue;
7684         EltIsUndef = false;
7685 
7686         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7687                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7688       }
7689 
7690       if (EltIsUndef)
7691         Ops.push_back(DAG.getUNDEF(DstEltVT));
7692       else
7693         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7694     }
7695 
7696     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7697     return DAG.getBuildVector(VT, DL, Ops);
7698   }
7699 
7700   // Finally, this must be the case where we are shrinking elements: each input
7701   // turns into multiple outputs.
7702   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7703   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7704                             NumOutputsPerInput*BV->getNumOperands());
7705   SmallVector<SDValue, 8> Ops;
7706 
7707   for (const SDValue &Op : BV->op_values()) {
7708     if (Op.isUndef()) {
7709       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7710       continue;
7711     }
7712 
7713     APInt OpVal = cast<ConstantSDNode>(Op)->
7714                   getAPIntValue().zextOrTrunc(SrcBitSize);
7715 
7716     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7717       APInt ThisVal = OpVal.trunc(DstBitSize);
7718       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7719       OpVal = OpVal.lshr(DstBitSize);
7720     }
7721 
7722     // For big endian targets, swap the order of the pieces of each element.
7723     if (DAG.getDataLayout().isBigEndian())
7724       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7725   }
7726 
7727   return DAG.getBuildVector(VT, DL, Ops);
7728 }
7729 
7730 /// Try to perform FMA combining on a given FADD node.
7731 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7732   SDValue N0 = N->getOperand(0);
7733   SDValue N1 = N->getOperand(1);
7734   EVT VT = N->getValueType(0);
7735   SDLoc SL(N);
7736 
7737   const TargetOptions &Options = DAG.getTarget().Options;
7738   bool AllowFusion =
7739       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7740 
7741   // Floating-point multiply-add with intermediate rounding.
7742   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7743 
7744   // Floating-point multiply-add without intermediate rounding.
7745   bool HasFMA =
7746       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7747       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7748 
7749   // No valid opcode, do not combine.
7750   if (!HasFMAD && !HasFMA)
7751     return SDValue();
7752 
7753   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7754   ;
7755   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7756     return SDValue();
7757 
7758   // Always prefer FMAD to FMA for precision.
7759   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7760   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7761   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7762 
7763   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7764   // prefer to fold the multiply with fewer uses.
7765   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7766       N1.getOpcode() == ISD::FMUL) {
7767     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7768       std::swap(N0, N1);
7769   }
7770 
7771   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7772   if (N0.getOpcode() == ISD::FMUL &&
7773       (Aggressive || N0->hasOneUse())) {
7774     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7775                        N0.getOperand(0), N0.getOperand(1), N1);
7776   }
7777 
7778   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7779   // Note: Commutes FADD operands.
7780   if (N1.getOpcode() == ISD::FMUL &&
7781       (Aggressive || N1->hasOneUse())) {
7782     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7783                        N1.getOperand(0), N1.getOperand(1), N0);
7784   }
7785 
7786   // Look through FP_EXTEND nodes to do more combining.
7787   if (AllowFusion && LookThroughFPExt) {
7788     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7789     if (N0.getOpcode() == ISD::FP_EXTEND) {
7790       SDValue N00 = N0.getOperand(0);
7791       if (N00.getOpcode() == ISD::FMUL)
7792         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7793                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7794                                        N00.getOperand(0)),
7795                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7796                                        N00.getOperand(1)), N1);
7797     }
7798 
7799     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7800     // Note: Commutes FADD operands.
7801     if (N1.getOpcode() == ISD::FP_EXTEND) {
7802       SDValue N10 = N1.getOperand(0);
7803       if (N10.getOpcode() == ISD::FMUL)
7804         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7805                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7806                                        N10.getOperand(0)),
7807                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7808                                        N10.getOperand(1)), N0);
7809     }
7810   }
7811 
7812   // More folding opportunities when target permits.
7813   if ((AllowFusion || HasFMAD)  && Aggressive) {
7814     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7815     if (N0.getOpcode() == PreferredFusedOpcode &&
7816         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7817       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7818                          N0.getOperand(0), N0.getOperand(1),
7819                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7820                                      N0.getOperand(2).getOperand(0),
7821                                      N0.getOperand(2).getOperand(1),
7822                                      N1));
7823     }
7824 
7825     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7826     if (N1->getOpcode() == PreferredFusedOpcode &&
7827         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7828       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7829                          N1.getOperand(0), N1.getOperand(1),
7830                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7831                                      N1.getOperand(2).getOperand(0),
7832                                      N1.getOperand(2).getOperand(1),
7833                                      N0));
7834     }
7835 
7836     if (AllowFusion && LookThroughFPExt) {
7837       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7838       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7839       auto FoldFAddFMAFPExtFMul = [&] (
7840           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7841         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7842                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7843                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7844                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7845                                        Z));
7846       };
7847       if (N0.getOpcode() == PreferredFusedOpcode) {
7848         SDValue N02 = N0.getOperand(2);
7849         if (N02.getOpcode() == ISD::FP_EXTEND) {
7850           SDValue N020 = N02.getOperand(0);
7851           if (N020.getOpcode() == ISD::FMUL)
7852             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7853                                         N020.getOperand(0), N020.getOperand(1),
7854                                         N1);
7855         }
7856       }
7857 
7858       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7859       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7860       // FIXME: This turns two single-precision and one double-precision
7861       // operation into two double-precision operations, which might not be
7862       // interesting for all targets, especially GPUs.
7863       auto FoldFAddFPExtFMAFMul = [&] (
7864           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7865         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7866                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7867                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7868                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7869                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7870                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7871                                        Z));
7872       };
7873       if (N0.getOpcode() == ISD::FP_EXTEND) {
7874         SDValue N00 = N0.getOperand(0);
7875         if (N00.getOpcode() == PreferredFusedOpcode) {
7876           SDValue N002 = N00.getOperand(2);
7877           if (N002.getOpcode() == ISD::FMUL)
7878             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7879                                         N002.getOperand(0), N002.getOperand(1),
7880                                         N1);
7881         }
7882       }
7883 
7884       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7885       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7886       if (N1.getOpcode() == PreferredFusedOpcode) {
7887         SDValue N12 = N1.getOperand(2);
7888         if (N12.getOpcode() == ISD::FP_EXTEND) {
7889           SDValue N120 = N12.getOperand(0);
7890           if (N120.getOpcode() == ISD::FMUL)
7891             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7892                                         N120.getOperand(0), N120.getOperand(1),
7893                                         N0);
7894         }
7895       }
7896 
7897       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7898       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7899       // FIXME: This turns two single-precision and one double-precision
7900       // operation into two double-precision operations, which might not be
7901       // interesting for all targets, especially GPUs.
7902       if (N1.getOpcode() == ISD::FP_EXTEND) {
7903         SDValue N10 = N1.getOperand(0);
7904         if (N10.getOpcode() == PreferredFusedOpcode) {
7905           SDValue N102 = N10.getOperand(2);
7906           if (N102.getOpcode() == ISD::FMUL)
7907             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7908                                         N102.getOperand(0), N102.getOperand(1),
7909                                         N0);
7910         }
7911       }
7912     }
7913   }
7914 
7915   return SDValue();
7916 }
7917 
7918 /// Try to perform FMA combining on a given FSUB node.
7919 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7920   SDValue N0 = N->getOperand(0);
7921   SDValue N1 = N->getOperand(1);
7922   EVT VT = N->getValueType(0);
7923   SDLoc SL(N);
7924 
7925   const TargetOptions &Options = DAG.getTarget().Options;
7926   bool AllowFusion =
7927       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7928 
7929   // Floating-point multiply-add with intermediate rounding.
7930   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7931 
7932   // Floating-point multiply-add without intermediate rounding.
7933   bool HasFMA =
7934       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7935       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7936 
7937   // No valid opcode, do not combine.
7938   if (!HasFMAD && !HasFMA)
7939     return SDValue();
7940 
7941   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7942   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7943     return SDValue();
7944 
7945   // Always prefer FMAD to FMA for precision.
7946   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7947   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7948   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7949 
7950   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7951   if (N0.getOpcode() == ISD::FMUL &&
7952       (Aggressive || N0->hasOneUse())) {
7953     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7954                        N0.getOperand(0), N0.getOperand(1),
7955                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7956   }
7957 
7958   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7959   // Note: Commutes FSUB operands.
7960   if (N1.getOpcode() == ISD::FMUL &&
7961       (Aggressive || N1->hasOneUse()))
7962     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7963                        DAG.getNode(ISD::FNEG, SL, VT,
7964                                    N1.getOperand(0)),
7965                        N1.getOperand(1), N0);
7966 
7967   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7968   if (N0.getOpcode() == ISD::FNEG &&
7969       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7970       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7971     SDValue N00 = N0.getOperand(0).getOperand(0);
7972     SDValue N01 = N0.getOperand(0).getOperand(1);
7973     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7974                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7975                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7976   }
7977 
7978   // Look through FP_EXTEND nodes to do more combining.
7979   if (AllowFusion && LookThroughFPExt) {
7980     // fold (fsub (fpext (fmul x, y)), z)
7981     //   -> (fma (fpext x), (fpext y), (fneg z))
7982     if (N0.getOpcode() == ISD::FP_EXTEND) {
7983       SDValue N00 = N0.getOperand(0);
7984       if (N00.getOpcode() == ISD::FMUL)
7985         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7986                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7987                                        N00.getOperand(0)),
7988                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7989                                        N00.getOperand(1)),
7990                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7991     }
7992 
7993     // fold (fsub x, (fpext (fmul y, z)))
7994     //   -> (fma (fneg (fpext y)), (fpext z), x)
7995     // Note: Commutes FSUB operands.
7996     if (N1.getOpcode() == ISD::FP_EXTEND) {
7997       SDValue N10 = N1.getOperand(0);
7998       if (N10.getOpcode() == ISD::FMUL)
7999         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8000                            DAG.getNode(ISD::FNEG, SL, VT,
8001                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8002                                                    N10.getOperand(0))),
8003                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8004                                        N10.getOperand(1)),
8005                            N0);
8006     }
8007 
8008     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8009     //   -> (fneg (fma (fpext x), (fpext y), z))
8010     // Note: This could be removed with appropriate canonicalization of the
8011     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8012     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8013     // from implementing the canonicalization in visitFSUB.
8014     if (N0.getOpcode() == ISD::FP_EXTEND) {
8015       SDValue N00 = N0.getOperand(0);
8016       if (N00.getOpcode() == ISD::FNEG) {
8017         SDValue N000 = N00.getOperand(0);
8018         if (N000.getOpcode() == ISD::FMUL) {
8019           return DAG.getNode(ISD::FNEG, SL, VT,
8020                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8021                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8022                                                      N000.getOperand(0)),
8023                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8024                                                      N000.getOperand(1)),
8025                                          N1));
8026         }
8027       }
8028     }
8029 
8030     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8031     //   -> (fneg (fma (fpext x)), (fpext y), z)
8032     // Note: This could be removed with appropriate canonicalization of the
8033     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8034     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8035     // from implementing the canonicalization in visitFSUB.
8036     if (N0.getOpcode() == ISD::FNEG) {
8037       SDValue N00 = N0.getOperand(0);
8038       if (N00.getOpcode() == ISD::FP_EXTEND) {
8039         SDValue N000 = N00.getOperand(0);
8040         if (N000.getOpcode() == ISD::FMUL) {
8041           return DAG.getNode(ISD::FNEG, SL, VT,
8042                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8043                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8044                                                      N000.getOperand(0)),
8045                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8046                                                      N000.getOperand(1)),
8047                                          N1));
8048         }
8049       }
8050     }
8051 
8052   }
8053 
8054   // More folding opportunities when target permits.
8055   if ((AllowFusion || HasFMAD) && Aggressive) {
8056     // fold (fsub (fma x, y, (fmul u, v)), z)
8057     //   -> (fma x, y (fma u, v, (fneg z)))
8058     if (N0.getOpcode() == PreferredFusedOpcode &&
8059         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8060       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8061                          N0.getOperand(0), N0.getOperand(1),
8062                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8063                                      N0.getOperand(2).getOperand(0),
8064                                      N0.getOperand(2).getOperand(1),
8065                                      DAG.getNode(ISD::FNEG, SL, VT,
8066                                                  N1)));
8067     }
8068 
8069     // fold (fsub x, (fma y, z, (fmul u, v)))
8070     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8071     if (N1.getOpcode() == PreferredFusedOpcode &&
8072         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8073       SDValue N20 = N1.getOperand(2).getOperand(0);
8074       SDValue N21 = N1.getOperand(2).getOperand(1);
8075       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8076                          DAG.getNode(ISD::FNEG, SL, VT,
8077                                      N1.getOperand(0)),
8078                          N1.getOperand(1),
8079                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8080                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8081 
8082                                      N21, N0));
8083     }
8084 
8085     if (AllowFusion && LookThroughFPExt) {
8086       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8087       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8088       if (N0.getOpcode() == PreferredFusedOpcode) {
8089         SDValue N02 = N0.getOperand(2);
8090         if (N02.getOpcode() == ISD::FP_EXTEND) {
8091           SDValue N020 = N02.getOperand(0);
8092           if (N020.getOpcode() == ISD::FMUL)
8093             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8094                                N0.getOperand(0), N0.getOperand(1),
8095                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8096                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8097                                                        N020.getOperand(0)),
8098                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8099                                                        N020.getOperand(1)),
8100                                            DAG.getNode(ISD::FNEG, SL, VT,
8101                                                        N1)));
8102         }
8103       }
8104 
8105       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8106       //   -> (fma (fpext x), (fpext y),
8107       //           (fma (fpext u), (fpext v), (fneg z)))
8108       // FIXME: This turns two single-precision and one double-precision
8109       // operation into two double-precision operations, which might not be
8110       // interesting for all targets, especially GPUs.
8111       if (N0.getOpcode() == ISD::FP_EXTEND) {
8112         SDValue N00 = N0.getOperand(0);
8113         if (N00.getOpcode() == PreferredFusedOpcode) {
8114           SDValue N002 = N00.getOperand(2);
8115           if (N002.getOpcode() == ISD::FMUL)
8116             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8117                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8118                                            N00.getOperand(0)),
8119                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8120                                            N00.getOperand(1)),
8121                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8122                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8123                                                        N002.getOperand(0)),
8124                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8125                                                        N002.getOperand(1)),
8126                                            DAG.getNode(ISD::FNEG, SL, VT,
8127                                                        N1)));
8128         }
8129       }
8130 
8131       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8132       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8133       if (N1.getOpcode() == PreferredFusedOpcode &&
8134         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8135         SDValue N120 = N1.getOperand(2).getOperand(0);
8136         if (N120.getOpcode() == ISD::FMUL) {
8137           SDValue N1200 = N120.getOperand(0);
8138           SDValue N1201 = N120.getOperand(1);
8139           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8140                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8141                              N1.getOperand(1),
8142                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8143                                          DAG.getNode(ISD::FNEG, SL, VT,
8144                                              DAG.getNode(ISD::FP_EXTEND, SL,
8145                                                          VT, N1200)),
8146                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8147                                                      N1201),
8148                                          N0));
8149         }
8150       }
8151 
8152       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8153       //   -> (fma (fneg (fpext y)), (fpext z),
8154       //           (fma (fneg (fpext u)), (fpext v), x))
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 (N1.getOpcode() == ISD::FP_EXTEND &&
8159         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8160         SDValue N100 = N1.getOperand(0).getOperand(0);
8161         SDValue N101 = N1.getOperand(0).getOperand(1);
8162         SDValue N102 = N1.getOperand(0).getOperand(2);
8163         if (N102.getOpcode() == ISD::FMUL) {
8164           SDValue N1020 = N102.getOperand(0);
8165           SDValue N1021 = N102.getOperand(1);
8166           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8167                              DAG.getNode(ISD::FNEG, SL, VT,
8168                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8169                                                      N100)),
8170                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8171                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8172                                          DAG.getNode(ISD::FNEG, SL, VT,
8173                                              DAG.getNode(ISD::FP_EXTEND, SL,
8174                                                          VT, N1020)),
8175                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8176                                                      N1021),
8177                                          N0));
8178         }
8179       }
8180     }
8181   }
8182 
8183   return SDValue();
8184 }
8185 
8186 /// Try to perform FMA combining on a given FMUL node.
8187 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8188   SDValue N0 = N->getOperand(0);
8189   SDValue N1 = N->getOperand(1);
8190   EVT VT = N->getValueType(0);
8191   SDLoc SL(N);
8192 
8193   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8194 
8195   const TargetOptions &Options = DAG.getTarget().Options;
8196   bool AllowFusion =
8197       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8198 
8199   // Floating-point multiply-add with intermediate rounding.
8200   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8201 
8202   // Floating-point multiply-add without intermediate rounding.
8203   bool HasFMA =
8204       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8205       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8206 
8207   // No valid opcode, do not combine.
8208   if (!HasFMAD && !HasFMA)
8209     return SDValue();
8210 
8211   // Always prefer FMAD to FMA for precision.
8212   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8213   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8214 
8215   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8216   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8217   auto FuseFADD = [&](SDValue X, SDValue Y) {
8218     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8219       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8220       if (XC1 && XC1->isExactlyValue(+1.0))
8221         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8222       if (XC1 && XC1->isExactlyValue(-1.0))
8223         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8224                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8225     }
8226     return SDValue();
8227   };
8228 
8229   if (SDValue FMA = FuseFADD(N0, N1))
8230     return FMA;
8231   if (SDValue FMA = FuseFADD(N1, N0))
8232     return FMA;
8233 
8234   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8235   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8236   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8237   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8238   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8239     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8240       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8241       if (XC0 && XC0->isExactlyValue(+1.0))
8242         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8243                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8244                            Y);
8245       if (XC0 && XC0->isExactlyValue(-1.0))
8246         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8247                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8248                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8249 
8250       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8251       if (XC1 && XC1->isExactlyValue(+1.0))
8252         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8253                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8254       if (XC1 && XC1->isExactlyValue(-1.0))
8255         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8256     }
8257     return SDValue();
8258   };
8259 
8260   if (SDValue FMA = FuseFSUB(N0, N1))
8261     return FMA;
8262   if (SDValue FMA = FuseFSUB(N1, N0))
8263     return FMA;
8264 
8265   return SDValue();
8266 }
8267 
8268 SDValue DAGCombiner::visitFADD(SDNode *N) {
8269   SDValue N0 = N->getOperand(0);
8270   SDValue N1 = N->getOperand(1);
8271   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8272   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8273   EVT VT = N->getValueType(0);
8274   SDLoc DL(N);
8275   const TargetOptions &Options = DAG.getTarget().Options;
8276   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8277 
8278   // fold vector ops
8279   if (VT.isVector())
8280     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8281       return FoldedVOp;
8282 
8283   // fold (fadd c1, c2) -> c1 + c2
8284   if (N0CFP && N1CFP)
8285     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8286 
8287   // canonicalize constant to RHS
8288   if (N0CFP && !N1CFP)
8289     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8290 
8291   // fold (fadd A, (fneg B)) -> (fsub A, B)
8292   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8293       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8294     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8295                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8296 
8297   // fold (fadd (fneg A), B) -> (fsub B, A)
8298   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8299       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8300     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8301                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8302 
8303   // If 'unsafe math' is enabled, fold lots of things.
8304   if (Options.UnsafeFPMath) {
8305     // No FP constant should be created after legalization as Instruction
8306     // Selection pass has a hard time dealing with FP constants.
8307     bool AllowNewConst = (Level < AfterLegalizeDAG);
8308 
8309     // fold (fadd A, 0) -> A
8310     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8311       if (N1C->isZero())
8312         return N0;
8313 
8314     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8315     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8316         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8317       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8318                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8319                                      Flags),
8320                          Flags);
8321 
8322     // If allowed, fold (fadd (fneg x), x) -> 0.0
8323     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8324       return DAG.getConstantFP(0.0, DL, VT);
8325 
8326     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8327     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8328       return DAG.getConstantFP(0.0, DL, VT);
8329 
8330     // We can fold chains of FADD's of the same value into multiplications.
8331     // This transform is not safe in general because we are reducing the number
8332     // of rounding steps.
8333     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8334       if (N0.getOpcode() == ISD::FMUL) {
8335         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8336         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8337 
8338         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8339         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8340           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8341                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8342           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8343         }
8344 
8345         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8346         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8347             N1.getOperand(0) == N1.getOperand(1) &&
8348             N0.getOperand(0) == N1.getOperand(0)) {
8349           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8350                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8351           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8352         }
8353       }
8354 
8355       if (N1.getOpcode() == ISD::FMUL) {
8356         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8357         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8358 
8359         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8360         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8361           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8362                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8363           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8364         }
8365 
8366         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8367         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8368             N0.getOperand(0) == N0.getOperand(1) &&
8369             N1.getOperand(0) == N0.getOperand(0)) {
8370           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8371                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8372           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8373         }
8374       }
8375 
8376       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8377         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8378         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8379         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8380             (N0.getOperand(0) == N1)) {
8381           return DAG.getNode(ISD::FMUL, DL, VT,
8382                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8383         }
8384       }
8385 
8386       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8387         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8388         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8389         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8390             N1.getOperand(0) == N0) {
8391           return DAG.getNode(ISD::FMUL, DL, VT,
8392                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8393         }
8394       }
8395 
8396       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8397       if (AllowNewConst &&
8398           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8399           N0.getOperand(0) == N0.getOperand(1) &&
8400           N1.getOperand(0) == N1.getOperand(1) &&
8401           N0.getOperand(0) == N1.getOperand(0)) {
8402         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8403                            DAG.getConstantFP(4.0, DL, VT), Flags);
8404       }
8405     }
8406   } // enable-unsafe-fp-math
8407 
8408   // FADD -> FMA combines:
8409   if (SDValue Fused = visitFADDForFMACombine(N)) {
8410     AddToWorklist(Fused.getNode());
8411     return Fused;
8412   }
8413   return SDValue();
8414 }
8415 
8416 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8417   SDValue N0 = N->getOperand(0);
8418   SDValue N1 = N->getOperand(1);
8419   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8420   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8421   EVT VT = N->getValueType(0);
8422   SDLoc dl(N);
8423   const TargetOptions &Options = DAG.getTarget().Options;
8424   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8425 
8426   // fold vector ops
8427   if (VT.isVector())
8428     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8429       return FoldedVOp;
8430 
8431   // fold (fsub c1, c2) -> c1-c2
8432   if (N0CFP && N1CFP)
8433     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8434 
8435   // fold (fsub A, (fneg B)) -> (fadd A, B)
8436   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8437     return DAG.getNode(ISD::FADD, dl, VT, N0,
8438                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8439 
8440   // If 'unsafe math' is enabled, fold lots of things.
8441   if (Options.UnsafeFPMath) {
8442     // (fsub A, 0) -> A
8443     if (N1CFP && N1CFP->isZero())
8444       return N0;
8445 
8446     // (fsub 0, B) -> -B
8447     if (N0CFP && N0CFP->isZero()) {
8448       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8449         return GetNegatedExpression(N1, DAG, LegalOperations);
8450       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8451         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8452     }
8453 
8454     // (fsub x, x) -> 0.0
8455     if (N0 == N1)
8456       return DAG.getConstantFP(0.0f, dl, VT);
8457 
8458     // (fsub x, (fadd x, y)) -> (fneg y)
8459     // (fsub x, (fadd y, x)) -> (fneg y)
8460     if (N1.getOpcode() == ISD::FADD) {
8461       SDValue N10 = N1->getOperand(0);
8462       SDValue N11 = N1->getOperand(1);
8463 
8464       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8465         return GetNegatedExpression(N11, DAG, LegalOperations);
8466 
8467       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8468         return GetNegatedExpression(N10, DAG, LegalOperations);
8469     }
8470   }
8471 
8472   // FSUB -> FMA combines:
8473   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8474     AddToWorklist(Fused.getNode());
8475     return Fused;
8476   }
8477 
8478   return SDValue();
8479 }
8480 
8481 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8482   SDValue N0 = N->getOperand(0);
8483   SDValue N1 = N->getOperand(1);
8484   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8485   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8486   EVT VT = N->getValueType(0);
8487   SDLoc DL(N);
8488   const TargetOptions &Options = DAG.getTarget().Options;
8489   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8490 
8491   // fold vector ops
8492   if (VT.isVector()) {
8493     // This just handles C1 * C2 for vectors. Other vector folds are below.
8494     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8495       return FoldedVOp;
8496   }
8497 
8498   // fold (fmul c1, c2) -> c1*c2
8499   if (N0CFP && N1CFP)
8500     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8501 
8502   // canonicalize constant to RHS
8503   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8504      !isConstantFPBuildVectorOrConstantFP(N1))
8505     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8506 
8507   // fold (fmul A, 1.0) -> A
8508   if (N1CFP && N1CFP->isExactlyValue(1.0))
8509     return N0;
8510 
8511   if (Options.UnsafeFPMath) {
8512     // fold (fmul A, 0) -> 0
8513     if (N1CFP && N1CFP->isZero())
8514       return N1;
8515 
8516     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8517     if (N0.getOpcode() == ISD::FMUL) {
8518       // Fold scalars or any vector constants (not just splats).
8519       // This fold is done in general by InstCombine, but extra fmul insts
8520       // may have been generated during lowering.
8521       SDValue N00 = N0.getOperand(0);
8522       SDValue N01 = N0.getOperand(1);
8523       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8524       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8525       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8526 
8527       // Check 1: Make sure that the first operand of the inner multiply is NOT
8528       // a constant. Otherwise, we may induce infinite looping.
8529       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8530         // Check 2: Make sure that the second operand of the inner multiply and
8531         // the second operand of the outer multiply are constants.
8532         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8533             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8534           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8535           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8536         }
8537       }
8538     }
8539 
8540     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8541     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8542     // during an early run of DAGCombiner can prevent folding with fmuls
8543     // inserted during lowering.
8544     if (N0.getOpcode() == ISD::FADD &&
8545         (N0.getOperand(0) == N0.getOperand(1)) &&
8546         N0.hasOneUse()) {
8547       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8548       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8549       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8550     }
8551   }
8552 
8553   // fold (fmul X, 2.0) -> (fadd X, X)
8554   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8555     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8556 
8557   // fold (fmul X, -1.0) -> (fneg X)
8558   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8559     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8560       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8561 
8562   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8563   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8564     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8565       // Both can be negated for free, check to see if at least one is cheaper
8566       // negated.
8567       if (LHSNeg == 2 || RHSNeg == 2)
8568         return DAG.getNode(ISD::FMUL, DL, VT,
8569                            GetNegatedExpression(N0, DAG, LegalOperations),
8570                            GetNegatedExpression(N1, DAG, LegalOperations),
8571                            Flags);
8572     }
8573   }
8574 
8575   // FMUL -> FMA combines:
8576   if (SDValue Fused = visitFMULForFMACombine(N)) {
8577     AddToWorklist(Fused.getNode());
8578     return Fused;
8579   }
8580 
8581   return SDValue();
8582 }
8583 
8584 SDValue DAGCombiner::visitFMA(SDNode *N) {
8585   SDValue N0 = N->getOperand(0);
8586   SDValue N1 = N->getOperand(1);
8587   SDValue N2 = N->getOperand(2);
8588   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8589   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8590   EVT VT = N->getValueType(0);
8591   SDLoc dl(N);
8592   const TargetOptions &Options = DAG.getTarget().Options;
8593 
8594   // Constant fold FMA.
8595   if (isa<ConstantFPSDNode>(N0) &&
8596       isa<ConstantFPSDNode>(N1) &&
8597       isa<ConstantFPSDNode>(N2)) {
8598     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8599   }
8600 
8601   if (Options.UnsafeFPMath) {
8602     if (N0CFP && N0CFP->isZero())
8603       return N2;
8604     if (N1CFP && N1CFP->isZero())
8605       return N2;
8606   }
8607   // TODO: The FMA node should have flags that propagate to these nodes.
8608   if (N0CFP && N0CFP->isExactlyValue(1.0))
8609     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8610   if (N1CFP && N1CFP->isExactlyValue(1.0))
8611     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8612 
8613   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8614   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8615      !isConstantFPBuildVectorOrConstantFP(N1))
8616     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8617 
8618   // TODO: FMA nodes should have flags that propagate to the created nodes.
8619   // For now, create a Flags object for use with all unsafe math transforms.
8620   SDNodeFlags Flags;
8621   Flags.setUnsafeAlgebra(true);
8622 
8623   if (Options.UnsafeFPMath) {
8624     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8625     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8626         isConstantFPBuildVectorOrConstantFP(N1) &&
8627         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8628       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8629                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8630                                      &Flags), &Flags);
8631     }
8632 
8633     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8634     if (N0.getOpcode() == ISD::FMUL &&
8635         isConstantFPBuildVectorOrConstantFP(N1) &&
8636         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8637       return DAG.getNode(ISD::FMA, dl, VT,
8638                          N0.getOperand(0),
8639                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8640                                      &Flags),
8641                          N2);
8642     }
8643   }
8644 
8645   // (fma x, 1, y) -> (fadd x, y)
8646   // (fma x, -1, y) -> (fadd (fneg x), y)
8647   if (N1CFP) {
8648     if (N1CFP->isExactlyValue(1.0))
8649       // TODO: The FMA node should have flags that propagate to this node.
8650       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8651 
8652     if (N1CFP->isExactlyValue(-1.0) &&
8653         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8654       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8655       AddToWorklist(RHSNeg.getNode());
8656       // TODO: The FMA node should have flags that propagate to this node.
8657       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8658     }
8659   }
8660 
8661   if (Options.UnsafeFPMath) {
8662     // (fma x, c, x) -> (fmul x, (c+1))
8663     if (N1CFP && N0 == N2) {
8664     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8665                          DAG.getNode(ISD::FADD, dl, VT,
8666                                      N1, DAG.getConstantFP(1.0, dl, VT),
8667                                      &Flags), &Flags);
8668     }
8669 
8670     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8671     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8672       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8673                          DAG.getNode(ISD::FADD, dl, VT,
8674                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8675                                      &Flags), &Flags);
8676     }
8677   }
8678 
8679   return SDValue();
8680 }
8681 
8682 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8683 // reciprocal.
8684 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8685 // Notice that this is not always beneficial. One reason is different target
8686 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8687 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8688 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8689 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8690   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8691   const SDNodeFlags *Flags = N->getFlags();
8692   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8693     return SDValue();
8694 
8695   // Skip if current node is a reciprocal.
8696   SDValue N0 = N->getOperand(0);
8697   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8698   if (N0CFP && N0CFP->isExactlyValue(1.0))
8699     return SDValue();
8700 
8701   // Exit early if the target does not want this transform or if there can't
8702   // possibly be enough uses of the divisor to make the transform worthwhile.
8703   SDValue N1 = N->getOperand(1);
8704   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8705   if (!MinUses || N1->use_size() < MinUses)
8706     return SDValue();
8707 
8708   // Find all FDIV users of the same divisor.
8709   // Use a set because duplicates may be present in the user list.
8710   SetVector<SDNode *> Users;
8711   for (auto *U : N1->uses()) {
8712     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8713       // This division is eligible for optimization only if global unsafe math
8714       // is enabled or if this division allows reciprocal formation.
8715       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8716         Users.insert(U);
8717     }
8718   }
8719 
8720   // Now that we have the actual number of divisor uses, make sure it meets
8721   // the minimum threshold specified by the target.
8722   if (Users.size() < MinUses)
8723     return SDValue();
8724 
8725   EVT VT = N->getValueType(0);
8726   SDLoc DL(N);
8727   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8728   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8729 
8730   // Dividend / Divisor -> Dividend * Reciprocal
8731   for (auto *U : Users) {
8732     SDValue Dividend = U->getOperand(0);
8733     if (Dividend != FPOne) {
8734       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8735                                     Reciprocal, Flags);
8736       CombineTo(U, NewNode);
8737     } else if (U != Reciprocal.getNode()) {
8738       // In the absence of fast-math-flags, this user node is always the
8739       // same node as Reciprocal, but with FMF they may be different nodes.
8740       CombineTo(U, Reciprocal);
8741     }
8742   }
8743   return SDValue(N, 0);  // N was replaced.
8744 }
8745 
8746 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8747   SDValue N0 = N->getOperand(0);
8748   SDValue N1 = N->getOperand(1);
8749   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8750   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8751   EVT VT = N->getValueType(0);
8752   SDLoc DL(N);
8753   const TargetOptions &Options = DAG.getTarget().Options;
8754   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8755 
8756   // fold vector ops
8757   if (VT.isVector())
8758     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8759       return FoldedVOp;
8760 
8761   // fold (fdiv c1, c2) -> c1/c2
8762   if (N0CFP && N1CFP)
8763     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8764 
8765   if (Options.UnsafeFPMath) {
8766     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8767     if (N1CFP) {
8768       // Compute the reciprocal 1.0 / c2.
8769       APFloat N1APF = N1CFP->getValueAPF();
8770       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8771       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8772       // Only do the transform if the reciprocal is a legal fp immediate that
8773       // isn't too nasty (eg NaN, denormal, ...).
8774       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8775           (!LegalOperations ||
8776            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8777            // backend)... we should handle this gracefully after Legalize.
8778            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8779            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8780            TLI.isFPImmLegal(Recip, VT)))
8781         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8782                            DAG.getConstantFP(Recip, DL, VT), Flags);
8783     }
8784 
8785     // If this FDIV is part of a reciprocal square root, it may be folded
8786     // into a target-specific square root estimate instruction.
8787     if (N1.getOpcode() == ISD::FSQRT) {
8788       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8789         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8790       }
8791     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8792                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8793       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8794                                           Flags)) {
8795         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8796         AddToWorklist(RV.getNode());
8797         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8798       }
8799     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8800                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8801       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8802                                           Flags)) {
8803         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8804         AddToWorklist(RV.getNode());
8805         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8806       }
8807     } else if (N1.getOpcode() == ISD::FMUL) {
8808       // Look through an FMUL. Even though this won't remove the FDIV directly,
8809       // it's still worthwhile to get rid of the FSQRT if possible.
8810       SDValue SqrtOp;
8811       SDValue OtherOp;
8812       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8813         SqrtOp = N1.getOperand(0);
8814         OtherOp = N1.getOperand(1);
8815       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8816         SqrtOp = N1.getOperand(1);
8817         OtherOp = N1.getOperand(0);
8818       }
8819       if (SqrtOp.getNode()) {
8820         // We found a FSQRT, so try to make this fold:
8821         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8822         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8823           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8824           AddToWorklist(RV.getNode());
8825           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8826         }
8827       }
8828     }
8829 
8830     // Fold into a reciprocal estimate and multiply instead of a real divide.
8831     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8832       AddToWorklist(RV.getNode());
8833       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8834     }
8835   }
8836 
8837   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8838   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8839     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8840       // Both can be negated for free, check to see if at least one is cheaper
8841       // negated.
8842       if (LHSNeg == 2 || RHSNeg == 2)
8843         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8844                            GetNegatedExpression(N0, DAG, LegalOperations),
8845                            GetNegatedExpression(N1, DAG, LegalOperations),
8846                            Flags);
8847     }
8848   }
8849 
8850   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8851     return CombineRepeatedDivisors;
8852 
8853   return SDValue();
8854 }
8855 
8856 SDValue DAGCombiner::visitFREM(SDNode *N) {
8857   SDValue N0 = N->getOperand(0);
8858   SDValue N1 = N->getOperand(1);
8859   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8860   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8861   EVT VT = N->getValueType(0);
8862 
8863   // fold (frem c1, c2) -> fmod(c1,c2)
8864   if (N0CFP && N1CFP)
8865     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8866                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8867 
8868   return SDValue();
8869 }
8870 
8871 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8872   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8873     return SDValue();
8874 
8875   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8876   // For now, create a Flags object for use with all unsafe math transforms.
8877   SDNodeFlags Flags;
8878   Flags.setUnsafeAlgebra(true);
8879 
8880   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8881   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8882   if (!RV)
8883     return SDValue();
8884 
8885   EVT VT = RV.getValueType();
8886   SDLoc DL(N);
8887   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8888   AddToWorklist(RV.getNode());
8889 
8890   // Unfortunately, RV is now NaN if the input was exactly 0.
8891   // Select out this case and force the answer to 0.
8892   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8893   EVT CCVT = getSetCCResultType(VT);
8894   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8895   AddToWorklist(ZeroCmp.getNode());
8896   AddToWorklist(RV.getNode());
8897 
8898   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8899                      ZeroCmp, Zero, RV);
8900 }
8901 
8902 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8903 /// copysign(x, fp_round(y)) -> copysign(x, y)
8904 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8905   SDValue N1 = N->getOperand(1);
8906   if ((N1.getOpcode() == ISD::FP_EXTEND ||
8907        N1.getOpcode() == ISD::FP_ROUND)) {
8908     // Do not optimize out type conversion of f128 type yet.
8909     // For some targets like x86_64, configuration is changed to keep one f128
8910     // value in one SSE register, but instruction selection cannot handle
8911     // FCOPYSIGN on SSE registers yet.
8912     EVT N1VT = N1->getValueType(0);
8913     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8914     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8915   }
8916   return false;
8917 }
8918 
8919 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8920   SDValue N0 = N->getOperand(0);
8921   SDValue N1 = N->getOperand(1);
8922   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8923   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8924   EVT VT = N->getValueType(0);
8925 
8926   if (N0CFP && N1CFP)  // Constant fold
8927     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8928 
8929   if (N1CFP) {
8930     const APFloat& V = N1CFP->getValueAPF();
8931     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8932     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8933     if (!V.isNegative()) {
8934       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8935         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8936     } else {
8937       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8938         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8939                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8940     }
8941   }
8942 
8943   // copysign(fabs(x), y) -> copysign(x, y)
8944   // copysign(fneg(x), y) -> copysign(x, y)
8945   // copysign(copysign(x,z), y) -> copysign(x, y)
8946   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8947       N0.getOpcode() == ISD::FCOPYSIGN)
8948     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8949                        N0.getOperand(0), N1);
8950 
8951   // copysign(x, abs(y)) -> abs(x)
8952   if (N1.getOpcode() == ISD::FABS)
8953     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8954 
8955   // copysign(x, copysign(y,z)) -> copysign(x, z)
8956   if (N1.getOpcode() == ISD::FCOPYSIGN)
8957     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8958                        N0, N1.getOperand(1));
8959 
8960   // copysign(x, fp_extend(y)) -> copysign(x, y)
8961   // copysign(x, fp_round(y)) -> copysign(x, y)
8962   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8963     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8964                        N0, N1.getOperand(0));
8965 
8966   return SDValue();
8967 }
8968 
8969 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8970   SDValue N0 = N->getOperand(0);
8971   EVT VT = N->getValueType(0);
8972   EVT OpVT = N0.getValueType();
8973 
8974   // fold (sint_to_fp c1) -> c1fp
8975   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
8976       // ...but only if the target supports immediate floating-point values
8977       (!LegalOperations ||
8978        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8979     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8980 
8981   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8982   // but UINT_TO_FP is legal on this target, try to convert.
8983   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8984       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8985     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8986     if (DAG.SignBitIsZero(N0))
8987       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8988   }
8989 
8990   // The next optimizations are desirable only if SELECT_CC can be lowered.
8991   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8992     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8993     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8994         !VT.isVector() &&
8995         (!LegalOperations ||
8996          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8997       SDLoc DL(N);
8998       SDValue Ops[] =
8999         { N0.getOperand(0), N0.getOperand(1),
9000           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9001           N0.getOperand(2) };
9002       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9003     }
9004 
9005     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9006     //      (select_cc x, y, 1.0, 0.0,, cc)
9007     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9008         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9009         (!LegalOperations ||
9010          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9011       SDLoc DL(N);
9012       SDValue Ops[] =
9013         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9014           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9015           N0.getOperand(0).getOperand(2) };
9016       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9017     }
9018   }
9019 
9020   return SDValue();
9021 }
9022 
9023 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9024   SDValue N0 = N->getOperand(0);
9025   EVT VT = N->getValueType(0);
9026   EVT OpVT = N0.getValueType();
9027 
9028   // fold (uint_to_fp c1) -> c1fp
9029   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9030       // ...but only if the target supports immediate floating-point values
9031       (!LegalOperations ||
9032        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9033     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9034 
9035   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9036   // but SINT_TO_FP is legal on this target, try to convert.
9037   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9038       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9039     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9040     if (DAG.SignBitIsZero(N0))
9041       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9042   }
9043 
9044   // The next optimizations are desirable only if SELECT_CC can be lowered.
9045   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9046     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9047 
9048     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9049         (!LegalOperations ||
9050          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9051       SDLoc DL(N);
9052       SDValue Ops[] =
9053         { N0.getOperand(0), N0.getOperand(1),
9054           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9055           N0.getOperand(2) };
9056       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9057     }
9058   }
9059 
9060   return SDValue();
9061 }
9062 
9063 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9064 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9065   SDValue N0 = N->getOperand(0);
9066   EVT VT = N->getValueType(0);
9067 
9068   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9069     return SDValue();
9070 
9071   SDValue Src = N0.getOperand(0);
9072   EVT SrcVT = Src.getValueType();
9073   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9074   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9075 
9076   // We can safely assume the conversion won't overflow the output range,
9077   // because (for example) (uint8_t)18293.f is undefined behavior.
9078 
9079   // Since we can assume the conversion won't overflow, our decision as to
9080   // whether the input will fit in the float should depend on the minimum
9081   // of the input range and output range.
9082 
9083   // This means this is also safe for a signed input and unsigned output, since
9084   // a negative input would lead to undefined behavior.
9085   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9086   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9087   unsigned ActualSize = std::min(InputSize, OutputSize);
9088   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9089 
9090   // We can only fold away the float conversion if the input range can be
9091   // represented exactly in the float range.
9092   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9093     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9094       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9095                                                        : ISD::ZERO_EXTEND;
9096       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9097     }
9098     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9099       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9100     return DAG.getBitcast(VT, Src);
9101   }
9102   return SDValue();
9103 }
9104 
9105 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9106   SDValue N0 = N->getOperand(0);
9107   EVT VT = N->getValueType(0);
9108 
9109   // fold (fp_to_sint c1fp) -> c1
9110   if (isConstantFPBuildVectorOrConstantFP(N0))
9111     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9112 
9113   return FoldIntToFPToInt(N, DAG);
9114 }
9115 
9116 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9117   SDValue N0 = N->getOperand(0);
9118   EVT VT = N->getValueType(0);
9119 
9120   // fold (fp_to_uint c1fp) -> c1
9121   if (isConstantFPBuildVectorOrConstantFP(N0))
9122     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9123 
9124   return FoldIntToFPToInt(N, DAG);
9125 }
9126 
9127 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9128   SDValue N0 = N->getOperand(0);
9129   SDValue N1 = N->getOperand(1);
9130   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9131   EVT VT = N->getValueType(0);
9132 
9133   // fold (fp_round c1fp) -> c1fp
9134   if (N0CFP)
9135     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9136 
9137   // fold (fp_round (fp_extend x)) -> x
9138   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9139     return N0.getOperand(0);
9140 
9141   // fold (fp_round (fp_round x)) -> (fp_round x)
9142   if (N0.getOpcode() == ISD::FP_ROUND) {
9143     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9144     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9145 
9146     // Skip this folding if it results in an fp_round from f80 to f16.
9147     //
9148     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9149     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9150     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9151     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9152     // x86.
9153     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9154       return SDValue();
9155 
9156     // If the first fp_round isn't a value preserving truncation, it might
9157     // introduce a tie in the second fp_round, that wouldn't occur in the
9158     // single-step fp_round we want to fold to.
9159     // In other words, double rounding isn't the same as rounding.
9160     // Also, this is a value preserving truncation iff both fp_round's are.
9161     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9162       SDLoc DL(N);
9163       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9164                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9165     }
9166   }
9167 
9168   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9169   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9170     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9171                               N0.getOperand(0), N1);
9172     AddToWorklist(Tmp.getNode());
9173     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9174                        Tmp, N0.getOperand(1));
9175   }
9176 
9177   return SDValue();
9178 }
9179 
9180 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9181   SDValue N0 = N->getOperand(0);
9182   EVT VT = N->getValueType(0);
9183   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9184   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9185 
9186   // fold (fp_round_inreg c1fp) -> c1fp
9187   if (N0CFP && isTypeLegal(EVT)) {
9188     SDLoc DL(N);
9189     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9190     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9191   }
9192 
9193   return SDValue();
9194 }
9195 
9196 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9197   SDValue N0 = N->getOperand(0);
9198   EVT VT = N->getValueType(0);
9199 
9200   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9201   if (N->hasOneUse() &&
9202       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9203     return SDValue();
9204 
9205   // fold (fp_extend c1fp) -> c1fp
9206   if (isConstantFPBuildVectorOrConstantFP(N0))
9207     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9208 
9209   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9210   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9211       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9212     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9213 
9214   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9215   // value of X.
9216   if (N0.getOpcode() == ISD::FP_ROUND
9217       && N0.getNode()->getConstantOperandVal(1) == 1) {
9218     SDValue In = N0.getOperand(0);
9219     if (In.getValueType() == VT) return In;
9220     if (VT.bitsLT(In.getValueType()))
9221       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9222                          In, N0.getOperand(1));
9223     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9224   }
9225 
9226   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9227   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9228        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9229     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9230     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9231                                      LN0->getChain(),
9232                                      LN0->getBasePtr(), N0.getValueType(),
9233                                      LN0->getMemOperand());
9234     CombineTo(N, ExtLoad);
9235     CombineTo(N0.getNode(),
9236               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9237                           N0.getValueType(), ExtLoad,
9238                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9239               ExtLoad.getValue(1));
9240     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9241   }
9242 
9243   return SDValue();
9244 }
9245 
9246 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9247   SDValue N0 = N->getOperand(0);
9248   EVT VT = N->getValueType(0);
9249 
9250   // fold (fceil c1) -> fceil(c1)
9251   if (isConstantFPBuildVectorOrConstantFP(N0))
9252     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9253 
9254   return SDValue();
9255 }
9256 
9257 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9258   SDValue N0 = N->getOperand(0);
9259   EVT VT = N->getValueType(0);
9260 
9261   // fold (ftrunc c1) -> ftrunc(c1)
9262   if (isConstantFPBuildVectorOrConstantFP(N0))
9263     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9264 
9265   return SDValue();
9266 }
9267 
9268 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9269   SDValue N0 = N->getOperand(0);
9270   EVT VT = N->getValueType(0);
9271 
9272   // fold (ffloor c1) -> ffloor(c1)
9273   if (isConstantFPBuildVectorOrConstantFP(N0))
9274     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9275 
9276   return SDValue();
9277 }
9278 
9279 // FIXME: FNEG and FABS have a lot in common; refactor.
9280 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9281   SDValue N0 = N->getOperand(0);
9282   EVT VT = N->getValueType(0);
9283 
9284   // Constant fold FNEG.
9285   if (isConstantFPBuildVectorOrConstantFP(N0))
9286     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9287 
9288   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9289                          &DAG.getTarget().Options))
9290     return GetNegatedExpression(N0, DAG, LegalOperations);
9291 
9292   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9293   // constant pool values.
9294   if (!TLI.isFNegFree(VT) &&
9295       N0.getOpcode() == ISD::BITCAST &&
9296       N0.getNode()->hasOneUse()) {
9297     SDValue Int = N0.getOperand(0);
9298     EVT IntVT = Int.getValueType();
9299     if (IntVT.isInteger() && !IntVT.isVector()) {
9300       APInt SignMask;
9301       if (N0.getValueType().isVector()) {
9302         // For a vector, get a mask such as 0x80... per scalar element
9303         // and splat it.
9304         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9305         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9306       } else {
9307         // For a scalar, just generate 0x80...
9308         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9309       }
9310       SDLoc DL0(N0);
9311       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9312                         DAG.getConstant(SignMask, DL0, IntVT));
9313       AddToWorklist(Int.getNode());
9314       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9315     }
9316   }
9317 
9318   // (fneg (fmul c, x)) -> (fmul -c, x)
9319   if (N0.getOpcode() == ISD::FMUL &&
9320       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9321     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9322     if (CFP1) {
9323       APFloat CVal = CFP1->getValueAPF();
9324       CVal.changeSign();
9325       if (Level >= AfterLegalizeDAG &&
9326           (TLI.isFPImmLegal(CVal, VT) ||
9327            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9328         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9329                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9330                                        N0.getOperand(1)),
9331                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9332     }
9333   }
9334 
9335   return SDValue();
9336 }
9337 
9338 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9339   SDValue N0 = N->getOperand(0);
9340   SDValue N1 = N->getOperand(1);
9341   EVT VT = N->getValueType(0);
9342   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9343   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9344 
9345   if (N0CFP && N1CFP) {
9346     const APFloat &C0 = N0CFP->getValueAPF();
9347     const APFloat &C1 = N1CFP->getValueAPF();
9348     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9349   }
9350 
9351   // Canonicalize to constant on RHS.
9352   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9353      !isConstantFPBuildVectorOrConstantFP(N1))
9354     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9355 
9356   return SDValue();
9357 }
9358 
9359 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9360   SDValue N0 = N->getOperand(0);
9361   SDValue N1 = N->getOperand(1);
9362   EVT VT = N->getValueType(0);
9363   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9364   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9365 
9366   if (N0CFP && N1CFP) {
9367     const APFloat &C0 = N0CFP->getValueAPF();
9368     const APFloat &C1 = N1CFP->getValueAPF();
9369     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9370   }
9371 
9372   // Canonicalize to constant on RHS.
9373   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9374      !isConstantFPBuildVectorOrConstantFP(N1))
9375     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9376 
9377   return SDValue();
9378 }
9379 
9380 SDValue DAGCombiner::visitFABS(SDNode *N) {
9381   SDValue N0 = N->getOperand(0);
9382   EVT VT = N->getValueType(0);
9383 
9384   // fold (fabs c1) -> fabs(c1)
9385   if (isConstantFPBuildVectorOrConstantFP(N0))
9386     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9387 
9388   // fold (fabs (fabs x)) -> (fabs x)
9389   if (N0.getOpcode() == ISD::FABS)
9390     return N->getOperand(0);
9391 
9392   // fold (fabs (fneg x)) -> (fabs x)
9393   // fold (fabs (fcopysign x, y)) -> (fabs x)
9394   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9395     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9396 
9397   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9398   // constant pool values.
9399   if (!TLI.isFAbsFree(VT) &&
9400       N0.getOpcode() == ISD::BITCAST &&
9401       N0.getNode()->hasOneUse()) {
9402     SDValue Int = N0.getOperand(0);
9403     EVT IntVT = Int.getValueType();
9404     if (IntVT.isInteger() && !IntVT.isVector()) {
9405       APInt SignMask;
9406       if (N0.getValueType().isVector()) {
9407         // For a vector, get a mask such as 0x7f... per scalar element
9408         // and splat it.
9409         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9410         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9411       } else {
9412         // For a scalar, just generate 0x7f...
9413         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9414       }
9415       SDLoc DL(N0);
9416       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9417                         DAG.getConstant(SignMask, DL, IntVT));
9418       AddToWorklist(Int.getNode());
9419       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9420     }
9421   }
9422 
9423   return SDValue();
9424 }
9425 
9426 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9427   SDValue Chain = N->getOperand(0);
9428   SDValue N1 = N->getOperand(1);
9429   SDValue N2 = N->getOperand(2);
9430 
9431   // If N is a constant we could fold this into a fallthrough or unconditional
9432   // branch. However that doesn't happen very often in normal code, because
9433   // Instcombine/SimplifyCFG should have handled the available opportunities.
9434   // If we did this folding here, it would be necessary to update the
9435   // MachineBasicBlock CFG, which is awkward.
9436 
9437   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9438   // on the target.
9439   if (N1.getOpcode() == ISD::SETCC &&
9440       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9441                                    N1.getOperand(0).getValueType())) {
9442     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9443                        Chain, N1.getOperand(2),
9444                        N1.getOperand(0), N1.getOperand(1), N2);
9445   }
9446 
9447   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9448       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9449        (N1.getOperand(0).hasOneUse() &&
9450         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9451     SDNode *Trunc = nullptr;
9452     if (N1.getOpcode() == ISD::TRUNCATE) {
9453       // Look pass the truncate.
9454       Trunc = N1.getNode();
9455       N1 = N1.getOperand(0);
9456     }
9457 
9458     // Match this pattern so that we can generate simpler code:
9459     //
9460     //   %a = ...
9461     //   %b = and i32 %a, 2
9462     //   %c = srl i32 %b, 1
9463     //   brcond i32 %c ...
9464     //
9465     // into
9466     //
9467     //   %a = ...
9468     //   %b = and i32 %a, 2
9469     //   %c = setcc eq %b, 0
9470     //   brcond %c ...
9471     //
9472     // This applies only when the AND constant value has one bit set and the
9473     // SRL constant is equal to the log2 of the AND constant. The back-end is
9474     // smart enough to convert the result into a TEST/JMP sequence.
9475     SDValue Op0 = N1.getOperand(0);
9476     SDValue Op1 = N1.getOperand(1);
9477 
9478     if (Op0.getOpcode() == ISD::AND &&
9479         Op1.getOpcode() == ISD::Constant) {
9480       SDValue AndOp1 = Op0.getOperand(1);
9481 
9482       if (AndOp1.getOpcode() == ISD::Constant) {
9483         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9484 
9485         if (AndConst.isPowerOf2() &&
9486             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9487           SDLoc DL(N);
9488           SDValue SetCC =
9489             DAG.getSetCC(DL,
9490                          getSetCCResultType(Op0.getValueType()),
9491                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9492                          ISD::SETNE);
9493 
9494           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9495                                           MVT::Other, Chain, SetCC, N2);
9496           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9497           // will convert it back to (X & C1) >> C2.
9498           CombineTo(N, NewBRCond, false);
9499           // Truncate is dead.
9500           if (Trunc)
9501             deleteAndRecombine(Trunc);
9502           // Replace the uses of SRL with SETCC
9503           WorklistRemover DeadNodes(*this);
9504           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9505           deleteAndRecombine(N1.getNode());
9506           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9507         }
9508       }
9509     }
9510 
9511     if (Trunc)
9512       // Restore N1 if the above transformation doesn't match.
9513       N1 = N->getOperand(1);
9514   }
9515 
9516   // Transform br(xor(x, y)) -> br(x != y)
9517   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9518   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9519     SDNode *TheXor = N1.getNode();
9520     SDValue Op0 = TheXor->getOperand(0);
9521     SDValue Op1 = TheXor->getOperand(1);
9522     if (Op0.getOpcode() == Op1.getOpcode()) {
9523       // Avoid missing important xor optimizations.
9524       if (SDValue Tmp = visitXOR(TheXor)) {
9525         if (Tmp.getNode() != TheXor) {
9526           DEBUG(dbgs() << "\nReplacing.8 ";
9527                 TheXor->dump(&DAG);
9528                 dbgs() << "\nWith: ";
9529                 Tmp.getNode()->dump(&DAG);
9530                 dbgs() << '\n');
9531           WorklistRemover DeadNodes(*this);
9532           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9533           deleteAndRecombine(TheXor);
9534           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9535                              MVT::Other, Chain, Tmp, N2);
9536         }
9537 
9538         // visitXOR has changed XOR's operands or replaced the XOR completely,
9539         // bail out.
9540         return SDValue(N, 0);
9541       }
9542     }
9543 
9544     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9545       bool Equal = false;
9546       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9547           Op0.getOpcode() == ISD::XOR) {
9548         TheXor = Op0.getNode();
9549         Equal = true;
9550       }
9551 
9552       EVT SetCCVT = N1.getValueType();
9553       if (LegalTypes)
9554         SetCCVT = getSetCCResultType(SetCCVT);
9555       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9556                                    SetCCVT,
9557                                    Op0, Op1,
9558                                    Equal ? ISD::SETEQ : ISD::SETNE);
9559       // Replace the uses of XOR with SETCC
9560       WorklistRemover DeadNodes(*this);
9561       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9562       deleteAndRecombine(N1.getNode());
9563       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9564                          MVT::Other, Chain, SetCC, N2);
9565     }
9566   }
9567 
9568   return SDValue();
9569 }
9570 
9571 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9572 //
9573 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9574   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9575   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9576 
9577   // If N is a constant we could fold this into a fallthrough or unconditional
9578   // branch. However that doesn't happen very often in normal code, because
9579   // Instcombine/SimplifyCFG should have handled the available opportunities.
9580   // If we did this folding here, it would be necessary to update the
9581   // MachineBasicBlock CFG, which is awkward.
9582 
9583   // Use SimplifySetCC to simplify SETCC's.
9584   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9585                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9586                                false);
9587   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9588 
9589   // fold to a simpler setcc
9590   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9591     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9592                        N->getOperand(0), Simp.getOperand(2),
9593                        Simp.getOperand(0), Simp.getOperand(1),
9594                        N->getOperand(4));
9595 
9596   return SDValue();
9597 }
9598 
9599 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9600 /// and that N may be folded in the load / store addressing mode.
9601 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9602                                     SelectionDAG &DAG,
9603                                     const TargetLowering &TLI) {
9604   EVT VT;
9605   unsigned AS;
9606 
9607   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9608     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9609       return false;
9610     VT = LD->getMemoryVT();
9611     AS = LD->getAddressSpace();
9612   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9613     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9614       return false;
9615     VT = ST->getMemoryVT();
9616     AS = ST->getAddressSpace();
9617   } else
9618     return false;
9619 
9620   TargetLowering::AddrMode AM;
9621   if (N->getOpcode() == ISD::ADD) {
9622     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9623     if (Offset)
9624       // [reg +/- imm]
9625       AM.BaseOffs = Offset->getSExtValue();
9626     else
9627       // [reg +/- reg]
9628       AM.Scale = 1;
9629   } else if (N->getOpcode() == ISD::SUB) {
9630     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9631     if (Offset)
9632       // [reg +/- imm]
9633       AM.BaseOffs = -Offset->getSExtValue();
9634     else
9635       // [reg +/- reg]
9636       AM.Scale = 1;
9637   } else
9638     return false;
9639 
9640   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9641                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9642 }
9643 
9644 /// Try turning a load/store into a pre-indexed load/store when the base
9645 /// pointer is an add or subtract and it has other uses besides the load/store.
9646 /// After the transformation, the new indexed load/store has effectively folded
9647 /// the add/subtract in and all of its other uses are redirected to the
9648 /// new load/store.
9649 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9650   if (Level < AfterLegalizeDAG)
9651     return false;
9652 
9653   bool isLoad = true;
9654   SDValue Ptr;
9655   EVT VT;
9656   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9657     if (LD->isIndexed())
9658       return false;
9659     VT = LD->getMemoryVT();
9660     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9661         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9662       return false;
9663     Ptr = LD->getBasePtr();
9664   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9665     if (ST->isIndexed())
9666       return false;
9667     VT = ST->getMemoryVT();
9668     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9669         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9670       return false;
9671     Ptr = ST->getBasePtr();
9672     isLoad = false;
9673   } else {
9674     return false;
9675   }
9676 
9677   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9678   // out.  There is no reason to make this a preinc/predec.
9679   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9680       Ptr.getNode()->hasOneUse())
9681     return false;
9682 
9683   // Ask the target to do addressing mode selection.
9684   SDValue BasePtr;
9685   SDValue Offset;
9686   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9687   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9688     return false;
9689 
9690   // Backends without true r+i pre-indexed forms may need to pass a
9691   // constant base with a variable offset so that constant coercion
9692   // will work with the patterns in canonical form.
9693   bool Swapped = false;
9694   if (isa<ConstantSDNode>(BasePtr)) {
9695     std::swap(BasePtr, Offset);
9696     Swapped = true;
9697   }
9698 
9699   // Don't create a indexed load / store with zero offset.
9700   if (isNullConstant(Offset))
9701     return false;
9702 
9703   // Try turning it into a pre-indexed load / store except when:
9704   // 1) The new base ptr is a frame index.
9705   // 2) If N is a store and the new base ptr is either the same as or is a
9706   //    predecessor of the value being stored.
9707   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9708   //    that would create a cycle.
9709   // 4) All uses are load / store ops that use it as old base ptr.
9710 
9711   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9712   // (plus the implicit offset) to a register to preinc anyway.
9713   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9714     return false;
9715 
9716   // Check #2.
9717   if (!isLoad) {
9718     SDValue Val = cast<StoreSDNode>(N)->getValue();
9719     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9720       return false;
9721   }
9722 
9723   // Caches for hasPredecessorHelper.
9724   SmallPtrSet<const SDNode *, 32> Visited;
9725   SmallVector<const SDNode *, 16> Worklist;
9726   Worklist.push_back(N);
9727 
9728   // If the offset is a constant, there may be other adds of constants that
9729   // can be folded with this one. We should do this to avoid having to keep
9730   // a copy of the original base pointer.
9731   SmallVector<SDNode *, 16> OtherUses;
9732   if (isa<ConstantSDNode>(Offset))
9733     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9734                               UE = BasePtr.getNode()->use_end();
9735          UI != UE; ++UI) {
9736       SDUse &Use = UI.getUse();
9737       // Skip the use that is Ptr and uses of other results from BasePtr's
9738       // node (important for nodes that return multiple results).
9739       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9740         continue;
9741 
9742       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9743         continue;
9744 
9745       if (Use.getUser()->getOpcode() != ISD::ADD &&
9746           Use.getUser()->getOpcode() != ISD::SUB) {
9747         OtherUses.clear();
9748         break;
9749       }
9750 
9751       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9752       if (!isa<ConstantSDNode>(Op1)) {
9753         OtherUses.clear();
9754         break;
9755       }
9756 
9757       // FIXME: In some cases, we can be smarter about this.
9758       if (Op1.getValueType() != Offset.getValueType()) {
9759         OtherUses.clear();
9760         break;
9761       }
9762 
9763       OtherUses.push_back(Use.getUser());
9764     }
9765 
9766   if (Swapped)
9767     std::swap(BasePtr, Offset);
9768 
9769   // Now check for #3 and #4.
9770   bool RealUse = false;
9771 
9772   for (SDNode *Use : Ptr.getNode()->uses()) {
9773     if (Use == N)
9774       continue;
9775     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9776       return false;
9777 
9778     // If Ptr may be folded in addressing mode of other use, then it's
9779     // not profitable to do this transformation.
9780     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9781       RealUse = true;
9782   }
9783 
9784   if (!RealUse)
9785     return false;
9786 
9787   SDValue Result;
9788   if (isLoad)
9789     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9790                                 BasePtr, Offset, AM);
9791   else
9792     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9793                                  BasePtr, Offset, AM);
9794   ++PreIndexedNodes;
9795   ++NodesCombined;
9796   DEBUG(dbgs() << "\nReplacing.4 ";
9797         N->dump(&DAG);
9798         dbgs() << "\nWith: ";
9799         Result.getNode()->dump(&DAG);
9800         dbgs() << '\n');
9801   WorklistRemover DeadNodes(*this);
9802   if (isLoad) {
9803     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9804     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9805   } else {
9806     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9807   }
9808 
9809   // Finally, since the node is now dead, remove it from the graph.
9810   deleteAndRecombine(N);
9811 
9812   if (Swapped)
9813     std::swap(BasePtr, Offset);
9814 
9815   // Replace other uses of BasePtr that can be updated to use Ptr
9816   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9817     unsigned OffsetIdx = 1;
9818     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9819       OffsetIdx = 0;
9820     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9821            BasePtr.getNode() && "Expected BasePtr operand");
9822 
9823     // We need to replace ptr0 in the following expression:
9824     //   x0 * offset0 + y0 * ptr0 = t0
9825     // knowing that
9826     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9827     //
9828     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9829     // indexed load/store and the expresion that needs to be re-written.
9830     //
9831     // Therefore, we have:
9832     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9833 
9834     ConstantSDNode *CN =
9835       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9836     int X0, X1, Y0, Y1;
9837     APInt Offset0 = CN->getAPIntValue();
9838     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9839 
9840     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9841     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9842     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9843     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9844 
9845     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9846 
9847     APInt CNV = Offset0;
9848     if (X0 < 0) CNV = -CNV;
9849     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9850     else CNV = CNV - Offset1;
9851 
9852     SDLoc DL(OtherUses[i]);
9853 
9854     // We can now generate the new expression.
9855     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9856     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9857 
9858     SDValue NewUse = DAG.getNode(Opcode,
9859                                  DL,
9860                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9861     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9862     deleteAndRecombine(OtherUses[i]);
9863   }
9864 
9865   // Replace the uses of Ptr with uses of the updated base value.
9866   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9867   deleteAndRecombine(Ptr.getNode());
9868 
9869   return true;
9870 }
9871 
9872 /// Try to combine a load/store with a add/sub of the base pointer node into a
9873 /// post-indexed load/store. The transformation folded the add/subtract into the
9874 /// new indexed load/store effectively and all of its uses are redirected to the
9875 /// new load/store.
9876 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9877   if (Level < AfterLegalizeDAG)
9878     return false;
9879 
9880   bool isLoad = true;
9881   SDValue Ptr;
9882   EVT VT;
9883   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9884     if (LD->isIndexed())
9885       return false;
9886     VT = LD->getMemoryVT();
9887     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9888         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9889       return false;
9890     Ptr = LD->getBasePtr();
9891   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9892     if (ST->isIndexed())
9893       return false;
9894     VT = ST->getMemoryVT();
9895     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9896         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9897       return false;
9898     Ptr = ST->getBasePtr();
9899     isLoad = false;
9900   } else {
9901     return false;
9902   }
9903 
9904   if (Ptr.getNode()->hasOneUse())
9905     return false;
9906 
9907   for (SDNode *Op : Ptr.getNode()->uses()) {
9908     if (Op == N ||
9909         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9910       continue;
9911 
9912     SDValue BasePtr;
9913     SDValue Offset;
9914     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9915     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9916       // Don't create a indexed load / store with zero offset.
9917       if (isNullConstant(Offset))
9918         continue;
9919 
9920       // Try turning it into a post-indexed load / store except when
9921       // 1) All uses are load / store ops that use it as base ptr (and
9922       //    it may be folded as addressing mmode).
9923       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9924       //    nor a successor of N. Otherwise, if Op is folded that would
9925       //    create a cycle.
9926 
9927       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9928         continue;
9929 
9930       // Check for #1.
9931       bool TryNext = false;
9932       for (SDNode *Use : BasePtr.getNode()->uses()) {
9933         if (Use == Ptr.getNode())
9934           continue;
9935 
9936         // If all the uses are load / store addresses, then don't do the
9937         // transformation.
9938         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9939           bool RealUse = false;
9940           for (SDNode *UseUse : Use->uses()) {
9941             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9942               RealUse = true;
9943           }
9944 
9945           if (!RealUse) {
9946             TryNext = true;
9947             break;
9948           }
9949         }
9950       }
9951 
9952       if (TryNext)
9953         continue;
9954 
9955       // Check for #2
9956       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9957         SDValue Result = isLoad
9958           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9959                                BasePtr, Offset, AM)
9960           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9961                                 BasePtr, Offset, AM);
9962         ++PostIndexedNodes;
9963         ++NodesCombined;
9964         DEBUG(dbgs() << "\nReplacing.5 ";
9965               N->dump(&DAG);
9966               dbgs() << "\nWith: ";
9967               Result.getNode()->dump(&DAG);
9968               dbgs() << '\n');
9969         WorklistRemover DeadNodes(*this);
9970         if (isLoad) {
9971           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9972           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9973         } else {
9974           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9975         }
9976 
9977         // Finally, since the node is now dead, remove it from the graph.
9978         deleteAndRecombine(N);
9979 
9980         // Replace the uses of Use with uses of the updated base value.
9981         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9982                                       Result.getValue(isLoad ? 1 : 0));
9983         deleteAndRecombine(Op);
9984         return true;
9985       }
9986     }
9987   }
9988 
9989   return false;
9990 }
9991 
9992 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9993 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9994   ISD::MemIndexedMode AM = LD->getAddressingMode();
9995   assert(AM != ISD::UNINDEXED);
9996   SDValue BP = LD->getOperand(1);
9997   SDValue Inc = LD->getOperand(2);
9998 
9999   // Some backends use TargetConstants for load offsets, but don't expect
10000   // TargetConstants in general ADD nodes. We can convert these constants into
10001   // regular Constants (if the constant is not opaque).
10002   assert((Inc.getOpcode() != ISD::TargetConstant ||
10003           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10004          "Cannot split out indexing using opaque target constants");
10005   if (Inc.getOpcode() == ISD::TargetConstant) {
10006     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10007     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10008                           ConstInc->getValueType(0));
10009   }
10010 
10011   unsigned Opc =
10012       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10013   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10014 }
10015 
10016 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10017   LoadSDNode *LD  = cast<LoadSDNode>(N);
10018   SDValue Chain = LD->getChain();
10019   SDValue Ptr   = LD->getBasePtr();
10020 
10021   // If load is not volatile and there are no uses of the loaded value (and
10022   // the updated indexed value in case of indexed loads), change uses of the
10023   // chain value into uses of the chain input (i.e. delete the dead load).
10024   if (!LD->isVolatile()) {
10025     if (N->getValueType(1) == MVT::Other) {
10026       // Unindexed loads.
10027       if (!N->hasAnyUseOfValue(0)) {
10028         // It's not safe to use the two value CombineTo variant here. e.g.
10029         // v1, chain2 = load chain1, loc
10030         // v2, chain3 = load chain2, loc
10031         // v3         = add v2, c
10032         // Now we replace use of chain2 with chain1.  This makes the second load
10033         // isomorphic to the one we are deleting, and thus makes this load live.
10034         DEBUG(dbgs() << "\nReplacing.6 ";
10035               N->dump(&DAG);
10036               dbgs() << "\nWith chain: ";
10037               Chain.getNode()->dump(&DAG);
10038               dbgs() << "\n");
10039         WorklistRemover DeadNodes(*this);
10040         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10041 
10042         if (N->use_empty())
10043           deleteAndRecombine(N);
10044 
10045         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10046       }
10047     } else {
10048       // Indexed loads.
10049       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10050 
10051       // If this load has an opaque TargetConstant offset, then we cannot split
10052       // the indexing into an add/sub directly (that TargetConstant may not be
10053       // valid for a different type of node, and we cannot convert an opaque
10054       // target constant into a regular constant).
10055       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10056                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10057 
10058       if (!N->hasAnyUseOfValue(0) &&
10059           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10060         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10061         SDValue Index;
10062         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10063           Index = SplitIndexingFromLoad(LD);
10064           // Try to fold the base pointer arithmetic into subsequent loads and
10065           // stores.
10066           AddUsersToWorklist(N);
10067         } else
10068           Index = DAG.getUNDEF(N->getValueType(1));
10069         DEBUG(dbgs() << "\nReplacing.7 ";
10070               N->dump(&DAG);
10071               dbgs() << "\nWith: ";
10072               Undef.getNode()->dump(&DAG);
10073               dbgs() << " and 2 other values\n");
10074         WorklistRemover DeadNodes(*this);
10075         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10076         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10077         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10078         deleteAndRecombine(N);
10079         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10080       }
10081     }
10082   }
10083 
10084   // If this load is directly stored, replace the load value with the stored
10085   // value.
10086   // TODO: Handle store large -> read small portion.
10087   // TODO: Handle TRUNCSTORE/LOADEXT
10088   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10089     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10090       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10091       if (PrevST->getBasePtr() == Ptr &&
10092           PrevST->getValue().getValueType() == N->getValueType(0))
10093       return CombineTo(N, Chain.getOperand(1), Chain);
10094     }
10095   }
10096 
10097   // Try to infer better alignment information than the load already has.
10098   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10099     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10100       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10101         SDValue NewLoad =
10102                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
10103                               LD->getValueType(0),
10104                               Chain, Ptr, LD->getPointerInfo(),
10105                               LD->getMemoryVT(),
10106                               LD->isVolatile(), LD->isNonTemporal(),
10107                               LD->isInvariant(), Align, LD->getAAInfo());
10108         if (NewLoad.getNode() != N)
10109           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10110       }
10111     }
10112   }
10113 
10114   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10115                                                   : DAG.getSubtarget().useAA();
10116 #ifndef NDEBUG
10117   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10118       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10119     UseAA = false;
10120 #endif
10121   if (UseAA && LD->isUnindexed()) {
10122     // Walk up chain skipping non-aliasing memory nodes.
10123     SDValue BetterChain = FindBetterChain(N, Chain);
10124 
10125     // If there is a better chain.
10126     if (Chain != BetterChain) {
10127       SDValue ReplLoad;
10128 
10129       // Replace the chain to void dependency.
10130       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10131         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10132                                BetterChain, Ptr, LD->getMemOperand());
10133       } else {
10134         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10135                                   LD->getValueType(0),
10136                                   BetterChain, Ptr, LD->getMemoryVT(),
10137                                   LD->getMemOperand());
10138       }
10139 
10140       // Create token factor to keep old chain connected.
10141       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10142                                   MVT::Other, Chain, ReplLoad.getValue(1));
10143 
10144       // Make sure the new and old chains are cleaned up.
10145       AddToWorklist(Token.getNode());
10146 
10147       // Replace uses with load result and token factor. Don't add users
10148       // to work list.
10149       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10150     }
10151   }
10152 
10153   // Try transforming N to an indexed load.
10154   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10155     return SDValue(N, 0);
10156 
10157   // Try to slice up N to more direct loads if the slices are mapped to
10158   // different register banks or pairing can take place.
10159   if (SliceUpLoad(N))
10160     return SDValue(N, 0);
10161 
10162   return SDValue();
10163 }
10164 
10165 namespace {
10166 /// \brief Helper structure used to slice a load in smaller loads.
10167 /// Basically a slice is obtained from the following sequence:
10168 /// Origin = load Ty1, Base
10169 /// Shift = srl Ty1 Origin, CstTy Amount
10170 /// Inst = trunc Shift to Ty2
10171 ///
10172 /// Then, it will be rewriten into:
10173 /// Slice = load SliceTy, Base + SliceOffset
10174 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10175 ///
10176 /// SliceTy is deduced from the number of bits that are actually used to
10177 /// build Inst.
10178 struct LoadedSlice {
10179   /// \brief Helper structure used to compute the cost of a slice.
10180   struct Cost {
10181     /// Are we optimizing for code size.
10182     bool ForCodeSize;
10183     /// Various cost.
10184     unsigned Loads;
10185     unsigned Truncates;
10186     unsigned CrossRegisterBanksCopies;
10187     unsigned ZExts;
10188     unsigned Shift;
10189 
10190     Cost(bool ForCodeSize = false)
10191         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10192           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10193 
10194     /// \brief Get the cost of one isolated slice.
10195     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10196         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10197           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10198       EVT TruncType = LS.Inst->getValueType(0);
10199       EVT LoadedType = LS.getLoadedType();
10200       if (TruncType != LoadedType &&
10201           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10202         ZExts = 1;
10203     }
10204 
10205     /// \brief Account for slicing gain in the current cost.
10206     /// Slicing provide a few gains like removing a shift or a
10207     /// truncate. This method allows to grow the cost of the original
10208     /// load with the gain from this slice.
10209     void addSliceGain(const LoadedSlice &LS) {
10210       // Each slice saves a truncate.
10211       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10212       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10213                               LS.Inst->getValueType(0)))
10214         ++Truncates;
10215       // If there is a shift amount, this slice gets rid of it.
10216       if (LS.Shift)
10217         ++Shift;
10218       // If this slice can merge a cross register bank copy, account for it.
10219       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10220         ++CrossRegisterBanksCopies;
10221     }
10222 
10223     Cost &operator+=(const Cost &RHS) {
10224       Loads += RHS.Loads;
10225       Truncates += RHS.Truncates;
10226       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10227       ZExts += RHS.ZExts;
10228       Shift += RHS.Shift;
10229       return *this;
10230     }
10231 
10232     bool operator==(const Cost &RHS) const {
10233       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10234              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10235              ZExts == RHS.ZExts && Shift == RHS.Shift;
10236     }
10237 
10238     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10239 
10240     bool operator<(const Cost &RHS) const {
10241       // Assume cross register banks copies are as expensive as loads.
10242       // FIXME: Do we want some more target hooks?
10243       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10244       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10245       // Unless we are optimizing for code size, consider the
10246       // expensive operation first.
10247       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10248         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10249       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10250              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10251     }
10252 
10253     bool operator>(const Cost &RHS) const { return RHS < *this; }
10254 
10255     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10256 
10257     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10258   };
10259   // The last instruction that represent the slice. This should be a
10260   // truncate instruction.
10261   SDNode *Inst;
10262   // The original load instruction.
10263   LoadSDNode *Origin;
10264   // The right shift amount in bits from the original load.
10265   unsigned Shift;
10266   // The DAG from which Origin came from.
10267   // This is used to get some contextual information about legal types, etc.
10268   SelectionDAG *DAG;
10269 
10270   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10271               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10272       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10273 
10274   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10275   /// \return Result is \p BitWidth and has used bits set to 1 and
10276   ///         not used bits set to 0.
10277   APInt getUsedBits() const {
10278     // Reproduce the trunc(lshr) sequence:
10279     // - Start from the truncated value.
10280     // - Zero extend to the desired bit width.
10281     // - Shift left.
10282     assert(Origin && "No original load to compare against.");
10283     unsigned BitWidth = Origin->getValueSizeInBits(0);
10284     assert(Inst && "This slice is not bound to an instruction");
10285     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10286            "Extracted slice is bigger than the whole type!");
10287     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10288     UsedBits.setAllBits();
10289     UsedBits = UsedBits.zext(BitWidth);
10290     UsedBits <<= Shift;
10291     return UsedBits;
10292   }
10293 
10294   /// \brief Get the size of the slice to be loaded in bytes.
10295   unsigned getLoadedSize() const {
10296     unsigned SliceSize = getUsedBits().countPopulation();
10297     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10298     return SliceSize / 8;
10299   }
10300 
10301   /// \brief Get the type that will be loaded for this slice.
10302   /// Note: This may not be the final type for the slice.
10303   EVT getLoadedType() const {
10304     assert(DAG && "Missing context");
10305     LLVMContext &Ctxt = *DAG->getContext();
10306     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10307   }
10308 
10309   /// \brief Get the alignment of the load used for this slice.
10310   unsigned getAlignment() const {
10311     unsigned Alignment = Origin->getAlignment();
10312     unsigned Offset = getOffsetFromBase();
10313     if (Offset != 0)
10314       Alignment = MinAlign(Alignment, Alignment + Offset);
10315     return Alignment;
10316   }
10317 
10318   /// \brief Check if this slice can be rewritten with legal operations.
10319   bool isLegal() const {
10320     // An invalid slice is not legal.
10321     if (!Origin || !Inst || !DAG)
10322       return false;
10323 
10324     // Offsets are for indexed load only, we do not handle that.
10325     if (!Origin->getOffset().isUndef())
10326       return false;
10327 
10328     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10329 
10330     // Check that the type is legal.
10331     EVT SliceType = getLoadedType();
10332     if (!TLI.isTypeLegal(SliceType))
10333       return false;
10334 
10335     // Check that the load is legal for this type.
10336     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10337       return false;
10338 
10339     // Check that the offset can be computed.
10340     // 1. Check its type.
10341     EVT PtrType = Origin->getBasePtr().getValueType();
10342     if (PtrType == MVT::Untyped || PtrType.isExtended())
10343       return false;
10344 
10345     // 2. Check that it fits in the immediate.
10346     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10347       return false;
10348 
10349     // 3. Check that the computation is legal.
10350     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10351       return false;
10352 
10353     // Check that the zext is legal if it needs one.
10354     EVT TruncateType = Inst->getValueType(0);
10355     if (TruncateType != SliceType &&
10356         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10357       return false;
10358 
10359     return true;
10360   }
10361 
10362   /// \brief Get the offset in bytes of this slice in the original chunk of
10363   /// bits.
10364   /// \pre DAG != nullptr.
10365   uint64_t getOffsetFromBase() const {
10366     assert(DAG && "Missing context.");
10367     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10368     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10369     uint64_t Offset = Shift / 8;
10370     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10371     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10372            "The size of the original loaded type is not a multiple of a"
10373            " byte.");
10374     // If Offset is bigger than TySizeInBytes, it means we are loading all
10375     // zeros. This should have been optimized before in the process.
10376     assert(TySizeInBytes > Offset &&
10377            "Invalid shift amount for given loaded size");
10378     if (IsBigEndian)
10379       Offset = TySizeInBytes - Offset - getLoadedSize();
10380     return Offset;
10381   }
10382 
10383   /// \brief Generate the sequence of instructions to load the slice
10384   /// represented by this object and redirect the uses of this slice to
10385   /// this new sequence of instructions.
10386   /// \pre this->Inst && this->Origin are valid Instructions and this
10387   /// object passed the legal check: LoadedSlice::isLegal returned true.
10388   /// \return The last instruction of the sequence used to load the slice.
10389   SDValue loadSlice() const {
10390     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10391     const SDValue &OldBaseAddr = Origin->getBasePtr();
10392     SDValue BaseAddr = OldBaseAddr;
10393     // Get the offset in that chunk of bytes w.r.t. the endianess.
10394     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10395     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10396     if (Offset) {
10397       // BaseAddr = BaseAddr + Offset.
10398       EVT ArithType = BaseAddr.getValueType();
10399       SDLoc DL(Origin);
10400       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10401                               DAG->getConstant(Offset, DL, ArithType));
10402     }
10403 
10404     // Create the type of the loaded slice according to its size.
10405     EVT SliceType = getLoadedType();
10406 
10407     // Create the load for the slice.
10408     SDValue LastInst = DAG->getLoad(
10409         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10410         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10411         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10412     // If the final type is not the same as the loaded type, this means that
10413     // we have to pad with zero. Create a zero extend for that.
10414     EVT FinalType = Inst->getValueType(0);
10415     if (SliceType != FinalType)
10416       LastInst =
10417           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10418     return LastInst;
10419   }
10420 
10421   /// \brief Check if this slice can be merged with an expensive cross register
10422   /// bank copy. E.g.,
10423   /// i = load i32
10424   /// f = bitcast i32 i to float
10425   bool canMergeExpensiveCrossRegisterBankCopy() const {
10426     if (!Inst || !Inst->hasOneUse())
10427       return false;
10428     SDNode *Use = *Inst->use_begin();
10429     if (Use->getOpcode() != ISD::BITCAST)
10430       return false;
10431     assert(DAG && "Missing context");
10432     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10433     EVT ResVT = Use->getValueType(0);
10434     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10435     const TargetRegisterClass *ArgRC =
10436         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10437     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10438       return false;
10439 
10440     // At this point, we know that we perform a cross-register-bank copy.
10441     // Check if it is expensive.
10442     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10443     // Assume bitcasts are cheap, unless both register classes do not
10444     // explicitly share a common sub class.
10445     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10446       return false;
10447 
10448     // Check if it will be merged with the load.
10449     // 1. Check the alignment constraint.
10450     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10451         ResVT.getTypeForEVT(*DAG->getContext()));
10452 
10453     if (RequiredAlignment > getAlignment())
10454       return false;
10455 
10456     // 2. Check that the load is a legal operation for that type.
10457     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10458       return false;
10459 
10460     // 3. Check that we do not have a zext in the way.
10461     if (Inst->getValueType(0) != getLoadedType())
10462       return false;
10463 
10464     return true;
10465   }
10466 };
10467 }
10468 
10469 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10470 /// \p UsedBits looks like 0..0 1..1 0..0.
10471 static bool areUsedBitsDense(const APInt &UsedBits) {
10472   // If all the bits are one, this is dense!
10473   if (UsedBits.isAllOnesValue())
10474     return true;
10475 
10476   // Get rid of the unused bits on the right.
10477   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10478   // Get rid of the unused bits on the left.
10479   if (NarrowedUsedBits.countLeadingZeros())
10480     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10481   // Check that the chunk of bits is completely used.
10482   return NarrowedUsedBits.isAllOnesValue();
10483 }
10484 
10485 /// \brief Check whether or not \p First and \p Second are next to each other
10486 /// in memory. This means that there is no hole between the bits loaded
10487 /// by \p First and the bits loaded by \p Second.
10488 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10489                                      const LoadedSlice &Second) {
10490   assert(First.Origin == Second.Origin && First.Origin &&
10491          "Unable to match different memory origins.");
10492   APInt UsedBits = First.getUsedBits();
10493   assert((UsedBits & Second.getUsedBits()) == 0 &&
10494          "Slices are not supposed to overlap.");
10495   UsedBits |= Second.getUsedBits();
10496   return areUsedBitsDense(UsedBits);
10497 }
10498 
10499 /// \brief Adjust the \p GlobalLSCost according to the target
10500 /// paring capabilities and the layout of the slices.
10501 /// \pre \p GlobalLSCost should account for at least as many loads as
10502 /// there is in the slices in \p LoadedSlices.
10503 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10504                                  LoadedSlice::Cost &GlobalLSCost) {
10505   unsigned NumberOfSlices = LoadedSlices.size();
10506   // If there is less than 2 elements, no pairing is possible.
10507   if (NumberOfSlices < 2)
10508     return;
10509 
10510   // Sort the slices so that elements that are likely to be next to each
10511   // other in memory are next to each other in the list.
10512   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10513             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10514     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10515     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10516   });
10517   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10518   // First (resp. Second) is the first (resp. Second) potentially candidate
10519   // to be placed in a paired load.
10520   const LoadedSlice *First = nullptr;
10521   const LoadedSlice *Second = nullptr;
10522   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10523                 // Set the beginning of the pair.
10524                                                            First = Second) {
10525 
10526     Second = &LoadedSlices[CurrSlice];
10527 
10528     // If First is NULL, it means we start a new pair.
10529     // Get to the next slice.
10530     if (!First)
10531       continue;
10532 
10533     EVT LoadedType = First->getLoadedType();
10534 
10535     // If the types of the slices are different, we cannot pair them.
10536     if (LoadedType != Second->getLoadedType())
10537       continue;
10538 
10539     // Check if the target supplies paired loads for this type.
10540     unsigned RequiredAlignment = 0;
10541     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10542       // move to the next pair, this type is hopeless.
10543       Second = nullptr;
10544       continue;
10545     }
10546     // Check if we meet the alignment requirement.
10547     if (RequiredAlignment > First->getAlignment())
10548       continue;
10549 
10550     // Check that both loads are next to each other in memory.
10551     if (!areSlicesNextToEachOther(*First, *Second))
10552       continue;
10553 
10554     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10555     --GlobalLSCost.Loads;
10556     // Move to the next pair.
10557     Second = nullptr;
10558   }
10559 }
10560 
10561 /// \brief Check the profitability of all involved LoadedSlice.
10562 /// Currently, it is considered profitable if there is exactly two
10563 /// involved slices (1) which are (2) next to each other in memory, and
10564 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10565 ///
10566 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10567 /// the elements themselves.
10568 ///
10569 /// FIXME: When the cost model will be mature enough, we can relax
10570 /// constraints (1) and (2).
10571 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10572                                 const APInt &UsedBits, bool ForCodeSize) {
10573   unsigned NumberOfSlices = LoadedSlices.size();
10574   if (StressLoadSlicing)
10575     return NumberOfSlices > 1;
10576 
10577   // Check (1).
10578   if (NumberOfSlices != 2)
10579     return false;
10580 
10581   // Check (2).
10582   if (!areUsedBitsDense(UsedBits))
10583     return false;
10584 
10585   // Check (3).
10586   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10587   // The original code has one big load.
10588   OrigCost.Loads = 1;
10589   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10590     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10591     // Accumulate the cost of all the slices.
10592     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10593     GlobalSlicingCost += SliceCost;
10594 
10595     // Account as cost in the original configuration the gain obtained
10596     // with the current slices.
10597     OrigCost.addSliceGain(LS);
10598   }
10599 
10600   // If the target supports paired load, adjust the cost accordingly.
10601   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10602   return OrigCost > GlobalSlicingCost;
10603 }
10604 
10605 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10606 /// operations, split it in the various pieces being extracted.
10607 ///
10608 /// This sort of thing is introduced by SROA.
10609 /// This slicing takes care not to insert overlapping loads.
10610 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10611 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10612   if (Level < AfterLegalizeDAG)
10613     return false;
10614 
10615   LoadSDNode *LD = cast<LoadSDNode>(N);
10616   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10617       !LD->getValueType(0).isInteger())
10618     return false;
10619 
10620   // Keep track of already used bits to detect overlapping values.
10621   // In that case, we will just abort the transformation.
10622   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10623 
10624   SmallVector<LoadedSlice, 4> LoadedSlices;
10625 
10626   // Check if this load is used as several smaller chunks of bits.
10627   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10628   // of computation for each trunc.
10629   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10630        UI != UIEnd; ++UI) {
10631     // Skip the uses of the chain.
10632     if (UI.getUse().getResNo() != 0)
10633       continue;
10634 
10635     SDNode *User = *UI;
10636     unsigned Shift = 0;
10637 
10638     // Check if this is a trunc(lshr).
10639     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10640         isa<ConstantSDNode>(User->getOperand(1))) {
10641       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10642       User = *User->use_begin();
10643     }
10644 
10645     // At this point, User is a Truncate, iff we encountered, trunc or
10646     // trunc(lshr).
10647     if (User->getOpcode() != ISD::TRUNCATE)
10648       return false;
10649 
10650     // The width of the type must be a power of 2 and greater than 8-bits.
10651     // Otherwise the load cannot be represented in LLVM IR.
10652     // Moreover, if we shifted with a non-8-bits multiple, the slice
10653     // will be across several bytes. We do not support that.
10654     unsigned Width = User->getValueSizeInBits(0);
10655     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10656       return 0;
10657 
10658     // Build the slice for this chain of computations.
10659     LoadedSlice LS(User, LD, Shift, &DAG);
10660     APInt CurrentUsedBits = LS.getUsedBits();
10661 
10662     // Check if this slice overlaps with another.
10663     if ((CurrentUsedBits & UsedBits) != 0)
10664       return false;
10665     // Update the bits used globally.
10666     UsedBits |= CurrentUsedBits;
10667 
10668     // Check if the new slice would be legal.
10669     if (!LS.isLegal())
10670       return false;
10671 
10672     // Record the slice.
10673     LoadedSlices.push_back(LS);
10674   }
10675 
10676   // Abort slicing if it does not seem to be profitable.
10677   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10678     return false;
10679 
10680   ++SlicedLoads;
10681 
10682   // Rewrite each chain to use an independent load.
10683   // By construction, each chain can be represented by a unique load.
10684 
10685   // Prepare the argument for the new token factor for all the slices.
10686   SmallVector<SDValue, 8> ArgChains;
10687   for (SmallVectorImpl<LoadedSlice>::const_iterator
10688            LSIt = LoadedSlices.begin(),
10689            LSItEnd = LoadedSlices.end();
10690        LSIt != LSItEnd; ++LSIt) {
10691     SDValue SliceInst = LSIt->loadSlice();
10692     CombineTo(LSIt->Inst, SliceInst, true);
10693     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10694       SliceInst = SliceInst.getOperand(0);
10695     assert(SliceInst->getOpcode() == ISD::LOAD &&
10696            "It takes more than a zext to get to the loaded slice!!");
10697     ArgChains.push_back(SliceInst.getValue(1));
10698   }
10699 
10700   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10701                               ArgChains);
10702   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10703   return true;
10704 }
10705 
10706 /// Check to see if V is (and load (ptr), imm), where the load is having
10707 /// specific bytes cleared out.  If so, return the byte size being masked out
10708 /// and the shift amount.
10709 static std::pair<unsigned, unsigned>
10710 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10711   std::pair<unsigned, unsigned> Result(0, 0);
10712 
10713   // Check for the structure we're looking for.
10714   if (V->getOpcode() != ISD::AND ||
10715       !isa<ConstantSDNode>(V->getOperand(1)) ||
10716       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10717     return Result;
10718 
10719   // Check the chain and pointer.
10720   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10721   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10722 
10723   // The store should be chained directly to the load or be an operand of a
10724   // tokenfactor.
10725   if (LD == Chain.getNode())
10726     ; // ok.
10727   else if (Chain->getOpcode() != ISD::TokenFactor)
10728     return Result; // Fail.
10729   else {
10730     bool isOk = false;
10731     for (const SDValue &ChainOp : Chain->op_values())
10732       if (ChainOp.getNode() == LD) {
10733         isOk = true;
10734         break;
10735       }
10736     if (!isOk) return Result;
10737   }
10738 
10739   // This only handles simple types.
10740   if (V.getValueType() != MVT::i16 &&
10741       V.getValueType() != MVT::i32 &&
10742       V.getValueType() != MVT::i64)
10743     return Result;
10744 
10745   // Check the constant mask.  Invert it so that the bits being masked out are
10746   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10747   // follow the sign bit for uniformity.
10748   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10749   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10750   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10751   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10752   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10753   if (NotMaskLZ == 64) return Result;  // All zero mask.
10754 
10755   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10756   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10757     return Result;
10758 
10759   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10760   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10761     NotMaskLZ -= 64-V.getValueSizeInBits();
10762 
10763   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10764   switch (MaskedBytes) {
10765   case 1:
10766   case 2:
10767   case 4: break;
10768   default: return Result; // All one mask, or 5-byte mask.
10769   }
10770 
10771   // Verify that the first bit starts at a multiple of mask so that the access
10772   // is aligned the same as the access width.
10773   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10774 
10775   Result.first = MaskedBytes;
10776   Result.second = NotMaskTZ/8;
10777   return Result;
10778 }
10779 
10780 
10781 /// Check to see if IVal is something that provides a value as specified by
10782 /// MaskInfo. If so, replace the specified store with a narrower store of
10783 /// truncated IVal.
10784 static SDNode *
10785 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10786                                 SDValue IVal, StoreSDNode *St,
10787                                 DAGCombiner *DC) {
10788   unsigned NumBytes = MaskInfo.first;
10789   unsigned ByteShift = MaskInfo.second;
10790   SelectionDAG &DAG = DC->getDAG();
10791 
10792   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10793   // that uses this.  If not, this is not a replacement.
10794   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10795                                   ByteShift*8, (ByteShift+NumBytes)*8);
10796   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10797 
10798   // Check that it is legal on the target to do this.  It is legal if the new
10799   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10800   // legalization.
10801   MVT VT = MVT::getIntegerVT(NumBytes*8);
10802   if (!DC->isTypeLegal(VT))
10803     return nullptr;
10804 
10805   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10806   // shifted by ByteShift and truncated down to NumBytes.
10807   if (ByteShift) {
10808     SDLoc DL(IVal);
10809     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10810                        DAG.getConstant(ByteShift*8, DL,
10811                                     DC->getShiftAmountTy(IVal.getValueType())));
10812   }
10813 
10814   // Figure out the offset for the store and the alignment of the access.
10815   unsigned StOffset;
10816   unsigned NewAlign = St->getAlignment();
10817 
10818   if (DAG.getDataLayout().isLittleEndian())
10819     StOffset = ByteShift;
10820   else
10821     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10822 
10823   SDValue Ptr = St->getBasePtr();
10824   if (StOffset) {
10825     SDLoc DL(IVal);
10826     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10827                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10828     NewAlign = MinAlign(NewAlign, StOffset);
10829   }
10830 
10831   // Truncate down to the new size.
10832   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10833 
10834   ++OpsNarrowed;
10835   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10836                       St->getPointerInfo().getWithOffset(StOffset),
10837                       false, false, NewAlign).getNode();
10838 }
10839 
10840 
10841 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10842 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10843 /// narrowing the load and store if it would end up being a win for performance
10844 /// or code size.
10845 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10846   StoreSDNode *ST  = cast<StoreSDNode>(N);
10847   if (ST->isVolatile())
10848     return SDValue();
10849 
10850   SDValue Chain = ST->getChain();
10851   SDValue Value = ST->getValue();
10852   SDValue Ptr   = ST->getBasePtr();
10853   EVT VT = Value.getValueType();
10854 
10855   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10856     return SDValue();
10857 
10858   unsigned Opc = Value.getOpcode();
10859 
10860   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10861   // is a byte mask indicating a consecutive number of bytes, check to see if
10862   // Y is known to provide just those bytes.  If so, we try to replace the
10863   // load + replace + store sequence with a single (narrower) store, which makes
10864   // the load dead.
10865   if (Opc == ISD::OR) {
10866     std::pair<unsigned, unsigned> MaskedLoad;
10867     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10868     if (MaskedLoad.first)
10869       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10870                                                   Value.getOperand(1), ST,this))
10871         return SDValue(NewST, 0);
10872 
10873     // Or is commutative, so try swapping X and Y.
10874     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10875     if (MaskedLoad.first)
10876       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10877                                                   Value.getOperand(0), ST,this))
10878         return SDValue(NewST, 0);
10879   }
10880 
10881   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10882       Value.getOperand(1).getOpcode() != ISD::Constant)
10883     return SDValue();
10884 
10885   SDValue N0 = Value.getOperand(0);
10886   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10887       Chain == SDValue(N0.getNode(), 1)) {
10888     LoadSDNode *LD = cast<LoadSDNode>(N0);
10889     if (LD->getBasePtr() != Ptr ||
10890         LD->getPointerInfo().getAddrSpace() !=
10891         ST->getPointerInfo().getAddrSpace())
10892       return SDValue();
10893 
10894     // Find the type to narrow it the load / op / store to.
10895     SDValue N1 = Value.getOperand(1);
10896     unsigned BitWidth = N1.getValueSizeInBits();
10897     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10898     if (Opc == ISD::AND)
10899       Imm ^= APInt::getAllOnesValue(BitWidth);
10900     if (Imm == 0 || Imm.isAllOnesValue())
10901       return SDValue();
10902     unsigned ShAmt = Imm.countTrailingZeros();
10903     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10904     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10905     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10906     // The narrowing should be profitable, the load/store operation should be
10907     // legal (or custom) and the store size should be equal to the NewVT width.
10908     while (NewBW < BitWidth &&
10909            (NewVT.getStoreSizeInBits() != NewBW ||
10910             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10911             !TLI.isNarrowingProfitable(VT, NewVT))) {
10912       NewBW = NextPowerOf2(NewBW);
10913       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10914     }
10915     if (NewBW >= BitWidth)
10916       return SDValue();
10917 
10918     // If the lsb changed does not start at the type bitwidth boundary,
10919     // start at the previous one.
10920     if (ShAmt % NewBW)
10921       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10922     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10923                                    std::min(BitWidth, ShAmt + NewBW));
10924     if ((Imm & Mask) == Imm) {
10925       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10926       if (Opc == ISD::AND)
10927         NewImm ^= APInt::getAllOnesValue(NewBW);
10928       uint64_t PtrOff = ShAmt / 8;
10929       // For big endian targets, we need to adjust the offset to the pointer to
10930       // load the correct bytes.
10931       if (DAG.getDataLayout().isBigEndian())
10932         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10933 
10934       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10935       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10936       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10937         return SDValue();
10938 
10939       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10940                                    Ptr.getValueType(), Ptr,
10941                                    DAG.getConstant(PtrOff, SDLoc(LD),
10942                                                    Ptr.getValueType()));
10943       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10944                                   LD->getChain(), NewPtr,
10945                                   LD->getPointerInfo().getWithOffset(PtrOff),
10946                                   LD->isVolatile(), LD->isNonTemporal(),
10947                                   LD->isInvariant(), NewAlign,
10948                                   LD->getAAInfo());
10949       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10950                                    DAG.getConstant(NewImm, SDLoc(Value),
10951                                                    NewVT));
10952       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10953                                    NewVal, NewPtr,
10954                                    ST->getPointerInfo().getWithOffset(PtrOff),
10955                                    false, false, NewAlign);
10956 
10957       AddToWorklist(NewPtr.getNode());
10958       AddToWorklist(NewLD.getNode());
10959       AddToWorklist(NewVal.getNode());
10960       WorklistRemover DeadNodes(*this);
10961       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10962       ++OpsNarrowed;
10963       return NewST;
10964     }
10965   }
10966 
10967   return SDValue();
10968 }
10969 
10970 /// For a given floating point load / store pair, if the load value isn't used
10971 /// by any other operations, then consider transforming the pair to integer
10972 /// load / store operations if the target deems the transformation profitable.
10973 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10974   StoreSDNode *ST  = cast<StoreSDNode>(N);
10975   SDValue Chain = ST->getChain();
10976   SDValue Value = ST->getValue();
10977   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10978       Value.hasOneUse() &&
10979       Chain == SDValue(Value.getNode(), 1)) {
10980     LoadSDNode *LD = cast<LoadSDNode>(Value);
10981     EVT VT = LD->getMemoryVT();
10982     if (!VT.isFloatingPoint() ||
10983         VT != ST->getMemoryVT() ||
10984         LD->isNonTemporal() ||
10985         ST->isNonTemporal() ||
10986         LD->getPointerInfo().getAddrSpace() != 0 ||
10987         ST->getPointerInfo().getAddrSpace() != 0)
10988       return SDValue();
10989 
10990     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10991     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10992         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10993         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10994         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10995       return SDValue();
10996 
10997     unsigned LDAlign = LD->getAlignment();
10998     unsigned STAlign = ST->getAlignment();
10999     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11000     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11001     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11002       return SDValue();
11003 
11004     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
11005                                 LD->getChain(), LD->getBasePtr(),
11006                                 LD->getPointerInfo(),
11007                                 false, false, false, LDAlign);
11008 
11009     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
11010                                  NewLD, ST->getBasePtr(),
11011                                  ST->getPointerInfo(),
11012                                  false, false, STAlign);
11013 
11014     AddToWorklist(NewLD.getNode());
11015     AddToWorklist(NewST.getNode());
11016     WorklistRemover DeadNodes(*this);
11017     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11018     ++LdStFP2Int;
11019     return NewST;
11020   }
11021 
11022   return SDValue();
11023 }
11024 
11025 namespace {
11026 /// Helper struct to parse and store a memory address as base + index + offset.
11027 /// We ignore sign extensions when it is safe to do so.
11028 /// The following two expressions are not equivalent. To differentiate we need
11029 /// to store whether there was a sign extension involved in the index
11030 /// computation.
11031 ///  (load (i64 add (i64 copyfromreg %c)
11032 ///                 (i64 signextend (add (i8 load %index)
11033 ///                                      (i8 1))))
11034 /// vs
11035 ///
11036 /// (load (i64 add (i64 copyfromreg %c)
11037 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11038 ///                                         (i32 1)))))
11039 struct BaseIndexOffset {
11040   SDValue Base;
11041   SDValue Index;
11042   int64_t Offset;
11043   bool IsIndexSignExt;
11044 
11045   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11046 
11047   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11048                   bool IsIndexSignExt) :
11049     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11050 
11051   bool equalBaseIndex(const BaseIndexOffset &Other) {
11052     return Other.Base == Base && Other.Index == Index &&
11053       Other.IsIndexSignExt == IsIndexSignExt;
11054   }
11055 
11056   /// Parses tree in Ptr for base, index, offset addresses.
11057   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11058     bool IsIndexSignExt = false;
11059 
11060     // Split up a folded GlobalAddress+Offset into its component parts.
11061     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11062       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11063         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11064                                                     SDLoc(GA),
11065                                                     GA->getValueType(0),
11066                                                     /*Offset=*/0,
11067                                                     /*isTargetGA=*/false,
11068                                                     GA->getTargetFlags()),
11069                                SDValue(),
11070                                GA->getOffset(),
11071                                IsIndexSignExt);
11072       }
11073 
11074     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11075     // instruction, then it could be just the BASE or everything else we don't
11076     // know how to handle. Just use Ptr as BASE and give up.
11077     if (Ptr->getOpcode() != ISD::ADD)
11078       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11079 
11080     // We know that we have at least an ADD instruction. Try to pattern match
11081     // the simple case of BASE + OFFSET.
11082     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11083       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11084       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11085                               IsIndexSignExt);
11086     }
11087 
11088     // Inside a loop the current BASE pointer is calculated using an ADD and a
11089     // MUL instruction. In this case Ptr is the actual BASE pointer.
11090     // (i64 add (i64 %array_ptr)
11091     //          (i64 mul (i64 %induction_var)
11092     //                   (i64 %element_size)))
11093     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11094       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11095 
11096     // Look at Base + Index + Offset cases.
11097     SDValue Base = Ptr->getOperand(0);
11098     SDValue IndexOffset = Ptr->getOperand(1);
11099 
11100     // Skip signextends.
11101     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11102       IndexOffset = IndexOffset->getOperand(0);
11103       IsIndexSignExt = true;
11104     }
11105 
11106     // Either the case of Base + Index (no offset) or something else.
11107     if (IndexOffset->getOpcode() != ISD::ADD)
11108       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11109 
11110     // Now we have the case of Base + Index + offset.
11111     SDValue Index = IndexOffset->getOperand(0);
11112     SDValue Offset = IndexOffset->getOperand(1);
11113 
11114     if (!isa<ConstantSDNode>(Offset))
11115       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11116 
11117     // Ignore signextends.
11118     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11119       Index = Index->getOperand(0);
11120       IsIndexSignExt = true;
11121     } else IsIndexSignExt = false;
11122 
11123     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11124     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11125   }
11126 };
11127 } // namespace
11128 
11129 // This is a helper function for visitMUL to check the profitability
11130 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11131 // MulNode is the original multiply, AddNode is (add x, c1),
11132 // and ConstNode is c2.
11133 //
11134 // If the (add x, c1) has multiple uses, we could increase
11135 // the number of adds if we make this transformation.
11136 // It would only be worth doing this if we can remove a
11137 // multiply in the process. Check for that here.
11138 // To illustrate:
11139 //     (A + c1) * c3
11140 //     (A + c2) * c3
11141 // We're checking for cases where we have common "c3 * A" expressions.
11142 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11143                                               SDValue &AddNode,
11144                                               SDValue &ConstNode) {
11145   APInt Val;
11146 
11147   // If the add only has one use, this would be OK to do.
11148   if (AddNode.getNode()->hasOneUse())
11149     return true;
11150 
11151   // Walk all the users of the constant with which we're multiplying.
11152   for (SDNode *Use : ConstNode->uses()) {
11153 
11154     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11155       continue;
11156 
11157     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11158       SDNode *OtherOp;
11159       SDNode *MulVar = AddNode.getOperand(0).getNode();
11160 
11161       // OtherOp is what we're multiplying against the constant.
11162       if (Use->getOperand(0) == ConstNode)
11163         OtherOp = Use->getOperand(1).getNode();
11164       else
11165         OtherOp = Use->getOperand(0).getNode();
11166 
11167       // Check to see if multiply is with the same operand of our "add".
11168       //
11169       //     ConstNode  = CONST
11170       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11171       //     ...
11172       //     AddNode  = (A + c1)  <-- MulVar is A.
11173       //         = AddNode * ConstNode   <-- current visiting instruction.
11174       //
11175       // If we make this transformation, we will have a common
11176       // multiply (ConstNode * A) that we can save.
11177       if (OtherOp == MulVar)
11178         return true;
11179 
11180       // Now check to see if a future expansion will give us a common
11181       // multiply.
11182       //
11183       //     ConstNode  = CONST
11184       //     AddNode    = (A + c1)
11185       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11186       //     ...
11187       //     OtherOp = (A + c2)
11188       //     Use     = OtherOp * ConstNode <-- visiting Use.
11189       //
11190       // If we make this transformation, we will have a common
11191       // multiply (CONST * A) after we also do the same transformation
11192       // to the "t2" instruction.
11193       if (OtherOp->getOpcode() == ISD::ADD &&
11194           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11195           OtherOp->getOperand(0).getNode() == MulVar)
11196         return true;
11197     }
11198   }
11199 
11200   // Didn't find a case where this would be profitable.
11201   return false;
11202 }
11203 
11204 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11205                                                   SDLoc SL,
11206                                                   ArrayRef<MemOpLink> Stores,
11207                                                   SmallVectorImpl<SDValue> &Chains,
11208                                                   EVT Ty) const {
11209   SmallVector<SDValue, 8> BuildVector;
11210 
11211   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11212     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11213     Chains.push_back(St->getChain());
11214     BuildVector.push_back(St->getValue());
11215   }
11216 
11217   return DAG.getBuildVector(Ty, SL, BuildVector);
11218 }
11219 
11220 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11221                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11222                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11223   // Make sure we have something to merge.
11224   if (NumStores < 2)
11225     return false;
11226 
11227   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11228   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11229   unsigned LatestNodeUsed = 0;
11230 
11231   for (unsigned i=0; i < NumStores; ++i) {
11232     // Find a chain for the new wide-store operand. Notice that some
11233     // of the store nodes that we found may not be selected for inclusion
11234     // in the wide store. The chain we use needs to be the chain of the
11235     // latest store node which is *used* and replaced by the wide store.
11236     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11237       LatestNodeUsed = i;
11238   }
11239 
11240   SmallVector<SDValue, 8> Chains;
11241 
11242   // The latest Node in the DAG.
11243   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11244   SDLoc DL(StoreNodes[0].MemNode);
11245 
11246   SDValue StoredVal;
11247   if (UseVector) {
11248     bool IsVec = MemVT.isVector();
11249     unsigned Elts = NumStores;
11250     if (IsVec) {
11251       // When merging vector stores, get the total number of elements.
11252       Elts *= MemVT.getVectorNumElements();
11253     }
11254     // Get the type for the merged vector store.
11255     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11256     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11257 
11258     if (IsConstantSrc) {
11259       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11260     } else {
11261       SmallVector<SDValue, 8> Ops;
11262       for (unsigned i = 0; i < NumStores; ++i) {
11263         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11264         SDValue Val = St->getValue();
11265         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11266         if (Val.getValueType() != MemVT)
11267           return false;
11268         Ops.push_back(Val);
11269         Chains.push_back(St->getChain());
11270       }
11271 
11272       // Build the extracted vector elements back into a vector.
11273       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11274                               DL, Ty, Ops);    }
11275   } else {
11276     // We should always use a vector store when merging extracted vector
11277     // elements, so this path implies a store of constants.
11278     assert(IsConstantSrc && "Merged vector elements should use vector store");
11279 
11280     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11281     APInt StoreInt(SizeInBits, 0);
11282 
11283     // Construct a single integer constant which is made of the smaller
11284     // constant inputs.
11285     bool IsLE = DAG.getDataLayout().isLittleEndian();
11286     for (unsigned i = 0; i < NumStores; ++i) {
11287       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11288       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11289       Chains.push_back(St->getChain());
11290 
11291       SDValue Val = St->getValue();
11292       StoreInt <<= ElementSizeBytes * 8;
11293       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11294         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11295       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11296         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11297       } else {
11298         llvm_unreachable("Invalid constant element type");
11299       }
11300     }
11301 
11302     // Create the new Load and Store operations.
11303     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11304     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11305   }
11306 
11307   assert(!Chains.empty());
11308 
11309   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11310   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11311                                   FirstInChain->getBasePtr(),
11312                                   FirstInChain->getPointerInfo(),
11313                                   false, false,
11314                                   FirstInChain->getAlignment());
11315 
11316   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11317                                                   : DAG.getSubtarget().useAA();
11318   if (UseAA) {
11319     // Replace all merged stores with the new store.
11320     for (unsigned i = 0; i < NumStores; ++i)
11321       CombineTo(StoreNodes[i].MemNode, NewStore);
11322   } else {
11323     // Replace the last store with the new store.
11324     CombineTo(LatestOp, NewStore);
11325     // Erase all other stores.
11326     for (unsigned i = 0; i < NumStores; ++i) {
11327       if (StoreNodes[i].MemNode == LatestOp)
11328         continue;
11329       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11330       // ReplaceAllUsesWith will replace all uses that existed when it was
11331       // called, but graph optimizations may cause new ones to appear. For
11332       // example, the case in pr14333 looks like
11333       //
11334       //  St's chain -> St -> another store -> X
11335       //
11336       // And the only difference from St to the other store is the chain.
11337       // When we change it's chain to be St's chain they become identical,
11338       // get CSEed and the net result is that X is now a use of St.
11339       // Since we know that St is redundant, just iterate.
11340       while (!St->use_empty())
11341         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11342       deleteAndRecombine(St);
11343     }
11344   }
11345 
11346   return true;
11347 }
11348 
11349 void DAGCombiner::getStoreMergeAndAliasCandidates(
11350     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11351     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11352   // This holds the base pointer, index, and the offset in bytes from the base
11353   // pointer.
11354   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11355 
11356   // We must have a base and an offset.
11357   if (!BasePtr.Base.getNode())
11358     return;
11359 
11360   // Do not handle stores to undef base pointers.
11361   if (BasePtr.Base.isUndef())
11362     return;
11363 
11364   // Walk up the chain and look for nodes with offsets from the same
11365   // base pointer. Stop when reaching an instruction with a different kind
11366   // or instruction which has a different base pointer.
11367   EVT MemVT = St->getMemoryVT();
11368   unsigned Seq = 0;
11369   StoreSDNode *Index = St;
11370 
11371 
11372   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11373                                                   : DAG.getSubtarget().useAA();
11374 
11375   if (UseAA) {
11376     // Look at other users of the same chain. Stores on the same chain do not
11377     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11378     // to be on the same chain, so don't bother looking at adjacent chains.
11379 
11380     SDValue Chain = St->getChain();
11381     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11382       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11383         if (I.getOperandNo() != 0)
11384           continue;
11385 
11386         if (OtherST->isVolatile() || OtherST->isIndexed())
11387           continue;
11388 
11389         if (OtherST->getMemoryVT() != MemVT)
11390           continue;
11391 
11392         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11393 
11394         if (Ptr.equalBaseIndex(BasePtr))
11395           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11396       }
11397     }
11398 
11399     return;
11400   }
11401 
11402   while (Index) {
11403     // If the chain has more than one use, then we can't reorder the mem ops.
11404     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11405       break;
11406 
11407     // Find the base pointer and offset for this memory node.
11408     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11409 
11410     // Check that the base pointer is the same as the original one.
11411     if (!Ptr.equalBaseIndex(BasePtr))
11412       break;
11413 
11414     // The memory operands must not be volatile.
11415     if (Index->isVolatile() || Index->isIndexed())
11416       break;
11417 
11418     // No truncation.
11419     if (Index->isTruncatingStore())
11420       break;
11421 
11422     // The stored memory type must be the same.
11423     if (Index->getMemoryVT() != MemVT)
11424       break;
11425 
11426     // We do not allow under-aligned stores in order to prevent
11427     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11428     // be irrelevant here; what MATTERS is that we not move memory
11429     // operations that potentially overlap past each-other.
11430     if (Index->getAlignment() < MemVT.getStoreSize())
11431       break;
11432 
11433     // We found a potential memory operand to merge.
11434     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11435 
11436     // Find the next memory operand in the chain. If the next operand in the
11437     // chain is a store then move up and continue the scan with the next
11438     // memory operand. If the next operand is a load save it and use alias
11439     // information to check if it interferes with anything.
11440     SDNode *NextInChain = Index->getChain().getNode();
11441     while (1) {
11442       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11443         // We found a store node. Use it for the next iteration.
11444         Index = STn;
11445         break;
11446       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11447         if (Ldn->isVolatile()) {
11448           Index = nullptr;
11449           break;
11450         }
11451 
11452         // Save the load node for later. Continue the scan.
11453         AliasLoadNodes.push_back(Ldn);
11454         NextInChain = Ldn->getChain().getNode();
11455         continue;
11456       } else {
11457         Index = nullptr;
11458         break;
11459       }
11460     }
11461   }
11462 }
11463 
11464 // We need to check that merging these stores does not cause a loop
11465 // in the DAG. Any store candidate may depend on another candidate
11466 // indirectly through its operand (we already consider dependencies
11467 // through the chain). Check in parallel by searching up from
11468 // non-chain operands of candidates.
11469 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11470     SmallVectorImpl<MemOpLink> &StoreNodes) {
11471   SmallPtrSet<const SDNode *, 16> Visited;
11472   SmallVector<const SDNode *, 8> Worklist;
11473   // search ops of store candidates
11474   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11475     SDNode *n = StoreNodes[i].MemNode;
11476     // Potential loops may happen only through non-chain operands
11477     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11478       Worklist.push_back(n->getOperand(j).getNode());
11479   }
11480   // search through DAG. We can stop early if we find a storenode
11481   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11482     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11483       return false;
11484   }
11485   return true;
11486 }
11487 
11488 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11489   if (OptLevel == CodeGenOpt::None)
11490     return false;
11491 
11492   EVT MemVT = St->getMemoryVT();
11493   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11494   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11495       Attribute::NoImplicitFloat);
11496 
11497   // This function cannot currently deal with non-byte-sized memory sizes.
11498   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11499     return false;
11500 
11501   if (!MemVT.isSimple())
11502     return false;
11503 
11504   // Perform an early exit check. Do not bother looking at stored values that
11505   // are not constants, loads, or extracted vector elements.
11506   SDValue StoredVal = St->getValue();
11507   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11508   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11509                        isa<ConstantFPSDNode>(StoredVal);
11510   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11511                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11512 
11513   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11514     return false;
11515 
11516   // Don't merge vectors into wider vectors if the source data comes from loads.
11517   // TODO: This restriction can be lifted by using logic similar to the
11518   // ExtractVecSrc case.
11519   if (MemVT.isVector() && IsLoadSrc)
11520     return false;
11521 
11522   // Only look at ends of store sequences.
11523   SDValue Chain = SDValue(St, 0);
11524   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11525     return false;
11526 
11527   // Save the LoadSDNodes that we find in the chain.
11528   // We need to make sure that these nodes do not interfere with
11529   // any of the store nodes.
11530   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11531 
11532   // Save the StoreSDNodes that we find in the chain.
11533   SmallVector<MemOpLink, 8> StoreNodes;
11534 
11535   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11536 
11537   // Check if there is anything to merge.
11538   if (StoreNodes.size() < 2)
11539     return false;
11540 
11541   // only do dep endence check in AA case
11542   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11543                                                   : DAG.getSubtarget().useAA();
11544   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11545     return false;
11546 
11547   // Sort the memory operands according to their distance from the
11548   // base pointer.  As a secondary criteria: make sure stores coming
11549   // later in the code come first in the list. This is important for
11550   // the non-UseAA case, because we're merging stores into the FINAL
11551   // store along a chain which potentially contains aliasing stores.
11552   // Thus, if there are multiple stores to the same address, the last
11553   // one can be considered for merging but not the others.
11554   std::sort(StoreNodes.begin(), StoreNodes.end(),
11555             [](MemOpLink LHS, MemOpLink RHS) {
11556     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11557            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11558             LHS.SequenceNum < RHS.SequenceNum);
11559   });
11560 
11561   // Scan the memory operations on the chain and find the first non-consecutive
11562   // store memory address.
11563   unsigned LastConsecutiveStore = 0;
11564   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11565   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11566 
11567     // Check that the addresses are consecutive starting from the second
11568     // element in the list of stores.
11569     if (i > 0) {
11570       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11571       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11572         break;
11573     }
11574 
11575     // Check if this store interferes with any of the loads that we found.
11576     // If we find a load that alias with this store. Stop the sequence.
11577     if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11578                     [&](LSBaseSDNode* Ldn) {
11579                       return isAlias(Ldn, StoreNodes[i].MemNode);
11580                     }))
11581       break;
11582 
11583     // Mark this node as useful.
11584     LastConsecutiveStore = i;
11585   }
11586 
11587   // The node with the lowest store address.
11588   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11589   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11590   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11591   LLVMContext &Context = *DAG.getContext();
11592   const DataLayout &DL = DAG.getDataLayout();
11593 
11594   // Store the constants into memory as one consecutive store.
11595   if (IsConstantSrc) {
11596     unsigned LastLegalType = 0;
11597     unsigned LastLegalVectorType = 0;
11598     bool NonZero = false;
11599     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11600       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11601       SDValue StoredVal = St->getValue();
11602 
11603       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11604         NonZero |= !C->isNullValue();
11605       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11606         NonZero |= !C->getConstantFPValue()->isNullValue();
11607       } else {
11608         // Non-constant.
11609         break;
11610       }
11611 
11612       // Find a legal type for the constant store.
11613       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11614       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11615       bool IsFast;
11616       if (TLI.isTypeLegal(StoreTy) &&
11617           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11618                                  FirstStoreAlign, &IsFast) && IsFast) {
11619         LastLegalType = i+1;
11620       // Or check whether a truncstore is legal.
11621       } else if (TLI.getTypeAction(Context, StoreTy) ==
11622                  TargetLowering::TypePromoteInteger) {
11623         EVT LegalizedStoredValueTy =
11624           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11625         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11626             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11627                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11628             IsFast) {
11629           LastLegalType = i + 1;
11630         }
11631       }
11632 
11633       // We only use vectors if the constant is known to be zero or the target
11634       // allows it and the function is not marked with the noimplicitfloat
11635       // attribute.
11636       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11637                                                         FirstStoreAS)) &&
11638           !NoVectors) {
11639         // Find a legal type for the vector store.
11640         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11641         if (TLI.isTypeLegal(Ty) &&
11642             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11643                                    FirstStoreAlign, &IsFast) && IsFast)
11644           LastLegalVectorType = i + 1;
11645       }
11646     }
11647 
11648     // Check if we found a legal integer type to store.
11649     if (LastLegalType == 0 && LastLegalVectorType == 0)
11650       return false;
11651 
11652     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11653     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11654 
11655     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11656                                            true, UseVector);
11657   }
11658 
11659   // When extracting multiple vector elements, try to store them
11660   // in one vector store rather than a sequence of scalar stores.
11661   if (IsExtractVecSrc) {
11662     unsigned NumStoresToMerge = 0;
11663     bool IsVec = MemVT.isVector();
11664     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11665       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11666       unsigned StoreValOpcode = St->getValue().getOpcode();
11667       // This restriction could be loosened.
11668       // Bail out if any stored values are not elements extracted from a vector.
11669       // It should be possible to handle mixed sources, but load sources need
11670       // more careful handling (see the block of code below that handles
11671       // consecutive loads).
11672       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11673           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11674         return false;
11675 
11676       // Find a legal type for the vector store.
11677       unsigned Elts = i + 1;
11678       if (IsVec) {
11679         // When merging vector stores, get the total number of elements.
11680         Elts *= MemVT.getVectorNumElements();
11681       }
11682       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11683       bool IsFast;
11684       if (TLI.isTypeLegal(Ty) &&
11685           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11686                                  FirstStoreAlign, &IsFast) && IsFast)
11687         NumStoresToMerge = i + 1;
11688     }
11689 
11690     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11691                                            false, true);
11692   }
11693 
11694   // Below we handle the case of multiple consecutive stores that
11695   // come from multiple consecutive loads. We merge them into a single
11696   // wide load and a single wide store.
11697 
11698   // Look for load nodes which are used by the stored values.
11699   SmallVector<MemOpLink, 8> LoadNodes;
11700 
11701   // Find acceptable loads. Loads need to have the same chain (token factor),
11702   // must not be zext, volatile, indexed, and they must be consecutive.
11703   BaseIndexOffset LdBasePtr;
11704   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11705     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11706     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11707     if (!Ld) break;
11708 
11709     // Loads must only have one use.
11710     if (!Ld->hasNUsesOfValue(1, 0))
11711       break;
11712 
11713     // The memory operands must not be volatile.
11714     if (Ld->isVolatile() || Ld->isIndexed())
11715       break;
11716 
11717     // We do not accept ext loads.
11718     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11719       break;
11720 
11721     // The stored memory type must be the same.
11722     if (Ld->getMemoryVT() != MemVT)
11723       break;
11724 
11725     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11726     // If this is not the first ptr that we check.
11727     if (LdBasePtr.Base.getNode()) {
11728       // The base ptr must be the same.
11729       if (!LdPtr.equalBaseIndex(LdBasePtr))
11730         break;
11731     } else {
11732       // Check that all other base pointers are the same as this one.
11733       LdBasePtr = LdPtr;
11734     }
11735 
11736     // We found a potential memory operand to merge.
11737     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11738   }
11739 
11740   if (LoadNodes.size() < 2)
11741     return false;
11742 
11743   // If we have load/store pair instructions and we only have two values,
11744   // don't bother.
11745   unsigned RequiredAlignment;
11746   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11747       St->getAlignment() >= RequiredAlignment)
11748     return false;
11749 
11750   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11751   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11752   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11753 
11754   // Scan the memory operations on the chain and find the first non-consecutive
11755   // load memory address. These variables hold the index in the store node
11756   // array.
11757   unsigned LastConsecutiveLoad = 0;
11758   // This variable refers to the size and not index in the array.
11759   unsigned LastLegalVectorType = 0;
11760   unsigned LastLegalIntegerType = 0;
11761   StartAddress = LoadNodes[0].OffsetFromBase;
11762   SDValue FirstChain = FirstLoad->getChain();
11763   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11764     // All loads must share the same chain.
11765     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11766       break;
11767 
11768     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11769     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11770       break;
11771     LastConsecutiveLoad = i;
11772     // Find a legal type for the vector store.
11773     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11774     bool IsFastSt, IsFastLd;
11775     if (TLI.isTypeLegal(StoreTy) &&
11776         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11777                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11778         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11779                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11780       LastLegalVectorType = i + 1;
11781     }
11782 
11783     // Find a legal type for the integer store.
11784     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11785     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11786     if (TLI.isTypeLegal(StoreTy) &&
11787         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11788                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11789         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11790                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11791       LastLegalIntegerType = i + 1;
11792     // Or check whether a truncstore and extload is legal.
11793     else if (TLI.getTypeAction(Context, StoreTy) ==
11794              TargetLowering::TypePromoteInteger) {
11795       EVT LegalizedStoredValueTy =
11796         TLI.getTypeToTransformTo(Context, StoreTy);
11797       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11798           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11799           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11800           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11801           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11802                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11803           IsFastSt &&
11804           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11805                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11806           IsFastLd)
11807         LastLegalIntegerType = i+1;
11808     }
11809   }
11810 
11811   // Only use vector types if the vector type is larger than the integer type.
11812   // If they are the same, use integers.
11813   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11814   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11815 
11816   // We add +1 here because the LastXXX variables refer to location while
11817   // the NumElem refers to array/index size.
11818   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11819   NumElem = std::min(LastLegalType, NumElem);
11820 
11821   if (NumElem < 2)
11822     return false;
11823 
11824   // Collect the chains from all merged stores.
11825   SmallVector<SDValue, 8> MergeStoreChains;
11826   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11827 
11828   // The latest Node in the DAG.
11829   unsigned LatestNodeUsed = 0;
11830   for (unsigned i=1; i<NumElem; ++i) {
11831     // Find a chain for the new wide-store operand. Notice that some
11832     // of the store nodes that we found may not be selected for inclusion
11833     // in the wide store. The chain we use needs to be the chain of the
11834     // latest store node which is *used* and replaced by the wide store.
11835     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11836       LatestNodeUsed = i;
11837 
11838     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11839   }
11840 
11841   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11842 
11843   // Find if it is better to use vectors or integers to load and store
11844   // to memory.
11845   EVT JointMemOpVT;
11846   if (UseVectorTy) {
11847     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11848   } else {
11849     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11850     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11851   }
11852 
11853   SDLoc LoadDL(LoadNodes[0].MemNode);
11854   SDLoc StoreDL(StoreNodes[0].MemNode);
11855 
11856   // The merged loads are required to have the same incoming chain, so
11857   // using the first's chain is acceptable.
11858   SDValue NewLoad = DAG.getLoad(
11859       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11860       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11861 
11862   SDValue NewStoreChain =
11863     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11864 
11865   SDValue NewStore = DAG.getStore(
11866     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11867       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11868 
11869   // Transfer chain users from old loads to the new load.
11870   for (unsigned i = 0; i < NumElem; ++i) {
11871     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11872     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11873                                   SDValue(NewLoad.getNode(), 1));
11874   }
11875 
11876   if (UseAA) {
11877     // Replace the all stores with the new store.
11878     for (unsigned i = 0; i < NumElem; ++i)
11879       CombineTo(StoreNodes[i].MemNode, NewStore);
11880   } else {
11881     // Replace the last store with the new store.
11882     CombineTo(LatestOp, NewStore);
11883     // Erase all other stores.
11884     for (unsigned i = 0; i < NumElem; ++i) {
11885       // Remove all Store nodes.
11886       if (StoreNodes[i].MemNode == LatestOp)
11887         continue;
11888       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11889       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11890       deleteAndRecombine(St);
11891     }
11892   }
11893 
11894   return true;
11895 }
11896 
11897 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11898   SDLoc SL(ST);
11899   SDValue ReplStore;
11900 
11901   // Replace the chain to avoid dependency.
11902   if (ST->isTruncatingStore()) {
11903     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11904                                   ST->getBasePtr(), ST->getMemoryVT(),
11905                                   ST->getMemOperand());
11906   } else {
11907     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11908                              ST->getMemOperand());
11909   }
11910 
11911   // Create token to keep both nodes around.
11912   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11913                               MVT::Other, ST->getChain(), ReplStore);
11914 
11915   // Make sure the new and old chains are cleaned up.
11916   AddToWorklist(Token.getNode());
11917 
11918   // Don't add users to work list.
11919   return CombineTo(ST, Token, false);
11920 }
11921 
11922 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11923   SDValue Value = ST->getValue();
11924   if (Value.getOpcode() == ISD::TargetConstantFP)
11925     return SDValue();
11926 
11927   SDLoc DL(ST);
11928 
11929   SDValue Chain = ST->getChain();
11930   SDValue Ptr = ST->getBasePtr();
11931 
11932   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11933 
11934   // NOTE: If the original store is volatile, this transform must not increase
11935   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11936   // processor operation but an i64 (which is not legal) requires two.  So the
11937   // transform should not be done in this case.
11938 
11939   SDValue Tmp;
11940   switch (CFP->getSimpleValueType(0).SimpleTy) {
11941   default:
11942     llvm_unreachable("Unknown FP type");
11943   case MVT::f16:    // We don't do this for these yet.
11944   case MVT::f80:
11945   case MVT::f128:
11946   case MVT::ppcf128:
11947     return SDValue();
11948   case MVT::f32:
11949     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11950         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11951       ;
11952       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11953                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11954                             MVT::i32);
11955       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11956     }
11957 
11958     return SDValue();
11959   case MVT::f64:
11960     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11961          !ST->isVolatile()) ||
11962         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11963       ;
11964       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11965                             getZExtValue(), SDLoc(CFP), MVT::i64);
11966       return DAG.getStore(Chain, DL, Tmp,
11967                           Ptr, ST->getMemOperand());
11968     }
11969 
11970     if (!ST->isVolatile() &&
11971         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11972       // Many FP stores are not made apparent until after legalize, e.g. for
11973       // argument passing.  Since this is so common, custom legalize the
11974       // 64-bit integer store into two 32-bit stores.
11975       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11976       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11977       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11978       if (DAG.getDataLayout().isBigEndian())
11979         std::swap(Lo, Hi);
11980 
11981       unsigned Alignment = ST->getAlignment();
11982       bool isVolatile = ST->isVolatile();
11983       bool isNonTemporal = ST->isNonTemporal();
11984       AAMDNodes AAInfo = ST->getAAInfo();
11985 
11986       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11987                                  Ptr, ST->getPointerInfo(),
11988                                  isVolatile, isNonTemporal,
11989                                  ST->getAlignment(), AAInfo);
11990       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11991                         DAG.getConstant(4, DL, Ptr.getValueType()));
11992       Alignment = MinAlign(Alignment, 4U);
11993       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11994                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11995                                  isVolatile, isNonTemporal,
11996                                  Alignment, AAInfo);
11997       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11998                          St0, St1);
11999     }
12000 
12001     return SDValue();
12002   }
12003 }
12004 
12005 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12006   StoreSDNode *ST  = cast<StoreSDNode>(N);
12007   SDValue Chain = ST->getChain();
12008   SDValue Value = ST->getValue();
12009   SDValue Ptr   = ST->getBasePtr();
12010 
12011   // If this is a store of a bit convert, store the input value if the
12012   // resultant store does not need a higher alignment than the original.
12013   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12014       ST->isUnindexed()) {
12015     EVT SVT = Value.getOperand(0).getValueType();
12016     if (((!LegalOperations && !ST->isVolatile()) ||
12017          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12018         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12019       unsigned OrigAlign = ST->getAlignment();
12020       bool Fast = false;
12021       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12022                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12023           Fast) {
12024         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
12025                             Ptr, ST->getPointerInfo(), ST->isVolatile(),
12026                             ST->isNonTemporal(), OrigAlign,
12027                             ST->getAAInfo());
12028       }
12029     }
12030   }
12031 
12032   // Turn 'store undef, Ptr' -> nothing.
12033   if (Value.isUndef() && ST->isUnindexed())
12034     return Chain;
12035 
12036   // Try to infer better alignment information than the store already has.
12037   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12038     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12039       if (Align > ST->getAlignment()) {
12040         SDValue NewStore =
12041                DAG.getTruncStore(Chain, SDLoc(N), Value,
12042                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
12043                                  ST->isVolatile(), ST->isNonTemporal(), Align,
12044                                  ST->getAAInfo());
12045         if (NewStore.getNode() != N)
12046           return CombineTo(ST, NewStore, true);
12047       }
12048     }
12049   }
12050 
12051   // Try transforming a pair floating point load / store ops to integer
12052   // load / store ops.
12053   if (SDValue NewST = TransformFPLoadStorePair(N))
12054     return NewST;
12055 
12056   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12057                                                   : DAG.getSubtarget().useAA();
12058 #ifndef NDEBUG
12059   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12060       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12061     UseAA = false;
12062 #endif
12063   if (UseAA && ST->isUnindexed()) {
12064     // FIXME: We should do this even without AA enabled. AA will just allow
12065     // FindBetterChain to work in more situations. The problem with this is that
12066     // any combine that expects memory operations to be on consecutive chains
12067     // first needs to be updated to look for users of the same chain.
12068 
12069     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12070     // adjacent stores.
12071     if (findBetterNeighborChains(ST)) {
12072       // replaceStoreChain uses CombineTo, which handled all of the worklist
12073       // manipulation. Return the original node to not do anything else.
12074       return SDValue(ST, 0);
12075     }
12076   }
12077 
12078   // Try transforming N to an indexed store.
12079   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12080     return SDValue(N, 0);
12081 
12082   // FIXME: is there such a thing as a truncating indexed store?
12083   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12084       Value.getValueType().isInteger()) {
12085     // See if we can simplify the input to this truncstore with knowledge that
12086     // only the low bits are being used.  For example:
12087     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12088     SDValue Shorter =
12089       GetDemandedBits(Value,
12090                       APInt::getLowBitsSet(
12091                         Value.getValueType().getScalarType().getSizeInBits(),
12092                         ST->getMemoryVT().getScalarType().getSizeInBits()));
12093     AddToWorklist(Value.getNode());
12094     if (Shorter.getNode())
12095       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12096                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12097 
12098     // Otherwise, see if we can simplify the operation with
12099     // SimplifyDemandedBits, which only works if the value has a single use.
12100     if (SimplifyDemandedBits(Value,
12101                         APInt::getLowBitsSet(
12102                           Value.getValueType().getScalarType().getSizeInBits(),
12103                           ST->getMemoryVT().getScalarType().getSizeInBits())))
12104       return SDValue(N, 0);
12105   }
12106 
12107   // If this is a load followed by a store to the same location, then the store
12108   // is dead/noop.
12109   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12110     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12111         ST->isUnindexed() && !ST->isVolatile() &&
12112         // There can't be any side effects between the load and store, such as
12113         // a call or store.
12114         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12115       // The store is dead, remove it.
12116       return Chain;
12117     }
12118   }
12119 
12120   // If this is a store followed by a store with the same value to the same
12121   // location, then the store is dead/noop.
12122   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12123     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12124         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12125         ST1->isUnindexed() && !ST1->isVolatile()) {
12126       // The store is dead, remove it.
12127       return Chain;
12128     }
12129   }
12130 
12131   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12132   // truncating store.  We can do this even if this is already a truncstore.
12133   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12134       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12135       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12136                             ST->getMemoryVT())) {
12137     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12138                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12139   }
12140 
12141   // Only perform this optimization before the types are legal, because we
12142   // don't want to perform this optimization on every DAGCombine invocation.
12143   if (!LegalTypes) {
12144     bool EverChanged = false;
12145 
12146     do {
12147       // There can be multiple store sequences on the same chain.
12148       // Keep trying to merge store sequences until we are unable to do so
12149       // or until we merge the last store on the chain.
12150       bool Changed = MergeConsecutiveStores(ST);
12151       EverChanged |= Changed;
12152       if (!Changed) break;
12153     } while (ST->getOpcode() != ISD::DELETED_NODE);
12154 
12155     if (EverChanged)
12156       return SDValue(N, 0);
12157   }
12158 
12159   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12160   //
12161   // Make sure to do this only after attempting to merge stores in order to
12162   //  avoid changing the types of some subset of stores due to visit order,
12163   //  preventing their merging.
12164   if (isa<ConstantFPSDNode>(Value)) {
12165     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12166       return NewSt;
12167   }
12168 
12169   return ReduceLoadOpStoreWidth(N);
12170 }
12171 
12172 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12173   SDValue InVec = N->getOperand(0);
12174   SDValue InVal = N->getOperand(1);
12175   SDValue EltNo = N->getOperand(2);
12176   SDLoc dl(N);
12177 
12178   // If the inserted element is an UNDEF, just use the input vector.
12179   if (InVal.isUndef())
12180     return InVec;
12181 
12182   EVT VT = InVec.getValueType();
12183 
12184   // If we can't generate a legal BUILD_VECTOR, exit
12185   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12186     return SDValue();
12187 
12188   // Check that we know which element is being inserted
12189   if (!isa<ConstantSDNode>(EltNo))
12190     return SDValue();
12191   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12192 
12193   // Canonicalize insert_vector_elt dag nodes.
12194   // Example:
12195   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12196   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12197   //
12198   // Do this only if the child insert_vector node has one use; also
12199   // do this only if indices are both constants and Idx1 < Idx0.
12200   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12201       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12202     unsigned OtherElt =
12203       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12204     if (Elt < OtherElt) {
12205       // Swap nodes.
12206       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12207                                   InVec.getOperand(0), InVal, EltNo);
12208       AddToWorklist(NewOp.getNode());
12209       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12210                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12211     }
12212   }
12213 
12214   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12215   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12216   // vector elements.
12217   SmallVector<SDValue, 8> Ops;
12218   // Do not combine these two vectors if the output vector will not replace
12219   // the input vector.
12220   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12221     Ops.append(InVec.getNode()->op_begin(),
12222                InVec.getNode()->op_end());
12223   } else if (InVec.isUndef()) {
12224     unsigned NElts = VT.getVectorNumElements();
12225     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12226   } else {
12227     return SDValue();
12228   }
12229 
12230   // Insert the element
12231   if (Elt < Ops.size()) {
12232     // All the operands of BUILD_VECTOR must have the same type;
12233     // we enforce that here.
12234     EVT OpVT = Ops[0].getValueType();
12235     if (InVal.getValueType() != OpVT)
12236       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12237                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12238                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12239     Ops[Elt] = InVal;
12240   }
12241 
12242   // Return the new vector
12243   return DAG.getBuildVector(VT, dl, Ops);
12244 }
12245 
12246 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12247     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12248   EVT ResultVT = EVE->getValueType(0);
12249   EVT VecEltVT = InVecVT.getVectorElementType();
12250   unsigned Align = OriginalLoad->getAlignment();
12251   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12252       VecEltVT.getTypeForEVT(*DAG.getContext()));
12253 
12254   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12255     return SDValue();
12256 
12257   Align = NewAlign;
12258 
12259   SDValue NewPtr = OriginalLoad->getBasePtr();
12260   SDValue Offset;
12261   EVT PtrType = NewPtr.getValueType();
12262   MachinePointerInfo MPI;
12263   SDLoc DL(EVE);
12264   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12265     int Elt = ConstEltNo->getZExtValue();
12266     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12267     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12268     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12269   } else {
12270     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12271     Offset = DAG.getNode(
12272         ISD::MUL, DL, PtrType, Offset,
12273         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12274     MPI = OriginalLoad->getPointerInfo();
12275   }
12276   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12277 
12278   // The replacement we need to do here is a little tricky: we need to
12279   // replace an extractelement of a load with a load.
12280   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12281   // Note that this replacement assumes that the extractvalue is the only
12282   // use of the load; that's okay because we don't want to perform this
12283   // transformation in other cases anyway.
12284   SDValue Load;
12285   SDValue Chain;
12286   if (ResultVT.bitsGT(VecEltVT)) {
12287     // If the result type of vextract is wider than the load, then issue an
12288     // extending load instead.
12289     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12290                                                   VecEltVT)
12291                                    ? ISD::ZEXTLOAD
12292                                    : ISD::EXTLOAD;
12293     Load = DAG.getExtLoad(
12294         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12295         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12296         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12297     Chain = Load.getValue(1);
12298   } else {
12299     Load = DAG.getLoad(
12300         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12301         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12302         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12303     Chain = Load.getValue(1);
12304     if (ResultVT.bitsLT(VecEltVT))
12305       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12306     else
12307       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12308   }
12309   WorklistRemover DeadNodes(*this);
12310   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12311   SDValue To[] = { Load, Chain };
12312   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12313   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12314   // worklist explicitly as well.
12315   AddToWorklist(Load.getNode());
12316   AddUsersToWorklist(Load.getNode()); // Add users too
12317   // Make sure to revisit this node to clean it up; it will usually be dead.
12318   AddToWorklist(EVE);
12319   ++OpsNarrowed;
12320   return SDValue(EVE, 0);
12321 }
12322 
12323 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12324   // (vextract (scalar_to_vector val, 0) -> val
12325   SDValue InVec = N->getOperand(0);
12326   EVT VT = InVec.getValueType();
12327   EVT NVT = N->getValueType(0);
12328 
12329   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12330     // Check if the result type doesn't match the inserted element type. A
12331     // SCALAR_TO_VECTOR may truncate the inserted element and the
12332     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12333     SDValue InOp = InVec.getOperand(0);
12334     if (InOp.getValueType() != NVT) {
12335       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12336       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12337     }
12338     return InOp;
12339   }
12340 
12341   SDValue EltNo = N->getOperand(1);
12342   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12343 
12344   // extract_vector_elt (build_vector x, y), 1 -> y
12345   if (ConstEltNo &&
12346       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12347       TLI.isTypeLegal(VT) &&
12348       (InVec.hasOneUse() ||
12349        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12350     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12351     EVT InEltVT = Elt.getValueType();
12352 
12353     // Sometimes build_vector's scalar input types do not match result type.
12354     if (NVT == InEltVT)
12355       return Elt;
12356 
12357     // TODO: It may be useful to truncate if free if the build_vector implicitly
12358     // converts.
12359   }
12360 
12361   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12362   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12363       ConstEltNo->isNullValue() && VT.isInteger()) {
12364     SDValue BCSrc = InVec.getOperand(0);
12365     if (BCSrc.getValueType().isScalarInteger())
12366       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12367   }
12368 
12369   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12370   // We only perform this optimization before the op legalization phase because
12371   // we may introduce new vector instructions which are not backed by TD
12372   // patterns. For example on AVX, extracting elements from a wide vector
12373   // without using extract_subvector. However, if we can find an underlying
12374   // scalar value, then we can always use that.
12375   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12376     int NumElem = VT.getVectorNumElements();
12377     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12378     // Find the new index to extract from.
12379     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12380 
12381     // Extracting an undef index is undef.
12382     if (OrigElt == -1)
12383       return DAG.getUNDEF(NVT);
12384 
12385     // Select the right vector half to extract from.
12386     SDValue SVInVec;
12387     if (OrigElt < NumElem) {
12388       SVInVec = InVec->getOperand(0);
12389     } else {
12390       SVInVec = InVec->getOperand(1);
12391       OrigElt -= NumElem;
12392     }
12393 
12394     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12395       SDValue InOp = SVInVec.getOperand(OrigElt);
12396       if (InOp.getValueType() != NVT) {
12397         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12398         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12399       }
12400 
12401       return InOp;
12402     }
12403 
12404     // FIXME: We should handle recursing on other vector shuffles and
12405     // scalar_to_vector here as well.
12406 
12407     if (!LegalOperations) {
12408       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12409       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12410                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12411     }
12412   }
12413 
12414   bool BCNumEltsChanged = false;
12415   EVT ExtVT = VT.getVectorElementType();
12416   EVT LVT = ExtVT;
12417 
12418   // If the result of load has to be truncated, then it's not necessarily
12419   // profitable.
12420   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12421     return SDValue();
12422 
12423   if (InVec.getOpcode() == ISD::BITCAST) {
12424     // Don't duplicate a load with other uses.
12425     if (!InVec.hasOneUse())
12426       return SDValue();
12427 
12428     EVT BCVT = InVec.getOperand(0).getValueType();
12429     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12430       return SDValue();
12431     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12432       BCNumEltsChanged = true;
12433     InVec = InVec.getOperand(0);
12434     ExtVT = BCVT.getVectorElementType();
12435   }
12436 
12437   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12438   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12439       ISD::isNormalLoad(InVec.getNode()) &&
12440       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12441     SDValue Index = N->getOperand(1);
12442     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12443       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12444                                                            OrigLoad);
12445   }
12446 
12447   // Perform only after legalization to ensure build_vector / vector_shuffle
12448   // optimizations have already been done.
12449   if (!LegalOperations) return SDValue();
12450 
12451   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12452   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12453   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12454 
12455   if (ConstEltNo) {
12456     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12457 
12458     LoadSDNode *LN0 = nullptr;
12459     const ShuffleVectorSDNode *SVN = nullptr;
12460     if (ISD::isNormalLoad(InVec.getNode())) {
12461       LN0 = cast<LoadSDNode>(InVec);
12462     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12463                InVec.getOperand(0).getValueType() == ExtVT &&
12464                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12465       // Don't duplicate a load with other uses.
12466       if (!InVec.hasOneUse())
12467         return SDValue();
12468 
12469       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12470     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12471       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12472       // =>
12473       // (load $addr+1*size)
12474 
12475       // Don't duplicate a load with other uses.
12476       if (!InVec.hasOneUse())
12477         return SDValue();
12478 
12479       // If the bit convert changed the number of elements, it is unsafe
12480       // to examine the mask.
12481       if (BCNumEltsChanged)
12482         return SDValue();
12483 
12484       // Select the input vector, guarding against out of range extract vector.
12485       unsigned NumElems = VT.getVectorNumElements();
12486       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12487       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12488 
12489       if (InVec.getOpcode() == ISD::BITCAST) {
12490         // Don't duplicate a load with other uses.
12491         if (!InVec.hasOneUse())
12492           return SDValue();
12493 
12494         InVec = InVec.getOperand(0);
12495       }
12496       if (ISD::isNormalLoad(InVec.getNode())) {
12497         LN0 = cast<LoadSDNode>(InVec);
12498         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12499         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12500       }
12501     }
12502 
12503     // Make sure we found a non-volatile load and the extractelement is
12504     // the only use.
12505     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12506       return SDValue();
12507 
12508     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12509     if (Elt == -1)
12510       return DAG.getUNDEF(LVT);
12511 
12512     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12513   }
12514 
12515   return SDValue();
12516 }
12517 
12518 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12519 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12520   // We perform this optimization post type-legalization because
12521   // the type-legalizer often scalarizes integer-promoted vectors.
12522   // Performing this optimization before may create bit-casts which
12523   // will be type-legalized to complex code sequences.
12524   // We perform this optimization only before the operation legalizer because we
12525   // may introduce illegal operations.
12526   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12527     return SDValue();
12528 
12529   unsigned NumInScalars = N->getNumOperands();
12530   SDLoc dl(N);
12531   EVT VT = N->getValueType(0);
12532 
12533   // Check to see if this is a BUILD_VECTOR of a bunch of values
12534   // which come from any_extend or zero_extend nodes. If so, we can create
12535   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12536   // optimizations. We do not handle sign-extend because we can't fill the sign
12537   // using shuffles.
12538   EVT SourceType = MVT::Other;
12539   bool AllAnyExt = true;
12540 
12541   for (unsigned i = 0; i != NumInScalars; ++i) {
12542     SDValue In = N->getOperand(i);
12543     // Ignore undef inputs.
12544     if (In.isUndef()) continue;
12545 
12546     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12547     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12548 
12549     // Abort if the element is not an extension.
12550     if (!ZeroExt && !AnyExt) {
12551       SourceType = MVT::Other;
12552       break;
12553     }
12554 
12555     // The input is a ZeroExt or AnyExt. Check the original type.
12556     EVT InTy = In.getOperand(0).getValueType();
12557 
12558     // Check that all of the widened source types are the same.
12559     if (SourceType == MVT::Other)
12560       // First time.
12561       SourceType = InTy;
12562     else if (InTy != SourceType) {
12563       // Multiple income types. Abort.
12564       SourceType = MVT::Other;
12565       break;
12566     }
12567 
12568     // Check if all of the extends are ANY_EXTENDs.
12569     AllAnyExt &= AnyExt;
12570   }
12571 
12572   // In order to have valid types, all of the inputs must be extended from the
12573   // same source type and all of the inputs must be any or zero extend.
12574   // Scalar sizes must be a power of two.
12575   EVT OutScalarTy = VT.getScalarType();
12576   bool ValidTypes = SourceType != MVT::Other &&
12577                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12578                  isPowerOf2_32(SourceType.getSizeInBits());
12579 
12580   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12581   // turn into a single shuffle instruction.
12582   if (!ValidTypes)
12583     return SDValue();
12584 
12585   bool isLE = DAG.getDataLayout().isLittleEndian();
12586   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12587   assert(ElemRatio > 1 && "Invalid element size ratio");
12588   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12589                                DAG.getConstant(0, SDLoc(N), SourceType);
12590 
12591   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12592   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12593 
12594   // Populate the new build_vector
12595   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12596     SDValue Cast = N->getOperand(i);
12597     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12598             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12599             Cast.isUndef()) && "Invalid cast opcode");
12600     SDValue In;
12601     if (Cast.isUndef())
12602       In = DAG.getUNDEF(SourceType);
12603     else
12604       In = Cast->getOperand(0);
12605     unsigned Index = isLE ? (i * ElemRatio) :
12606                             (i * ElemRatio + (ElemRatio - 1));
12607 
12608     assert(Index < Ops.size() && "Invalid index");
12609     Ops[Index] = In;
12610   }
12611 
12612   // The type of the new BUILD_VECTOR node.
12613   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12614   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12615          "Invalid vector size");
12616   // Check if the new vector type is legal.
12617   if (!isTypeLegal(VecVT)) return SDValue();
12618 
12619   // Make the new BUILD_VECTOR.
12620   SDValue BV = DAG.getBuildVector(VecVT, dl, Ops);
12621 
12622   // The new BUILD_VECTOR node has the potential to be further optimized.
12623   AddToWorklist(BV.getNode());
12624   // Bitcast to the desired type.
12625   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12626 }
12627 
12628 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12629   EVT VT = N->getValueType(0);
12630 
12631   unsigned NumInScalars = N->getNumOperands();
12632   SDLoc dl(N);
12633 
12634   EVT SrcVT = MVT::Other;
12635   unsigned Opcode = ISD::DELETED_NODE;
12636   unsigned NumDefs = 0;
12637 
12638   for (unsigned i = 0; i != NumInScalars; ++i) {
12639     SDValue In = N->getOperand(i);
12640     unsigned Opc = In.getOpcode();
12641 
12642     if (Opc == ISD::UNDEF)
12643       continue;
12644 
12645     // If all scalar values are floats and converted from integers.
12646     if (Opcode == ISD::DELETED_NODE &&
12647         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12648       Opcode = Opc;
12649     }
12650 
12651     if (Opc != Opcode)
12652       return SDValue();
12653 
12654     EVT InVT = In.getOperand(0).getValueType();
12655 
12656     // If all scalar values are typed differently, bail out. It's chosen to
12657     // simplify BUILD_VECTOR of integer types.
12658     if (SrcVT == MVT::Other)
12659       SrcVT = InVT;
12660     if (SrcVT != InVT)
12661       return SDValue();
12662     NumDefs++;
12663   }
12664 
12665   // If the vector has just one element defined, it's not worth to fold it into
12666   // a vectorized one.
12667   if (NumDefs < 2)
12668     return SDValue();
12669 
12670   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12671          && "Should only handle conversion from integer to float.");
12672   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12673 
12674   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12675 
12676   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12677     return SDValue();
12678 
12679   // Just because the floating-point vector type is legal does not necessarily
12680   // mean that the corresponding integer vector type is.
12681   if (!isTypeLegal(NVT))
12682     return SDValue();
12683 
12684   SmallVector<SDValue, 8> Opnds;
12685   for (unsigned i = 0; i != NumInScalars; ++i) {
12686     SDValue In = N->getOperand(i);
12687 
12688     if (In.isUndef())
12689       Opnds.push_back(DAG.getUNDEF(SrcVT));
12690     else
12691       Opnds.push_back(In.getOperand(0));
12692   }
12693   SDValue BV = DAG.getBuildVector(NVT, dl, Opnds);
12694   AddToWorklist(BV.getNode());
12695 
12696   return DAG.getNode(Opcode, dl, VT, BV);
12697 }
12698 
12699 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12700   unsigned NumInScalars = N->getNumOperands();
12701   SDLoc dl(N);
12702   EVT VT = N->getValueType(0);
12703 
12704   // A vector built entirely of undefs is undef.
12705   if (ISD::allOperandsUndef(N))
12706     return DAG.getUNDEF(VT);
12707 
12708   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12709     return V;
12710 
12711   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12712     return V;
12713 
12714   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12715   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12716   // at most two distinct vectors, turn this into a shuffle node.
12717 
12718   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12719   if (!isTypeLegal(VT))
12720     return SDValue();
12721 
12722   // May only combine to shuffle after legalize if shuffle is legal.
12723   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12724     return SDValue();
12725 
12726   SDValue VecIn1, VecIn2;
12727   bool UsesZeroVector = false;
12728   for (unsigned i = 0; i != NumInScalars; ++i) {
12729     SDValue Op = N->getOperand(i);
12730     // Ignore undef inputs.
12731     if (Op.isUndef()) continue;
12732 
12733     // See if we can combine this build_vector into a blend with a zero vector.
12734     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12735       UsesZeroVector = true;
12736       continue;
12737     }
12738 
12739     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12740     // constant index, bail out.
12741     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12742         !isa<ConstantSDNode>(Op.getOperand(1))) {
12743       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12744       break;
12745     }
12746 
12747     // We allow up to two distinct input vectors.
12748     SDValue ExtractedFromVec = Op.getOperand(0);
12749     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12750       continue;
12751 
12752     if (!VecIn1.getNode()) {
12753       VecIn1 = ExtractedFromVec;
12754     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12755       VecIn2 = ExtractedFromVec;
12756     } else {
12757       // Too many inputs.
12758       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12759       break;
12760     }
12761   }
12762 
12763   // If everything is good, we can make a shuffle operation.
12764   if (VecIn1.getNode()) {
12765     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12766     SmallVector<int, 8> Mask;
12767     for (unsigned i = 0; i != NumInScalars; ++i) {
12768       unsigned Opcode = N->getOperand(i).getOpcode();
12769       if (Opcode == ISD::UNDEF) {
12770         Mask.push_back(-1);
12771         continue;
12772       }
12773 
12774       // Operands can also be zero.
12775       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12776         assert(UsesZeroVector &&
12777                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12778                "Unexpected node found!");
12779         Mask.push_back(NumInScalars+i);
12780         continue;
12781       }
12782 
12783       // If extracting from the first vector, just use the index directly.
12784       SDValue Extract = N->getOperand(i);
12785       SDValue ExtVal = Extract.getOperand(1);
12786       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12787       if (Extract.getOperand(0) == VecIn1) {
12788         Mask.push_back(ExtIndex);
12789         continue;
12790       }
12791 
12792       // Otherwise, use InIdx + InputVecSize
12793       Mask.push_back(InNumElements + ExtIndex);
12794     }
12795 
12796     // Avoid introducing illegal shuffles with zero.
12797     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12798       return SDValue();
12799 
12800     // We can't generate a shuffle node with mismatched input and output types.
12801     // Attempt to transform a single input vector to the correct type.
12802     if ((VT != VecIn1.getValueType())) {
12803       // If the input vector type has a different base type to the output
12804       // vector type, bail out.
12805       EVT VTElemType = VT.getVectorElementType();
12806       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12807           (VecIn2.getNode() &&
12808            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12809         return SDValue();
12810 
12811       // If the input vector is too small, widen it.
12812       // We only support widening of vectors which are half the size of the
12813       // output registers. For example XMM->YMM widening on X86 with AVX.
12814       EVT VecInT = VecIn1.getValueType();
12815       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12816         // If we only have one small input, widen it by adding undef values.
12817         if (!VecIn2.getNode())
12818           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12819                                DAG.getUNDEF(VecIn1.getValueType()));
12820         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12821           // If we have two small inputs of the same type, try to concat them.
12822           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12823           VecIn2 = SDValue(nullptr, 0);
12824         } else
12825           return SDValue();
12826       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12827         // If the input vector is too large, try to split it.
12828         // We don't support having two input vectors that are too large.
12829         // If the zero vector was used, we can not split the vector,
12830         // since we'd need 3 inputs.
12831         if (UsesZeroVector || VecIn2.getNode())
12832           return SDValue();
12833 
12834         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12835           return SDValue();
12836 
12837         // Try to replace VecIn1 with two extract_subvectors
12838         // No need to update the masks, they should still be correct.
12839         VecIn2 = DAG.getNode(
12840             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12841             DAG.getConstant(VT.getVectorNumElements(), dl,
12842                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12843         VecIn1 = DAG.getNode(
12844             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12845             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12846       } else
12847         return SDValue();
12848     }
12849 
12850     if (UsesZeroVector)
12851       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12852                                 DAG.getConstantFP(0.0, dl, VT);
12853     else
12854       // If VecIn2 is unused then change it to undef.
12855       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12856 
12857     // Check that we were able to transform all incoming values to the same
12858     // type.
12859     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12860         VecIn1.getValueType() != VT)
12861           return SDValue();
12862 
12863     // Return the new VECTOR_SHUFFLE node.
12864     SDValue Ops[2];
12865     Ops[0] = VecIn1;
12866     Ops[1] = VecIn2;
12867     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12868   }
12869 
12870   return SDValue();
12871 }
12872 
12873 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12875   EVT OpVT = N->getOperand(0).getValueType();
12876 
12877   // If the operands are legal vectors, leave them alone.
12878   if (TLI.isTypeLegal(OpVT))
12879     return SDValue();
12880 
12881   SDLoc DL(N);
12882   EVT VT = N->getValueType(0);
12883   SmallVector<SDValue, 8> Ops;
12884 
12885   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12886   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12887 
12888   // Keep track of what we encounter.
12889   bool AnyInteger = false;
12890   bool AnyFP = false;
12891   for (const SDValue &Op : N->ops()) {
12892     if (ISD::BITCAST == Op.getOpcode() &&
12893         !Op.getOperand(0).getValueType().isVector())
12894       Ops.push_back(Op.getOperand(0));
12895     else if (ISD::UNDEF == Op.getOpcode())
12896       Ops.push_back(ScalarUndef);
12897     else
12898       return SDValue();
12899 
12900     // Note whether we encounter an integer or floating point scalar.
12901     // If it's neither, bail out, it could be something weird like x86mmx.
12902     EVT LastOpVT = Ops.back().getValueType();
12903     if (LastOpVT.isFloatingPoint())
12904       AnyFP = true;
12905     else if (LastOpVT.isInteger())
12906       AnyInteger = true;
12907     else
12908       return SDValue();
12909   }
12910 
12911   // If any of the operands is a floating point scalar bitcast to a vector,
12912   // use floating point types throughout, and bitcast everything.
12913   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12914   if (AnyFP) {
12915     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12916     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12917     if (AnyInteger) {
12918       for (SDValue &Op : Ops) {
12919         if (Op.getValueType() == SVT)
12920           continue;
12921         if (Op.isUndef())
12922           Op = ScalarUndef;
12923         else
12924           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12925       }
12926     }
12927   }
12928 
12929   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12930                                VT.getSizeInBits() / SVT.getSizeInBits());
12931   return DAG.getNode(ISD::BITCAST, DL, VT,
12932                      DAG.getBuildVector(VecVT, DL, Ops));
12933 }
12934 
12935 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12936 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12937 // most two distinct vectors the same size as the result, attempt to turn this
12938 // into a legal shuffle.
12939 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12940   EVT VT = N->getValueType(0);
12941   EVT OpVT = N->getOperand(0).getValueType();
12942   int NumElts = VT.getVectorNumElements();
12943   int NumOpElts = OpVT.getVectorNumElements();
12944 
12945   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12946   SmallVector<int, 8> Mask;
12947 
12948   for (SDValue Op : N->ops()) {
12949     // Peek through any bitcast.
12950     while (Op.getOpcode() == ISD::BITCAST)
12951       Op = Op.getOperand(0);
12952 
12953     // UNDEF nodes convert to UNDEF shuffle mask values.
12954     if (Op.isUndef()) {
12955       Mask.append((unsigned)NumOpElts, -1);
12956       continue;
12957     }
12958 
12959     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12960       return SDValue();
12961 
12962     // What vector are we extracting the subvector from and at what index?
12963     SDValue ExtVec = Op.getOperand(0);
12964 
12965     // We want the EVT of the original extraction to correctly scale the
12966     // extraction index.
12967     EVT ExtVT = ExtVec.getValueType();
12968 
12969     // Peek through any bitcast.
12970     while (ExtVec.getOpcode() == ISD::BITCAST)
12971       ExtVec = ExtVec.getOperand(0);
12972 
12973     // UNDEF nodes convert to UNDEF shuffle mask values.
12974     if (ExtVec.isUndef()) {
12975       Mask.append((unsigned)NumOpElts, -1);
12976       continue;
12977     }
12978 
12979     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12980       return SDValue();
12981     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12982 
12983     // Ensure that we are extracting a subvector from a vector the same
12984     // size as the result.
12985     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12986       return SDValue();
12987 
12988     // Scale the subvector index to account for any bitcast.
12989     int NumExtElts = ExtVT.getVectorNumElements();
12990     if (0 == (NumExtElts % NumElts))
12991       ExtIdx /= (NumExtElts / NumElts);
12992     else if (0 == (NumElts % NumExtElts))
12993       ExtIdx *= (NumElts / NumExtElts);
12994     else
12995       return SDValue();
12996 
12997     // At most we can reference 2 inputs in the final shuffle.
12998     if (SV0.isUndef() || SV0 == ExtVec) {
12999       SV0 = ExtVec;
13000       for (int i = 0; i != NumOpElts; ++i)
13001         Mask.push_back(i + ExtIdx);
13002     } else if (SV1.isUndef() || SV1 == ExtVec) {
13003       SV1 = ExtVec;
13004       for (int i = 0; i != NumOpElts; ++i)
13005         Mask.push_back(i + ExtIdx + NumElts);
13006     } else {
13007       return SDValue();
13008     }
13009   }
13010 
13011   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13012     return SDValue();
13013 
13014   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13015                               DAG.getBitcast(VT, SV1), Mask);
13016 }
13017 
13018 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13019   // If we only have one input vector, we don't need to do any concatenation.
13020   if (N->getNumOperands() == 1)
13021     return N->getOperand(0);
13022 
13023   // Check if all of the operands are undefs.
13024   EVT VT = N->getValueType(0);
13025   if (ISD::allOperandsUndef(N))
13026     return DAG.getUNDEF(VT);
13027 
13028   // Optimize concat_vectors where all but the first of the vectors are undef.
13029   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13030         return Op.isUndef();
13031       })) {
13032     SDValue In = N->getOperand(0);
13033     assert(In.getValueType().isVector() && "Must concat vectors");
13034 
13035     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13036     if (In->getOpcode() == ISD::BITCAST &&
13037         !In->getOperand(0)->getValueType(0).isVector()) {
13038       SDValue Scalar = In->getOperand(0);
13039 
13040       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13041       // look through the trunc so we can still do the transform:
13042       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13043       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13044           !TLI.isTypeLegal(Scalar.getValueType()) &&
13045           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13046         Scalar = Scalar->getOperand(0);
13047 
13048       EVT SclTy = Scalar->getValueType(0);
13049 
13050       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13051         return SDValue();
13052 
13053       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13054                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13055       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13056         return SDValue();
13057 
13058       SDLoc dl = SDLoc(N);
13059       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
13060       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
13061     }
13062   }
13063 
13064   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13065   // We have already tested above for an UNDEF only concatenation.
13066   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13067   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13068   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13069     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13070   };
13071   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13072     SmallVector<SDValue, 8> Opnds;
13073     EVT SVT = VT.getScalarType();
13074 
13075     EVT MinVT = SVT;
13076     if (!SVT.isFloatingPoint()) {
13077       // If BUILD_VECTOR are from built from integer, they may have different
13078       // operand types. Get the smallest type and truncate all operands to it.
13079       bool FoundMinVT = false;
13080       for (const SDValue &Op : N->ops())
13081         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13082           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13083           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13084           FoundMinVT = true;
13085         }
13086       assert(FoundMinVT && "Concat vector type mismatch");
13087     }
13088 
13089     for (const SDValue &Op : N->ops()) {
13090       EVT OpVT = Op.getValueType();
13091       unsigned NumElts = OpVT.getVectorNumElements();
13092 
13093       if (ISD::UNDEF == Op.getOpcode())
13094         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13095 
13096       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13097         if (SVT.isFloatingPoint()) {
13098           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13099           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13100         } else {
13101           for (unsigned i = 0; i != NumElts; ++i)
13102             Opnds.push_back(
13103                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13104         }
13105       }
13106     }
13107 
13108     assert(VT.getVectorNumElements() == Opnds.size() &&
13109            "Concat vector type mismatch");
13110     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13111   }
13112 
13113   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13114   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13115     return V;
13116 
13117   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13118   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13119     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13120       return V;
13121 
13122   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13123   // nodes often generate nop CONCAT_VECTOR nodes.
13124   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13125   // place the incoming vectors at the exact same location.
13126   SDValue SingleSource = SDValue();
13127   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13128 
13129   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13130     SDValue Op = N->getOperand(i);
13131 
13132     if (Op.isUndef())
13133       continue;
13134 
13135     // Check if this is the identity extract:
13136     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13137       return SDValue();
13138 
13139     // Find the single incoming vector for the extract_subvector.
13140     if (SingleSource.getNode()) {
13141       if (Op.getOperand(0) != SingleSource)
13142         return SDValue();
13143     } else {
13144       SingleSource = Op.getOperand(0);
13145 
13146       // Check the source type is the same as the type of the result.
13147       // If not, this concat may extend the vector, so we can not
13148       // optimize it away.
13149       if (SingleSource.getValueType() != N->getValueType(0))
13150         return SDValue();
13151     }
13152 
13153     unsigned IdentityIndex = i * PartNumElem;
13154     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13155     // The extract index must be constant.
13156     if (!CS)
13157       return SDValue();
13158 
13159     // Check that we are reading from the identity index.
13160     if (CS->getZExtValue() != IdentityIndex)
13161       return SDValue();
13162   }
13163 
13164   if (SingleSource.getNode())
13165     return SingleSource;
13166 
13167   return SDValue();
13168 }
13169 
13170 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13171   EVT NVT = N->getValueType(0);
13172   SDValue V = N->getOperand(0);
13173 
13174   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13175     // Combine:
13176     //    (extract_subvec (concat V1, V2, ...), i)
13177     // Into:
13178     //    Vi if possible
13179     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13180     // type.
13181     if (V->getOperand(0).getValueType() != NVT)
13182       return SDValue();
13183     unsigned Idx = N->getConstantOperandVal(1);
13184     unsigned NumElems = NVT.getVectorNumElements();
13185     assert((Idx % NumElems) == 0 &&
13186            "IDX in concat is not a multiple of the result vector length.");
13187     return V->getOperand(Idx / NumElems);
13188   }
13189 
13190   // Skip bitcasting
13191   if (V->getOpcode() == ISD::BITCAST)
13192     V = V.getOperand(0);
13193 
13194   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13195     SDLoc dl(N);
13196     // Handle only simple case where vector being inserted and vector
13197     // being extracted are of same type, and are half size of larger vectors.
13198     EVT BigVT = V->getOperand(0).getValueType();
13199     EVT SmallVT = V->getOperand(1).getValueType();
13200     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13201       return SDValue();
13202 
13203     // Only handle cases where both indexes are constants with the same type.
13204     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13205     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13206 
13207     if (InsIdx && ExtIdx &&
13208         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13209         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13210       // Combine:
13211       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13212       // Into:
13213       //    indices are equal or bit offsets are equal => V1
13214       //    otherwise => (extract_subvec V1, ExtIdx)
13215       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13216           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13217         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
13218       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
13219                          DAG.getNode(ISD::BITCAST, dl,
13220                                      N->getOperand(0).getValueType(),
13221                                      V->getOperand(0)), N->getOperand(1));
13222     }
13223   }
13224 
13225   return SDValue();
13226 }
13227 
13228 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13229                                                  SDValue V, SelectionDAG &DAG) {
13230   SDLoc DL(V);
13231   EVT VT = V.getValueType();
13232 
13233   switch (V.getOpcode()) {
13234   default:
13235     return V;
13236 
13237   case ISD::CONCAT_VECTORS: {
13238     EVT OpVT = V->getOperand(0).getValueType();
13239     int OpSize = OpVT.getVectorNumElements();
13240     SmallBitVector OpUsedElements(OpSize, false);
13241     bool FoundSimplification = false;
13242     SmallVector<SDValue, 4> NewOps;
13243     NewOps.reserve(V->getNumOperands());
13244     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13245       SDValue Op = V->getOperand(i);
13246       bool OpUsed = false;
13247       for (int j = 0; j < OpSize; ++j)
13248         if (UsedElements[i * OpSize + j]) {
13249           OpUsedElements[j] = true;
13250           OpUsed = true;
13251         }
13252       NewOps.push_back(
13253           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13254                  : DAG.getUNDEF(OpVT));
13255       FoundSimplification |= Op == NewOps.back();
13256       OpUsedElements.reset();
13257     }
13258     if (FoundSimplification)
13259       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13260     return V;
13261   }
13262 
13263   case ISD::INSERT_SUBVECTOR: {
13264     SDValue BaseV = V->getOperand(0);
13265     SDValue SubV = V->getOperand(1);
13266     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13267     if (!IdxN)
13268       return V;
13269 
13270     int SubSize = SubV.getValueType().getVectorNumElements();
13271     int Idx = IdxN->getZExtValue();
13272     bool SubVectorUsed = false;
13273     SmallBitVector SubUsedElements(SubSize, false);
13274     for (int i = 0; i < SubSize; ++i)
13275       if (UsedElements[i + Idx]) {
13276         SubVectorUsed = true;
13277         SubUsedElements[i] = true;
13278         UsedElements[i + Idx] = false;
13279       }
13280 
13281     // Now recurse on both the base and sub vectors.
13282     SDValue SimplifiedSubV =
13283         SubVectorUsed
13284             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13285             : DAG.getUNDEF(SubV.getValueType());
13286     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13287     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13288       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13289                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13290     return V;
13291   }
13292   }
13293 }
13294 
13295 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13296                                        SDValue N1, SelectionDAG &DAG) {
13297   EVT VT = SVN->getValueType(0);
13298   int NumElts = VT.getVectorNumElements();
13299   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13300   for (int M : SVN->getMask())
13301     if (M >= 0 && M < NumElts)
13302       N0UsedElements[M] = true;
13303     else if (M >= NumElts)
13304       N1UsedElements[M - NumElts] = true;
13305 
13306   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13307   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13308   if (S0 == N0 && S1 == N1)
13309     return SDValue();
13310 
13311   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13312 }
13313 
13314 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13315 // or turn a shuffle of a single concat into simpler shuffle then concat.
13316 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13317   EVT VT = N->getValueType(0);
13318   unsigned NumElts = VT.getVectorNumElements();
13319 
13320   SDValue N0 = N->getOperand(0);
13321   SDValue N1 = N->getOperand(1);
13322   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13323 
13324   SmallVector<SDValue, 4> Ops;
13325   EVT ConcatVT = N0.getOperand(0).getValueType();
13326   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13327   unsigned NumConcats = NumElts / NumElemsPerConcat;
13328 
13329   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13330   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13331   // half vector elements.
13332   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13333       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13334                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13335     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13336                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13337     N1 = DAG.getUNDEF(ConcatVT);
13338     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13339   }
13340 
13341   // Look at every vector that's inserted. We're looking for exact
13342   // subvector-sized copies from a concatenated vector
13343   for (unsigned I = 0; I != NumConcats; ++I) {
13344     // Make sure we're dealing with a copy.
13345     unsigned Begin = I * NumElemsPerConcat;
13346     bool AllUndef = true, NoUndef = true;
13347     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13348       if (SVN->getMaskElt(J) >= 0)
13349         AllUndef = false;
13350       else
13351         NoUndef = false;
13352     }
13353 
13354     if (NoUndef) {
13355       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13356         return SDValue();
13357 
13358       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13359         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13360           return SDValue();
13361 
13362       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13363       if (FirstElt < N0.getNumOperands())
13364         Ops.push_back(N0.getOperand(FirstElt));
13365       else
13366         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13367 
13368     } else if (AllUndef) {
13369       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13370     } else { // Mixed with general masks and undefs, can't do optimization.
13371       return SDValue();
13372     }
13373   }
13374 
13375   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13376 }
13377 
13378 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13379   EVT VT = N->getValueType(0);
13380   unsigned NumElts = VT.getVectorNumElements();
13381 
13382   SDValue N0 = N->getOperand(0);
13383   SDValue N1 = N->getOperand(1);
13384 
13385   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13386 
13387   // Canonicalize shuffle undef, undef -> undef
13388   if (N0.isUndef() && N1.isUndef())
13389     return DAG.getUNDEF(VT);
13390 
13391   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13392 
13393   // Canonicalize shuffle v, v -> v, undef
13394   if (N0 == N1) {
13395     SmallVector<int, 8> NewMask;
13396     for (unsigned i = 0; i != NumElts; ++i) {
13397       int Idx = SVN->getMaskElt(i);
13398       if (Idx >= (int)NumElts) Idx -= NumElts;
13399       NewMask.push_back(Idx);
13400     }
13401     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13402                                 &NewMask[0]);
13403   }
13404 
13405   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13406   if (N0.isUndef()) {
13407     SmallVector<int, 8> NewMask;
13408     for (unsigned i = 0; i != NumElts; ++i) {
13409       int Idx = SVN->getMaskElt(i);
13410       if (Idx >= 0) {
13411         if (Idx >= (int)NumElts)
13412           Idx -= NumElts;
13413         else
13414           Idx = -1; // remove reference to lhs
13415       }
13416       NewMask.push_back(Idx);
13417     }
13418     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13419                                 &NewMask[0]);
13420   }
13421 
13422   // Remove references to rhs if it is undef
13423   if (N1.isUndef()) {
13424     bool Changed = false;
13425     SmallVector<int, 8> NewMask;
13426     for (unsigned i = 0; i != NumElts; ++i) {
13427       int Idx = SVN->getMaskElt(i);
13428       if (Idx >= (int)NumElts) {
13429         Idx = -1;
13430         Changed = true;
13431       }
13432       NewMask.push_back(Idx);
13433     }
13434     if (Changed)
13435       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13436   }
13437 
13438   // If it is a splat, check if the argument vector is another splat or a
13439   // build_vector.
13440   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13441     SDNode *V = N0.getNode();
13442 
13443     // If this is a bit convert that changes the element type of the vector but
13444     // not the number of vector elements, look through it.  Be careful not to
13445     // look though conversions that change things like v4f32 to v2f64.
13446     if (V->getOpcode() == ISD::BITCAST) {
13447       SDValue ConvInput = V->getOperand(0);
13448       if (ConvInput.getValueType().isVector() &&
13449           ConvInput.getValueType().getVectorNumElements() == NumElts)
13450         V = ConvInput.getNode();
13451     }
13452 
13453     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13454       assert(V->getNumOperands() == NumElts &&
13455              "BUILD_VECTOR has wrong number of operands");
13456       SDValue Base;
13457       bool AllSame = true;
13458       for (unsigned i = 0; i != NumElts; ++i) {
13459         if (!V->getOperand(i).isUndef()) {
13460           Base = V->getOperand(i);
13461           break;
13462         }
13463       }
13464       // Splat of <u, u, u, u>, return <u, u, u, u>
13465       if (!Base.getNode())
13466         return N0;
13467       for (unsigned i = 0; i != NumElts; ++i) {
13468         if (V->getOperand(i) != Base) {
13469           AllSame = false;
13470           break;
13471         }
13472       }
13473       // Splat of <x, x, x, x>, return <x, x, x, x>
13474       if (AllSame)
13475         return N0;
13476 
13477       // Canonicalize any other splat as a build_vector.
13478       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13479       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13480       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13481 
13482       // We may have jumped through bitcasts, so the type of the
13483       // BUILD_VECTOR may not match the type of the shuffle.
13484       if (V->getValueType(0) != VT)
13485         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13486       return NewBV;
13487     }
13488   }
13489 
13490   // There are various patterns used to build up a vector from smaller vectors,
13491   // subvectors, or elements. Scan chains of these and replace unused insertions
13492   // or components with undef.
13493   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13494     return S;
13495 
13496   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13497       Level < AfterLegalizeVectorOps &&
13498       (N1.isUndef() ||
13499       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13500        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13501     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13502       return V;
13503   }
13504 
13505   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13506   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13507   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13508     SmallVector<SDValue, 8> Ops;
13509     for (int M : SVN->getMask()) {
13510       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13511       if (M >= 0) {
13512         int Idx = M % NumElts;
13513         SDValue &S = (M < (int)NumElts ? N0 : N1);
13514         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13515           Op = S.getOperand(Idx);
13516         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13517           if (Idx == 0)
13518             Op = S.getOperand(0);
13519         } else {
13520           // Operand can't be combined - bail out.
13521           break;
13522         }
13523       }
13524       Ops.push_back(Op);
13525     }
13526     if (Ops.size() == VT.getVectorNumElements()) {
13527       // BUILD_VECTOR requires all inputs to be of the same type, find the
13528       // maximum type and extend them all.
13529       EVT SVT = VT.getScalarType();
13530       if (SVT.isInteger())
13531         for (SDValue &Op : Ops)
13532           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13533       if (SVT != VT.getScalarType())
13534         for (SDValue &Op : Ops)
13535           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13536                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13537                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13538       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13539     }
13540   }
13541 
13542   // If this shuffle only has a single input that is a bitcasted shuffle,
13543   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13544   // back to their original types.
13545   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13546       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13547       TLI.isTypeLegal(VT)) {
13548 
13549     // Peek through the bitcast only if there is one user.
13550     SDValue BC0 = N0;
13551     while (BC0.getOpcode() == ISD::BITCAST) {
13552       if (!BC0.hasOneUse())
13553         break;
13554       BC0 = BC0.getOperand(0);
13555     }
13556 
13557     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13558       if (Scale == 1)
13559         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13560 
13561       SmallVector<int, 8> NewMask;
13562       for (int M : Mask)
13563         for (int s = 0; s != Scale; ++s)
13564           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13565       return NewMask;
13566     };
13567 
13568     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13569       EVT SVT = VT.getScalarType();
13570       EVT InnerVT = BC0->getValueType(0);
13571       EVT InnerSVT = InnerVT.getScalarType();
13572 
13573       // Determine which shuffle works with the smaller scalar type.
13574       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13575       EVT ScaleSVT = ScaleVT.getScalarType();
13576 
13577       if (TLI.isTypeLegal(ScaleVT) &&
13578           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13579           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13580 
13581         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13582         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13583 
13584         // Scale the shuffle masks to the smaller scalar type.
13585         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13586         SmallVector<int, 8> InnerMask =
13587             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13588         SmallVector<int, 8> OuterMask =
13589             ScaleShuffleMask(SVN->getMask(), OuterScale);
13590 
13591         // Merge the shuffle masks.
13592         SmallVector<int, 8> NewMask;
13593         for (int M : OuterMask)
13594           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13595 
13596         // Test for shuffle mask legality over both commutations.
13597         SDValue SV0 = BC0->getOperand(0);
13598         SDValue SV1 = BC0->getOperand(1);
13599         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13600         if (!LegalMask) {
13601           std::swap(SV0, SV1);
13602           ShuffleVectorSDNode::commuteMask(NewMask);
13603           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13604         }
13605 
13606         if (LegalMask) {
13607           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13608           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13609           return DAG.getNode(
13610               ISD::BITCAST, SDLoc(N), VT,
13611               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13612         }
13613       }
13614     }
13615   }
13616 
13617   // Canonicalize shuffles according to rules:
13618   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13619   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13620   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13621   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13622       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13623       TLI.isTypeLegal(VT)) {
13624     // The incoming shuffle must be of the same type as the result of the
13625     // current shuffle.
13626     assert(N1->getOperand(0).getValueType() == VT &&
13627            "Shuffle types don't match");
13628 
13629     SDValue SV0 = N1->getOperand(0);
13630     SDValue SV1 = N1->getOperand(1);
13631     bool HasSameOp0 = N0 == SV0;
13632     bool IsSV1Undef = SV1.isUndef();
13633     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13634       // Commute the operands of this shuffle so that next rule
13635       // will trigger.
13636       return DAG.getCommutedVectorShuffle(*SVN);
13637   }
13638 
13639   // Try to fold according to rules:
13640   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13641   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13642   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13643   // Don't try to fold shuffles with illegal type.
13644   // Only fold if this shuffle is the only user of the other shuffle.
13645   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13646       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13647     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13648 
13649     // The incoming shuffle must be of the same type as the result of the
13650     // current shuffle.
13651     assert(OtherSV->getOperand(0).getValueType() == VT &&
13652            "Shuffle types don't match");
13653 
13654     SDValue SV0, SV1;
13655     SmallVector<int, 4> Mask;
13656     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13657     // operand, and SV1 as the second operand.
13658     for (unsigned i = 0; i != NumElts; ++i) {
13659       int Idx = SVN->getMaskElt(i);
13660       if (Idx < 0) {
13661         // Propagate Undef.
13662         Mask.push_back(Idx);
13663         continue;
13664       }
13665 
13666       SDValue CurrentVec;
13667       if (Idx < (int)NumElts) {
13668         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13669         // shuffle mask to identify which vector is actually referenced.
13670         Idx = OtherSV->getMaskElt(Idx);
13671         if (Idx < 0) {
13672           // Propagate Undef.
13673           Mask.push_back(Idx);
13674           continue;
13675         }
13676 
13677         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13678                                            : OtherSV->getOperand(1);
13679       } else {
13680         // This shuffle index references an element within N1.
13681         CurrentVec = N1;
13682       }
13683 
13684       // Simple case where 'CurrentVec' is UNDEF.
13685       if (CurrentVec.isUndef()) {
13686         Mask.push_back(-1);
13687         continue;
13688       }
13689 
13690       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13691       // will be the first or second operand of the combined shuffle.
13692       Idx = Idx % NumElts;
13693       if (!SV0.getNode() || SV0 == CurrentVec) {
13694         // Ok. CurrentVec is the left hand side.
13695         // Update the mask accordingly.
13696         SV0 = CurrentVec;
13697         Mask.push_back(Idx);
13698         continue;
13699       }
13700 
13701       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13702       if (SV1.getNode() && SV1 != CurrentVec)
13703         return SDValue();
13704 
13705       // Ok. CurrentVec is the right hand side.
13706       // Update the mask accordingly.
13707       SV1 = CurrentVec;
13708       Mask.push_back(Idx + NumElts);
13709     }
13710 
13711     // Check if all indices in Mask are Undef. In case, propagate Undef.
13712     bool isUndefMask = true;
13713     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13714       isUndefMask &= Mask[i] < 0;
13715 
13716     if (isUndefMask)
13717       return DAG.getUNDEF(VT);
13718 
13719     if (!SV0.getNode())
13720       SV0 = DAG.getUNDEF(VT);
13721     if (!SV1.getNode())
13722       SV1 = DAG.getUNDEF(VT);
13723 
13724     // Avoid introducing shuffles with illegal mask.
13725     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13726       ShuffleVectorSDNode::commuteMask(Mask);
13727 
13728       if (!TLI.isShuffleMaskLegal(Mask, VT))
13729         return SDValue();
13730 
13731       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13732       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13733       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13734       std::swap(SV0, SV1);
13735     }
13736 
13737     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13738     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13739     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13740     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13741   }
13742 
13743   return SDValue();
13744 }
13745 
13746 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13747   SDValue InVal = N->getOperand(0);
13748   EVT VT = N->getValueType(0);
13749 
13750   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13751   // with a VECTOR_SHUFFLE.
13752   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13753     SDValue InVec = InVal->getOperand(0);
13754     SDValue EltNo = InVal->getOperand(1);
13755 
13756     // FIXME: We could support implicit truncation if the shuffle can be
13757     // scaled to a smaller vector scalar type.
13758     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13759     if (C0 && VT == InVec.getValueType() &&
13760         VT.getScalarType() == InVal.getValueType()) {
13761       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13762       int Elt = C0->getZExtValue();
13763       NewMask[0] = Elt;
13764 
13765       if (TLI.isShuffleMaskLegal(NewMask, VT))
13766         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13767                                     NewMask);
13768     }
13769   }
13770 
13771   return SDValue();
13772 }
13773 
13774 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13775   SDValue N0 = N->getOperand(0);
13776   SDValue N2 = N->getOperand(2);
13777 
13778   // If the input vector is a concatenation, and the insert replaces
13779   // one of the halves, we can optimize into a single concat_vectors.
13780   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13781       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13782     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13783     EVT VT = N->getValueType(0);
13784 
13785     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13786     // (concat_vectors Z, Y)
13787     if (InsIdx == 0)
13788       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13789                          N->getOperand(1), N0.getOperand(1));
13790 
13791     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13792     // (concat_vectors X, Z)
13793     if (InsIdx == VT.getVectorNumElements()/2)
13794       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13795                          N0.getOperand(0), N->getOperand(1));
13796   }
13797 
13798   return SDValue();
13799 }
13800 
13801 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13802   SDValue N0 = N->getOperand(0);
13803 
13804   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13805   if (N0->getOpcode() == ISD::FP16_TO_FP)
13806     return N0->getOperand(0);
13807 
13808   return SDValue();
13809 }
13810 
13811 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13812   SDValue N0 = N->getOperand(0);
13813 
13814   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13815   if (N0->getOpcode() == ISD::AND) {
13816     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13817     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13818       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13819                          N0.getOperand(0));
13820     }
13821   }
13822 
13823   return SDValue();
13824 }
13825 
13826 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13827 /// with the destination vector and a zero vector.
13828 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13829 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13830 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13831   EVT VT = N->getValueType(0);
13832   SDValue LHS = N->getOperand(0);
13833   SDValue RHS = N->getOperand(1);
13834   SDLoc dl(N);
13835 
13836   // Make sure we're not running after operation legalization where it
13837   // may have custom lowered the vector shuffles.
13838   if (LegalOperations)
13839     return SDValue();
13840 
13841   if (N->getOpcode() != ISD::AND)
13842     return SDValue();
13843 
13844   if (RHS.getOpcode() == ISD::BITCAST)
13845     RHS = RHS.getOperand(0);
13846 
13847   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13848     return SDValue();
13849 
13850   EVT RVT = RHS.getValueType();
13851   unsigned NumElts = RHS.getNumOperands();
13852 
13853   // Attempt to create a valid clear mask, splitting the mask into
13854   // sub elements and checking to see if each is
13855   // all zeros or all ones - suitable for shuffle masking.
13856   auto BuildClearMask = [&](int Split) {
13857     int NumSubElts = NumElts * Split;
13858     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13859 
13860     SmallVector<int, 8> Indices;
13861     for (int i = 0; i != NumSubElts; ++i) {
13862       int EltIdx = i / Split;
13863       int SubIdx = i % Split;
13864       SDValue Elt = RHS.getOperand(EltIdx);
13865       if (Elt.isUndef()) {
13866         Indices.push_back(-1);
13867         continue;
13868       }
13869 
13870       APInt Bits;
13871       if (isa<ConstantSDNode>(Elt))
13872         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13873       else if (isa<ConstantFPSDNode>(Elt))
13874         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13875       else
13876         return SDValue();
13877 
13878       // Extract the sub element from the constant bit mask.
13879       if (DAG.getDataLayout().isBigEndian()) {
13880         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13881       } else {
13882         Bits = Bits.lshr(SubIdx * NumSubBits);
13883       }
13884 
13885       if (Split > 1)
13886         Bits = Bits.trunc(NumSubBits);
13887 
13888       if (Bits.isAllOnesValue())
13889         Indices.push_back(i);
13890       else if (Bits == 0)
13891         Indices.push_back(i + NumSubElts);
13892       else
13893         return SDValue();
13894     }
13895 
13896     // Let's see if the target supports this vector_shuffle.
13897     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13898     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13899     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13900       return SDValue();
13901 
13902     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13903     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13904                                                    DAG.getBitcast(ClearVT, LHS),
13905                                                    Zero, &Indices[0]));
13906   };
13907 
13908   // Determine maximum split level (byte level masking).
13909   int MaxSplit = 1;
13910   if (RVT.getScalarSizeInBits() % 8 == 0)
13911     MaxSplit = RVT.getScalarSizeInBits() / 8;
13912 
13913   for (int Split = 1; Split <= MaxSplit; ++Split)
13914     if (RVT.getScalarSizeInBits() % Split == 0)
13915       if (SDValue S = BuildClearMask(Split))
13916         return S;
13917 
13918   return SDValue();
13919 }
13920 
13921 /// Visit a binary vector operation, like ADD.
13922 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13923   assert(N->getValueType(0).isVector() &&
13924          "SimplifyVBinOp only works on vectors!");
13925 
13926   SDValue LHS = N->getOperand(0);
13927   SDValue RHS = N->getOperand(1);
13928   SDValue Ops[] = {LHS, RHS};
13929 
13930   // See if we can constant fold the vector operation.
13931   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13932           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13933     return Fold;
13934 
13935   // Try to convert a constant mask AND into a shuffle clear mask.
13936   if (SDValue Shuffle = XformToShuffleWithZero(N))
13937     return Shuffle;
13938 
13939   // Type legalization might introduce new shuffles in the DAG.
13940   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13941   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13942   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13943       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13944       LHS.getOperand(1).isUndef() &&
13945       RHS.getOperand(1).isUndef()) {
13946     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13947     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13948 
13949     if (SVN0->getMask().equals(SVN1->getMask())) {
13950       EVT VT = N->getValueType(0);
13951       SDValue UndefVector = LHS.getOperand(1);
13952       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13953                                      LHS.getOperand(0), RHS.getOperand(0),
13954                                      N->getFlags());
13955       AddUsersToWorklist(N);
13956       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13957                                   &SVN0->getMask()[0]);
13958     }
13959   }
13960 
13961   return SDValue();
13962 }
13963 
13964 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13965                                     SDValue N1, SDValue N2){
13966   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13967 
13968   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13969                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13970 
13971   // If we got a simplified select_cc node back from SimplifySelectCC, then
13972   // break it down into a new SETCC node, and a new SELECT node, and then return
13973   // the SELECT node, since we were called with a SELECT node.
13974   if (SCC.getNode()) {
13975     // Check to see if we got a select_cc back (to turn into setcc/select).
13976     // Otherwise, just return whatever node we got back, like fabs.
13977     if (SCC.getOpcode() == ISD::SELECT_CC) {
13978       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13979                                   N0.getValueType(),
13980                                   SCC.getOperand(0), SCC.getOperand(1),
13981                                   SCC.getOperand(4));
13982       AddToWorklist(SETCC.getNode());
13983       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13984                            SCC.getOperand(2), SCC.getOperand(3));
13985     }
13986 
13987     return SCC;
13988   }
13989   return SDValue();
13990 }
13991 
13992 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13993 /// being selected between, see if we can simplify the select.  Callers of this
13994 /// should assume that TheSelect is deleted if this returns true.  As such, they
13995 /// should return the appropriate thing (e.g. the node) back to the top-level of
13996 /// the DAG combiner loop to avoid it being looked at.
13997 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13998                                     SDValue RHS) {
13999 
14000   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14001   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14002   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14003     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14004       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14005       SDValue Sqrt = RHS;
14006       ISD::CondCode CC;
14007       SDValue CmpLHS;
14008       const ConstantFPSDNode *Zero = nullptr;
14009 
14010       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14011         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14012         CmpLHS = TheSelect->getOperand(0);
14013         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14014       } else {
14015         // SELECT or VSELECT
14016         SDValue Cmp = TheSelect->getOperand(0);
14017         if (Cmp.getOpcode() == ISD::SETCC) {
14018           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14019           CmpLHS = Cmp.getOperand(0);
14020           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14021         }
14022       }
14023       if (Zero && Zero->isZero() &&
14024           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14025           CC == ISD::SETULT || CC == ISD::SETLT)) {
14026         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14027         CombineTo(TheSelect, Sqrt);
14028         return true;
14029       }
14030     }
14031   }
14032   // Cannot simplify select with vector condition
14033   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14034 
14035   // If this is a select from two identical things, try to pull the operation
14036   // through the select.
14037   if (LHS.getOpcode() != RHS.getOpcode() ||
14038       !LHS.hasOneUse() || !RHS.hasOneUse())
14039     return false;
14040 
14041   // If this is a load and the token chain is identical, replace the select
14042   // of two loads with a load through a select of the address to load from.
14043   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14044   // constants have been dropped into the constant pool.
14045   if (LHS.getOpcode() == ISD::LOAD) {
14046     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14047     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14048 
14049     // Token chains must be identical.
14050     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14051         // Do not let this transformation reduce the number of volatile loads.
14052         LLD->isVolatile() || RLD->isVolatile() ||
14053         // FIXME: If either is a pre/post inc/dec load,
14054         // we'd need to split out the address adjustment.
14055         LLD->isIndexed() || RLD->isIndexed() ||
14056         // If this is an EXTLOAD, the VT's must match.
14057         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14058         // If this is an EXTLOAD, the kind of extension must match.
14059         (LLD->getExtensionType() != RLD->getExtensionType() &&
14060          // The only exception is if one of the extensions is anyext.
14061          LLD->getExtensionType() != ISD::EXTLOAD &&
14062          RLD->getExtensionType() != ISD::EXTLOAD) ||
14063         // FIXME: this discards src value information.  This is
14064         // over-conservative. It would be beneficial to be able to remember
14065         // both potential memory locations.  Since we are discarding
14066         // src value info, don't do the transformation if the memory
14067         // locations are not in the default address space.
14068         LLD->getPointerInfo().getAddrSpace() != 0 ||
14069         RLD->getPointerInfo().getAddrSpace() != 0 ||
14070         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14071                                       LLD->getBasePtr().getValueType()))
14072       return false;
14073 
14074     // Check that the select condition doesn't reach either load.  If so,
14075     // folding this will induce a cycle into the DAG.  If not, this is safe to
14076     // xform, so create a select of the addresses.
14077     SDValue Addr;
14078     if (TheSelect->getOpcode() == ISD::SELECT) {
14079       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14080       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14081           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14082         return false;
14083       // The loads must not depend on one another.
14084       if (LLD->isPredecessorOf(RLD) ||
14085           RLD->isPredecessorOf(LLD))
14086         return false;
14087       Addr = DAG.getSelect(SDLoc(TheSelect),
14088                            LLD->getBasePtr().getValueType(),
14089                            TheSelect->getOperand(0), LLD->getBasePtr(),
14090                            RLD->getBasePtr());
14091     } else {  // Otherwise SELECT_CC
14092       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14093       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14094 
14095       if ((LLD->hasAnyUseOfValue(1) &&
14096            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14097           (RLD->hasAnyUseOfValue(1) &&
14098            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14099         return false;
14100 
14101       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14102                          LLD->getBasePtr().getValueType(),
14103                          TheSelect->getOperand(0),
14104                          TheSelect->getOperand(1),
14105                          LLD->getBasePtr(), RLD->getBasePtr(),
14106                          TheSelect->getOperand(4));
14107     }
14108 
14109     SDValue Load;
14110     // It is safe to replace the two loads if they have different alignments,
14111     // but the new load must be the minimum (most restrictive) alignment of the
14112     // inputs.
14113     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
14114     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14115     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14116       Load = DAG.getLoad(TheSelect->getValueType(0),
14117                          SDLoc(TheSelect),
14118                          // FIXME: Discards pointer and AA info.
14119                          LLD->getChain(), Addr, MachinePointerInfo(),
14120                          LLD->isVolatile(), LLD->isNonTemporal(),
14121                          isInvariant, Alignment);
14122     } else {
14123       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
14124                             RLD->getExtensionType() : LLD->getExtensionType(),
14125                             SDLoc(TheSelect),
14126                             TheSelect->getValueType(0),
14127                             // FIXME: Discards pointer and AA info.
14128                             LLD->getChain(), Addr, MachinePointerInfo(),
14129                             LLD->getMemoryVT(), LLD->isVolatile(),
14130                             LLD->isNonTemporal(), isInvariant, Alignment);
14131     }
14132 
14133     // Users of the select now use the result of the load.
14134     CombineTo(TheSelect, Load);
14135 
14136     // Users of the old loads now use the new load's chain.  We know the
14137     // old-load value is dead now.
14138     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14139     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14140     return true;
14141   }
14142 
14143   return false;
14144 }
14145 
14146 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14147 /// where 'cond' is the comparison specified by CC.
14148 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
14149                                       SDValue N2, SDValue N3,
14150                                       ISD::CondCode CC, bool NotExtCompare) {
14151   // (x ? y : y) -> y.
14152   if (N2 == N3) return N2;
14153 
14154   EVT VT = N2.getValueType();
14155   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14156   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14157 
14158   // Determine if the condition we're dealing with is constant
14159   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14160                               N0, N1, CC, DL, false);
14161   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14162 
14163   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14164     // fold select_cc true, x, y -> x
14165     // fold select_cc false, x, y -> y
14166     return !SCCC->isNullValue() ? N2 : N3;
14167   }
14168 
14169   // Check to see if we can simplify the select into an fabs node
14170   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14171     // Allow either -0.0 or 0.0
14172     if (CFP->isZero()) {
14173       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14174       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14175           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14176           N2 == N3.getOperand(0))
14177         return DAG.getNode(ISD::FABS, DL, VT, N0);
14178 
14179       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14180       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14181           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14182           N2.getOperand(0) == N3)
14183         return DAG.getNode(ISD::FABS, DL, VT, N3);
14184     }
14185   }
14186 
14187   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14188   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14189   // in it.  This is a win when the constant is not otherwise available because
14190   // it replaces two constant pool loads with one.  We only do this if the FP
14191   // type is known to be legal, because if it isn't, then we are before legalize
14192   // types an we want the other legalization to happen first (e.g. to avoid
14193   // messing with soft float) and if the ConstantFP is not legal, because if
14194   // it is legal, we may not need to store the FP constant in a constant pool.
14195   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14196     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14197       if (TLI.isTypeLegal(N2.getValueType()) &&
14198           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14199                TargetLowering::Legal &&
14200            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14201            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14202           // If both constants have multiple uses, then we won't need to do an
14203           // extra load, they are likely around in registers for other users.
14204           (TV->hasOneUse() || FV->hasOneUse())) {
14205         Constant *Elts[] = {
14206           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14207           const_cast<ConstantFP*>(TV->getConstantFPValue())
14208         };
14209         Type *FPTy = Elts[0]->getType();
14210         const DataLayout &TD = DAG.getDataLayout();
14211 
14212         // Create a ConstantArray of the two constants.
14213         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14214         SDValue CPIdx =
14215             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14216                                 TD.getPrefTypeAlignment(FPTy));
14217         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14218 
14219         // Get the offsets to the 0 and 1 element of the array so that we can
14220         // select between them.
14221         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14222         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14223         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14224 
14225         SDValue Cond = DAG.getSetCC(DL,
14226                                     getSetCCResultType(N0.getValueType()),
14227                                     N0, N1, CC);
14228         AddToWorklist(Cond.getNode());
14229         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14230                                           Cond, One, Zero);
14231         AddToWorklist(CstOffset.getNode());
14232         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14233                             CstOffset);
14234         AddToWorklist(CPIdx.getNode());
14235         return DAG.getLoad(
14236             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14237             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14238             false, false, false, Alignment);
14239       }
14240     }
14241 
14242   // Check to see if we can perform the "gzip trick", transforming
14243   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14244   if (isNullConstant(N3) && CC == ISD::SETLT &&
14245       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14246        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14247     EVT XType = N0.getValueType();
14248     EVT AType = N2.getValueType();
14249     if (XType.bitsGE(AType)) {
14250       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14251       // single-bit constant.
14252       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14253         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14254         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14255         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14256                                        getShiftAmountTy(N0.getValueType()));
14257         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14258                                     XType, N0, ShCt);
14259         AddToWorklist(Shift.getNode());
14260 
14261         if (XType.bitsGT(AType)) {
14262           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14263           AddToWorklist(Shift.getNode());
14264         }
14265 
14266         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14267       }
14268 
14269       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14270                                   XType, N0,
14271                                   DAG.getConstant(XType.getSizeInBits() - 1,
14272                                                   SDLoc(N0),
14273                                          getShiftAmountTy(N0.getValueType())));
14274       AddToWorklist(Shift.getNode());
14275 
14276       if (XType.bitsGT(AType)) {
14277         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14278         AddToWorklist(Shift.getNode());
14279       }
14280 
14281       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14282     }
14283   }
14284 
14285   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14286   // where y is has a single bit set.
14287   // A plaintext description would be, we can turn the SELECT_CC into an AND
14288   // when the condition can be materialized as an all-ones register.  Any
14289   // single bit-test can be materialized as an all-ones register with
14290   // shift-left and shift-right-arith.
14291   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14292       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14293     SDValue AndLHS = N0->getOperand(0);
14294     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14295     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14296       // Shift the tested bit over the sign bit.
14297       APInt AndMask = ConstAndRHS->getAPIntValue();
14298       SDValue ShlAmt =
14299         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14300                         getShiftAmountTy(AndLHS.getValueType()));
14301       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14302 
14303       // Now arithmetic right shift it all the way over, so the result is either
14304       // all-ones, or zero.
14305       SDValue ShrAmt =
14306         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14307                         getShiftAmountTy(Shl.getValueType()));
14308       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14309 
14310       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14311     }
14312   }
14313 
14314   // fold select C, 16, 0 -> shl C, 4
14315   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14316       TLI.getBooleanContents(N0.getValueType()) ==
14317           TargetLowering::ZeroOrOneBooleanContent) {
14318 
14319     // If the caller doesn't want us to simplify this into a zext of a compare,
14320     // don't do it.
14321     if (NotExtCompare && N2C->isOne())
14322       return SDValue();
14323 
14324     // Get a SetCC of the condition
14325     // NOTE: Don't create a SETCC if it's not legal on this target.
14326     if (!LegalOperations ||
14327         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14328       SDValue Temp, SCC;
14329       // cast from setcc result type to select result type
14330       if (LegalTypes) {
14331         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14332                             N0, N1, CC);
14333         if (N2.getValueType().bitsLT(SCC.getValueType()))
14334           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14335                                         N2.getValueType());
14336         else
14337           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14338                              N2.getValueType(), SCC);
14339       } else {
14340         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14341         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14342                            N2.getValueType(), SCC);
14343       }
14344 
14345       AddToWorklist(SCC.getNode());
14346       AddToWorklist(Temp.getNode());
14347 
14348       if (N2C->isOne())
14349         return Temp;
14350 
14351       // shl setcc result by log2 n2c
14352       return DAG.getNode(
14353           ISD::SHL, DL, N2.getValueType(), Temp,
14354           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14355                           getShiftAmountTy(Temp.getValueType())));
14356     }
14357   }
14358 
14359   // Check to see if this is an integer abs.
14360   // select_cc setg[te] X,  0,  X, -X ->
14361   // select_cc setgt    X, -1,  X, -X ->
14362   // select_cc setl[te] X,  0, -X,  X ->
14363   // select_cc setlt    X,  1, -X,  X ->
14364   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14365   if (N1C) {
14366     ConstantSDNode *SubC = nullptr;
14367     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14368          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14369         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14370       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14371     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14372               (N1C->isOne() && CC == ISD::SETLT)) &&
14373              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14374       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14375 
14376     EVT XType = N0.getValueType();
14377     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14378       SDLoc DL(N0);
14379       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14380                                   N0,
14381                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14382                                          getShiftAmountTy(N0.getValueType())));
14383       SDValue Add = DAG.getNode(ISD::ADD, DL,
14384                                 XType, N0, Shift);
14385       AddToWorklist(Shift.getNode());
14386       AddToWorklist(Add.getNode());
14387       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14388     }
14389   }
14390 
14391   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14392   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14393   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14394   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14395   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14396   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14397   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14398   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14399   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14400     SDValue ValueOnZero = N2;
14401     SDValue Count = N3;
14402     // If the condition is NE instead of E, swap the operands.
14403     if (CC == ISD::SETNE)
14404       std::swap(ValueOnZero, Count);
14405     // Check if the value on zero is a constant equal to the bits in the type.
14406     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14407       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14408         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14409         // legal, combine to just cttz.
14410         if ((Count.getOpcode() == ISD::CTTZ ||
14411              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14412             N0 == Count.getOperand(0) &&
14413             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14414           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14415         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14416         // legal, combine to just ctlz.
14417         if ((Count.getOpcode() == ISD::CTLZ ||
14418              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14419             N0 == Count.getOperand(0) &&
14420             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14421           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14422       }
14423     }
14424   }
14425 
14426   return SDValue();
14427 }
14428 
14429 /// This is a stub for TargetLowering::SimplifySetCC.
14430 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14431                                    SDValue N1, ISD::CondCode Cond,
14432                                    SDLoc DL, bool foldBooleans) {
14433   TargetLowering::DAGCombinerInfo
14434     DagCombineInfo(DAG, Level, false, this);
14435   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14436 }
14437 
14438 /// Given an ISD::SDIV node expressing a divide by constant, return
14439 /// a DAG expression to select that will generate the same value by multiplying
14440 /// by a magic number.
14441 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14442 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14443   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14444   if (!C)
14445     return SDValue();
14446 
14447   // Avoid division by zero.
14448   if (C->isNullValue())
14449     return SDValue();
14450 
14451   std::vector<SDNode*> Built;
14452   SDValue S =
14453       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14454 
14455   for (SDNode *N : Built)
14456     AddToWorklist(N);
14457   return S;
14458 }
14459 
14460 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14461 /// DAG expression that will generate the same value by right shifting.
14462 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14463   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14464   if (!C)
14465     return SDValue();
14466 
14467   // Avoid division by zero.
14468   if (C->isNullValue())
14469     return SDValue();
14470 
14471   std::vector<SDNode *> Built;
14472   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14473 
14474   for (SDNode *N : Built)
14475     AddToWorklist(N);
14476   return S;
14477 }
14478 
14479 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14480 /// expression that will generate the same value by multiplying by a magic
14481 /// number.
14482 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14483 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14484   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14485   if (!C)
14486     return SDValue();
14487 
14488   // Avoid division by zero.
14489   if (C->isNullValue())
14490     return SDValue();
14491 
14492   std::vector<SDNode*> Built;
14493   SDValue S =
14494       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14495 
14496   for (SDNode *N : Built)
14497     AddToWorklist(N);
14498   return S;
14499 }
14500 
14501 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14502   if (Level >= AfterLegalizeDAG)
14503     return SDValue();
14504 
14505   // Expose the DAG combiner to the target combiner implementations.
14506   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14507 
14508   unsigned Iterations = 0;
14509   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14510     if (Iterations) {
14511       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14512       // For the reciprocal, we need to find the zero of the function:
14513       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14514       //     =>
14515       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14516       //     does not require additional intermediate precision]
14517       EVT VT = Op.getValueType();
14518       SDLoc DL(Op);
14519       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14520 
14521       AddToWorklist(Est.getNode());
14522 
14523       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14524       for (unsigned i = 0; i < Iterations; ++i) {
14525         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14526         AddToWorklist(NewEst.getNode());
14527 
14528         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14529         AddToWorklist(NewEst.getNode());
14530 
14531         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14532         AddToWorklist(NewEst.getNode());
14533 
14534         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14535         AddToWorklist(Est.getNode());
14536       }
14537     }
14538     return Est;
14539   }
14540 
14541   return SDValue();
14542 }
14543 
14544 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14545 /// For the reciprocal sqrt, we need to find the zero of the function:
14546 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14547 ///     =>
14548 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14549 /// As a result, we precompute A/2 prior to the iteration loop.
14550 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14551                                           unsigned Iterations,
14552                                           SDNodeFlags *Flags) {
14553   EVT VT = Arg.getValueType();
14554   SDLoc DL(Arg);
14555   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14556 
14557   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14558   // this entire sequence requires only one FP constant.
14559   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14560   AddToWorklist(HalfArg.getNode());
14561 
14562   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14563   AddToWorklist(HalfArg.getNode());
14564 
14565   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14566   for (unsigned i = 0; i < Iterations; ++i) {
14567     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14568     AddToWorklist(NewEst.getNode());
14569 
14570     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14571     AddToWorklist(NewEst.getNode());
14572 
14573     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14574     AddToWorklist(NewEst.getNode());
14575 
14576     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14577     AddToWorklist(Est.getNode());
14578   }
14579   return Est;
14580 }
14581 
14582 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14583 /// For the reciprocal sqrt, we need to find the zero of the function:
14584 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14585 ///     =>
14586 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14587 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14588                                           unsigned Iterations,
14589                                           SDNodeFlags *Flags) {
14590   EVT VT = Arg.getValueType();
14591   SDLoc DL(Arg);
14592   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14593   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14594 
14595   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14596   for (unsigned i = 0; i < Iterations; ++i) {
14597     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14598     AddToWorklist(HalfEst.getNode());
14599 
14600     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14601     AddToWorklist(Est.getNode());
14602 
14603     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14604     AddToWorklist(Est.getNode());
14605 
14606     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14607     AddToWorklist(Est.getNode());
14608 
14609     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14610     AddToWorklist(Est.getNode());
14611   }
14612   return Est;
14613 }
14614 
14615 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14616   if (Level >= AfterLegalizeDAG)
14617     return SDValue();
14618 
14619   // Expose the DAG combiner to the target combiner implementations.
14620   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14621   unsigned Iterations = 0;
14622   bool UseOneConstNR = false;
14623   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14624     AddToWorklist(Est.getNode());
14625     if (Iterations) {
14626       Est = UseOneConstNR ?
14627         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14628         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14629     }
14630     return Est;
14631   }
14632 
14633   return SDValue();
14634 }
14635 
14636 /// Return true if base is a frame index, which is known not to alias with
14637 /// anything but itself.  Provides base object and offset as results.
14638 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14639                            const GlobalValue *&GV, const void *&CV) {
14640   // Assume it is a primitive operation.
14641   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14642 
14643   // If it's an adding a simple constant then integrate the offset.
14644   if (Base.getOpcode() == ISD::ADD) {
14645     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14646       Base = Base.getOperand(0);
14647       Offset += C->getZExtValue();
14648     }
14649   }
14650 
14651   // Return the underlying GlobalValue, and update the Offset.  Return false
14652   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14653   // by multiple nodes with different offsets.
14654   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14655     GV = G->getGlobal();
14656     Offset += G->getOffset();
14657     return false;
14658   }
14659 
14660   // Return the underlying Constant value, and update the Offset.  Return false
14661   // for ConstantSDNodes since the same constant pool entry may be represented
14662   // by multiple nodes with different offsets.
14663   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14664     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14665                                          : (const void *)C->getConstVal();
14666     Offset += C->getOffset();
14667     return false;
14668   }
14669   // If it's any of the following then it can't alias with anything but itself.
14670   return isa<FrameIndexSDNode>(Base);
14671 }
14672 
14673 /// Return true if there is any possibility that the two addresses overlap.
14674 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14675   // If they are the same then they must be aliases.
14676   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14677 
14678   // If they are both volatile then they cannot be reordered.
14679   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14680 
14681   // If one operation reads from invariant memory, and the other may store, they
14682   // cannot alias. These should really be checking the equivalent of mayWrite,
14683   // but it only matters for memory nodes other than load /store.
14684   if (Op0->isInvariant() && Op1->writeMem())
14685     return false;
14686 
14687   if (Op1->isInvariant() && Op0->writeMem())
14688     return false;
14689 
14690   // Gather base node and offset information.
14691   SDValue Base1, Base2;
14692   int64_t Offset1, Offset2;
14693   const GlobalValue *GV1, *GV2;
14694   const void *CV1, *CV2;
14695   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14696                                       Base1, Offset1, GV1, CV1);
14697   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14698                                       Base2, Offset2, GV2, CV2);
14699 
14700   // If they have a same base address then check to see if they overlap.
14701   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14702     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14703              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14704 
14705   // It is possible for different frame indices to alias each other, mostly
14706   // when tail call optimization reuses return address slots for arguments.
14707   // To catch this case, look up the actual index of frame indices to compute
14708   // the real alias relationship.
14709   if (isFrameIndex1 && isFrameIndex2) {
14710     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14711     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14712     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14713     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14714              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14715   }
14716 
14717   // Otherwise, if we know what the bases are, and they aren't identical, then
14718   // we know they cannot alias.
14719   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14720     return false;
14721 
14722   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14723   // compared to the size and offset of the access, we may be able to prove they
14724   // do not alias.  This check is conservative for now to catch cases created by
14725   // splitting vector types.
14726   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14727       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14728       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14729        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14730       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14731     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14732     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14733 
14734     // There is no overlap between these relatively aligned accesses of similar
14735     // size, return no alias.
14736     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14737         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14738       return false;
14739   }
14740 
14741   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14742                    ? CombinerGlobalAA
14743                    : DAG.getSubtarget().useAA();
14744 #ifndef NDEBUG
14745   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14746       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14747     UseAA = false;
14748 #endif
14749   if (UseAA &&
14750       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14751     // Use alias analysis information.
14752     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14753                                  Op1->getSrcValueOffset());
14754     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14755         Op0->getSrcValueOffset() - MinOffset;
14756     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14757         Op1->getSrcValueOffset() - MinOffset;
14758     AliasResult AAResult =
14759         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14760                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14761                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14762                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14763     if (AAResult == NoAlias)
14764       return false;
14765   }
14766 
14767   // Otherwise we have to assume they alias.
14768   return true;
14769 }
14770 
14771 /// Walk up chain skipping non-aliasing memory nodes,
14772 /// looking for aliasing nodes and adding them to the Aliases vector.
14773 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14774                                    SmallVectorImpl<SDValue> &Aliases) {
14775   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14776   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14777 
14778   // Get alias information for node.
14779   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14780 
14781   // Starting off.
14782   Chains.push_back(OriginalChain);
14783   unsigned Depth = 0;
14784 
14785   // Look at each chain and determine if it is an alias.  If so, add it to the
14786   // aliases list.  If not, then continue up the chain looking for the next
14787   // candidate.
14788   while (!Chains.empty()) {
14789     SDValue Chain = Chains.pop_back_val();
14790 
14791     // For TokenFactor nodes, look at each operand and only continue up the
14792     // chain until we reach the depth limit.
14793     //
14794     // FIXME: The depth check could be made to return the last non-aliasing
14795     // chain we found before we hit a tokenfactor rather than the original
14796     // chain.
14797     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14798       Aliases.clear();
14799       Aliases.push_back(OriginalChain);
14800       return;
14801     }
14802 
14803     // Don't bother if we've been before.
14804     if (!Visited.insert(Chain.getNode()).second)
14805       continue;
14806 
14807     switch (Chain.getOpcode()) {
14808     case ISD::EntryToken:
14809       // Entry token is ideal chain operand, but handled in FindBetterChain.
14810       break;
14811 
14812     case ISD::LOAD:
14813     case ISD::STORE: {
14814       // Get alias information for Chain.
14815       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14816           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14817 
14818       // If chain is alias then stop here.
14819       if (!(IsLoad && IsOpLoad) &&
14820           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14821         Aliases.push_back(Chain);
14822       } else {
14823         // Look further up the chain.
14824         Chains.push_back(Chain.getOperand(0));
14825         ++Depth;
14826       }
14827       break;
14828     }
14829 
14830     case ISD::TokenFactor:
14831       // We have to check each of the operands of the token factor for "small"
14832       // token factors, so we queue them up.  Adding the operands to the queue
14833       // (stack) in reverse order maintains the original order and increases the
14834       // likelihood that getNode will find a matching token factor (CSE.)
14835       if (Chain.getNumOperands() > 16) {
14836         Aliases.push_back(Chain);
14837         break;
14838       }
14839       for (unsigned n = Chain.getNumOperands(); n;)
14840         Chains.push_back(Chain.getOperand(--n));
14841       ++Depth;
14842       break;
14843 
14844     default:
14845       // For all other instructions we will just have to take what we can get.
14846       Aliases.push_back(Chain);
14847       break;
14848     }
14849   }
14850 }
14851 
14852 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14853 /// (aliasing node.)
14854 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14855   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14856 
14857   // Accumulate all the aliases to this node.
14858   GatherAllAliases(N, OldChain, Aliases);
14859 
14860   // If no operands then chain to entry token.
14861   if (Aliases.size() == 0)
14862     return DAG.getEntryNode();
14863 
14864   // If a single operand then chain to it.  We don't need to revisit it.
14865   if (Aliases.size() == 1)
14866     return Aliases[0];
14867 
14868   // Construct a custom tailored token factor.
14869   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14870 }
14871 
14872 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14873   // This holds the base pointer, index, and the offset in bytes from the base
14874   // pointer.
14875   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
14876 
14877   // We must have a base and an offset.
14878   if (!BasePtr.Base.getNode())
14879     return false;
14880 
14881   // Do not handle stores to undef base pointers.
14882   if (BasePtr.Base.isUndef())
14883     return false;
14884 
14885   SmallVector<StoreSDNode *, 8> ChainedStores;
14886   ChainedStores.push_back(St);
14887 
14888   // Walk up the chain and look for nodes with offsets from the same
14889   // base pointer. Stop when reaching an instruction with a different kind
14890   // or instruction which has a different base pointer.
14891   StoreSDNode *Index = St;
14892   while (Index) {
14893     // If the chain has more than one use, then we can't reorder the mem ops.
14894     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14895       break;
14896 
14897     if (Index->isVolatile() || Index->isIndexed())
14898       break;
14899 
14900     // Find the base pointer and offset for this memory node.
14901     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
14902 
14903     // Check that the base pointer is the same as the original one.
14904     if (!Ptr.equalBaseIndex(BasePtr))
14905       break;
14906 
14907     // Find the next memory operand in the chain. If the next operand in the
14908     // chain is a store then move up and continue the scan with the next
14909     // memory operand. If the next operand is a load save it and use alias
14910     // information to check if it interferes with anything.
14911     SDNode *NextInChain = Index->getChain().getNode();
14912     while (true) {
14913       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14914         // We found a store node. Use it for the next iteration.
14915         if (STn->isVolatile() || STn->isIndexed()) {
14916           Index = nullptr;
14917           break;
14918         }
14919         ChainedStores.push_back(STn);
14920         Index = STn;
14921         break;
14922       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14923         NextInChain = Ldn->getChain().getNode();
14924         continue;
14925       } else {
14926         Index = nullptr;
14927         break;
14928       }
14929     }
14930   }
14931 
14932   bool MadeChange = false;
14933   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14934 
14935   for (StoreSDNode *ChainedStore : ChainedStores) {
14936     SDValue Chain = ChainedStore->getChain();
14937     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14938 
14939     if (Chain != BetterChain) {
14940       MadeChange = true;
14941       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14942     }
14943   }
14944 
14945   // Do all replacements after finding the replacements to make to avoid making
14946   // the chains more complicated by introducing new TokenFactors.
14947   for (auto Replacement : BetterChains)
14948     replaceStoreChain(Replacement.first, Replacement.second);
14949 
14950   return MadeChange;
14951 }
14952 
14953 /// This is the entry point for the file.
14954 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14955                            CodeGenOpt::Level OptLevel) {
14956   /// This is the main entry point to this class.
14957   DAGCombiner(*this, AA, OptLevel).Run(Level);
14958 }
14959