]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Update tcpdump to 4.9.0.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43
44 #define DEBUG_TYPE "dagcombine"
45
46 STATISTIC(NodesCombined   , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
52
53 namespace {
54   static cl::opt<bool>
55     CombinerAA("combiner-alias-analysis", cl::Hidden,
56                cl::desc("Enable DAG combiner alias-analysis heuristics"));
57
58   static cl::opt<bool>
59     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60                cl::desc("Enable DAG combiner's use of IR alias analysis"));
61
62   static cl::opt<bool>
63     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64                cl::desc("Enable DAG combiner's use of TBAA"));
65
66 #ifndef NDEBUG
67   static cl::opt<std::string>
68     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69                cl::desc("Only use DAG-combiner alias analysis in this"
70                         " function"));
71 #endif
72
73   /// Hidden option to stress test load slicing, i.e., when this option
74   /// is enabled, load slicing bypasses most of its profitability guards.
75   static cl::opt<bool>
76   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77                     cl::desc("Bypass the profitability model of load "
78                              "slicing"),
79                     cl::init(false));
80
81   static cl::opt<bool>
82     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83                       cl::desc("DAG combiner may split indexing from loads"));
84
85 //------------------------------ DAGCombiner ---------------------------------//
86
87   class DAGCombiner {
88     SelectionDAG &DAG;
89     const TargetLowering &TLI;
90     CombineLevel Level;
91     CodeGenOpt::Level OptLevel;
92     bool LegalOperations;
93     bool LegalTypes;
94     bool ForCodeSize;
95
96     /// \brief Worklist of all of the nodes that need to be simplified.
97     ///
98     /// This must behave as a stack -- new nodes to process are pushed onto the
99     /// back and when processing we pop off of the back.
100     ///
101     /// The worklist will not contain duplicates but may contain null entries
102     /// due to nodes being deleted from the underlying DAG.
103     SmallVector<SDNode *, 64> Worklist;
104
105     /// \brief Mapping from an SDNode to its position on the worklist.
106     ///
107     /// This is used to find and remove nodes from the worklist (by nulling
108     /// them) when they are deleted from the underlying DAG. It relies on
109     /// stable indices of nodes within the worklist.
110     DenseMap<SDNode *, unsigned> WorklistMap;
111
112     /// \brief Set of nodes which have been combined (at least once).
113     ///
114     /// This is used to allow us to reliably add any operands of a DAG node
115     /// which have not yet been combined to the worklist.
116     SmallPtrSet<SDNode *, 32> CombinedNodes;
117
118     // AA - Used for DAG load/store alias analysis.
119     AliasAnalysis &AA;
120
121     /// When an instruction is simplified, add all users of the instruction to
122     /// the work lists because they might get more simplified now.
123     void AddUsersToWorklist(SDNode *N) {
124       for (SDNode *Node : N->uses())
125         AddToWorklist(Node);
126     }
127
128     /// Call the node-specific routine that folds each particular type of node.
129     SDValue visit(SDNode *N);
130
131   public:
132     /// Add to the worklist making sure its instance is at the back (next to be
133     /// processed.)
134     void AddToWorklist(SDNode *N) {
135       // Skip handle nodes as they can't usefully be combined and confuse the
136       // zero-use deletion strategy.
137       if (N->getOpcode() == ISD::HANDLENODE)
138         return;
139
140       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141         Worklist.push_back(N);
142     }
143
144     /// Remove all instances of N from the worklist.
145     void removeFromWorklist(SDNode *N) {
146       CombinedNodes.erase(N);
147
148       auto It = WorklistMap.find(N);
149       if (It == WorklistMap.end())
150         return; // Not in the worklist.
151
152       // Null out the entry rather than erasing it to avoid a linear operation.
153       Worklist[It->second] = nullptr;
154       WorklistMap.erase(It);
155     }
156
157     void deleteAndRecombine(SDNode *N);
158     bool recursivelyDeleteUnusedNodes(SDNode *N);
159
160     /// Replaces all uses of the results of one DAG node with new values.
161     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162                       bool AddTo = true);
163
164     /// Replaces all uses of the results of one DAG node with new values.
165     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166       return CombineTo(N, &Res, 1, AddTo);
167     }
168
169     /// Replaces all uses of the results of one DAG node with new values.
170     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171                       bool AddTo = true) {
172       SDValue To[] = { Res0, Res1 };
173       return CombineTo(N, To, 2, AddTo);
174     }
175
176     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177
178   private:
179
180     /// Check the specified integer node value to see if it can be simplified or
181     /// if things it uses can be simplified by bit propagation.
182     /// If so, return true.
183     bool SimplifyDemandedBits(SDValue Op) {
184       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
185       APInt Demanded = APInt::getAllOnesValue(BitWidth);
186       return SimplifyDemandedBits(Op, Demanded);
187     }
188
189     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190
191     bool CombineToPreIndexedLoadStore(SDNode *N);
192     bool CombineToPostIndexedLoadStore(SDNode *N);
193     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
194     bool SliceUpLoad(SDNode *N);
195
196     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
197     ///   load.
198     ///
199     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
200     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
201     /// \param EltNo index of the vector element to load.
202     /// \param OriginalLoad load that EVE came from to be replaced.
203     /// \returns EVE on success SDValue() on failure.
204     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
205         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
206     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
207     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
208     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue PromoteIntBinOp(SDValue Op);
211     SDValue PromoteIntShiftOp(SDValue Op);
212     SDValue PromoteExtend(SDValue Op);
213     bool PromoteLoad(SDValue Op);
214
215     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
216                          SDValue ExtLoad, const SDLoc &DL,
217                          ISD::NodeType ExtType);
218
219     /// Call the node-specific routine that knows how to fold each
220     /// particular type of node. If that doesn't do anything, try the
221     /// target-specific DAG combines.
222     SDValue combine(SDNode *N);
223
224     // Visitation implementation - Implement dag node combining for different
225     // node types.  The semantics are as follows:
226     // Return Value:
227     //   SDValue.getNode() == 0 - No change was made
228     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
229     //   otherwise              - N should be replaced by the returned Operand.
230     //
231     SDValue visitTokenFactor(SDNode *N);
232     SDValue visitMERGE_VALUES(SDNode *N);
233     SDValue visitADD(SDNode *N);
234     SDValue visitSUB(SDNode *N);
235     SDValue visitADDC(SDNode *N);
236     SDValue visitSUBC(SDNode *N);
237     SDValue visitADDE(SDNode *N);
238     SDValue visitSUBE(SDNode *N);
239     SDValue visitMUL(SDNode *N);
240     SDValue useDivRem(SDNode *N);
241     SDValue visitSDIV(SDNode *N);
242     SDValue visitUDIV(SDNode *N);
243     SDValue visitREM(SDNode *N);
244     SDValue visitMULHU(SDNode *N);
245     SDValue visitMULHS(SDNode *N);
246     SDValue visitSMUL_LOHI(SDNode *N);
247     SDValue visitUMUL_LOHI(SDNode *N);
248     SDValue visitSMULO(SDNode *N);
249     SDValue visitUMULO(SDNode *N);
250     SDValue visitIMINMAX(SDNode *N);
251     SDValue visitAND(SDNode *N);
252     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitOR(SDNode *N);
254     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitXOR(SDNode *N);
256     SDValue SimplifyVBinOp(SDNode *N);
257     SDValue visitSHL(SDNode *N);
258     SDValue visitSRA(SDNode *N);
259     SDValue visitSRL(SDNode *N);
260     SDValue visitRotate(SDNode *N);
261     SDValue visitBSWAP(SDNode *N);
262     SDValue visitBITREVERSE(SDNode *N);
263     SDValue visitCTLZ(SDNode *N);
264     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTTZ(SDNode *N);
266     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
267     SDValue visitCTPOP(SDNode *N);
268     SDValue visitSELECT(SDNode *N);
269     SDValue visitVSELECT(SDNode *N);
270     SDValue visitSELECT_CC(SDNode *N);
271     SDValue visitSETCC(SDNode *N);
272     SDValue visitSETCCE(SDNode *N);
273     SDValue visitSIGN_EXTEND(SDNode *N);
274     SDValue visitZERO_EXTEND(SDNode *N);
275     SDValue visitANY_EXTEND(SDNode *N);
276     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
277     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
278     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
279     SDValue visitTRUNCATE(SDNode *N);
280     SDValue visitBITCAST(SDNode *N);
281     SDValue visitBUILD_PAIR(SDNode *N);
282     SDValue visitFADD(SDNode *N);
283     SDValue visitFSUB(SDNode *N);
284     SDValue visitFMUL(SDNode *N);
285     SDValue visitFMA(SDNode *N);
286     SDValue visitFDIV(SDNode *N);
287     SDValue visitFREM(SDNode *N);
288     SDValue visitFSQRT(SDNode *N);
289     SDValue visitFCOPYSIGN(SDNode *N);
290     SDValue visitSINT_TO_FP(SDNode *N);
291     SDValue visitUINT_TO_FP(SDNode *N);
292     SDValue visitFP_TO_SINT(SDNode *N);
293     SDValue visitFP_TO_UINT(SDNode *N);
294     SDValue visitFP_ROUND(SDNode *N);
295     SDValue visitFP_ROUND_INREG(SDNode *N);
296     SDValue visitFP_EXTEND(SDNode *N);
297     SDValue visitFNEG(SDNode *N);
298     SDValue visitFABS(SDNode *N);
299     SDValue visitFCEIL(SDNode *N);
300     SDValue visitFTRUNC(SDNode *N);
301     SDValue visitFFLOOR(SDNode *N);
302     SDValue visitFMINNUM(SDNode *N);
303     SDValue visitFMAXNUM(SDNode *N);
304     SDValue visitBRCOND(SDNode *N);
305     SDValue visitBR_CC(SDNode *N);
306     SDValue visitLOAD(SDNode *N);
307
308     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
309     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
310
311     SDValue visitSTORE(SDNode *N);
312     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
313     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
314     SDValue visitBUILD_VECTOR(SDNode *N);
315     SDValue visitCONCAT_VECTORS(SDNode *N);
316     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
317     SDValue visitVECTOR_SHUFFLE(SDNode *N);
318     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
319     SDValue visitINSERT_SUBVECTOR(SDNode *N);
320     SDValue visitMLOAD(SDNode *N);
321     SDValue visitMSTORE(SDNode *N);
322     SDValue visitMGATHER(SDNode *N);
323     SDValue visitMSCATTER(SDNode *N);
324     SDValue visitFP_TO_FP16(SDNode *N);
325     SDValue visitFP16_TO_FP(SDNode *N);
326
327     SDValue visitFADDForFMACombine(SDNode *N);
328     SDValue visitFSUBForFMACombine(SDNode *N);
329     SDValue visitFMULForFMACombine(SDNode *N);
330
331     SDValue XformToShuffleWithZero(SDNode *N);
332     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
333                            SDValue RHS);
334
335     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
336
337     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
338     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
339     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
340     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
341                              SDValue N2, SDValue N3, ISD::CondCode CC,
342                              bool NotExtCompare = false);
343     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
344                           const SDLoc &DL, bool foldBooleans = true);
345
346     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
347                            SDValue &CC) const;
348     bool isOneUseSetCC(SDValue N) const;
349
350     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
351                                          unsigned HiOp);
352     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
353     SDValue CombineExtLoad(SDNode *N);
354     SDValue combineRepeatedFPDivisors(SDNode *N);
355     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
356     SDValue BuildSDIV(SDNode *N);
357     SDValue BuildSDIVPow2(SDNode *N);
358     SDValue BuildUDIV(SDNode *N);
359     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
360     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
361     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
362     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
363     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
364                                 SDNodeFlags *Flags, bool Reciprocal);
365     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
366                                 SDNodeFlags *Flags, bool Reciprocal);
367     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
368                                bool DemandHighBits = true);
369     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
370     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
371                               SDValue InnerPos, SDValue InnerNeg,
372                               unsigned PosOpcode, unsigned NegOpcode,
373                               const SDLoc &DL);
374     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
375     SDValue ReduceLoadWidth(SDNode *N);
376     SDValue ReduceLoadOpStoreWidth(SDNode *N);
377     SDValue TransformFPLoadStorePair(SDNode *N);
378     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
379     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
380
381     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
382
383     /// Walk up chain skipping non-aliasing memory nodes,
384     /// looking for aliasing nodes and adding them to the Aliases vector.
385     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
386                           SmallVectorImpl<SDValue> &Aliases);
387
388     /// Return true if there is any possibility that the two addresses overlap.
389     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
390
391     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
392     /// chain (aliasing node.)
393     SDValue FindBetterChain(SDNode *N, SDValue Chain);
394
395     /// Try to replace a store and any possibly adjacent stores on
396     /// consecutive chains with better chains. Return true only if St is
397     /// replaced.
398     ///
399     /// Notice that other chains may still be replaced even if the function
400     /// returns false.
401     bool findBetterNeighborChains(StoreSDNode *St);
402
403     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
404     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
405
406     /// Holds a pointer to an LSBaseSDNode as well as information on where it
407     /// is located in a sequence of memory operations connected by a chain.
408     struct MemOpLink {
409       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
410       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
411       // Ptr to the mem node.
412       LSBaseSDNode *MemNode;
413       // Offset from the base ptr.
414       int64_t OffsetFromBase;
415       // What is the sequence number of this mem node.
416       // Lowest mem operand in the DAG starts at zero.
417       unsigned SequenceNum;
418     };
419
420     /// This is a helper function for visitMUL to check the profitability
421     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
422     /// MulNode is the original multiply, AddNode is (add x, c1),
423     /// and ConstNode is c2.
424     bool isMulAddWithConstProfitable(SDNode *MulNode,
425                                      SDValue &AddNode,
426                                      SDValue &ConstNode);
427
428     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
429     /// constant build_vector of the stored constant values in Stores.
430     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
431                                          ArrayRef<MemOpLink> Stores,
432                                          SmallVectorImpl<SDValue> &Chains,
433                                          EVT Ty) const;
434
435     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
436     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
437     /// the type of the loaded value to be extended.  LoadedVT returns the type
438     /// of the original loaded value.  NarrowLoad returns whether the load would
439     /// need to be narrowed in order to match.
440     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
441                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
442                           bool &NarrowLoad);
443
444     /// This is a helper function for MergeConsecutiveStores. When the source
445     /// elements of the consecutive stores are all constants or all extracted
446     /// vector elements, try to merge them into one larger store.
447     /// \return True if a merged store was created.
448     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
449                                          EVT MemVT, unsigned NumStores,
450                                          bool IsConstantSrc, bool UseVector);
451
452     /// This is a helper function for MergeConsecutiveStores.
453     /// Stores that may be merged are placed in StoreNodes.
454     /// Loads that may alias with those stores are placed in AliasLoadNodes.
455     void getStoreMergeAndAliasCandidates(
456         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
457         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
458
459     /// Helper function for MergeConsecutiveStores. Checks if
460     /// Candidate stores have indirect dependency through their
461     /// operands. \return True if safe to merge
462     bool checkMergeStoreCandidatesForDependencies(
463         SmallVectorImpl<MemOpLink> &StoreNodes);
464
465     /// Merge consecutive store operations into a wide store.
466     /// This optimization uses wide integers or vectors when possible.
467     /// \return True if some memory operations were changed.
468     bool MergeConsecutiveStores(StoreSDNode *N);
469
470     /// \brief Try to transform a truncation where C is a constant:
471     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
472     ///
473     /// \p N needs to be a truncation and its first operand an AND. Other
474     /// requirements are checked by the function (e.g. that trunc is
475     /// single-use) and if missed an empty SDValue is returned.
476     SDValue distributeTruncateThroughAnd(SDNode *N);
477
478   public:
479     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
480         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
481           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
482       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
483     }
484
485     /// Runs the dag combiner on all nodes in the work list
486     void Run(CombineLevel AtLevel);
487
488     SelectionDAG &getDAG() const { return DAG; }
489
490     /// Returns a type large enough to hold any valid shift amount - before type
491     /// legalization these can be huge.
492     EVT getShiftAmountTy(EVT LHSTy) {
493       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
494       if (LHSTy.isVector())
495         return LHSTy;
496       auto &DL = DAG.getDataLayout();
497       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
498                         : TLI.getPointerTy(DL);
499     }
500
501     /// This method returns true if we are running before type legalization or
502     /// if the specified VT is legal.
503     bool isTypeLegal(const EVT &VT) {
504       if (!LegalTypes) return true;
505       return TLI.isTypeLegal(VT);
506     }
507
508     /// Convenience wrapper around TargetLowering::getSetCCResultType
509     EVT getSetCCResultType(EVT VT) const {
510       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
511     }
512   };
513 }
514
515
516 namespace {
517 /// This class is a DAGUpdateListener that removes any deleted
518 /// nodes from the worklist.
519 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
520   DAGCombiner &DC;
521 public:
522   explicit WorklistRemover(DAGCombiner &dc)
523     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
524
525   void NodeDeleted(SDNode *N, SDNode *E) override {
526     DC.removeFromWorklist(N);
527   }
528 };
529 }
530
531 //===----------------------------------------------------------------------===//
532 //  TargetLowering::DAGCombinerInfo implementation
533 //===----------------------------------------------------------------------===//
534
535 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
536   ((DAGCombiner*)DC)->AddToWorklist(N);
537 }
538
539 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
540   ((DAGCombiner*)DC)->removeFromWorklist(N);
541 }
542
543 SDValue TargetLowering::DAGCombinerInfo::
544 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
545   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
546 }
547
548 SDValue TargetLowering::DAGCombinerInfo::
549 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
550   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
551 }
552
553
554 SDValue TargetLowering::DAGCombinerInfo::
555 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
556   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
557 }
558
559 void TargetLowering::DAGCombinerInfo::
560 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
561   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
562 }
563
564 //===----------------------------------------------------------------------===//
565 // Helper Functions
566 //===----------------------------------------------------------------------===//
567
568 void DAGCombiner::deleteAndRecombine(SDNode *N) {
569   removeFromWorklist(N);
570
571   // If the operands of this node are only used by the node, they will now be
572   // dead. Make sure to re-visit them and recursively delete dead nodes.
573   for (const SDValue &Op : N->ops())
574     // For an operand generating multiple values, one of the values may
575     // become dead allowing further simplification (e.g. split index
576     // arithmetic from an indexed load).
577     if (Op->hasOneUse() || Op->getNumValues() > 1)
578       AddToWorklist(Op.getNode());
579
580   DAG.DeleteNode(N);
581 }
582
583 /// Return 1 if we can compute the negated form of the specified expression for
584 /// the same cost as the expression itself, or 2 if we can compute the negated
585 /// form more cheaply than the expression itself.
586 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
587                                const TargetLowering &TLI,
588                                const TargetOptions *Options,
589                                unsigned Depth = 0) {
590   // fneg is removable even if it has multiple uses.
591   if (Op.getOpcode() == ISD::FNEG) return 2;
592
593   // Don't allow anything with multiple uses.
594   if (!Op.hasOneUse()) return 0;
595
596   // Don't recurse exponentially.
597   if (Depth > 6) return 0;
598
599   switch (Op.getOpcode()) {
600   default: return false;
601   case ISD::ConstantFP:
602     // Don't invert constant FP values after legalize.  The negated constant
603     // isn't necessarily legal.
604     return LegalOperations ? 0 : 1;
605   case ISD::FADD:
606     // FIXME: determine better conditions for this xform.
607     if (!Options->UnsafeFPMath) return 0;
608
609     // After operation legalization, it might not be legal to create new FSUBs.
610     if (LegalOperations &&
611         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
612       return 0;
613
614     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
615     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
616                                     Options, Depth + 1))
617       return V;
618     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
619     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
620                               Depth + 1);
621   case ISD::FSUB:
622     // We can't turn -(A-B) into B-A when we honor signed zeros.
623     if (!Options->UnsafeFPMath) return 0;
624
625     // fold (fneg (fsub A, B)) -> (fsub B, A)
626     return 1;
627
628   case ISD::FMUL:
629   case ISD::FDIV:
630     if (Options->HonorSignDependentRoundingFPMath()) return 0;
631
632     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
633     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
634                                     Options, Depth + 1))
635       return V;
636
637     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
638                               Depth + 1);
639
640   case ISD::FP_EXTEND:
641   case ISD::FP_ROUND:
642   case ISD::FSIN:
643     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
644                               Depth + 1);
645   }
646 }
647
648 /// If isNegatibleForFree returns true, return the newly negated expression.
649 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
650                                     bool LegalOperations, unsigned Depth = 0) {
651   const TargetOptions &Options = DAG.getTarget().Options;
652   // fneg is removable even if it has multiple uses.
653   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
654
655   // Don't allow anything with multiple uses.
656   assert(Op.hasOneUse() && "Unknown reuse!");
657
658   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
659
660   const SDNodeFlags *Flags = Op.getNode()->getFlags();
661
662   switch (Op.getOpcode()) {
663   default: llvm_unreachable("Unknown code");
664   case ISD::ConstantFP: {
665     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
666     V.changeSign();
667     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
668   }
669   case ISD::FADD:
670     // FIXME: determine better conditions for this xform.
671     assert(Options.UnsafeFPMath);
672
673     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
674     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
675                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
676       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
677                          GetNegatedExpression(Op.getOperand(0), DAG,
678                                               LegalOperations, Depth+1),
679                          Op.getOperand(1), Flags);
680     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
681     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
682                        GetNegatedExpression(Op.getOperand(1), DAG,
683                                             LegalOperations, Depth+1),
684                        Op.getOperand(0), Flags);
685   case ISD::FSUB:
686     // We can't turn -(A-B) into B-A when we honor signed zeros.
687     assert(Options.UnsafeFPMath);
688
689     // fold (fneg (fsub 0, B)) -> B
690     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
691       if (N0CFP->isZero())
692         return Op.getOperand(1);
693
694     // fold (fneg (fsub A, B)) -> (fsub B, A)
695     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
696                        Op.getOperand(1), Op.getOperand(0), Flags);
697
698   case ISD::FMUL:
699   case ISD::FDIV:
700     assert(!Options.HonorSignDependentRoundingFPMath());
701
702     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
703     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
704                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
705       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
706                          GetNegatedExpression(Op.getOperand(0), DAG,
707                                               LegalOperations, Depth+1),
708                          Op.getOperand(1), Flags);
709
710     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
711     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
712                        Op.getOperand(0),
713                        GetNegatedExpression(Op.getOperand(1), DAG,
714                                             LegalOperations, Depth+1), Flags);
715
716   case ISD::FP_EXTEND:
717   case ISD::FSIN:
718     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
719                        GetNegatedExpression(Op.getOperand(0), DAG,
720                                             LegalOperations, Depth+1));
721   case ISD::FP_ROUND:
722       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
723                          GetNegatedExpression(Op.getOperand(0), DAG,
724                                               LegalOperations, Depth+1),
725                          Op.getOperand(1));
726   }
727 }
728
729 // Return true if this node is a setcc, or is a select_cc
730 // that selects between the target values used for true and false, making it
731 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
732 // the appropriate nodes based on the type of node we are checking. This
733 // simplifies life a bit for the callers.
734 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
735                                     SDValue &CC) const {
736   if (N.getOpcode() == ISD::SETCC) {
737     LHS = N.getOperand(0);
738     RHS = N.getOperand(1);
739     CC  = N.getOperand(2);
740     return true;
741   }
742
743   if (N.getOpcode() != ISD::SELECT_CC ||
744       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
745       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
746     return false;
747
748   if (TLI.getBooleanContents(N.getValueType()) ==
749       TargetLowering::UndefinedBooleanContent)
750     return false;
751
752   LHS = N.getOperand(0);
753   RHS = N.getOperand(1);
754   CC  = N.getOperand(4);
755   return true;
756 }
757
758 /// Return true if this is a SetCC-equivalent operation with only one use.
759 /// If this is true, it allows the users to invert the operation for free when
760 /// it is profitable to do so.
761 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
762   SDValue N0, N1, N2;
763   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
764     return true;
765   return false;
766 }
767
768 // \brief Returns the SDNode if it is a constant float BuildVector
769 // or constant float.
770 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
771   if (isa<ConstantFPSDNode>(N))
772     return N.getNode();
773   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
774     return N.getNode();
775   return nullptr;
776 }
777
778 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
779 // int.
780 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
781   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
782     return CN;
783
784   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
785     BitVector UndefElements;
786     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
787
788     // BuildVectors can truncate their operands. Ignore that case here.
789     // FIXME: We blindly ignore splats which include undef which is overly
790     // pessimistic.
791     if (CN && UndefElements.none() &&
792         CN->getValueType(0) == N.getValueType().getScalarType())
793       return CN;
794   }
795
796   return nullptr;
797 }
798
799 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
800 // float.
801 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
802   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
803     return CN;
804
805   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
806     BitVector UndefElements;
807     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
808
809     if (CN && UndefElements.none())
810       return CN;
811   }
812
813   return nullptr;
814 }
815
816 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
817                                     SDValue N1) {
818   EVT VT = N0.getValueType();
819   if (N0.getOpcode() == Opc) {
820     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
821       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
822         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
823         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
824           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
825         return SDValue();
826       }
827       if (N0.hasOneUse()) {
828         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
829         // use
830         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
831         if (!OpNode.getNode())
832           return SDValue();
833         AddToWorklist(OpNode.getNode());
834         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
835       }
836     }
837   }
838
839   if (N1.getOpcode() == Opc) {
840     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
841       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
842         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
843         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
844           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
845         return SDValue();
846       }
847       if (N1.hasOneUse()) {
848         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
849         // use
850         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
851         if (!OpNode.getNode())
852           return SDValue();
853         AddToWorklist(OpNode.getNode());
854         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
855       }
856     }
857   }
858
859   return SDValue();
860 }
861
862 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
863                                bool AddTo) {
864   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
865   ++NodesCombined;
866   DEBUG(dbgs() << "\nReplacing.1 ";
867         N->dump(&DAG);
868         dbgs() << "\nWith: ";
869         To[0].getNode()->dump(&DAG);
870         dbgs() << " and " << NumTo-1 << " other values\n");
871   for (unsigned i = 0, e = NumTo; i != e; ++i)
872     assert((!To[i].getNode() ||
873             N->getValueType(i) == To[i].getValueType()) &&
874            "Cannot combine value to value of different type!");
875
876   WorklistRemover DeadNodes(*this);
877   DAG.ReplaceAllUsesWith(N, To);
878   if (AddTo) {
879     // Push the new nodes and any users onto the worklist
880     for (unsigned i = 0, e = NumTo; i != e; ++i) {
881       if (To[i].getNode()) {
882         AddToWorklist(To[i].getNode());
883         AddUsersToWorklist(To[i].getNode());
884       }
885     }
886   }
887
888   // Finally, if the node is now dead, remove it from the graph.  The node
889   // may not be dead if the replacement process recursively simplified to
890   // something else needing this node.
891   if (N->use_empty())
892     deleteAndRecombine(N);
893   return SDValue(N, 0);
894 }
895
896 void DAGCombiner::
897 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
898   // Replace all uses.  If any nodes become isomorphic to other nodes and
899   // are deleted, make sure to remove them from our worklist.
900   WorklistRemover DeadNodes(*this);
901   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
902
903   // Push the new node and any (possibly new) users onto the worklist.
904   AddToWorklist(TLO.New.getNode());
905   AddUsersToWorklist(TLO.New.getNode());
906
907   // Finally, if the node is now dead, remove it from the graph.  The node
908   // may not be dead if the replacement process recursively simplified to
909   // something else needing this node.
910   if (TLO.Old.getNode()->use_empty())
911     deleteAndRecombine(TLO.Old.getNode());
912 }
913
914 /// Check the specified integer node value to see if it can be simplified or if
915 /// things it uses can be simplified by bit propagation. If so, return true.
916 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
917   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
918   APInt KnownZero, KnownOne;
919   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
920     return false;
921
922   // Revisit the node.
923   AddToWorklist(Op.getNode());
924
925   // Replace the old value with the new one.
926   ++NodesCombined;
927   DEBUG(dbgs() << "\nReplacing.2 ";
928         TLO.Old.getNode()->dump(&DAG);
929         dbgs() << "\nWith: ";
930         TLO.New.getNode()->dump(&DAG);
931         dbgs() << '\n');
932
933   CommitTargetLoweringOpt(TLO);
934   return true;
935 }
936
937 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
938   SDLoc dl(Load);
939   EVT VT = Load->getValueType(0);
940   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
941
942   DEBUG(dbgs() << "\nReplacing.9 ";
943         Load->dump(&DAG);
944         dbgs() << "\nWith: ";
945         Trunc.getNode()->dump(&DAG);
946         dbgs() << '\n');
947   WorklistRemover DeadNodes(*this);
948   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
949   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
950   deleteAndRecombine(Load);
951   AddToWorklist(Trunc.getNode());
952 }
953
954 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
955   Replace = false;
956   SDLoc dl(Op);
957   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
958     LoadSDNode *LD = cast<LoadSDNode>(Op);
959     EVT MemVT = LD->getMemoryVT();
960     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
961       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
962                                                        : ISD::EXTLOAD)
963       : LD->getExtensionType();
964     Replace = true;
965     return DAG.getExtLoad(ExtType, dl, PVT,
966                           LD->getChain(), LD->getBasePtr(),
967                           MemVT, LD->getMemOperand());
968   }
969
970   unsigned Opc = Op.getOpcode();
971   switch (Opc) {
972   default: break;
973   case ISD::AssertSext:
974     return DAG.getNode(ISD::AssertSext, dl, PVT,
975                        SExtPromoteOperand(Op.getOperand(0), PVT),
976                        Op.getOperand(1));
977   case ISD::AssertZext:
978     return DAG.getNode(ISD::AssertZext, dl, PVT,
979                        ZExtPromoteOperand(Op.getOperand(0), PVT),
980                        Op.getOperand(1));
981   case ISD::Constant: {
982     unsigned ExtOpc =
983       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
984     return DAG.getNode(ExtOpc, dl, PVT, Op);
985   }
986   }
987
988   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
989     return SDValue();
990   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
991 }
992
993 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
994   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
995     return SDValue();
996   EVT OldVT = Op.getValueType();
997   SDLoc dl(Op);
998   bool Replace = false;
999   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1000   if (!NewOp.getNode())
1001     return SDValue();
1002   AddToWorklist(NewOp.getNode());
1003
1004   if (Replace)
1005     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1006   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1007                      DAG.getValueType(OldVT));
1008 }
1009
1010 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1011   EVT OldVT = Op.getValueType();
1012   SDLoc dl(Op);
1013   bool Replace = false;
1014   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1015   if (!NewOp.getNode())
1016     return SDValue();
1017   AddToWorklist(NewOp.getNode());
1018
1019   if (Replace)
1020     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1021   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1022 }
1023
1024 /// Promote the specified integer binary operation if the target indicates it is
1025 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1026 /// i32 since i16 instructions are longer.
1027 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1028   if (!LegalOperations)
1029     return SDValue();
1030
1031   EVT VT = Op.getValueType();
1032   if (VT.isVector() || !VT.isInteger())
1033     return SDValue();
1034
1035   // If operation type is 'undesirable', e.g. i16 on x86, consider
1036   // promoting it.
1037   unsigned Opc = Op.getOpcode();
1038   if (TLI.isTypeDesirableForOp(Opc, VT))
1039     return SDValue();
1040
1041   EVT PVT = VT;
1042   // Consult target whether it is a good idea to promote this operation and
1043   // what's the right type to promote it to.
1044   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1045     assert(PVT != VT && "Don't know what type to promote to!");
1046
1047     bool Replace0 = false;
1048     SDValue N0 = Op.getOperand(0);
1049     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1050     if (!NN0.getNode())
1051       return SDValue();
1052
1053     bool Replace1 = false;
1054     SDValue N1 = Op.getOperand(1);
1055     SDValue NN1;
1056     if (N0 == N1)
1057       NN1 = NN0;
1058     else {
1059       NN1 = PromoteOperand(N1, PVT, Replace1);
1060       if (!NN1.getNode())
1061         return SDValue();
1062     }
1063
1064     AddToWorklist(NN0.getNode());
1065     if (NN1.getNode())
1066       AddToWorklist(NN1.getNode());
1067
1068     if (Replace0)
1069       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1070     if (Replace1)
1071       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1072
1073     DEBUG(dbgs() << "\nPromoting ";
1074           Op.getNode()->dump(&DAG));
1075     SDLoc dl(Op);
1076     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1077                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1078   }
1079   return SDValue();
1080 }
1081
1082 /// Promote the specified integer shift operation if the target indicates it is
1083 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1084 /// i32 since i16 instructions are longer.
1085 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1086   if (!LegalOperations)
1087     return SDValue();
1088
1089   EVT VT = Op.getValueType();
1090   if (VT.isVector() || !VT.isInteger())
1091     return SDValue();
1092
1093   // If operation type is 'undesirable', e.g. i16 on x86, consider
1094   // promoting it.
1095   unsigned Opc = Op.getOpcode();
1096   if (TLI.isTypeDesirableForOp(Opc, VT))
1097     return SDValue();
1098
1099   EVT PVT = VT;
1100   // Consult target whether it is a good idea to promote this operation and
1101   // what's the right type to promote it to.
1102   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1103     assert(PVT != VT && "Don't know what type to promote to!");
1104
1105     bool Replace = false;
1106     SDValue N0 = Op.getOperand(0);
1107     if (Opc == ISD::SRA)
1108       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1109     else if (Opc == ISD::SRL)
1110       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1111     else
1112       N0 = PromoteOperand(N0, PVT, Replace);
1113     if (!N0.getNode())
1114       return SDValue();
1115
1116     AddToWorklist(N0.getNode());
1117     if (Replace)
1118       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1119
1120     DEBUG(dbgs() << "\nPromoting ";
1121           Op.getNode()->dump(&DAG));
1122     SDLoc dl(Op);
1123     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1124                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1125   }
1126   return SDValue();
1127 }
1128
1129 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1130   if (!LegalOperations)
1131     return SDValue();
1132
1133   EVT VT = Op.getValueType();
1134   if (VT.isVector() || !VT.isInteger())
1135     return SDValue();
1136
1137   // If operation type is 'undesirable', e.g. i16 on x86, consider
1138   // promoting it.
1139   unsigned Opc = Op.getOpcode();
1140   if (TLI.isTypeDesirableForOp(Opc, VT))
1141     return SDValue();
1142
1143   EVT PVT = VT;
1144   // Consult target whether it is a good idea to promote this operation and
1145   // what's the right type to promote it to.
1146   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1147     assert(PVT != VT && "Don't know what type to promote to!");
1148     // fold (aext (aext x)) -> (aext x)
1149     // fold (aext (zext x)) -> (zext x)
1150     // fold (aext (sext x)) -> (sext x)
1151     DEBUG(dbgs() << "\nPromoting ";
1152           Op.getNode()->dump(&DAG));
1153     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1154   }
1155   return SDValue();
1156 }
1157
1158 bool DAGCombiner::PromoteLoad(SDValue Op) {
1159   if (!LegalOperations)
1160     return false;
1161
1162   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1163     return false;
1164
1165   EVT VT = Op.getValueType();
1166   if (VT.isVector() || !VT.isInteger())
1167     return false;
1168
1169   // If operation type is 'undesirable', e.g. i16 on x86, consider
1170   // promoting it.
1171   unsigned Opc = Op.getOpcode();
1172   if (TLI.isTypeDesirableForOp(Opc, VT))
1173     return false;
1174
1175   EVT PVT = VT;
1176   // Consult target whether it is a good idea to promote this operation and
1177   // what's the right type to promote it to.
1178   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1179     assert(PVT != VT && "Don't know what type to promote to!");
1180
1181     SDLoc dl(Op);
1182     SDNode *N = Op.getNode();
1183     LoadSDNode *LD = cast<LoadSDNode>(N);
1184     EVT MemVT = LD->getMemoryVT();
1185     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1186       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1187                                                        : ISD::EXTLOAD)
1188       : LD->getExtensionType();
1189     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1190                                    LD->getChain(), LD->getBasePtr(),
1191                                    MemVT, LD->getMemOperand());
1192     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1193
1194     DEBUG(dbgs() << "\nPromoting ";
1195           N->dump(&DAG);
1196           dbgs() << "\nTo: ";
1197           Result.getNode()->dump(&DAG);
1198           dbgs() << '\n');
1199     WorklistRemover DeadNodes(*this);
1200     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1201     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1202     deleteAndRecombine(N);
1203     AddToWorklist(Result.getNode());
1204     return true;
1205   }
1206   return false;
1207 }
1208
1209 /// \brief Recursively delete a node which has no uses and any operands for
1210 /// which it is the only use.
1211 ///
1212 /// Note that this both deletes the nodes and removes them from the worklist.
1213 /// It also adds any nodes who have had a user deleted to the worklist as they
1214 /// may now have only one use and subject to other combines.
1215 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1216   if (!N->use_empty())
1217     return false;
1218
1219   SmallSetVector<SDNode *, 16> Nodes;
1220   Nodes.insert(N);
1221   do {
1222     N = Nodes.pop_back_val();
1223     if (!N)
1224       continue;
1225
1226     if (N->use_empty()) {
1227       for (const SDValue &ChildN : N->op_values())
1228         Nodes.insert(ChildN.getNode());
1229
1230       removeFromWorklist(N);
1231       DAG.DeleteNode(N);
1232     } else {
1233       AddToWorklist(N);
1234     }
1235   } while (!Nodes.empty());
1236   return true;
1237 }
1238
1239 //===----------------------------------------------------------------------===//
1240 //  Main DAG Combiner implementation
1241 //===----------------------------------------------------------------------===//
1242
1243 void DAGCombiner::Run(CombineLevel AtLevel) {
1244   // set the instance variables, so that the various visit routines may use it.
1245   Level = AtLevel;
1246   LegalOperations = Level >= AfterLegalizeVectorOps;
1247   LegalTypes = Level >= AfterLegalizeTypes;
1248
1249   // Add all the dag nodes to the worklist.
1250   for (SDNode &Node : DAG.allnodes())
1251     AddToWorklist(&Node);
1252
1253   // Create a dummy node (which is not added to allnodes), that adds a reference
1254   // to the root node, preventing it from being deleted, and tracking any
1255   // changes of the root.
1256   HandleSDNode Dummy(DAG.getRoot());
1257
1258   // While the worklist isn't empty, find a node and try to combine it.
1259   while (!WorklistMap.empty()) {
1260     SDNode *N;
1261     // The Worklist holds the SDNodes in order, but it may contain null entries.
1262     do {
1263       N = Worklist.pop_back_val();
1264     } while (!N);
1265
1266     bool GoodWorklistEntry = WorklistMap.erase(N);
1267     (void)GoodWorklistEntry;
1268     assert(GoodWorklistEntry &&
1269            "Found a worklist entry without a corresponding map entry!");
1270
1271     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1272     // N is deleted from the DAG, since they too may now be dead or may have a
1273     // reduced number of uses, allowing other xforms.
1274     if (recursivelyDeleteUnusedNodes(N))
1275       continue;
1276
1277     WorklistRemover DeadNodes(*this);
1278
1279     // If this combine is running after legalizing the DAG, re-legalize any
1280     // nodes pulled off the worklist.
1281     if (Level == AfterLegalizeDAG) {
1282       SmallSetVector<SDNode *, 16> UpdatedNodes;
1283       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1284
1285       for (SDNode *LN : UpdatedNodes) {
1286         AddToWorklist(LN);
1287         AddUsersToWorklist(LN);
1288       }
1289       if (!NIsValid)
1290         continue;
1291     }
1292
1293     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1294
1295     // Add any operands of the new node which have not yet been combined to the
1296     // worklist as well. Because the worklist uniques things already, this
1297     // won't repeatedly process the same operand.
1298     CombinedNodes.insert(N);
1299     for (const SDValue &ChildN : N->op_values())
1300       if (!CombinedNodes.count(ChildN.getNode()))
1301         AddToWorklist(ChildN.getNode());
1302
1303     SDValue RV = combine(N);
1304
1305     if (!RV.getNode())
1306       continue;
1307
1308     ++NodesCombined;
1309
1310     // If we get back the same node we passed in, rather than a new node or
1311     // zero, we know that the node must have defined multiple values and
1312     // CombineTo was used.  Since CombineTo takes care of the worklist
1313     // mechanics for us, we have no work to do in this case.
1314     if (RV.getNode() == N)
1315       continue;
1316
1317     assert(N->getOpcode() != ISD::DELETED_NODE &&
1318            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1319            "Node was deleted but visit returned new node!");
1320
1321     DEBUG(dbgs() << " ... into: ";
1322           RV.getNode()->dump(&DAG));
1323
1324     if (N->getNumValues() == RV.getNode()->getNumValues())
1325       DAG.ReplaceAllUsesWith(N, RV.getNode());
1326     else {
1327       assert(N->getValueType(0) == RV.getValueType() &&
1328              N->getNumValues() == 1 && "Type mismatch");
1329       SDValue OpV = RV;
1330       DAG.ReplaceAllUsesWith(N, &OpV);
1331     }
1332
1333     // Push the new node and any users onto the worklist
1334     AddToWorklist(RV.getNode());
1335     AddUsersToWorklist(RV.getNode());
1336
1337     // Finally, if the node is now dead, remove it from the graph.  The node
1338     // may not be dead if the replacement process recursively simplified to
1339     // something else needing this node. This will also take care of adding any
1340     // operands which have lost a user to the worklist.
1341     recursivelyDeleteUnusedNodes(N);
1342   }
1343
1344   // If the root changed (e.g. it was a dead load, update the root).
1345   DAG.setRoot(Dummy.getValue());
1346   DAG.RemoveDeadNodes();
1347 }
1348
1349 SDValue DAGCombiner::visit(SDNode *N) {
1350   switch (N->getOpcode()) {
1351   default: break;
1352   case ISD::TokenFactor:        return visitTokenFactor(N);
1353   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1354   case ISD::ADD:                return visitADD(N);
1355   case ISD::SUB:                return visitSUB(N);
1356   case ISD::ADDC:               return visitADDC(N);
1357   case ISD::SUBC:               return visitSUBC(N);
1358   case ISD::ADDE:               return visitADDE(N);
1359   case ISD::SUBE:               return visitSUBE(N);
1360   case ISD::MUL:                return visitMUL(N);
1361   case ISD::SDIV:               return visitSDIV(N);
1362   case ISD::UDIV:               return visitUDIV(N);
1363   case ISD::SREM:
1364   case ISD::UREM:               return visitREM(N);
1365   case ISD::MULHU:              return visitMULHU(N);
1366   case ISD::MULHS:              return visitMULHS(N);
1367   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1368   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1369   case ISD::SMULO:              return visitSMULO(N);
1370   case ISD::UMULO:              return visitUMULO(N);
1371   case ISD::SMIN:
1372   case ISD::SMAX:
1373   case ISD::UMIN:
1374   case ISD::UMAX:               return visitIMINMAX(N);
1375   case ISD::AND:                return visitAND(N);
1376   case ISD::OR:                 return visitOR(N);
1377   case ISD::XOR:                return visitXOR(N);
1378   case ISD::SHL:                return visitSHL(N);
1379   case ISD::SRA:                return visitSRA(N);
1380   case ISD::SRL:                return visitSRL(N);
1381   case ISD::ROTR:
1382   case ISD::ROTL:               return visitRotate(N);
1383   case ISD::BSWAP:              return visitBSWAP(N);
1384   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1385   case ISD::CTLZ:               return visitCTLZ(N);
1386   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1387   case ISD::CTTZ:               return visitCTTZ(N);
1388   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1389   case ISD::CTPOP:              return visitCTPOP(N);
1390   case ISD::SELECT:             return visitSELECT(N);
1391   case ISD::VSELECT:            return visitVSELECT(N);
1392   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1393   case ISD::SETCC:              return visitSETCC(N);
1394   case ISD::SETCCE:             return visitSETCCE(N);
1395   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1396   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1397   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1398   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1399   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1400   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1401   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1402   case ISD::BITCAST:            return visitBITCAST(N);
1403   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1404   case ISD::FADD:               return visitFADD(N);
1405   case ISD::FSUB:               return visitFSUB(N);
1406   case ISD::FMUL:               return visitFMUL(N);
1407   case ISD::FMA:                return visitFMA(N);
1408   case ISD::FDIV:               return visitFDIV(N);
1409   case ISD::FREM:               return visitFREM(N);
1410   case ISD::FSQRT:              return visitFSQRT(N);
1411   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1412   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1413   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1414   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1415   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1416   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1417   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1418   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1419   case ISD::FNEG:               return visitFNEG(N);
1420   case ISD::FABS:               return visitFABS(N);
1421   case ISD::FFLOOR:             return visitFFLOOR(N);
1422   case ISD::FMINNUM:            return visitFMINNUM(N);
1423   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1424   case ISD::FCEIL:              return visitFCEIL(N);
1425   case ISD::FTRUNC:             return visitFTRUNC(N);
1426   case ISD::BRCOND:             return visitBRCOND(N);
1427   case ISD::BR_CC:              return visitBR_CC(N);
1428   case ISD::LOAD:               return visitLOAD(N);
1429   case ISD::STORE:              return visitSTORE(N);
1430   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1431   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1432   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1433   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1434   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1435   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1436   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1437   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1438   case ISD::MGATHER:            return visitMGATHER(N);
1439   case ISD::MLOAD:              return visitMLOAD(N);
1440   case ISD::MSCATTER:           return visitMSCATTER(N);
1441   case ISD::MSTORE:             return visitMSTORE(N);
1442   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1443   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1444   }
1445   return SDValue();
1446 }
1447
1448 SDValue DAGCombiner::combine(SDNode *N) {
1449   SDValue RV = visit(N);
1450
1451   // If nothing happened, try a target-specific DAG combine.
1452   if (!RV.getNode()) {
1453     assert(N->getOpcode() != ISD::DELETED_NODE &&
1454            "Node was deleted but visit returned NULL!");
1455
1456     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1457         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1458
1459       // Expose the DAG combiner to the target combiner impls.
1460       TargetLowering::DAGCombinerInfo
1461         DagCombineInfo(DAG, Level, false, this);
1462
1463       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1464     }
1465   }
1466
1467   // If nothing happened still, try promoting the operation.
1468   if (!RV.getNode()) {
1469     switch (N->getOpcode()) {
1470     default: break;
1471     case ISD::ADD:
1472     case ISD::SUB:
1473     case ISD::MUL:
1474     case ISD::AND:
1475     case ISD::OR:
1476     case ISD::XOR:
1477       RV = PromoteIntBinOp(SDValue(N, 0));
1478       break;
1479     case ISD::SHL:
1480     case ISD::SRA:
1481     case ISD::SRL:
1482       RV = PromoteIntShiftOp(SDValue(N, 0));
1483       break;
1484     case ISD::SIGN_EXTEND:
1485     case ISD::ZERO_EXTEND:
1486     case ISD::ANY_EXTEND:
1487       RV = PromoteExtend(SDValue(N, 0));
1488       break;
1489     case ISD::LOAD:
1490       if (PromoteLoad(SDValue(N, 0)))
1491         RV = SDValue(N, 0);
1492       break;
1493     }
1494   }
1495
1496   // If N is a commutative binary node, try commuting it to enable more
1497   // sdisel CSE.
1498   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1499       N->getNumValues() == 1) {
1500     SDValue N0 = N->getOperand(0);
1501     SDValue N1 = N->getOperand(1);
1502
1503     // Constant operands are canonicalized to RHS.
1504     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1505       SDValue Ops[] = {N1, N0};
1506       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1507                                             N->getFlags());
1508       if (CSENode)
1509         return SDValue(CSENode, 0);
1510     }
1511   }
1512
1513   return RV;
1514 }
1515
1516 /// Given a node, return its input chain if it has one, otherwise return a null
1517 /// sd operand.
1518 static SDValue getInputChainForNode(SDNode *N) {
1519   if (unsigned NumOps = N->getNumOperands()) {
1520     if (N->getOperand(0).getValueType() == MVT::Other)
1521       return N->getOperand(0);
1522     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1523       return N->getOperand(NumOps-1);
1524     for (unsigned i = 1; i < NumOps-1; ++i)
1525       if (N->getOperand(i).getValueType() == MVT::Other)
1526         return N->getOperand(i);
1527   }
1528   return SDValue();
1529 }
1530
1531 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1532   // If N has two operands, where one has an input chain equal to the other,
1533   // the 'other' chain is redundant.
1534   if (N->getNumOperands() == 2) {
1535     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1536       return N->getOperand(0);
1537     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1538       return N->getOperand(1);
1539   }
1540
1541   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1542   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1543   SmallPtrSet<SDNode*, 16> SeenOps;
1544   bool Changed = false;             // If we should replace this token factor.
1545
1546   // Start out with this token factor.
1547   TFs.push_back(N);
1548
1549   // Iterate through token factors.  The TFs grows when new token factors are
1550   // encountered.
1551   for (unsigned i = 0; i < TFs.size(); ++i) {
1552     SDNode *TF = TFs[i];
1553
1554     // Check each of the operands.
1555     for (const SDValue &Op : TF->op_values()) {
1556
1557       switch (Op.getOpcode()) {
1558       case ISD::EntryToken:
1559         // Entry tokens don't need to be added to the list. They are
1560         // redundant.
1561         Changed = true;
1562         break;
1563
1564       case ISD::TokenFactor:
1565         if (Op.hasOneUse() &&
1566             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1567           // Queue up for processing.
1568           TFs.push_back(Op.getNode());
1569           // Clean up in case the token factor is removed.
1570           AddToWorklist(Op.getNode());
1571           Changed = true;
1572           break;
1573         }
1574         // Fall thru
1575
1576       default:
1577         // Only add if it isn't already in the list.
1578         if (SeenOps.insert(Op.getNode()).second)
1579           Ops.push_back(Op);
1580         else
1581           Changed = true;
1582         break;
1583       }
1584     }
1585   }
1586
1587   SDValue Result;
1588
1589   // If we've changed things around then replace token factor.
1590   if (Changed) {
1591     if (Ops.empty()) {
1592       // The entry token is the only possible outcome.
1593       Result = DAG.getEntryNode();
1594     } else {
1595       // New and improved token factor.
1596       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1597     }
1598
1599     // Add users to worklist if AA is enabled, since it may introduce
1600     // a lot of new chained token factors while removing memory deps.
1601     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1602       : DAG.getSubtarget().useAA();
1603     return CombineTo(N, Result, UseAA /*add to worklist*/);
1604   }
1605
1606   return Result;
1607 }
1608
1609 /// MERGE_VALUES can always be eliminated.
1610 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1611   WorklistRemover DeadNodes(*this);
1612   // Replacing results may cause a different MERGE_VALUES to suddenly
1613   // be CSE'd with N, and carry its uses with it. Iterate until no
1614   // uses remain, to ensure that the node can be safely deleted.
1615   // First add the users of this node to the work list so that they
1616   // can be tried again once they have new operands.
1617   AddUsersToWorklist(N);
1618   do {
1619     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1620       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1621   } while (!N->use_empty());
1622   deleteAndRecombine(N);
1623   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1624 }
1625
1626 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1627 /// ConstantSDNode pointer else nullptr.
1628 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1629   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1630   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1631 }
1632
1633 SDValue DAGCombiner::visitADD(SDNode *N) {
1634   SDValue N0 = N->getOperand(0);
1635   SDValue N1 = N->getOperand(1);
1636   EVT VT = N0.getValueType();
1637
1638   // fold vector ops
1639   if (VT.isVector()) {
1640     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1641       return FoldedVOp;
1642
1643     // fold (add x, 0) -> x, vector edition
1644     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1645       return N0;
1646     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1647       return N1;
1648   }
1649
1650   // fold (add x, undef) -> undef
1651   if (N0.isUndef())
1652     return N0;
1653   if (N1.isUndef())
1654     return N1;
1655   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1656     // canonicalize constant to RHS
1657     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1658       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1659     // fold (add c1, c2) -> c1+c2
1660     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT,
1661                                       N0.getNode(), N1.getNode());
1662   }
1663   // fold (add x, 0) -> x
1664   if (isNullConstant(N1))
1665     return N0;
1666   // fold ((c1-A)+c2) -> (c1+c2)-A
1667   if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) {
1668     if (N0.getOpcode() == ISD::SUB)
1669       if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1670         SDLoc DL(N);
1671         return DAG.getNode(ISD::SUB, DL, VT,
1672                            DAG.getConstant(N1C->getAPIntValue()+
1673                                            N0C->getAPIntValue(), DL, VT),
1674                            N0.getOperand(1));
1675       }
1676   }
1677   // reassociate add
1678   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1679     return RADD;
1680   // fold ((0-A) + B) -> B-A
1681   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1682     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1683   // fold (A + (0-B)) -> A-B
1684   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1685     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1686   // fold (A+(B-A)) -> B
1687   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1688     return N1.getOperand(0);
1689   // fold ((B-A)+A) -> B
1690   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1691     return N0.getOperand(0);
1692   // fold (A+(B-(A+C))) to (B-C)
1693   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1694       N0 == N1.getOperand(1).getOperand(0))
1695     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1696                        N1.getOperand(1).getOperand(1));
1697   // fold (A+(B-(C+A))) to (B-C)
1698   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1699       N0 == N1.getOperand(1).getOperand(1))
1700     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1701                        N1.getOperand(1).getOperand(0));
1702   // fold (A+((B-A)+or-C)) to (B+or-C)
1703   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1704       N1.getOperand(0).getOpcode() == ISD::SUB &&
1705       N0 == N1.getOperand(0).getOperand(1))
1706     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1707                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1708
1709   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1710   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1711     SDValue N00 = N0.getOperand(0);
1712     SDValue N01 = N0.getOperand(1);
1713     SDValue N10 = N1.getOperand(0);
1714     SDValue N11 = N1.getOperand(1);
1715
1716     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1717       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1718                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1719                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1720   }
1721
1722   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1723     return SDValue(N, 0);
1724
1725   // fold (a+b) -> (a|b) iff a and b share no bits.
1726   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1727       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1728     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1729
1730   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1731   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1732       isNullConstant(N1.getOperand(0).getOperand(0)))
1733     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1734                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1735                                    N1.getOperand(0).getOperand(1),
1736                                    N1.getOperand(1)));
1737   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1738       isNullConstant(N0.getOperand(0).getOperand(0)))
1739     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1740                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1741                                    N0.getOperand(0).getOperand(1),
1742                                    N0.getOperand(1)));
1743
1744   if (N1.getOpcode() == ISD::AND) {
1745     SDValue AndOp0 = N1.getOperand(0);
1746     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1747     unsigned DestBits = VT.getScalarType().getSizeInBits();
1748
1749     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1750     // and similar xforms where the inner op is either ~0 or 0.
1751     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1752       SDLoc DL(N);
1753       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1754     }
1755   }
1756
1757   // add (sext i1), X -> sub X, (zext i1)
1758   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1759       N0.getOperand(0).getValueType() == MVT::i1 &&
1760       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1761     SDLoc DL(N);
1762     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1763     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1764   }
1765
1766   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1767   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1768     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1769     if (TN->getVT() == MVT::i1) {
1770       SDLoc DL(N);
1771       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1772                                  DAG.getConstant(1, DL, VT));
1773       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1774     }
1775   }
1776
1777   return SDValue();
1778 }
1779
1780 SDValue DAGCombiner::visitADDC(SDNode *N) {
1781   SDValue N0 = N->getOperand(0);
1782   SDValue N1 = N->getOperand(1);
1783   EVT VT = N0.getValueType();
1784
1785   // If the flag result is dead, turn this into an ADD.
1786   if (!N->hasAnyUseOfValue(1))
1787     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1788                      DAG.getNode(ISD::CARRY_FALSE,
1789                                  SDLoc(N), MVT::Glue));
1790
1791   // canonicalize constant to RHS.
1792   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1793   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1794   if (N0C && !N1C)
1795     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1796
1797   // fold (addc x, 0) -> x + no carry out
1798   if (isNullConstant(N1))
1799     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1800                                         SDLoc(N), MVT::Glue));
1801
1802   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1803   APInt LHSZero, LHSOne;
1804   APInt RHSZero, RHSOne;
1805   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1806
1807   if (LHSZero.getBoolValue()) {
1808     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1809
1810     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1811     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1812     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1813       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1814                        DAG.getNode(ISD::CARRY_FALSE,
1815                                    SDLoc(N), MVT::Glue));
1816   }
1817
1818   return SDValue();
1819 }
1820
1821 SDValue DAGCombiner::visitADDE(SDNode *N) {
1822   SDValue N0 = N->getOperand(0);
1823   SDValue N1 = N->getOperand(1);
1824   SDValue CarryIn = N->getOperand(2);
1825
1826   // canonicalize constant to RHS
1827   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1828   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1829   if (N0C && !N1C)
1830     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1831                        N1, N0, CarryIn);
1832
1833   // fold (adde x, y, false) -> (addc x, y)
1834   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1835     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1836
1837   return SDValue();
1838 }
1839
1840 // Since it may not be valid to emit a fold to zero for vector initializers
1841 // check if we can before folding.
1842 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1843                              SelectionDAG &DAG, bool LegalOperations,
1844                              bool LegalTypes) {
1845   if (!VT.isVector())
1846     return DAG.getConstant(0, DL, VT);
1847   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1848     return DAG.getConstant(0, DL, VT);
1849   return SDValue();
1850 }
1851
1852 SDValue DAGCombiner::visitSUB(SDNode *N) {
1853   SDValue N0 = N->getOperand(0);
1854   SDValue N1 = N->getOperand(1);
1855   EVT VT = N0.getValueType();
1856
1857   // fold vector ops
1858   if (VT.isVector()) {
1859     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1860       return FoldedVOp;
1861
1862     // fold (sub x, 0) -> x, vector edition
1863     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1864       return N0;
1865   }
1866
1867   // fold (sub x, x) -> 0
1868   // FIXME: Refactor this and xor and other similar operations together.
1869   if (N0 == N1)
1870     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1871   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1872       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1873     // fold (sub c1, c2) -> c1-c2
1874     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT,
1875                                       N0.getNode(), N1.getNode());
1876   }
1877   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1878   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1879   // fold (sub x, c) -> (add x, -c)
1880   if (N1C) {
1881     SDLoc DL(N);
1882     return DAG.getNode(ISD::ADD, DL, VT, N0,
1883                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1884   }
1885   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1886   if (isAllOnesConstant(N0))
1887     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1888   // fold A-(A-B) -> B
1889   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1890     return N1.getOperand(1);
1891   // fold (A+B)-A -> B
1892   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1893     return N0.getOperand(1);
1894   // fold (A+B)-B -> A
1895   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1896     return N0.getOperand(0);
1897   // fold C2-(A+C1) -> (C2-C1)-A
1898   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1899     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1900   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1901     SDLoc DL(N);
1902     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1903                                    DL, VT);
1904     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1905                        N1.getOperand(0));
1906   }
1907   // fold ((A+(B+or-C))-B) -> A+or-C
1908   if (N0.getOpcode() == ISD::ADD &&
1909       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1910        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1911       N0.getOperand(1).getOperand(0) == N1)
1912     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1913                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1914   // fold ((A+(C+B))-B) -> A+C
1915   if (N0.getOpcode() == ISD::ADD &&
1916       N0.getOperand(1).getOpcode() == ISD::ADD &&
1917       N0.getOperand(1).getOperand(1) == N1)
1918     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1919                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1920   // fold ((A-(B-C))-C) -> A-B
1921   if (N0.getOpcode() == ISD::SUB &&
1922       N0.getOperand(1).getOpcode() == ISD::SUB &&
1923       N0.getOperand(1).getOperand(1) == N1)
1924     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1925                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1926
1927   // If either operand of a sub is undef, the result is undef
1928   if (N0.isUndef())
1929     return N0;
1930   if (N1.isUndef())
1931     return N1;
1932
1933   // If the relocation model supports it, consider symbol offsets.
1934   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1935     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1936       // fold (sub Sym, c) -> Sym-c
1937       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1938         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1939                                     GA->getOffset() -
1940                                       (uint64_t)N1C->getSExtValue());
1941       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1942       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1943         if (GA->getGlobal() == GB->getGlobal())
1944           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1945                                  SDLoc(N), VT);
1946     }
1947
1948   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1949   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1950     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1951     if (TN->getVT() == MVT::i1) {
1952       SDLoc DL(N);
1953       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1954                                  DAG.getConstant(1, DL, VT));
1955       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1956     }
1957   }
1958
1959   return SDValue();
1960 }
1961
1962 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1963   SDValue N0 = N->getOperand(0);
1964   SDValue N1 = N->getOperand(1);
1965   EVT VT = N0.getValueType();
1966   SDLoc DL(N);
1967
1968   // If the flag result is dead, turn this into an SUB.
1969   if (!N->hasAnyUseOfValue(1))
1970     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1971                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1972
1973   // fold (subc x, x) -> 0 + no borrow
1974   if (N0 == N1)
1975     return CombineTo(N, DAG.getConstant(0, DL, VT),
1976                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1977
1978   // fold (subc x, 0) -> x + no borrow
1979   if (isNullConstant(N1))
1980     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1981
1982   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1983   if (isAllOnesConstant(N0))
1984     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
1985                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1986
1987   return SDValue();
1988 }
1989
1990 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1991   SDValue N0 = N->getOperand(0);
1992   SDValue N1 = N->getOperand(1);
1993   SDValue CarryIn = N->getOperand(2);
1994
1995   // fold (sube x, y, false) -> (subc x, y)
1996   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1997     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1998
1999   return SDValue();
2000 }
2001
2002 SDValue DAGCombiner::visitMUL(SDNode *N) {
2003   SDValue N0 = N->getOperand(0);
2004   SDValue N1 = N->getOperand(1);
2005   EVT VT = N0.getValueType();
2006
2007   // fold (mul x, undef) -> 0
2008   if (N0.isUndef() || N1.isUndef())
2009     return DAG.getConstant(0, SDLoc(N), VT);
2010
2011   bool N0IsConst = false;
2012   bool N1IsConst = false;
2013   bool N1IsOpaqueConst = false;
2014   bool N0IsOpaqueConst = false;
2015   APInt ConstValue0, ConstValue1;
2016   // fold vector ops
2017   if (VT.isVector()) {
2018     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2019       return FoldedVOp;
2020
2021     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2022     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2023   } else {
2024     N0IsConst = isa<ConstantSDNode>(N0);
2025     if (N0IsConst) {
2026       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2027       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2028     }
2029     N1IsConst = isa<ConstantSDNode>(N1);
2030     if (N1IsConst) {
2031       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2032       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2033     }
2034   }
2035
2036   // fold (mul c1, c2) -> c1*c2
2037   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2038     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2039                                       N0.getNode(), N1.getNode());
2040
2041   // canonicalize constant to RHS (vector doesn't have to splat)
2042   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2043      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2044     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2045   // fold (mul x, 0) -> 0
2046   if (N1IsConst && ConstValue1 == 0)
2047     return N1;
2048   // We require a splat of the entire scalar bit width for non-contiguous
2049   // bit patterns.
2050   bool IsFullSplat =
2051     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2052   // fold (mul x, 1) -> x
2053   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2054     return N0;
2055   // fold (mul x, -1) -> 0-x
2056   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2057     SDLoc DL(N);
2058     return DAG.getNode(ISD::SUB, DL, VT,
2059                        DAG.getConstant(0, DL, VT), N0);
2060   }
2061   // fold (mul x, (1 << c)) -> x << c
2062   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2063       IsFullSplat) {
2064     SDLoc DL(N);
2065     return DAG.getNode(ISD::SHL, DL, VT, N0,
2066                        DAG.getConstant(ConstValue1.logBase2(), DL,
2067                                        getShiftAmountTy(N0.getValueType())));
2068   }
2069   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2070   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2071       IsFullSplat) {
2072     unsigned Log2Val = (-ConstValue1).logBase2();
2073     SDLoc DL(N);
2074     // FIXME: If the input is something that is easily negated (e.g. a
2075     // single-use add), we should put the negate there.
2076     return DAG.getNode(ISD::SUB, DL, VT,
2077                        DAG.getConstant(0, DL, VT),
2078                        DAG.getNode(ISD::SHL, DL, VT, N0,
2079                             DAG.getConstant(Log2Val, DL,
2080                                       getShiftAmountTy(N0.getValueType()))));
2081   }
2082
2083   APInt Val;
2084   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2085   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2086       (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2087        isa<ConstantSDNode>(N0.getOperand(1)))) {
2088     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2089     AddToWorklist(C3.getNode());
2090     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2091   }
2092
2093   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2094   // use.
2095   {
2096     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2097     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2098     if (N0.getOpcode() == ISD::SHL &&
2099         (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2100          isa<ConstantSDNode>(N0.getOperand(1))) &&
2101         N0.getNode()->hasOneUse()) {
2102       Sh = N0; Y = N1;
2103     } else if (N1.getOpcode() == ISD::SHL &&
2104                isa<ConstantSDNode>(N1.getOperand(1)) &&
2105                N1.getNode()->hasOneUse()) {
2106       Sh = N1; Y = N0;
2107     }
2108
2109     if (Sh.getNode()) {
2110       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2111       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2112     }
2113   }
2114
2115   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2116   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2117       N0.getOpcode() == ISD::ADD &&
2118       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2119       isMulAddWithConstProfitable(N, N0, N1))
2120       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2121                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2122                                      N0.getOperand(0), N1),
2123                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2124                                      N0.getOperand(1), N1));
2125
2126   // reassociate mul
2127   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2128     return RMUL;
2129
2130   return SDValue();
2131 }
2132
2133 /// Return true if divmod libcall is available.
2134 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2135                                      const TargetLowering &TLI) {
2136   RTLIB::Libcall LC;
2137   EVT NodeType = Node->getValueType(0);
2138   if (!NodeType.isSimple())
2139     return false;
2140   switch (NodeType.getSimpleVT().SimpleTy) {
2141   default: return false; // No libcall for vector types.
2142   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2143   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2144   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2145   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2146   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2147   }
2148
2149   return TLI.getLibcallName(LC) != nullptr;
2150 }
2151
2152 /// Issue divrem if both quotient and remainder are needed.
2153 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2154   if (Node->use_empty())
2155     return SDValue(); // This is a dead node, leave it alone.
2156
2157   unsigned Opcode = Node->getOpcode();
2158   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2159   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2160
2161   // DivMod lib calls can still work on non-legal types if using lib-calls.
2162   EVT VT = Node->getValueType(0);
2163   if (VT.isVector() || !VT.isInteger())
2164     return SDValue();
2165
2166   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2167     return SDValue();
2168
2169   // If DIVREM is going to get expanded into a libcall,
2170   // but there is no libcall available, then don't combine.
2171   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2172       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2173     return SDValue();
2174
2175   // If div is legal, it's better to do the normal expansion
2176   unsigned OtherOpcode = 0;
2177   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2178     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2179     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2180       return SDValue();
2181   } else {
2182     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2183     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2184       return SDValue();
2185   }
2186
2187   SDValue Op0 = Node->getOperand(0);
2188   SDValue Op1 = Node->getOperand(1);
2189   SDValue combined;
2190   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2191          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2192     SDNode *User = *UI;
2193     if (User == Node || User->use_empty())
2194       continue;
2195     // Convert the other matching node(s), too;
2196     // otherwise, the DIVREM may get target-legalized into something
2197     // target-specific that we won't be able to recognize.
2198     unsigned UserOpc = User->getOpcode();
2199     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2200         User->getOperand(0) == Op0 &&
2201         User->getOperand(1) == Op1) {
2202       if (!combined) {
2203         if (UserOpc == OtherOpcode) {
2204           SDVTList VTs = DAG.getVTList(VT, VT);
2205           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2206         } else if (UserOpc == DivRemOpc) {
2207           combined = SDValue(User, 0);
2208         } else {
2209           assert(UserOpc == Opcode);
2210           continue;
2211         }
2212       }
2213       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2214         CombineTo(User, combined);
2215       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2216         CombineTo(User, combined.getValue(1));
2217     }
2218   }
2219   return combined;
2220 }
2221
2222 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2223   SDValue N0 = N->getOperand(0);
2224   SDValue N1 = N->getOperand(1);
2225   EVT VT = N->getValueType(0);
2226
2227   // fold vector ops
2228   if (VT.isVector())
2229     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2230       return FoldedVOp;
2231
2232   SDLoc DL(N);
2233
2234   // fold (sdiv c1, c2) -> c1/c2
2235   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2236   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2237   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2238     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2239   // fold (sdiv X, 1) -> X
2240   if (N1C && N1C->isOne())
2241     return N0;
2242   // fold (sdiv X, -1) -> 0-X
2243   if (N1C && N1C->isAllOnesValue())
2244     return DAG.getNode(ISD::SUB, DL, VT,
2245                        DAG.getConstant(0, DL, VT), N0);
2246
2247   // If we know the sign bits of both operands are zero, strength reduce to a
2248   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2249   if (!VT.isVector()) {
2250     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2251       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2252   }
2253
2254   // fold (sdiv X, pow2) -> simple ops after legalize
2255   // FIXME: We check for the exact bit here because the generic lowering gives
2256   // better results in that case. The target-specific lowering should learn how
2257   // to handle exact sdivs efficiently.
2258   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2259       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2260       (N1C->getAPIntValue().isPowerOf2() ||
2261        (-N1C->getAPIntValue()).isPowerOf2())) {
2262     // Target-specific implementation of sdiv x, pow2.
2263     if (SDValue Res = BuildSDIVPow2(N))
2264       return Res;
2265
2266     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2267
2268     // Splat the sign bit into the register
2269     SDValue SGN =
2270         DAG.getNode(ISD::SRA, DL, VT, N0,
2271                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2272                                     getShiftAmountTy(N0.getValueType())));
2273     AddToWorklist(SGN.getNode());
2274
2275     // Add (N0 < 0) ? abs2 - 1 : 0;
2276     SDValue SRL =
2277         DAG.getNode(ISD::SRL, DL, VT, SGN,
2278                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2279                                     getShiftAmountTy(SGN.getValueType())));
2280     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2281     AddToWorklist(SRL.getNode());
2282     AddToWorklist(ADD.getNode());    // Divide by pow2
2283     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2284                   DAG.getConstant(lg2, DL,
2285                                   getShiftAmountTy(ADD.getValueType())));
2286
2287     // If we're dividing by a positive value, we're done.  Otherwise, we must
2288     // negate the result.
2289     if (N1C->getAPIntValue().isNonNegative())
2290       return SRA;
2291
2292     AddToWorklist(SRA.getNode());
2293     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2294   }
2295
2296   // If integer divide is expensive and we satisfy the requirements, emit an
2297   // alternate sequence.  Targets may check function attributes for size/speed
2298   // trade-offs.
2299   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2300   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2301     if (SDValue Op = BuildSDIV(N))
2302       return Op;
2303
2304   // sdiv, srem -> sdivrem
2305   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2306   // Otherwise, we break the simplification logic in visitREM().
2307   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2308     if (SDValue DivRem = useDivRem(N))
2309         return DivRem;
2310
2311   // undef / X -> 0
2312   if (N0.isUndef())
2313     return DAG.getConstant(0, DL, VT);
2314   // X / undef -> undef
2315   if (N1.isUndef())
2316     return N1;
2317
2318   return SDValue();
2319 }
2320
2321 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2322   SDValue N0 = N->getOperand(0);
2323   SDValue N1 = N->getOperand(1);
2324   EVT VT = N->getValueType(0);
2325
2326   // fold vector ops
2327   if (VT.isVector())
2328     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2329       return FoldedVOp;
2330
2331   SDLoc DL(N);
2332
2333   // fold (udiv c1, c2) -> c1/c2
2334   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2335   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2336   if (N0C && N1C)
2337     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2338                                                     N0C, N1C))
2339       return Folded;
2340   // fold (udiv x, (1 << c)) -> x >>u c
2341   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2342     return DAG.getNode(ISD::SRL, DL, VT, N0,
2343                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2344                                        getShiftAmountTy(N0.getValueType())));
2345
2346   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2347   if (N1.getOpcode() == ISD::SHL) {
2348     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2349       if (SHC->getAPIntValue().isPowerOf2()) {
2350         EVT ADDVT = N1.getOperand(1).getValueType();
2351         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2352                                   N1.getOperand(1),
2353                                   DAG.getConstant(SHC->getAPIntValue()
2354                                                                   .logBase2(),
2355                                                   DL, ADDVT));
2356         AddToWorklist(Add.getNode());
2357         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2358       }
2359     }
2360   }
2361
2362   // fold (udiv x, c) -> alternate
2363   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2364   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2365     if (SDValue Op = BuildUDIV(N))
2366       return Op;
2367
2368   // sdiv, srem -> sdivrem
2369   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2370   // Otherwise, we break the simplification logic in visitREM().
2371   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2372     if (SDValue DivRem = useDivRem(N))
2373         return DivRem;
2374
2375   // undef / X -> 0
2376   if (N0.isUndef())
2377     return DAG.getConstant(0, DL, VT);
2378   // X / undef -> undef
2379   if (N1.isUndef())
2380     return N1;
2381
2382   return SDValue();
2383 }
2384
2385 // handles ISD::SREM and ISD::UREM
2386 SDValue DAGCombiner::visitREM(SDNode *N) {
2387   unsigned Opcode = N->getOpcode();
2388   SDValue N0 = N->getOperand(0);
2389   SDValue N1 = N->getOperand(1);
2390   EVT VT = N->getValueType(0);
2391   bool isSigned = (Opcode == ISD::SREM);
2392   SDLoc DL(N);
2393
2394   // fold (rem c1, c2) -> c1%c2
2395   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2396   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2397   if (N0C && N1C)
2398     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2399       return Folded;
2400
2401   if (isSigned) {
2402     // If we know the sign bits of both operands are zero, strength reduce to a
2403     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2404     if (!VT.isVector()) {
2405       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2406         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2407     }
2408   } else {
2409     // fold (urem x, pow2) -> (and x, pow2-1)
2410     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2411         N1C->getAPIntValue().isPowerOf2()) {
2412       return DAG.getNode(ISD::AND, DL, VT, N0,
2413                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2414     }
2415     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2416     if (N1.getOpcode() == ISD::SHL) {
2417       ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0));
2418       if (SHC && SHC->getAPIntValue().isPowerOf2()) {
2419         APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits());
2420         SDValue Add =
2421             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2422         AddToWorklist(Add.getNode());
2423         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2424       }
2425     }
2426   }
2427
2428   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2429
2430   // If X/C can be simplified by the division-by-constant logic, lower
2431   // X%C to the equivalent of X-X/C*C.
2432   // To avoid mangling nodes, this simplification requires that the combine()
2433   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2434   // against this by skipping the simplification if isIntDivCheap().  When
2435   // div is not cheap, combine will not return a DIVREM.  Regardless,
2436   // checking cheapness here makes sense since the simplification results in
2437   // fatter code.
2438   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2439     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2440     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2441     AddToWorklist(Div.getNode());
2442     SDValue OptimizedDiv = combine(Div.getNode());
2443     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2444       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2445              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2446       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2447       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2448       AddToWorklist(Mul.getNode());
2449       return Sub;
2450     }
2451   }
2452
2453   // sdiv, srem -> sdivrem
2454   if (SDValue DivRem = useDivRem(N))
2455     return DivRem.getValue(1);
2456
2457   // undef % X -> 0
2458   if (N0.isUndef())
2459     return DAG.getConstant(0, DL, VT);
2460   // X % undef -> undef
2461   if (N1.isUndef())
2462     return N1;
2463
2464   return SDValue();
2465 }
2466
2467 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2468   SDValue N0 = N->getOperand(0);
2469   SDValue N1 = N->getOperand(1);
2470   EVT VT = N->getValueType(0);
2471   SDLoc DL(N);
2472
2473   // fold (mulhs x, 0) -> 0
2474   if (isNullConstant(N1))
2475     return N1;
2476   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2477   if (isOneConstant(N1)) {
2478     SDLoc DL(N);
2479     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2480                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2481                                        DL,
2482                                        getShiftAmountTy(N0.getValueType())));
2483   }
2484   // fold (mulhs x, undef) -> 0
2485   if (N0.isUndef() || N1.isUndef())
2486     return DAG.getConstant(0, SDLoc(N), VT);
2487
2488   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2489   // plus a shift.
2490   if (VT.isSimple() && !VT.isVector()) {
2491     MVT Simple = VT.getSimpleVT();
2492     unsigned SimpleSize = Simple.getSizeInBits();
2493     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2494     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2495       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2496       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2497       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2498       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2499             DAG.getConstant(SimpleSize, DL,
2500                             getShiftAmountTy(N1.getValueType())));
2501       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2502     }
2503   }
2504
2505   return SDValue();
2506 }
2507
2508 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2509   SDValue N0 = N->getOperand(0);
2510   SDValue N1 = N->getOperand(1);
2511   EVT VT = N->getValueType(0);
2512   SDLoc DL(N);
2513
2514   // fold (mulhu x, 0) -> 0
2515   if (isNullConstant(N1))
2516     return N1;
2517   // fold (mulhu x, 1) -> 0
2518   if (isOneConstant(N1))
2519     return DAG.getConstant(0, DL, N0.getValueType());
2520   // fold (mulhu x, undef) -> 0
2521   if (N0.isUndef() || N1.isUndef())
2522     return DAG.getConstant(0, DL, VT);
2523
2524   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2525   // plus a shift.
2526   if (VT.isSimple() && !VT.isVector()) {
2527     MVT Simple = VT.getSimpleVT();
2528     unsigned SimpleSize = Simple.getSizeInBits();
2529     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2530     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2531       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2532       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2533       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2534       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2535             DAG.getConstant(SimpleSize, DL,
2536                             getShiftAmountTy(N1.getValueType())));
2537       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2538     }
2539   }
2540
2541   return SDValue();
2542 }
2543
2544 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2545 /// give the opcodes for the two computations that are being performed. Return
2546 /// true if a simplification was made.
2547 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2548                                                 unsigned HiOp) {
2549   // If the high half is not needed, just compute the low half.
2550   bool HiExists = N->hasAnyUseOfValue(1);
2551   if (!HiExists &&
2552       (!LegalOperations ||
2553        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2554     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2555     return CombineTo(N, Res, Res);
2556   }
2557
2558   // If the low half is not needed, just compute the high half.
2559   bool LoExists = N->hasAnyUseOfValue(0);
2560   if (!LoExists &&
2561       (!LegalOperations ||
2562        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2563     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2564     return CombineTo(N, Res, Res);
2565   }
2566
2567   // If both halves are used, return as it is.
2568   if (LoExists && HiExists)
2569     return SDValue();
2570
2571   // If the two computed results can be simplified separately, separate them.
2572   if (LoExists) {
2573     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2574     AddToWorklist(Lo.getNode());
2575     SDValue LoOpt = combine(Lo.getNode());
2576     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2577         (!LegalOperations ||
2578          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2579       return CombineTo(N, LoOpt, LoOpt);
2580   }
2581
2582   if (HiExists) {
2583     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2584     AddToWorklist(Hi.getNode());
2585     SDValue HiOpt = combine(Hi.getNode());
2586     if (HiOpt.getNode() && HiOpt != Hi &&
2587         (!LegalOperations ||
2588          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2589       return CombineTo(N, HiOpt, HiOpt);
2590   }
2591
2592   return SDValue();
2593 }
2594
2595 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2596   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2597     return Res;
2598
2599   EVT VT = N->getValueType(0);
2600   SDLoc DL(N);
2601
2602   // If the type is twice as wide is legal, transform the mulhu to a wider
2603   // multiply plus a shift.
2604   if (VT.isSimple() && !VT.isVector()) {
2605     MVT Simple = VT.getSimpleVT();
2606     unsigned SimpleSize = Simple.getSizeInBits();
2607     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2608     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2609       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2610       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2611       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2612       // Compute the high part as N1.
2613       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2614             DAG.getConstant(SimpleSize, DL,
2615                             getShiftAmountTy(Lo.getValueType())));
2616       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2617       // Compute the low part as N0.
2618       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2619       return CombineTo(N, Lo, Hi);
2620     }
2621   }
2622
2623   return SDValue();
2624 }
2625
2626 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2627   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2628     return Res;
2629
2630   EVT VT = N->getValueType(0);
2631   SDLoc DL(N);
2632
2633   // If the type is twice as wide is legal, transform the mulhu to a wider
2634   // multiply plus a shift.
2635   if (VT.isSimple() && !VT.isVector()) {
2636     MVT Simple = VT.getSimpleVT();
2637     unsigned SimpleSize = Simple.getSizeInBits();
2638     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2639     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2640       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2641       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2642       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2643       // Compute the high part as N1.
2644       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2645             DAG.getConstant(SimpleSize, DL,
2646                             getShiftAmountTy(Lo.getValueType())));
2647       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2648       // Compute the low part as N0.
2649       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2650       return CombineTo(N, Lo, Hi);
2651     }
2652   }
2653
2654   return SDValue();
2655 }
2656
2657 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2658   // (smulo x, 2) -> (saddo x, x)
2659   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2660     if (C2->getAPIntValue() == 2)
2661       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2662                          N->getOperand(0), N->getOperand(0));
2663
2664   return SDValue();
2665 }
2666
2667 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2668   // (umulo x, 2) -> (uaddo x, x)
2669   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2670     if (C2->getAPIntValue() == 2)
2671       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2672                          N->getOperand(0), N->getOperand(0));
2673
2674   return SDValue();
2675 }
2676
2677 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2678   SDValue N0 = N->getOperand(0);
2679   SDValue N1 = N->getOperand(1);
2680   EVT VT = N0.getValueType();
2681
2682   // fold vector ops
2683   if (VT.isVector())
2684     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2685       return FoldedVOp;
2686
2687   // fold (add c1, c2) -> c1+c2
2688   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2689   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2690   if (N0C && N1C)
2691     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2692
2693   // canonicalize constant to RHS
2694   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2695      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2696     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2697
2698   return SDValue();
2699 }
2700
2701 /// If this is a binary operator with two operands of the same opcode, try to
2702 /// simplify it.
2703 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2704   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2705   EVT VT = N0.getValueType();
2706   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2707
2708   // Bail early if none of these transforms apply.
2709   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2710
2711   // For each of OP in AND/OR/XOR:
2712   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2713   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2714   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2715   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2716   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2717   //
2718   // do not sink logical op inside of a vector extend, since it may combine
2719   // into a vsetcc.
2720   EVT Op0VT = N0.getOperand(0).getValueType();
2721   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2722        N0.getOpcode() == ISD::SIGN_EXTEND ||
2723        N0.getOpcode() == ISD::BSWAP ||
2724        // Avoid infinite looping with PromoteIntBinOp.
2725        (N0.getOpcode() == ISD::ANY_EXTEND &&
2726         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2727        (N0.getOpcode() == ISD::TRUNCATE &&
2728         (!TLI.isZExtFree(VT, Op0VT) ||
2729          !TLI.isTruncateFree(Op0VT, VT)) &&
2730         TLI.isTypeLegal(Op0VT))) &&
2731       !VT.isVector() &&
2732       Op0VT == N1.getOperand(0).getValueType() &&
2733       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2734     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2735                                  N0.getOperand(0).getValueType(),
2736                                  N0.getOperand(0), N1.getOperand(0));
2737     AddToWorklist(ORNode.getNode());
2738     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2739   }
2740
2741   // For each of OP in SHL/SRL/SRA/AND...
2742   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2743   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2744   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2745   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2746        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2747       N0.getOperand(1) == N1.getOperand(1)) {
2748     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2749                                  N0.getOperand(0).getValueType(),
2750                                  N0.getOperand(0), N1.getOperand(0));
2751     AddToWorklist(ORNode.getNode());
2752     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2753                        ORNode, N0.getOperand(1));
2754   }
2755
2756   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2757   // Only perform this optimization up until type legalization, before
2758   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2759   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2760   // we don't want to undo this promotion.
2761   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2762   // on scalars.
2763   if ((N0.getOpcode() == ISD::BITCAST ||
2764        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2765        Level <= AfterLegalizeTypes) {
2766     SDValue In0 = N0.getOperand(0);
2767     SDValue In1 = N1.getOperand(0);
2768     EVT In0Ty = In0.getValueType();
2769     EVT In1Ty = In1.getValueType();
2770     SDLoc DL(N);
2771     // If both incoming values are integers, and the original types are the
2772     // same.
2773     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2774       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2775       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2776       AddToWorklist(Op.getNode());
2777       return BC;
2778     }
2779   }
2780
2781   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2782   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2783   // If both shuffles use the same mask, and both shuffle within a single
2784   // vector, then it is worthwhile to move the swizzle after the operation.
2785   // The type-legalizer generates this pattern when loading illegal
2786   // vector types from memory. In many cases this allows additional shuffle
2787   // optimizations.
2788   // There are other cases where moving the shuffle after the xor/and/or
2789   // is profitable even if shuffles don't perform a swizzle.
2790   // If both shuffles use the same mask, and both shuffles have the same first
2791   // or second operand, then it might still be profitable to move the shuffle
2792   // after the xor/and/or operation.
2793   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2794     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2795     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2796
2797     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2798            "Inputs to shuffles are not the same type");
2799
2800     // Check that both shuffles use the same mask. The masks are known to be of
2801     // the same length because the result vector type is the same.
2802     // Check also that shuffles have only one use to avoid introducing extra
2803     // instructions.
2804     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2805         SVN0->getMask().equals(SVN1->getMask())) {
2806       SDValue ShOp = N0->getOperand(1);
2807
2808       // Don't try to fold this node if it requires introducing a
2809       // build vector of all zeros that might be illegal at this stage.
2810       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2811         if (!LegalTypes)
2812           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2813         else
2814           ShOp = SDValue();
2815       }
2816
2817       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2818       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2819       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2820       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2821         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2822                                       N0->getOperand(0), N1->getOperand(0));
2823         AddToWorklist(NewNode.getNode());
2824         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2825                                     SVN0->getMask());
2826       }
2827
2828       // Don't try to fold this node if it requires introducing a
2829       // build vector of all zeros that might be illegal at this stage.
2830       ShOp = N0->getOperand(0);
2831       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2832         if (!LegalTypes)
2833           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2834         else
2835           ShOp = SDValue();
2836       }
2837
2838       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2839       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2840       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2841       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2842         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2843                                       N0->getOperand(1), N1->getOperand(1));
2844         AddToWorklist(NewNode.getNode());
2845         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2846                                     SVN0->getMask());
2847       }
2848     }
2849   }
2850
2851   return SDValue();
2852 }
2853
2854 /// This contains all DAGCombine rules which reduce two values combined by
2855 /// an And operation to a single value. This makes them reusable in the context
2856 /// of visitSELECT(). Rules involving constants are not included as
2857 /// visitSELECT() already handles those cases.
2858 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2859                                   SDNode *LocReference) {
2860   EVT VT = N1.getValueType();
2861
2862   // fold (and x, undef) -> 0
2863   if (N0.isUndef() || N1.isUndef())
2864     return DAG.getConstant(0, SDLoc(LocReference), VT);
2865   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2866   SDValue LL, LR, RL, RR, CC0, CC1;
2867   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2868     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2869     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2870
2871     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2872         LL.getValueType().isInteger()) {
2873       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2874       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2875         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2876                                      LR.getValueType(), LL, RL);
2877         AddToWorklist(ORNode.getNode());
2878         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2879       }
2880       if (isAllOnesConstant(LR)) {
2881         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2882         if (Op1 == ISD::SETEQ) {
2883           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2884                                         LR.getValueType(), LL, RL);
2885           AddToWorklist(ANDNode.getNode());
2886           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2887         }
2888         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2889         if (Op1 == ISD::SETGT) {
2890           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2891                                        LR.getValueType(), LL, RL);
2892           AddToWorklist(ORNode.getNode());
2893           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2894         }
2895       }
2896     }
2897     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2898     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2899         Op0 == Op1 && LL.getValueType().isInteger() &&
2900       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2901                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2902       SDLoc DL(N0);
2903       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2904                                     LL, DAG.getConstant(1, DL,
2905                                                         LL.getValueType()));
2906       AddToWorklist(ADDNode.getNode());
2907       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2908                           DAG.getConstant(2, DL, LL.getValueType()),
2909                           ISD::SETUGE);
2910     }
2911     // canonicalize equivalent to ll == rl
2912     if (LL == RR && LR == RL) {
2913       Op1 = ISD::getSetCCSwappedOperands(Op1);
2914       std::swap(RL, RR);
2915     }
2916     if (LL == RL && LR == RR) {
2917       bool isInteger = LL.getValueType().isInteger();
2918       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2919       if (Result != ISD::SETCC_INVALID &&
2920           (!LegalOperations ||
2921            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2922             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2923         EVT CCVT = getSetCCResultType(LL.getValueType());
2924         if (N0.getValueType() == CCVT ||
2925             (!LegalOperations && N0.getValueType() == MVT::i1))
2926           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2927                               LL, LR, Result);
2928       }
2929     }
2930   }
2931
2932   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2933       VT.getSizeInBits() <= 64) {
2934     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2935       APInt ADDC = ADDI->getAPIntValue();
2936       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2937         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2938         // immediate for an add, but it is legal if its top c2 bits are set,
2939         // transform the ADD so the immediate doesn't need to be materialized
2940         // in a register.
2941         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2942           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2943                                              SRLI->getZExtValue());
2944           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2945             ADDC |= Mask;
2946             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2947               SDLoc DL(N0);
2948               SDValue NewAdd =
2949                 DAG.getNode(ISD::ADD, DL, VT,
2950                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2951               CombineTo(N0.getNode(), NewAdd);
2952               // Return N so it doesn't get rechecked!
2953               return SDValue(LocReference, 0);
2954             }
2955           }
2956         }
2957       }
2958     }
2959   }
2960
2961   // Reduce bit extract of low half of an integer to the narrower type.
2962   // (and (srl i64:x, K), KMask) ->
2963   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
2964   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2965     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
2966       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2967         unsigned Size = VT.getSizeInBits();
2968         const APInt &AndMask = CAnd->getAPIntValue();
2969         unsigned ShiftBits = CShift->getZExtValue();
2970         unsigned MaskBits = AndMask.countTrailingOnes();
2971         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
2972
2973         if (APIntOps::isMask(AndMask) &&
2974             // Required bits must not span the two halves of the integer and
2975             // must fit in the half size type.
2976             (ShiftBits + MaskBits <= Size / 2) &&
2977             TLI.isNarrowingProfitable(VT, HalfVT) &&
2978             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
2979             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2980             TLI.isTruncateFree(VT, HalfVT) &&
2981             TLI.isZExtFree(HalfVT, VT)) {
2982           // The isNarrowingProfitable is to avoid regressions on PPC and
2983           // AArch64 which match a few 64-bit bit insert / bit extract patterns
2984           // on downstream users of this. Those patterns could probably be
2985           // extended to handle extensions mixed in.
2986
2987           SDValue SL(N0);
2988           assert(ShiftBits != 0 && MaskBits <= Size);
2989
2990           // Extracting the highest bit of the low half.
2991           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
2992           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
2993                                       N0.getOperand(0));
2994
2995           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
2996           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
2997           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
2998           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
2999           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3000         }
3001       }
3002     }
3003   }
3004
3005   return SDValue();
3006 }
3007
3008 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3009                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3010                                    bool &NarrowLoad) {
3011   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3012
3013   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3014     return false;
3015
3016   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3017   LoadedVT = LoadN->getMemoryVT();
3018
3019   if (ExtVT == LoadedVT &&
3020       (!LegalOperations ||
3021        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3022     // ZEXTLOAD will match without needing to change the size of the value being
3023     // loaded.
3024     NarrowLoad = false;
3025     return true;
3026   }
3027
3028   // Do not change the width of a volatile load.
3029   if (LoadN->isVolatile())
3030     return false;
3031
3032   // Do not generate loads of non-round integer types since these can
3033   // be expensive (and would be wrong if the type is not byte sized).
3034   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3035     return false;
3036
3037   if (LegalOperations &&
3038       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3039     return false;
3040
3041   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3042     return false;
3043
3044   NarrowLoad = true;
3045   return true;
3046 }
3047
3048 SDValue DAGCombiner::visitAND(SDNode *N) {
3049   SDValue N0 = N->getOperand(0);
3050   SDValue N1 = N->getOperand(1);
3051   EVT VT = N1.getValueType();
3052
3053   // fold vector ops
3054   if (VT.isVector()) {
3055     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3056       return FoldedVOp;
3057
3058     // fold (and x, 0) -> 0, vector edition
3059     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3060       // do not return N0, because undef node may exist in N0
3061       return DAG.getConstant(
3062           APInt::getNullValue(
3063               N0.getValueType().getScalarType().getSizeInBits()),
3064           SDLoc(N), N0.getValueType());
3065     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3066       // do not return N1, because undef node may exist in N1
3067       return DAG.getConstant(
3068           APInt::getNullValue(
3069               N1.getValueType().getScalarType().getSizeInBits()),
3070           SDLoc(N), N1.getValueType());
3071
3072     // fold (and x, -1) -> x, vector edition
3073     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3074       return N1;
3075     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3076       return N0;
3077   }
3078
3079   // fold (and c1, c2) -> c1&c2
3080   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3081   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3082   if (N0C && N1C && !N1C->isOpaque())
3083     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3084   // canonicalize constant to RHS
3085   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3086      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3087     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3088   // fold (and x, -1) -> x
3089   if (isAllOnesConstant(N1))
3090     return N0;
3091   // if (and x, c) is known to be zero, return 0
3092   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3093   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3094                                    APInt::getAllOnesValue(BitWidth)))
3095     return DAG.getConstant(0, SDLoc(N), VT);
3096   // reassociate and
3097   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3098     return RAND;
3099   // fold (and (or x, C), D) -> D if (C & D) == D
3100   if (N1C && N0.getOpcode() == ISD::OR)
3101     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3102       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3103         return N1;
3104   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3105   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3106     SDValue N0Op0 = N0.getOperand(0);
3107     APInt Mask = ~N1C->getAPIntValue();
3108     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3109     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3110       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3111                                  N0.getValueType(), N0Op0);
3112
3113       // Replace uses of the AND with uses of the Zero extend node.
3114       CombineTo(N, Zext);
3115
3116       // We actually want to replace all uses of the any_extend with the
3117       // zero_extend, to avoid duplicating things.  This will later cause this
3118       // AND to be folded.
3119       CombineTo(N0.getNode(), Zext);
3120       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3121     }
3122   }
3123   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3124   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3125   // already be zero by virtue of the width of the base type of the load.
3126   //
3127   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3128   // more cases.
3129   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3130        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3131        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3132        N0.getOperand(0).getResNo() == 0) ||
3133       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3134     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3135                                          N0 : N0.getOperand(0) );
3136
3137     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3138     // This can be a pure constant or a vector splat, in which case we treat the
3139     // vector as a scalar and use the splat value.
3140     APInt Constant = APInt::getNullValue(1);
3141     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3142       Constant = C->getAPIntValue();
3143     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3144       APInt SplatValue, SplatUndef;
3145       unsigned SplatBitSize;
3146       bool HasAnyUndefs;
3147       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3148                                              SplatBitSize, HasAnyUndefs);
3149       if (IsSplat) {
3150         // Undef bits can contribute to a possible optimisation if set, so
3151         // set them.
3152         SplatValue |= SplatUndef;
3153
3154         // The splat value may be something like "0x00FFFFFF", which means 0 for
3155         // the first vector value and FF for the rest, repeating. We need a mask
3156         // that will apply equally to all members of the vector, so AND all the
3157         // lanes of the constant together.
3158         EVT VT = Vector->getValueType(0);
3159         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3160
3161         // If the splat value has been compressed to a bitlength lower
3162         // than the size of the vector lane, we need to re-expand it to
3163         // the lane size.
3164         if (BitWidth > SplatBitSize)
3165           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3166                SplatBitSize < BitWidth;
3167                SplatBitSize = SplatBitSize * 2)
3168             SplatValue |= SplatValue.shl(SplatBitSize);
3169
3170         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3171         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3172         if (SplatBitSize % BitWidth == 0) {
3173           Constant = APInt::getAllOnesValue(BitWidth);
3174           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3175             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3176         }
3177       }
3178     }
3179
3180     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3181     // actually legal and isn't going to get expanded, else this is a false
3182     // optimisation.
3183     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3184                                                     Load->getValueType(0),
3185                                                     Load->getMemoryVT());
3186
3187     // Resize the constant to the same size as the original memory access before
3188     // extension. If it is still the AllOnesValue then this AND is completely
3189     // unneeded.
3190     Constant =
3191       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3192
3193     bool B;
3194     switch (Load->getExtensionType()) {
3195     default: B = false; break;
3196     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3197     case ISD::ZEXTLOAD:
3198     case ISD::NON_EXTLOAD: B = true; break;
3199     }
3200
3201     if (B && Constant.isAllOnesValue()) {
3202       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3203       // preserve semantics once we get rid of the AND.
3204       SDValue NewLoad(Load, 0);
3205       if (Load->getExtensionType() == ISD::EXTLOAD) {
3206         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3207                               Load->getValueType(0), SDLoc(Load),
3208                               Load->getChain(), Load->getBasePtr(),
3209                               Load->getOffset(), Load->getMemoryVT(),
3210                               Load->getMemOperand());
3211         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3212         if (Load->getNumValues() == 3) {
3213           // PRE/POST_INC loads have 3 values.
3214           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3215                            NewLoad.getValue(2) };
3216           CombineTo(Load, To, 3, true);
3217         } else {
3218           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3219         }
3220       }
3221
3222       // Fold the AND away, taking care not to fold to the old load node if we
3223       // replaced it.
3224       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3225
3226       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3227     }
3228   }
3229
3230   // fold (and (load x), 255) -> (zextload x, i8)
3231   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3232   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3233   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3234               (N0.getOpcode() == ISD::ANY_EXTEND &&
3235                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3236     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3237     LoadSDNode *LN0 = HasAnyExt
3238       ? cast<LoadSDNode>(N0.getOperand(0))
3239       : cast<LoadSDNode>(N0);
3240     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3241         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3242       auto NarrowLoad = false;
3243       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3244       EVT ExtVT, LoadedVT;
3245       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3246                            NarrowLoad)) {
3247         if (!NarrowLoad) {
3248           SDValue NewLoad =
3249             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3250                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3251                            LN0->getMemOperand());
3252           AddToWorklist(N);
3253           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3254           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3255         } else {
3256           EVT PtrType = LN0->getOperand(1).getValueType();
3257
3258           unsigned Alignment = LN0->getAlignment();
3259           SDValue NewPtr = LN0->getBasePtr();
3260
3261           // For big endian targets, we need to add an offset to the pointer
3262           // to load the correct bytes.  For little endian systems, we merely
3263           // need to read fewer bytes from the same pointer.
3264           if (DAG.getDataLayout().isBigEndian()) {
3265             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3266             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3267             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3268             SDLoc DL(LN0);
3269             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3270                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3271             Alignment = MinAlign(Alignment, PtrOff);
3272           }
3273
3274           AddToWorklist(NewPtr.getNode());
3275
3276           SDValue Load = DAG.getExtLoad(
3277               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3278               LN0->getPointerInfo(), ExtVT, Alignment,
3279               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3280           AddToWorklist(N);
3281           CombineTo(LN0, Load, Load.getValue(1));
3282           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3283         }
3284       }
3285     }
3286   }
3287
3288   if (SDValue Combined = visitANDLike(N0, N1, N))
3289     return Combined;
3290
3291   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3292   if (N0.getOpcode() == N1.getOpcode())
3293     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3294       return Tmp;
3295
3296   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3297   // fold (and (sra)) -> (and (srl)) when possible.
3298   if (!VT.isVector() &&
3299       SimplifyDemandedBits(SDValue(N, 0)))
3300     return SDValue(N, 0);
3301
3302   // fold (zext_inreg (extload x)) -> (zextload x)
3303   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3304     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3305     EVT MemVT = LN0->getMemoryVT();
3306     // If we zero all the possible extended bits, then we can turn this into
3307     // a zextload if we are running before legalize or the operation is legal.
3308     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3309     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3310                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3311         ((!LegalOperations && !LN0->isVolatile()) ||
3312          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3313       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3314                                        LN0->getChain(), LN0->getBasePtr(),
3315                                        MemVT, LN0->getMemOperand());
3316       AddToWorklist(N);
3317       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3318       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3319     }
3320   }
3321   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3322   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3323       N0.hasOneUse()) {
3324     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3325     EVT MemVT = LN0->getMemoryVT();
3326     // If we zero all the possible extended bits, then we can turn this into
3327     // a zextload if we are running before legalize or the operation is legal.
3328     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3329     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3330                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3331         ((!LegalOperations && !LN0->isVolatile()) ||
3332          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3333       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3334                                        LN0->getChain(), LN0->getBasePtr(),
3335                                        MemVT, LN0->getMemOperand());
3336       AddToWorklist(N);
3337       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3338       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3339     }
3340   }
3341   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3342   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3343     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3344                                            N0.getOperand(1), false))
3345       return BSwap;
3346   }
3347
3348   return SDValue();
3349 }
3350
3351 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3352 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3353                                         bool DemandHighBits) {
3354   if (!LegalOperations)
3355     return SDValue();
3356
3357   EVT VT = N->getValueType(0);
3358   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3359     return SDValue();
3360   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3361     return SDValue();
3362
3363   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3364   bool LookPassAnd0 = false;
3365   bool LookPassAnd1 = false;
3366   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3367       std::swap(N0, N1);
3368   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3369       std::swap(N0, N1);
3370   if (N0.getOpcode() == ISD::AND) {
3371     if (!N0.getNode()->hasOneUse())
3372       return SDValue();
3373     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3374     if (!N01C || N01C->getZExtValue() != 0xFF00)
3375       return SDValue();
3376     N0 = N0.getOperand(0);
3377     LookPassAnd0 = true;
3378   }
3379
3380   if (N1.getOpcode() == ISD::AND) {
3381     if (!N1.getNode()->hasOneUse())
3382       return SDValue();
3383     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3384     if (!N11C || N11C->getZExtValue() != 0xFF)
3385       return SDValue();
3386     N1 = N1.getOperand(0);
3387     LookPassAnd1 = true;
3388   }
3389
3390   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3391     std::swap(N0, N1);
3392   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3393     return SDValue();
3394   if (!N0.getNode()->hasOneUse() ||
3395       !N1.getNode()->hasOneUse())
3396     return SDValue();
3397
3398   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3399   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3400   if (!N01C || !N11C)
3401     return SDValue();
3402   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3403     return SDValue();
3404
3405   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3406   SDValue N00 = N0->getOperand(0);
3407   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3408     if (!N00.getNode()->hasOneUse())
3409       return SDValue();
3410     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3411     if (!N001C || N001C->getZExtValue() != 0xFF)
3412       return SDValue();
3413     N00 = N00.getOperand(0);
3414     LookPassAnd0 = true;
3415   }
3416
3417   SDValue N10 = N1->getOperand(0);
3418   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3419     if (!N10.getNode()->hasOneUse())
3420       return SDValue();
3421     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3422     if (!N101C || N101C->getZExtValue() != 0xFF00)
3423       return SDValue();
3424     N10 = N10.getOperand(0);
3425     LookPassAnd1 = true;
3426   }
3427
3428   if (N00 != N10)
3429     return SDValue();
3430
3431   // Make sure everything beyond the low halfword gets set to zero since the SRL
3432   // 16 will clear the top bits.
3433   unsigned OpSizeInBits = VT.getSizeInBits();
3434   if (DemandHighBits && OpSizeInBits > 16) {
3435     // If the left-shift isn't masked out then the only way this is a bswap is
3436     // if all bits beyond the low 8 are 0. In that case the entire pattern
3437     // reduces to a left shift anyway: leave it for other parts of the combiner.
3438     if (!LookPassAnd0)
3439       return SDValue();
3440
3441     // However, if the right shift isn't masked out then it might be because
3442     // it's not needed. See if we can spot that too.
3443     if (!LookPassAnd1 &&
3444         !DAG.MaskedValueIsZero(
3445             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3446       return SDValue();
3447   }
3448
3449   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3450   if (OpSizeInBits > 16) {
3451     SDLoc DL(N);
3452     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3453                       DAG.getConstant(OpSizeInBits - 16, DL,
3454                                       getShiftAmountTy(VT)));
3455   }
3456   return Res;
3457 }
3458
3459 /// Return true if the specified node is an element that makes up a 32-bit
3460 /// packed halfword byteswap.
3461 /// ((x & 0x000000ff) << 8) |
3462 /// ((x & 0x0000ff00) >> 8) |
3463 /// ((x & 0x00ff0000) << 8) |
3464 /// ((x & 0xff000000) >> 8)
3465 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3466   if (!N.getNode()->hasOneUse())
3467     return false;
3468
3469   unsigned Opc = N.getOpcode();
3470   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3471     return false;
3472
3473   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3474   if (!N1C)
3475     return false;
3476
3477   unsigned Num;
3478   switch (N1C->getZExtValue()) {
3479   default:
3480     return false;
3481   case 0xFF:       Num = 0; break;
3482   case 0xFF00:     Num = 1; break;
3483   case 0xFF0000:   Num = 2; break;
3484   case 0xFF000000: Num = 3; break;
3485   }
3486
3487   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3488   SDValue N0 = N.getOperand(0);
3489   if (Opc == ISD::AND) {
3490     if (Num == 0 || Num == 2) {
3491       // (x >> 8) & 0xff
3492       // (x >> 8) & 0xff0000
3493       if (N0.getOpcode() != ISD::SRL)
3494         return false;
3495       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3496       if (!C || C->getZExtValue() != 8)
3497         return false;
3498     } else {
3499       // (x << 8) & 0xff00
3500       // (x << 8) & 0xff000000
3501       if (N0.getOpcode() != ISD::SHL)
3502         return false;
3503       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3504       if (!C || C->getZExtValue() != 8)
3505         return false;
3506     }
3507   } else if (Opc == ISD::SHL) {
3508     // (x & 0xff) << 8
3509     // (x & 0xff0000) << 8
3510     if (Num != 0 && Num != 2)
3511       return false;
3512     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3513     if (!C || C->getZExtValue() != 8)
3514       return false;
3515   } else { // Opc == ISD::SRL
3516     // (x & 0xff00) >> 8
3517     // (x & 0xff000000) >> 8
3518     if (Num != 1 && Num != 3)
3519       return false;
3520     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3521     if (!C || C->getZExtValue() != 8)
3522       return false;
3523   }
3524
3525   if (Parts[Num])
3526     return false;
3527
3528   Parts[Num] = N0.getOperand(0).getNode();
3529   return true;
3530 }
3531
3532 /// Match a 32-bit packed halfword bswap. That is
3533 /// ((x & 0x000000ff) << 8) |
3534 /// ((x & 0x0000ff00) >> 8) |
3535 /// ((x & 0x00ff0000) << 8) |
3536 /// ((x & 0xff000000) >> 8)
3537 /// => (rotl (bswap x), 16)
3538 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3539   if (!LegalOperations)
3540     return SDValue();
3541
3542   EVT VT = N->getValueType(0);
3543   if (VT != MVT::i32)
3544     return SDValue();
3545   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3546     return SDValue();
3547
3548   // Look for either
3549   // (or (or (and), (and)), (or (and), (and)))
3550   // (or (or (or (and), (and)), (and)), (and))
3551   if (N0.getOpcode() != ISD::OR)
3552     return SDValue();
3553   SDValue N00 = N0.getOperand(0);
3554   SDValue N01 = N0.getOperand(1);
3555   SDNode *Parts[4] = {};
3556
3557   if (N1.getOpcode() == ISD::OR &&
3558       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3559     // (or (or (and), (and)), (or (and), (and)))
3560     SDValue N000 = N00.getOperand(0);
3561     if (!isBSwapHWordElement(N000, Parts))
3562       return SDValue();
3563
3564     SDValue N001 = N00.getOperand(1);
3565     if (!isBSwapHWordElement(N001, Parts))
3566       return SDValue();
3567     SDValue N010 = N01.getOperand(0);
3568     if (!isBSwapHWordElement(N010, Parts))
3569       return SDValue();
3570     SDValue N011 = N01.getOperand(1);
3571     if (!isBSwapHWordElement(N011, Parts))
3572       return SDValue();
3573   } else {
3574     // (or (or (or (and), (and)), (and)), (and))
3575     if (!isBSwapHWordElement(N1, Parts))
3576       return SDValue();
3577     if (!isBSwapHWordElement(N01, Parts))
3578       return SDValue();
3579     if (N00.getOpcode() != ISD::OR)
3580       return SDValue();
3581     SDValue N000 = N00.getOperand(0);
3582     if (!isBSwapHWordElement(N000, Parts))
3583       return SDValue();
3584     SDValue N001 = N00.getOperand(1);
3585     if (!isBSwapHWordElement(N001, Parts))
3586       return SDValue();
3587   }
3588
3589   // Make sure the parts are all coming from the same node.
3590   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3591     return SDValue();
3592
3593   SDLoc DL(N);
3594   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3595                               SDValue(Parts[0], 0));
3596
3597   // Result of the bswap should be rotated by 16. If it's not legal, then
3598   // do  (x << 16) | (x >> 16).
3599   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3600   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3601     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3602   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3603     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3604   return DAG.getNode(ISD::OR, DL, VT,
3605                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3606                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3607 }
3608
3609 /// This contains all DAGCombine rules which reduce two values combined by
3610 /// an Or operation to a single value \see visitANDLike().
3611 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3612   EVT VT = N1.getValueType();
3613   // fold (or x, undef) -> -1
3614   if (!LegalOperations &&
3615       (N0.isUndef() || N1.isUndef())) {
3616     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3617     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3618                            SDLoc(LocReference), VT);
3619   }
3620   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3621   SDValue LL, LR, RL, RR, CC0, CC1;
3622   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3623     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3624     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3625
3626     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3627       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3628       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3629       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3630         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3631                                      LR.getValueType(), LL, RL);
3632         AddToWorklist(ORNode.getNode());
3633         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3634       }
3635       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3636       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3637       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3638         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3639                                       LR.getValueType(), LL, RL);
3640         AddToWorklist(ANDNode.getNode());
3641         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3642       }
3643     }
3644     // canonicalize equivalent to ll == rl
3645     if (LL == RR && LR == RL) {
3646       Op1 = ISD::getSetCCSwappedOperands(Op1);
3647       std::swap(RL, RR);
3648     }
3649     if (LL == RL && LR == RR) {
3650       bool isInteger = LL.getValueType().isInteger();
3651       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3652       if (Result != ISD::SETCC_INVALID &&
3653           (!LegalOperations ||
3654            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3655             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3656         EVT CCVT = getSetCCResultType(LL.getValueType());
3657         if (N0.getValueType() == CCVT ||
3658             (!LegalOperations && N0.getValueType() == MVT::i1))
3659           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3660                               LL, LR, Result);
3661       }
3662     }
3663   }
3664
3665   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3666   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3667       // Don't increase # computations.
3668       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3669     // We can only do this xform if we know that bits from X that are set in C2
3670     // but not in C1 are already zero.  Likewise for Y.
3671     if (const ConstantSDNode *N0O1C =
3672         getAsNonOpaqueConstant(N0.getOperand(1))) {
3673       if (const ConstantSDNode *N1O1C =
3674           getAsNonOpaqueConstant(N1.getOperand(1))) {
3675         // We can only do this xform if we know that bits from X that are set in
3676         // C2 but not in C1 are already zero.  Likewise for Y.
3677         const APInt &LHSMask = N0O1C->getAPIntValue();
3678         const APInt &RHSMask = N1O1C->getAPIntValue();
3679
3680         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3681             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3682           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3683                                   N0.getOperand(0), N1.getOperand(0));
3684           SDLoc DL(LocReference);
3685           return DAG.getNode(ISD::AND, DL, VT, X,
3686                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3687         }
3688       }
3689     }
3690   }
3691
3692   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3693   if (N0.getOpcode() == ISD::AND &&
3694       N1.getOpcode() == ISD::AND &&
3695       N0.getOperand(0) == N1.getOperand(0) &&
3696       // Don't increase # computations.
3697       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3698     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3699                             N0.getOperand(1), N1.getOperand(1));
3700     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3701   }
3702
3703   return SDValue();
3704 }
3705
3706 SDValue DAGCombiner::visitOR(SDNode *N) {
3707   SDValue N0 = N->getOperand(0);
3708   SDValue N1 = N->getOperand(1);
3709   EVT VT = N1.getValueType();
3710
3711   // fold vector ops
3712   if (VT.isVector()) {
3713     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3714       return FoldedVOp;
3715
3716     // fold (or x, 0) -> x, vector edition
3717     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3718       return N1;
3719     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3720       return N0;
3721
3722     // fold (or x, -1) -> -1, vector edition
3723     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3724       // do not return N0, because undef node may exist in N0
3725       return DAG.getConstant(
3726           APInt::getAllOnesValue(
3727               N0.getValueType().getScalarType().getSizeInBits()),
3728           SDLoc(N), N0.getValueType());
3729     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3730       // do not return N1, because undef node may exist in N1
3731       return DAG.getConstant(
3732           APInt::getAllOnesValue(
3733               N1.getValueType().getScalarType().getSizeInBits()),
3734           SDLoc(N), N1.getValueType());
3735
3736     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3737     // Do this only if the resulting shuffle is legal.
3738     if (isa<ShuffleVectorSDNode>(N0) &&
3739         isa<ShuffleVectorSDNode>(N1) &&
3740         // Avoid folding a node with illegal type.
3741         TLI.isTypeLegal(VT)) {
3742       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3743       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3744       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3745       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3746       // Ensure both shuffles have a zero input.
3747       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3748         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3749         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3750         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3751         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3752         bool CanFold = true;
3753         int NumElts = VT.getVectorNumElements();
3754         SmallVector<int, 4> Mask(NumElts);
3755
3756         for (int i = 0; i != NumElts; ++i) {
3757           int M0 = SV0->getMaskElt(i);
3758           int M1 = SV1->getMaskElt(i);
3759
3760           // Determine if either index is pointing to a zero vector.
3761           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3762           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3763
3764           // If one element is zero and the otherside is undef, keep undef.
3765           // This also handles the case that both are undef.
3766           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3767             Mask[i] = -1;
3768             continue;
3769           }
3770
3771           // Make sure only one of the elements is zero.
3772           if (M0Zero == M1Zero) {
3773             CanFold = false;
3774             break;
3775           }
3776
3777           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3778
3779           // We have a zero and non-zero element. If the non-zero came from
3780           // SV0 make the index a LHS index. If it came from SV1, make it
3781           // a RHS index. We need to mod by NumElts because we don't care
3782           // which operand it came from in the original shuffles.
3783           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3784         }
3785
3786         if (CanFold) {
3787           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3788           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3789
3790           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3791           if (!LegalMask) {
3792             std::swap(NewLHS, NewRHS);
3793             ShuffleVectorSDNode::commuteMask(Mask);
3794             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3795           }
3796
3797           if (LegalMask)
3798             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3799         }
3800       }
3801     }
3802   }
3803
3804   // fold (or c1, c2) -> c1|c2
3805   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3806   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3807   if (N0C && N1C && !N1C->isOpaque())
3808     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3809   // canonicalize constant to RHS
3810   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3811      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3812     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3813   // fold (or x, 0) -> x
3814   if (isNullConstant(N1))
3815     return N0;
3816   // fold (or x, -1) -> -1
3817   if (isAllOnesConstant(N1))
3818     return N1;
3819   // fold (or x, c) -> c iff (x & ~c) == 0
3820   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3821     return N1;
3822
3823   if (SDValue Combined = visitORLike(N0, N1, N))
3824     return Combined;
3825
3826   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3827   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3828     return BSwap;
3829   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3830     return BSwap;
3831
3832   // reassociate or
3833   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3834     return ROR;
3835   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3836   // iff (c1 & c2) == 0.
3837   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3838              isa<ConstantSDNode>(N0.getOperand(1))) {
3839     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3840     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3841       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3842                                                    N1C, C1))
3843         return DAG.getNode(
3844             ISD::AND, SDLoc(N), VT,
3845             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3846       return SDValue();
3847     }
3848   }
3849   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3850   if (N0.getOpcode() == N1.getOpcode())
3851     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3852       return Tmp;
3853
3854   // See if this is some rotate idiom.
3855   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3856     return SDValue(Rot, 0);
3857
3858   // Simplify the operands using demanded-bits information.
3859   if (!VT.isVector() &&
3860       SimplifyDemandedBits(SDValue(N, 0)))
3861     return SDValue(N, 0);
3862
3863   return SDValue();
3864 }
3865
3866 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3867 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3868   if (Op.getOpcode() == ISD::AND) {
3869     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3870       Mask = Op.getOperand(1);
3871       Op = Op.getOperand(0);
3872     } else {
3873       return false;
3874     }
3875   }
3876
3877   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3878     Shift = Op;
3879     return true;
3880   }
3881
3882   return false;
3883 }
3884
3885 // Return true if we can prove that, whenever Neg and Pos are both in the
3886 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3887 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3888 //
3889 //     (or (shift1 X, Neg), (shift2 X, Pos))
3890 //
3891 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3892 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3893 // to consider shift amounts with defined behavior.
3894 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3895   // If EltSize is a power of 2 then:
3896   //
3897   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3898   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3899   //
3900   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3901   // for the stronger condition:
3902   //
3903   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3904   //
3905   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3906   // we can just replace Neg with Neg' for the rest of the function.
3907   //
3908   // In other cases we check for the even stronger condition:
3909   //
3910   //     Neg == EltSize - Pos                                    [B]
3911   //
3912   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3913   // behavior if Pos == 0 (and consequently Neg == EltSize).
3914   //
3915   // We could actually use [A] whenever EltSize is a power of 2, but the
3916   // only extra cases that it would match are those uninteresting ones
3917   // where Neg and Pos are never in range at the same time.  E.g. for
3918   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3919   // as well as (sub 32, Pos), but:
3920   //
3921   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3922   //
3923   // always invokes undefined behavior for 32-bit X.
3924   //
3925   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3926   unsigned MaskLoBits = 0;
3927   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3928     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3929       if (NegC->getAPIntValue() == EltSize - 1) {
3930         Neg = Neg.getOperand(0);
3931         MaskLoBits = Log2_64(EltSize);
3932       }
3933     }
3934   }
3935
3936   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3937   if (Neg.getOpcode() != ISD::SUB)
3938     return false;
3939   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3940   if (!NegC)
3941     return false;
3942   SDValue NegOp1 = Neg.getOperand(1);
3943
3944   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3945   // Pos'.  The truncation is redundant for the purpose of the equality.
3946   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3947     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3948       if (PosC->getAPIntValue() == EltSize - 1)
3949         Pos = Pos.getOperand(0);
3950
3951   // The condition we need is now:
3952   //
3953   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3954   //
3955   // If NegOp1 == Pos then we need:
3956   //
3957   //              EltSize & Mask == NegC & Mask
3958   //
3959   // (because "x & Mask" is a truncation and distributes through subtraction).
3960   APInt Width;
3961   if (Pos == NegOp1)
3962     Width = NegC->getAPIntValue();
3963
3964   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3965   // Then the condition we want to prove becomes:
3966   //
3967   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3968   //
3969   // which, again because "x & Mask" is a truncation, becomes:
3970   //
3971   //                NegC & Mask == (EltSize - PosC) & Mask
3972   //             EltSize & Mask == (NegC + PosC) & Mask
3973   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3974     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3975       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3976     else
3977       return false;
3978   } else
3979     return false;
3980
3981   // Now we just need to check that EltSize & Mask == Width & Mask.
3982   if (MaskLoBits)
3983     // EltSize & Mask is 0 since Mask is EltSize - 1.
3984     return Width.getLoBits(MaskLoBits) == 0;
3985   return Width == EltSize;
3986 }
3987
3988 // A subroutine of MatchRotate used once we have found an OR of two opposite
3989 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3990 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3991 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3992 // Neg with outer conversions stripped away.
3993 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3994                                        SDValue Neg, SDValue InnerPos,
3995                                        SDValue InnerNeg, unsigned PosOpcode,
3996                                        unsigned NegOpcode, const SDLoc &DL) {
3997   // fold (or (shl x, (*ext y)),
3998   //          (srl x, (*ext (sub 32, y)))) ->
3999   //   (rotl x, y) or (rotr x, (sub 32, y))
4000   //
4001   // fold (or (shl x, (*ext (sub 32, y))),
4002   //          (srl x, (*ext y))) ->
4003   //   (rotr x, y) or (rotl x, (sub 32, y))
4004   EVT VT = Shifted.getValueType();
4005   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4006     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4007     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4008                        HasPos ? Pos : Neg).getNode();
4009   }
4010
4011   return nullptr;
4012 }
4013
4014 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4015 // idioms for rotate, and if the target supports rotation instructions, generate
4016 // a rot[lr].
4017 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4018   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4019   EVT VT = LHS.getValueType();
4020   if (!TLI.isTypeLegal(VT)) return nullptr;
4021
4022   // The target must have at least one rotate flavor.
4023   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4024   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4025   if (!HasROTL && !HasROTR) return nullptr;
4026
4027   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4028   SDValue LHSShift;   // The shift.
4029   SDValue LHSMask;    // AND value if any.
4030   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4031     return nullptr; // Not part of a rotate.
4032
4033   SDValue RHSShift;   // The shift.
4034   SDValue RHSMask;    // AND value if any.
4035   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4036     return nullptr; // Not part of a rotate.
4037
4038   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4039     return nullptr;   // Not shifting the same value.
4040
4041   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4042     return nullptr;   // Shifts must disagree.
4043
4044   // Canonicalize shl to left side in a shl/srl pair.
4045   if (RHSShift.getOpcode() == ISD::SHL) {
4046     std::swap(LHS, RHS);
4047     std::swap(LHSShift, RHSShift);
4048     std::swap(LHSMask, RHSMask);
4049   }
4050
4051   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4052   SDValue LHSShiftArg = LHSShift.getOperand(0);
4053   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4054   SDValue RHSShiftArg = RHSShift.getOperand(0);
4055   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4056
4057   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4058   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4059   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4060     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4061     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4062     if ((LShVal + RShVal) != EltSizeInBits)
4063       return nullptr;
4064
4065     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4066                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4067
4068     // If there is an AND of either shifted operand, apply it to the result.
4069     if (LHSMask.getNode() || RHSMask.getNode()) {
4070       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4071       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4072
4073       if (LHSMask.getNode()) {
4074         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4075         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4076                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4077                                        DAG.getConstant(RHSBits, DL, VT)));
4078       }
4079       if (RHSMask.getNode()) {
4080         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4081         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4082                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4083                                        DAG.getConstant(LHSBits, DL, VT)));
4084       }
4085
4086       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4087     }
4088
4089     return Rot.getNode();
4090   }
4091
4092   // If there is a mask here, and we have a variable shift, we can't be sure
4093   // that we're masking out the right stuff.
4094   if (LHSMask.getNode() || RHSMask.getNode())
4095     return nullptr;
4096
4097   // If the shift amount is sign/zext/any-extended just peel it off.
4098   SDValue LExtOp0 = LHSShiftAmt;
4099   SDValue RExtOp0 = RHSShiftAmt;
4100   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4101        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4102        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4103        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4104       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4105        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4106        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4107        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4108     LExtOp0 = LHSShiftAmt.getOperand(0);
4109     RExtOp0 = RHSShiftAmt.getOperand(0);
4110   }
4111
4112   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4113                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4114   if (TryL)
4115     return TryL;
4116
4117   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4118                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4119   if (TryR)
4120     return TryR;
4121
4122   return nullptr;
4123 }
4124
4125 SDValue DAGCombiner::visitXOR(SDNode *N) {
4126   SDValue N0 = N->getOperand(0);
4127   SDValue N1 = N->getOperand(1);
4128   EVT VT = N0.getValueType();
4129
4130   // fold vector ops
4131   if (VT.isVector()) {
4132     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4133       return FoldedVOp;
4134
4135     // fold (xor x, 0) -> x, vector edition
4136     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4137       return N1;
4138     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4139       return N0;
4140   }
4141
4142   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4143   if (N0.isUndef() && N1.isUndef())
4144     return DAG.getConstant(0, SDLoc(N), VT);
4145   // fold (xor x, undef) -> undef
4146   if (N0.isUndef())
4147     return N0;
4148   if (N1.isUndef())
4149     return N1;
4150   // fold (xor c1, c2) -> c1^c2
4151   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4152   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4153   if (N0C && N1C)
4154     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4155   // canonicalize constant to RHS
4156   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4157      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4158     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4159   // fold (xor x, 0) -> x
4160   if (isNullConstant(N1))
4161     return N0;
4162   // reassociate xor
4163   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4164     return RXOR;
4165
4166   // fold !(x cc y) -> (x !cc y)
4167   SDValue LHS, RHS, CC;
4168   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4169     bool isInt = LHS.getValueType().isInteger();
4170     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4171                                                isInt);
4172
4173     if (!LegalOperations ||
4174         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4175       switch (N0.getOpcode()) {
4176       default:
4177         llvm_unreachable("Unhandled SetCC Equivalent!");
4178       case ISD::SETCC:
4179         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4180       case ISD::SELECT_CC:
4181         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4182                                N0.getOperand(3), NotCC);
4183       }
4184     }
4185   }
4186
4187   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4188   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4189       N0.getNode()->hasOneUse() &&
4190       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4191     SDValue V = N0.getOperand(0);
4192     SDLoc DL(N0);
4193     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4194                     DAG.getConstant(1, DL, V.getValueType()));
4195     AddToWorklist(V.getNode());
4196     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4197   }
4198
4199   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4200   if (isOneConstant(N1) && VT == MVT::i1 &&
4201       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4202     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4203     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4204       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4205       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4206       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4207       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4208       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4209     }
4210   }
4211   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4212   if (isAllOnesConstant(N1) &&
4213       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4214     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4215     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4216       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4217       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4218       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4219       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4220       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4221     }
4222   }
4223   // fold (xor (and x, y), y) -> (and (not x), y)
4224   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4225       N0->getOperand(1) == N1) {
4226     SDValue X = N0->getOperand(0);
4227     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4228     AddToWorklist(NotX.getNode());
4229     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4230   }
4231   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4232   if (N1C && N0.getOpcode() == ISD::XOR) {
4233     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4234       SDLoc DL(N);
4235       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4236                          DAG.getConstant(N1C->getAPIntValue() ^
4237                                          N00C->getAPIntValue(), DL, VT));
4238     }
4239     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4240       SDLoc DL(N);
4241       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4242                          DAG.getConstant(N1C->getAPIntValue() ^
4243                                          N01C->getAPIntValue(), DL, VT));
4244     }
4245   }
4246   // fold (xor x, x) -> 0
4247   if (N0 == N1)
4248     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4249
4250   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4251   // Here is a concrete example of this equivalence:
4252   // i16   x ==  14
4253   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4254   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4255   //
4256   // =>
4257   //
4258   // i16     ~1      == 0b1111111111111110
4259   // i16 rol(~1, 14) == 0b1011111111111111
4260   //
4261   // Some additional tips to help conceptualize this transform:
4262   // - Try to see the operation as placing a single zero in a value of all ones.
4263   // - There exists no value for x which would allow the result to contain zero.
4264   // - Values of x larger than the bitwidth are undefined and do not require a
4265   //   consistent result.
4266   // - Pushing the zero left requires shifting one bits in from the right.
4267   // A rotate left of ~1 is a nice way of achieving the desired result.
4268   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4269       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4270     SDLoc DL(N);
4271     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4272                        N0.getOperand(1));
4273   }
4274
4275   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4276   if (N0.getOpcode() == N1.getOpcode())
4277     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4278       return Tmp;
4279
4280   // Simplify the expression using non-local knowledge.
4281   if (!VT.isVector() &&
4282       SimplifyDemandedBits(SDValue(N, 0)))
4283     return SDValue(N, 0);
4284
4285   return SDValue();
4286 }
4287
4288 /// Handle transforms common to the three shifts, when the shift amount is a
4289 /// constant.
4290 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4291   SDNode *LHS = N->getOperand(0).getNode();
4292   if (!LHS->hasOneUse()) return SDValue();
4293
4294   // We want to pull some binops through shifts, so that we have (and (shift))
4295   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4296   // thing happens with address calculations, so it's important to canonicalize
4297   // it.
4298   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4299
4300   switch (LHS->getOpcode()) {
4301   default: return SDValue();
4302   case ISD::OR:
4303   case ISD::XOR:
4304     HighBitSet = false; // We can only transform sra if the high bit is clear.
4305     break;
4306   case ISD::AND:
4307     HighBitSet = true;  // We can only transform sra if the high bit is set.
4308     break;
4309   case ISD::ADD:
4310     if (N->getOpcode() != ISD::SHL)
4311       return SDValue(); // only shl(add) not sr[al](add).
4312     HighBitSet = false; // We can only transform sra if the high bit is clear.
4313     break;
4314   }
4315
4316   // We require the RHS of the binop to be a constant and not opaque as well.
4317   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4318   if (!BinOpCst) return SDValue();
4319
4320   // FIXME: disable this unless the input to the binop is a shift by a constant.
4321   // If it is not a shift, it pessimizes some common cases like:
4322   //
4323   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4324   //    int bar(int *X, int i) { return X[i & 255]; }
4325   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4326   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4327        BinOpLHSVal->getOpcode() != ISD::SRA &&
4328        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4329       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4330     return SDValue();
4331
4332   EVT VT = N->getValueType(0);
4333
4334   // If this is a signed shift right, and the high bit is modified by the
4335   // logical operation, do not perform the transformation. The highBitSet
4336   // boolean indicates the value of the high bit of the constant which would
4337   // cause it to be modified for this operation.
4338   if (N->getOpcode() == ISD::SRA) {
4339     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4340     if (BinOpRHSSignSet != HighBitSet)
4341       return SDValue();
4342   }
4343
4344   if (!TLI.isDesirableToCommuteWithShift(LHS))
4345     return SDValue();
4346
4347   // Fold the constants, shifting the binop RHS by the shift amount.
4348   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4349                                N->getValueType(0),
4350                                LHS->getOperand(1), N->getOperand(1));
4351   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4352
4353   // Create the new shift.
4354   SDValue NewShift = DAG.getNode(N->getOpcode(),
4355                                  SDLoc(LHS->getOperand(0)),
4356                                  VT, LHS->getOperand(0), N->getOperand(1));
4357
4358   // Create the new binop.
4359   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4360 }
4361
4362 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4363   assert(N->getOpcode() == ISD::TRUNCATE);
4364   assert(N->getOperand(0).getOpcode() == ISD::AND);
4365
4366   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4367   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4368     SDValue N01 = N->getOperand(0).getOperand(1);
4369
4370     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4371       if (!N01C->isOpaque()) {
4372         EVT TruncVT = N->getValueType(0);
4373         SDValue N00 = N->getOperand(0).getOperand(0);
4374         APInt TruncC = N01C->getAPIntValue();
4375         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4376         SDLoc DL(N);
4377
4378         return DAG.getNode(ISD::AND, DL, TruncVT,
4379                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4380                            DAG.getConstant(TruncC, DL, TruncVT));
4381       }
4382     }
4383   }
4384
4385   return SDValue();
4386 }
4387
4388 SDValue DAGCombiner::visitRotate(SDNode *N) {
4389   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4390   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4391       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4392     if (SDValue NewOp1 =
4393             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4394       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4395                          N->getOperand(0), NewOp1);
4396   }
4397   return SDValue();
4398 }
4399
4400 SDValue DAGCombiner::visitSHL(SDNode *N) {
4401   SDValue N0 = N->getOperand(0);
4402   SDValue N1 = N->getOperand(1);
4403   EVT VT = N0.getValueType();
4404   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4405
4406   // fold vector ops
4407   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4408   if (VT.isVector()) {
4409     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4410       return FoldedVOp;
4411
4412     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4413     // If setcc produces all-one true value then:
4414     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4415     if (N1CV && N1CV->isConstant()) {
4416       if (N0.getOpcode() == ISD::AND) {
4417         SDValue N00 = N0->getOperand(0);
4418         SDValue N01 = N0->getOperand(1);
4419         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4420
4421         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4422             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4423                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4424           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4425                                                      N01CV, N1CV))
4426             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4427         }
4428       } else {
4429         N1C = isConstOrConstSplat(N1);
4430       }
4431     }
4432   }
4433
4434   // fold (shl c1, c2) -> c1<<c2
4435   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4436   if (N0C && N1C && !N1C->isOpaque())
4437     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4438   // fold (shl 0, x) -> 0
4439   if (isNullConstant(N0))
4440     return N0;
4441   // fold (shl x, c >= size(x)) -> undef
4442   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4443     return DAG.getUNDEF(VT);
4444   // fold (shl x, 0) -> x
4445   if (N1C && N1C->isNullValue())
4446     return N0;
4447   // fold (shl undef, x) -> 0
4448   if (N0.isUndef())
4449     return DAG.getConstant(0, SDLoc(N), VT);
4450   // if (shl x, c) is known to be zero, return 0
4451   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4452                             APInt::getAllOnesValue(OpSizeInBits)))
4453     return DAG.getConstant(0, SDLoc(N), VT);
4454   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4455   if (N1.getOpcode() == ISD::TRUNCATE &&
4456       N1.getOperand(0).getOpcode() == ISD::AND) {
4457     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4458       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4459   }
4460
4461   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4462     return SDValue(N, 0);
4463
4464   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4465   if (N1C && N0.getOpcode() == ISD::SHL) {
4466     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4467       uint64_t c1 = N0C1->getZExtValue();
4468       uint64_t c2 = N1C->getZExtValue();
4469       SDLoc DL(N);
4470       if (c1 + c2 >= OpSizeInBits)
4471         return DAG.getConstant(0, DL, VT);
4472       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4473                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4474     }
4475   }
4476
4477   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4478   // For this to be valid, the second form must not preserve any of the bits
4479   // that are shifted out by the inner shift in the first form.  This means
4480   // the outer shift size must be >= the number of bits added by the ext.
4481   // As a corollary, we don't care what kind of ext it is.
4482   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4483               N0.getOpcode() == ISD::ANY_EXTEND ||
4484               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4485       N0.getOperand(0).getOpcode() == ISD::SHL) {
4486     SDValue N0Op0 = N0.getOperand(0);
4487     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4488       uint64_t c1 = N0Op0C1->getZExtValue();
4489       uint64_t c2 = N1C->getZExtValue();
4490       EVT InnerShiftVT = N0Op0.getValueType();
4491       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4492       if (c2 >= OpSizeInBits - InnerShiftSize) {
4493         SDLoc DL(N0);
4494         if (c1 + c2 >= OpSizeInBits)
4495           return DAG.getConstant(0, DL, VT);
4496         return DAG.getNode(ISD::SHL, DL, VT,
4497                            DAG.getNode(N0.getOpcode(), DL, VT,
4498                                        N0Op0->getOperand(0)),
4499                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4500       }
4501     }
4502   }
4503
4504   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4505   // Only fold this if the inner zext has no other uses to avoid increasing
4506   // the total number of instructions.
4507   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4508       N0.getOperand(0).getOpcode() == ISD::SRL) {
4509     SDValue N0Op0 = N0.getOperand(0);
4510     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4511       uint64_t c1 = N0Op0C1->getZExtValue();
4512       if (c1 < VT.getScalarSizeInBits()) {
4513         uint64_t c2 = N1C->getZExtValue();
4514         if (c1 == c2) {
4515           SDValue NewOp0 = N0.getOperand(0);
4516           EVT CountVT = NewOp0.getOperand(1).getValueType();
4517           SDLoc DL(N);
4518           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4519                                        NewOp0,
4520                                        DAG.getConstant(c2, DL, CountVT));
4521           AddToWorklist(NewSHL.getNode());
4522           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4523         }
4524       }
4525     }
4526   }
4527
4528   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4529   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4530   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4531       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4532     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4533       uint64_t C1 = N0C1->getZExtValue();
4534       uint64_t C2 = N1C->getZExtValue();
4535       SDLoc DL(N);
4536       if (C1 <= C2)
4537         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4538                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4539       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4540                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4541     }
4542   }
4543
4544   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4545   //                               (and (srl x, (sub c1, c2), MASK)
4546   // Only fold this if the inner shift has no other uses -- if it does, folding
4547   // this will increase the total number of instructions.
4548   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4549     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4550       uint64_t c1 = N0C1->getZExtValue();
4551       if (c1 < OpSizeInBits) {
4552         uint64_t c2 = N1C->getZExtValue();
4553         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4554         SDValue Shift;
4555         if (c2 > c1) {
4556           Mask = Mask.shl(c2 - c1);
4557           SDLoc DL(N);
4558           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4559                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4560         } else {
4561           Mask = Mask.lshr(c1 - c2);
4562           SDLoc DL(N);
4563           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4564                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4565         }
4566         SDLoc DL(N0);
4567         return DAG.getNode(ISD::AND, DL, VT, Shift,
4568                            DAG.getConstant(Mask, DL, VT));
4569       }
4570     }
4571   }
4572   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4573   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4574     unsigned BitSize = VT.getScalarSizeInBits();
4575     SDLoc DL(N);
4576     SDValue HiBitsMask =
4577       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4578                                             BitSize - N1C->getZExtValue()),
4579                       DL, VT);
4580     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4581                        HiBitsMask);
4582   }
4583
4584   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4585   // Variant of version done on multiply, except mul by a power of 2 is turned
4586   // into a shift.
4587   APInt Val;
4588   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4589       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4590        ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4591     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4592     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4593     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4594   }
4595
4596   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4597   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4598     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4599       if (SDValue Folded =
4600               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4601         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4602     }
4603   }
4604
4605   if (N1C && !N1C->isOpaque())
4606     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4607       return NewSHL;
4608
4609   return SDValue();
4610 }
4611
4612 SDValue DAGCombiner::visitSRA(SDNode *N) {
4613   SDValue N0 = N->getOperand(0);
4614   SDValue N1 = N->getOperand(1);
4615   EVT VT = N0.getValueType();
4616   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4617
4618   // fold vector ops
4619   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4620   if (VT.isVector()) {
4621     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4622       return FoldedVOp;
4623
4624     N1C = isConstOrConstSplat(N1);
4625   }
4626
4627   // fold (sra c1, c2) -> (sra c1, c2)
4628   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4629   if (N0C && N1C && !N1C->isOpaque())
4630     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4631   // fold (sra 0, x) -> 0
4632   if (isNullConstant(N0))
4633     return N0;
4634   // fold (sra -1, x) -> -1
4635   if (isAllOnesConstant(N0))
4636     return N0;
4637   // fold (sra x, (setge c, size(x))) -> undef
4638   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4639     return DAG.getUNDEF(VT);
4640   // fold (sra x, 0) -> x
4641   if (N1C && N1C->isNullValue())
4642     return N0;
4643   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4644   // sext_inreg.
4645   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4646     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4647     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4648     if (VT.isVector())
4649       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4650                                ExtVT, VT.getVectorNumElements());
4651     if ((!LegalOperations ||
4652          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4653       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4654                          N0.getOperand(0), DAG.getValueType(ExtVT));
4655   }
4656
4657   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4658   if (N1C && N0.getOpcode() == ISD::SRA) {
4659     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4660       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4661       if (Sum >= OpSizeInBits)
4662         Sum = OpSizeInBits - 1;
4663       SDLoc DL(N);
4664       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4665                          DAG.getConstant(Sum, DL, N1.getValueType()));
4666     }
4667   }
4668
4669   // fold (sra (shl X, m), (sub result_size, n))
4670   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4671   // result_size - n != m.
4672   // If truncate is free for the target sext(shl) is likely to result in better
4673   // code.
4674   if (N0.getOpcode() == ISD::SHL && N1C) {
4675     // Get the two constanst of the shifts, CN0 = m, CN = n.
4676     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4677     if (N01C) {
4678       LLVMContext &Ctx = *DAG.getContext();
4679       // Determine what the truncate's result bitsize and type would be.
4680       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4681
4682       if (VT.isVector())
4683         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4684
4685       // Determine the residual right-shift amount.
4686       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4687
4688       // If the shift is not a no-op (in which case this should be just a sign
4689       // extend already), the truncated to type is legal, sign_extend is legal
4690       // on that type, and the truncate to that type is both legal and free,
4691       // perform the transform.
4692       if ((ShiftAmt > 0) &&
4693           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4694           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4695           TLI.isTruncateFree(VT, TruncVT)) {
4696
4697         SDLoc DL(N);
4698         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4699             getShiftAmountTy(N0.getOperand(0).getValueType()));
4700         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4701                                     N0.getOperand(0), Amt);
4702         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4703                                     Shift);
4704         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4705                            N->getValueType(0), Trunc);
4706       }
4707     }
4708   }
4709
4710   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4711   if (N1.getOpcode() == ISD::TRUNCATE &&
4712       N1.getOperand(0).getOpcode() == ISD::AND) {
4713     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4714       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4715   }
4716
4717   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4718   //      if c1 is equal to the number of bits the trunc removes
4719   if (N0.getOpcode() == ISD::TRUNCATE &&
4720       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4721        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4722       N0.getOperand(0).hasOneUse() &&
4723       N0.getOperand(0).getOperand(1).hasOneUse() &&
4724       N1C) {
4725     SDValue N0Op0 = N0.getOperand(0);
4726     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4727       unsigned LargeShiftVal = LargeShift->getZExtValue();
4728       EVT LargeVT = N0Op0.getValueType();
4729
4730       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4731         SDLoc DL(N);
4732         SDValue Amt =
4733           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4734                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4735         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4736                                   N0Op0.getOperand(0), Amt);
4737         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4738       }
4739     }
4740   }
4741
4742   // Simplify, based on bits shifted out of the LHS.
4743   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4744     return SDValue(N, 0);
4745
4746
4747   // If the sign bit is known to be zero, switch this to a SRL.
4748   if (DAG.SignBitIsZero(N0))
4749     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4750
4751   if (N1C && !N1C->isOpaque())
4752     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4753       return NewSRA;
4754
4755   return SDValue();
4756 }
4757
4758 SDValue DAGCombiner::visitSRL(SDNode *N) {
4759   SDValue N0 = N->getOperand(0);
4760   SDValue N1 = N->getOperand(1);
4761   EVT VT = N0.getValueType();
4762   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4763
4764   // fold vector ops
4765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4766   if (VT.isVector()) {
4767     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4768       return FoldedVOp;
4769
4770     N1C = isConstOrConstSplat(N1);
4771   }
4772
4773   // fold (srl c1, c2) -> c1 >>u c2
4774   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4775   if (N0C && N1C && !N1C->isOpaque())
4776     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4777   // fold (srl 0, x) -> 0
4778   if (isNullConstant(N0))
4779     return N0;
4780   // fold (srl x, c >= size(x)) -> undef
4781   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4782     return DAG.getUNDEF(VT);
4783   // fold (srl x, 0) -> x
4784   if (N1C && N1C->isNullValue())
4785     return N0;
4786   // if (srl x, c) is known to be zero, return 0
4787   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4788                                    APInt::getAllOnesValue(OpSizeInBits)))
4789     return DAG.getConstant(0, SDLoc(N), VT);
4790
4791   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4792   if (N1C && N0.getOpcode() == ISD::SRL) {
4793     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4794       uint64_t c1 = N01C->getZExtValue();
4795       uint64_t c2 = N1C->getZExtValue();
4796       SDLoc DL(N);
4797       if (c1 + c2 >= OpSizeInBits)
4798         return DAG.getConstant(0, DL, VT);
4799       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4800                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4801     }
4802   }
4803
4804   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4805   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4806       N0.getOperand(0).getOpcode() == ISD::SRL &&
4807       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4808     uint64_t c1 =
4809       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4810     uint64_t c2 = N1C->getZExtValue();
4811     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4812     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4813     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4814     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4815     if (c1 + OpSizeInBits == InnerShiftSize) {
4816       SDLoc DL(N0);
4817       if (c1 + c2 >= InnerShiftSize)
4818         return DAG.getConstant(0, DL, VT);
4819       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4820                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4821                                      N0.getOperand(0)->getOperand(0),
4822                                      DAG.getConstant(c1 + c2, DL,
4823                                                      ShiftCountVT)));
4824     }
4825   }
4826
4827   // fold (srl (shl x, c), c) -> (and x, cst2)
4828   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4829     unsigned BitSize = N0.getScalarValueSizeInBits();
4830     if (BitSize <= 64) {
4831       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4832       SDLoc DL(N);
4833       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4834                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4835     }
4836   }
4837
4838   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4839   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4840     // Shifting in all undef bits?
4841     EVT SmallVT = N0.getOperand(0).getValueType();
4842     unsigned BitSize = SmallVT.getScalarSizeInBits();
4843     if (N1C->getZExtValue() >= BitSize)
4844       return DAG.getUNDEF(VT);
4845
4846     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4847       uint64_t ShiftAmt = N1C->getZExtValue();
4848       SDLoc DL0(N0);
4849       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4850                                        N0.getOperand(0),
4851                           DAG.getConstant(ShiftAmt, DL0,
4852                                           getShiftAmountTy(SmallVT)));
4853       AddToWorklist(SmallShift.getNode());
4854       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4855       SDLoc DL(N);
4856       return DAG.getNode(ISD::AND, DL, VT,
4857                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4858                          DAG.getConstant(Mask, DL, VT));
4859     }
4860   }
4861
4862   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4863   // bit, which is unmodified by sra.
4864   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4865     if (N0.getOpcode() == ISD::SRA)
4866       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4867   }
4868
4869   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4870   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4871       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4872     APInt KnownZero, KnownOne;
4873     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4874
4875     // If any of the input bits are KnownOne, then the input couldn't be all
4876     // zeros, thus the result of the srl will always be zero.
4877     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4878
4879     // If all of the bits input the to ctlz node are known to be zero, then
4880     // the result of the ctlz is "32" and the result of the shift is one.
4881     APInt UnknownBits = ~KnownZero;
4882     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4883
4884     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4885     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4886       // Okay, we know that only that the single bit specified by UnknownBits
4887       // could be set on input to the CTLZ node. If this bit is set, the SRL
4888       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4889       // to an SRL/XOR pair, which is likely to simplify more.
4890       unsigned ShAmt = UnknownBits.countTrailingZeros();
4891       SDValue Op = N0.getOperand(0);
4892
4893       if (ShAmt) {
4894         SDLoc DL(N0);
4895         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4896                   DAG.getConstant(ShAmt, DL,
4897                                   getShiftAmountTy(Op.getValueType())));
4898         AddToWorklist(Op.getNode());
4899       }
4900
4901       SDLoc DL(N);
4902       return DAG.getNode(ISD::XOR, DL, VT,
4903                          Op, DAG.getConstant(1, DL, VT));
4904     }
4905   }
4906
4907   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4908   if (N1.getOpcode() == ISD::TRUNCATE &&
4909       N1.getOperand(0).getOpcode() == ISD::AND) {
4910     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4911       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4912   }
4913
4914   // fold operands of srl based on knowledge that the low bits are not
4915   // demanded.
4916   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4917     return SDValue(N, 0);
4918
4919   if (N1C && !N1C->isOpaque())
4920     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4921       return NewSRL;
4922
4923   // Attempt to convert a srl of a load into a narrower zero-extending load.
4924   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4925     return NarrowLoad;
4926
4927   // Here is a common situation. We want to optimize:
4928   //
4929   //   %a = ...
4930   //   %b = and i32 %a, 2
4931   //   %c = srl i32 %b, 1
4932   //   brcond i32 %c ...
4933   //
4934   // into
4935   //
4936   //   %a = ...
4937   //   %b = and %a, 2
4938   //   %c = setcc eq %b, 0
4939   //   brcond %c ...
4940   //
4941   // However when after the source operand of SRL is optimized into AND, the SRL
4942   // itself may not be optimized further. Look for it and add the BRCOND into
4943   // the worklist.
4944   if (N->hasOneUse()) {
4945     SDNode *Use = *N->use_begin();
4946     if (Use->getOpcode() == ISD::BRCOND)
4947       AddToWorklist(Use);
4948     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4949       // Also look pass the truncate.
4950       Use = *Use->use_begin();
4951       if (Use->getOpcode() == ISD::BRCOND)
4952         AddToWorklist(Use);
4953     }
4954   }
4955
4956   return SDValue();
4957 }
4958
4959 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4960   SDValue N0 = N->getOperand(0);
4961   EVT VT = N->getValueType(0);
4962
4963   // fold (bswap c1) -> c2
4964   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4965     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4966   // fold (bswap (bswap x)) -> x
4967   if (N0.getOpcode() == ISD::BSWAP)
4968     return N0->getOperand(0);
4969   return SDValue();
4970 }
4971
4972 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
4973   SDValue N0 = N->getOperand(0);
4974
4975   // fold (bitreverse (bitreverse x)) -> x
4976   if (N0.getOpcode() == ISD::BITREVERSE)
4977     return N0.getOperand(0);
4978   return SDValue();
4979 }
4980
4981 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4982   SDValue N0 = N->getOperand(0);
4983   EVT VT = N->getValueType(0);
4984
4985   // fold (ctlz c1) -> c2
4986   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4987     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4988   return SDValue();
4989 }
4990
4991 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4992   SDValue N0 = N->getOperand(0);
4993   EVT VT = N->getValueType(0);
4994
4995   // fold (ctlz_zero_undef c1) -> c2
4996   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4997     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4998   return SDValue();
4999 }
5000
5001 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5002   SDValue N0 = N->getOperand(0);
5003   EVT VT = N->getValueType(0);
5004
5005   // fold (cttz c1) -> c2
5006   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5007     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5008   return SDValue();
5009 }
5010
5011 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5012   SDValue N0 = N->getOperand(0);
5013   EVT VT = N->getValueType(0);
5014
5015   // fold (cttz_zero_undef c1) -> c2
5016   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5017     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5018   return SDValue();
5019 }
5020
5021 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5022   SDValue N0 = N->getOperand(0);
5023   EVT VT = N->getValueType(0);
5024
5025   // fold (ctpop c1) -> c2
5026   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5027     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5028   return SDValue();
5029 }
5030
5031
5032 /// \brief Generate Min/Max node
5033 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5034                                    SDValue RHS, SDValue True, SDValue False,
5035                                    ISD::CondCode CC, const TargetLowering &TLI,
5036                                    SelectionDAG &DAG) {
5037   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5038     return SDValue();
5039
5040   switch (CC) {
5041   case ISD::SETOLT:
5042   case ISD::SETOLE:
5043   case ISD::SETLT:
5044   case ISD::SETLE:
5045   case ISD::SETULT:
5046   case ISD::SETULE: {
5047     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5048     if (TLI.isOperationLegal(Opcode, VT))
5049       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5050     return SDValue();
5051   }
5052   case ISD::SETOGT:
5053   case ISD::SETOGE:
5054   case ISD::SETGT:
5055   case ISD::SETGE:
5056   case ISD::SETUGT:
5057   case ISD::SETUGE: {
5058     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5059     if (TLI.isOperationLegal(Opcode, VT))
5060       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5061     return SDValue();
5062   }
5063   default:
5064     return SDValue();
5065   }
5066 }
5067
5068 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5069   SDValue N0 = N->getOperand(0);
5070   SDValue N1 = N->getOperand(1);
5071   SDValue N2 = N->getOperand(2);
5072   EVT VT = N->getValueType(0);
5073   EVT VT0 = N0.getValueType();
5074
5075   // fold (select C, X, X) -> X
5076   if (N1 == N2)
5077     return N1;
5078   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5079     // fold (select true, X, Y) -> X
5080     // fold (select false, X, Y) -> Y
5081     return !N0C->isNullValue() ? N1 : N2;
5082   }
5083   // fold (select C, 1, X) -> (or C, X)
5084   if (VT == MVT::i1 && isOneConstant(N1))
5085     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5086   // fold (select C, 0, 1) -> (xor C, 1)
5087   // We can't do this reliably if integer based booleans have different contents
5088   // to floating point based booleans. This is because we can't tell whether we
5089   // have an integer-based boolean or a floating-point-based boolean unless we
5090   // can find the SETCC that produced it and inspect its operands. This is
5091   // fairly easy if C is the SETCC node, but it can potentially be
5092   // undiscoverable (or not reasonably discoverable). For example, it could be
5093   // in another basic block or it could require searching a complicated
5094   // expression.
5095   if (VT.isInteger() &&
5096       (VT0 == MVT::i1 || (VT0.isInteger() &&
5097                           TLI.getBooleanContents(false, false) ==
5098                               TLI.getBooleanContents(false, true) &&
5099                           TLI.getBooleanContents(false, false) ==
5100                               TargetLowering::ZeroOrOneBooleanContent)) &&
5101       isNullConstant(N1) && isOneConstant(N2)) {
5102     SDValue XORNode;
5103     if (VT == VT0) {
5104       SDLoc DL(N);
5105       return DAG.getNode(ISD::XOR, DL, VT0,
5106                          N0, DAG.getConstant(1, DL, VT0));
5107     }
5108     SDLoc DL0(N0);
5109     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5110                           N0, DAG.getConstant(1, DL0, VT0));
5111     AddToWorklist(XORNode.getNode());
5112     if (VT.bitsGT(VT0))
5113       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5114     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5115   }
5116   // fold (select C, 0, X) -> (and (not C), X)
5117   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5118     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5119     AddToWorklist(NOTNode.getNode());
5120     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5121   }
5122   // fold (select C, X, 1) -> (or (not C), X)
5123   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5124     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5125     AddToWorklist(NOTNode.getNode());
5126     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5127   }
5128   // fold (select C, X, 0) -> (and C, X)
5129   if (VT == MVT::i1 && isNullConstant(N2))
5130     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5131   // fold (select X, X, Y) -> (or X, Y)
5132   // fold (select X, 1, Y) -> (or X, Y)
5133   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5134     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5135   // fold (select X, Y, X) -> (and X, Y)
5136   // fold (select X, Y, 0) -> (and X, Y)
5137   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5138     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5139
5140   // If we can fold this based on the true/false value, do so.
5141   if (SimplifySelectOps(N, N1, N2))
5142     return SDValue(N, 0);  // Don't revisit N.
5143
5144   if (VT0 == MVT::i1) {
5145     // The code in this block deals with the following 2 equivalences:
5146     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5147     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5148     // The target can specify its prefered form with the
5149     // shouldNormalizeToSelectSequence() callback. However we always transform
5150     // to the right anyway if we find the inner select exists in the DAG anyway
5151     // and we always transform to the left side if we know that we can further
5152     // optimize the combination of the conditions.
5153     bool normalizeToSequence
5154       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5155     // select (and Cond0, Cond1), X, Y
5156     //   -> select Cond0, (select Cond1, X, Y), Y
5157     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5158       SDValue Cond0 = N0->getOperand(0);
5159       SDValue Cond1 = N0->getOperand(1);
5160       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5161                                         N1.getValueType(), Cond1, N1, N2);
5162       if (normalizeToSequence || !InnerSelect.use_empty())
5163         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5164                            InnerSelect, N2);
5165     }
5166     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5167     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5168       SDValue Cond0 = N0->getOperand(0);
5169       SDValue Cond1 = N0->getOperand(1);
5170       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5171                                         N1.getValueType(), Cond1, N1, N2);
5172       if (normalizeToSequence || !InnerSelect.use_empty())
5173         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5174                            InnerSelect);
5175     }
5176
5177     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5178     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5179       SDValue N1_0 = N1->getOperand(0);
5180       SDValue N1_1 = N1->getOperand(1);
5181       SDValue N1_2 = N1->getOperand(2);
5182       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5183         // Create the actual and node if we can generate good code for it.
5184         if (!normalizeToSequence) {
5185           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5186                                     N0, N1_0);
5187           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5188                              N1_1, N2);
5189         }
5190         // Otherwise see if we can optimize the "and" to a better pattern.
5191         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5192           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5193                              N1_1, N2);
5194       }
5195     }
5196     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5197     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5198       SDValue N2_0 = N2->getOperand(0);
5199       SDValue N2_1 = N2->getOperand(1);
5200       SDValue N2_2 = N2->getOperand(2);
5201       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5202         // Create the actual or node if we can generate good code for it.
5203         if (!normalizeToSequence) {
5204           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5205                                    N0, N2_0);
5206           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5207                              N1, N2_2);
5208         }
5209         // Otherwise see if we can optimize to a better pattern.
5210         if (SDValue Combined = visitORLike(N0, N2_0, N))
5211           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5212                              N1, N2_2);
5213       }
5214     }
5215   }
5216
5217   // fold selects based on a setcc into other things, such as min/max/abs
5218   if (N0.getOpcode() == ISD::SETCC) {
5219     // select x, y (fcmp lt x, y) -> fminnum x, y
5220     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5221     //
5222     // This is OK if we don't care about what happens if either operand is a
5223     // NaN.
5224     //
5225
5226     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5227     // no signed zeros as well as no nans.
5228     const TargetOptions &Options = DAG.getTarget().Options;
5229     if (Options.UnsafeFPMath &&
5230         VT.isFloatingPoint() && N0.hasOneUse() &&
5231         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5232       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5233
5234       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5235                                                 N0.getOperand(1), N1, N2, CC,
5236                                                 TLI, DAG))
5237         return FMinMax;
5238     }
5239
5240     if ((!LegalOperations &&
5241          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5242         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5243       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5244                          N0.getOperand(0), N0.getOperand(1),
5245                          N1, N2, N0.getOperand(2));
5246     return SimplifySelect(SDLoc(N), N0, N1, N2);
5247   }
5248
5249   return SDValue();
5250 }
5251
5252 static
5253 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5254   SDLoc DL(N);
5255   EVT LoVT, HiVT;
5256   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5257
5258   // Split the inputs.
5259   SDValue Lo, Hi, LL, LH, RL, RH;
5260   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5261   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5262
5263   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5264   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5265
5266   return std::make_pair(Lo, Hi);
5267 }
5268
5269 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5270 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5271 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5272   SDLoc dl(N);
5273   SDValue Cond = N->getOperand(0);
5274   SDValue LHS = N->getOperand(1);
5275   SDValue RHS = N->getOperand(2);
5276   EVT VT = N->getValueType(0);
5277   int NumElems = VT.getVectorNumElements();
5278   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5279          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5280          Cond.getOpcode() == ISD::BUILD_VECTOR);
5281
5282   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5283   // binary ones here.
5284   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5285     return SDValue();
5286
5287   // We're sure we have an even number of elements due to the
5288   // concat_vectors we have as arguments to vselect.
5289   // Skip BV elements until we find one that's not an UNDEF
5290   // After we find an UNDEF element, keep looping until we get to half the
5291   // length of the BV and see if all the non-undef nodes are the same.
5292   ConstantSDNode *BottomHalf = nullptr;
5293   for (int i = 0; i < NumElems / 2; ++i) {
5294     if (Cond->getOperand(i)->isUndef())
5295       continue;
5296
5297     if (BottomHalf == nullptr)
5298       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5299     else if (Cond->getOperand(i).getNode() != BottomHalf)
5300       return SDValue();
5301   }
5302
5303   // Do the same for the second half of the BuildVector
5304   ConstantSDNode *TopHalf = nullptr;
5305   for (int i = NumElems / 2; i < NumElems; ++i) {
5306     if (Cond->getOperand(i)->isUndef())
5307       continue;
5308
5309     if (TopHalf == nullptr)
5310       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5311     else if (Cond->getOperand(i).getNode() != TopHalf)
5312       return SDValue();
5313   }
5314
5315   assert(TopHalf && BottomHalf &&
5316          "One half of the selector was all UNDEFs and the other was all the "
5317          "same value. This should have been addressed before this function.");
5318   return DAG.getNode(
5319       ISD::CONCAT_VECTORS, dl, VT,
5320       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5321       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5322 }
5323
5324 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5325
5326   if (Level >= AfterLegalizeTypes)
5327     return SDValue();
5328
5329   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5330   SDValue Mask = MSC->getMask();
5331   SDValue Data  = MSC->getValue();
5332   SDLoc DL(N);
5333
5334   // If the MSCATTER data type requires splitting and the mask is provided by a
5335   // SETCC, then split both nodes and its operands before legalization. This
5336   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5337   // and enables future optimizations (e.g. min/max pattern matching on X86).
5338   if (Mask.getOpcode() != ISD::SETCC)
5339     return SDValue();
5340
5341   // Check if any splitting is required.
5342   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5343       TargetLowering::TypeSplitVector)
5344     return SDValue();
5345   SDValue MaskLo, MaskHi, Lo, Hi;
5346   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5347
5348   EVT LoVT, HiVT;
5349   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5350
5351   SDValue Chain = MSC->getChain();
5352
5353   EVT MemoryVT = MSC->getMemoryVT();
5354   unsigned Alignment = MSC->getOriginalAlignment();
5355
5356   EVT LoMemVT, HiMemVT;
5357   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5358
5359   SDValue DataLo, DataHi;
5360   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5361
5362   SDValue BasePtr = MSC->getBasePtr();
5363   SDValue IndexLo, IndexHi;
5364   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5365
5366   MachineMemOperand *MMO = DAG.getMachineFunction().
5367     getMachineMemOperand(MSC->getPointerInfo(),
5368                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5369                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5370
5371   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5372   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5373                             DL, OpsLo, MMO);
5374
5375   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5376   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5377                             DL, OpsHi, MMO);
5378
5379   AddToWorklist(Lo.getNode());
5380   AddToWorklist(Hi.getNode());
5381
5382   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5383 }
5384
5385 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5386
5387   if (Level >= AfterLegalizeTypes)
5388     return SDValue();
5389
5390   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5391   SDValue Mask = MST->getMask();
5392   SDValue Data  = MST->getValue();
5393   SDLoc DL(N);
5394
5395   // If the MSTORE data type requires splitting and the mask is provided by a
5396   // SETCC, then split both nodes and its operands before legalization. This
5397   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5398   // and enables future optimizations (e.g. min/max pattern matching on X86).
5399   if (Mask.getOpcode() == ISD::SETCC) {
5400
5401     // Check if any splitting is required.
5402     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5403         TargetLowering::TypeSplitVector)
5404       return SDValue();
5405
5406     SDValue MaskLo, MaskHi, Lo, Hi;
5407     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5408
5409     EVT LoVT, HiVT;
5410     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5411
5412     SDValue Chain = MST->getChain();
5413     SDValue Ptr   = MST->getBasePtr();
5414
5415     EVT MemoryVT = MST->getMemoryVT();
5416     unsigned Alignment = MST->getOriginalAlignment();
5417
5418     // if Alignment is equal to the vector size,
5419     // take the half of it for the second part
5420     unsigned SecondHalfAlignment =
5421       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5422          Alignment/2 : Alignment;
5423
5424     EVT LoMemVT, HiMemVT;
5425     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5426
5427     SDValue DataLo, DataHi;
5428     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5429
5430     MachineMemOperand *MMO = DAG.getMachineFunction().
5431       getMachineMemOperand(MST->getPointerInfo(),
5432                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5433                            Alignment, MST->getAAInfo(), MST->getRanges());
5434
5435     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5436                             MST->isTruncatingStore());
5437
5438     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5439     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5440                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5441
5442     MMO = DAG.getMachineFunction().
5443       getMachineMemOperand(MST->getPointerInfo(),
5444                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5445                            SecondHalfAlignment, MST->getAAInfo(),
5446                            MST->getRanges());
5447
5448     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5449                             MST->isTruncatingStore());
5450
5451     AddToWorklist(Lo.getNode());
5452     AddToWorklist(Hi.getNode());
5453
5454     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5455   }
5456   return SDValue();
5457 }
5458
5459 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5460
5461   if (Level >= AfterLegalizeTypes)
5462     return SDValue();
5463
5464   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5465   SDValue Mask = MGT->getMask();
5466   SDLoc DL(N);
5467
5468   // If the MGATHER result requires splitting and the mask is provided by a
5469   // SETCC, then split both nodes and its operands before legalization. This
5470   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5471   // and enables future optimizations (e.g. min/max pattern matching on X86).
5472
5473   if (Mask.getOpcode() != ISD::SETCC)
5474     return SDValue();
5475
5476   EVT VT = N->getValueType(0);
5477
5478   // Check if any splitting is required.
5479   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5480       TargetLowering::TypeSplitVector)
5481     return SDValue();
5482
5483   SDValue MaskLo, MaskHi, Lo, Hi;
5484   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5485
5486   SDValue Src0 = MGT->getValue();
5487   SDValue Src0Lo, Src0Hi;
5488   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5489
5490   EVT LoVT, HiVT;
5491   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5492
5493   SDValue Chain = MGT->getChain();
5494   EVT MemoryVT = MGT->getMemoryVT();
5495   unsigned Alignment = MGT->getOriginalAlignment();
5496
5497   EVT LoMemVT, HiMemVT;
5498   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5499
5500   SDValue BasePtr = MGT->getBasePtr();
5501   SDValue Index = MGT->getIndex();
5502   SDValue IndexLo, IndexHi;
5503   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5504
5505   MachineMemOperand *MMO = DAG.getMachineFunction().
5506     getMachineMemOperand(MGT->getPointerInfo(),
5507                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5508                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5509
5510   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5511   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5512                             MMO);
5513
5514   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5515   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5516                             MMO);
5517
5518   AddToWorklist(Lo.getNode());
5519   AddToWorklist(Hi.getNode());
5520
5521   // Build a factor node to remember that this load is independent of the
5522   // other one.
5523   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5524                       Hi.getValue(1));
5525
5526   // Legalized the chain result - switch anything that used the old chain to
5527   // use the new one.
5528   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5529
5530   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5531
5532   SDValue RetOps[] = { GatherRes, Chain };
5533   return DAG.getMergeValues(RetOps, DL);
5534 }
5535
5536 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5537
5538   if (Level >= AfterLegalizeTypes)
5539     return SDValue();
5540
5541   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5542   SDValue Mask = MLD->getMask();
5543   SDLoc DL(N);
5544
5545   // If the MLOAD result requires splitting and the mask is provided by a
5546   // SETCC, then split both nodes and its operands before legalization. This
5547   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5548   // and enables future optimizations (e.g. min/max pattern matching on X86).
5549
5550   if (Mask.getOpcode() == ISD::SETCC) {
5551     EVT VT = N->getValueType(0);
5552
5553     // Check if any splitting is required.
5554     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5555         TargetLowering::TypeSplitVector)
5556       return SDValue();
5557
5558     SDValue MaskLo, MaskHi, Lo, Hi;
5559     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5560
5561     SDValue Src0 = MLD->getSrc0();
5562     SDValue Src0Lo, Src0Hi;
5563     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5564
5565     EVT LoVT, HiVT;
5566     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5567
5568     SDValue Chain = MLD->getChain();
5569     SDValue Ptr   = MLD->getBasePtr();
5570     EVT MemoryVT = MLD->getMemoryVT();
5571     unsigned Alignment = MLD->getOriginalAlignment();
5572
5573     // if Alignment is equal to the vector size,
5574     // take the half of it for the second part
5575     unsigned SecondHalfAlignment =
5576       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5577          Alignment/2 : Alignment;
5578
5579     EVT LoMemVT, HiMemVT;
5580     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5581
5582     MachineMemOperand *MMO = DAG.getMachineFunction().
5583     getMachineMemOperand(MLD->getPointerInfo(),
5584                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5585                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5586
5587     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5588                            ISD::NON_EXTLOAD);
5589
5590     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5591     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5592                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5593
5594     MMO = DAG.getMachineFunction().
5595     getMachineMemOperand(MLD->getPointerInfo(),
5596                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5597                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5598
5599     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5600                            ISD::NON_EXTLOAD);
5601
5602     AddToWorklist(Lo.getNode());
5603     AddToWorklist(Hi.getNode());
5604
5605     // Build a factor node to remember that this load is independent of the
5606     // other one.
5607     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5608                         Hi.getValue(1));
5609
5610     // Legalized the chain result - switch anything that used the old chain to
5611     // use the new one.
5612     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5613
5614     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5615
5616     SDValue RetOps[] = { LoadRes, Chain };
5617     return DAG.getMergeValues(RetOps, DL);
5618   }
5619   return SDValue();
5620 }
5621
5622 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5623   SDValue N0 = N->getOperand(0);
5624   SDValue N1 = N->getOperand(1);
5625   SDValue N2 = N->getOperand(2);
5626   SDLoc DL(N);
5627
5628   // Canonicalize integer abs.
5629   // vselect (setg[te] X,  0),  X, -X ->
5630   // vselect (setgt    X, -1),  X, -X ->
5631   // vselect (setl[te] X,  0), -X,  X ->
5632   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5633   if (N0.getOpcode() == ISD::SETCC) {
5634     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5635     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5636     bool isAbs = false;
5637     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5638
5639     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5640          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5641         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5642       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5643     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5644              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5645       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5646
5647     if (isAbs) {
5648       EVT VT = LHS.getValueType();
5649       SDValue Shift = DAG.getNode(
5650           ISD::SRA, DL, VT, LHS,
5651           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5652       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5653       AddToWorklist(Shift.getNode());
5654       AddToWorklist(Add.getNode());
5655       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5656     }
5657   }
5658
5659   if (SimplifySelectOps(N, N1, N2))
5660     return SDValue(N, 0);  // Don't revisit N.
5661
5662   // If the VSELECT result requires splitting and the mask is provided by a
5663   // SETCC, then split both nodes and its operands before legalization. This
5664   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5665   // and enables future optimizations (e.g. min/max pattern matching on X86).
5666   if (N0.getOpcode() == ISD::SETCC) {
5667     EVT VT = N->getValueType(0);
5668
5669     // Check if any splitting is required.
5670     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5671         TargetLowering::TypeSplitVector)
5672       return SDValue();
5673
5674     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5675     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5676     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5677     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5678
5679     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5680     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5681
5682     // Add the new VSELECT nodes to the work list in case they need to be split
5683     // again.
5684     AddToWorklist(Lo.getNode());
5685     AddToWorklist(Hi.getNode());
5686
5687     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5688   }
5689
5690   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5691   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5692     return N1;
5693   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5694   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5695     return N2;
5696
5697   // The ConvertSelectToConcatVector function is assuming both the above
5698   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5699   // and addressed.
5700   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5701       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5702       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5703     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5704       return CV;
5705   }
5706
5707   return SDValue();
5708 }
5709
5710 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5711   SDValue N0 = N->getOperand(0);
5712   SDValue N1 = N->getOperand(1);
5713   SDValue N2 = N->getOperand(2);
5714   SDValue N3 = N->getOperand(3);
5715   SDValue N4 = N->getOperand(4);
5716   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5717
5718   // fold select_cc lhs, rhs, x, x, cc -> x
5719   if (N2 == N3)
5720     return N2;
5721
5722   // Determine if the condition we're dealing with is constant
5723   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5724                                   CC, SDLoc(N), false)) {
5725     AddToWorklist(SCC.getNode());
5726
5727     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5728       if (!SCCC->isNullValue())
5729         return N2;    // cond always true -> true val
5730       else
5731         return N3;    // cond always false -> false val
5732     } else if (SCC->isUndef()) {
5733       // When the condition is UNDEF, just return the first operand. This is
5734       // coherent the DAG creation, no setcc node is created in this case
5735       return N2;
5736     } else if (SCC.getOpcode() == ISD::SETCC) {
5737       // Fold to a simpler select_cc
5738       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5739                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5740                          SCC.getOperand(2));
5741     }
5742   }
5743
5744   // If we can fold this based on the true/false value, do so.
5745   if (SimplifySelectOps(N, N2, N3))
5746     return SDValue(N, 0);  // Don't revisit N.
5747
5748   // fold select_cc into other things, such as min/max/abs
5749   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5750 }
5751
5752 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5753   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5754                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5755                        SDLoc(N));
5756 }
5757
5758 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5759   SDValue LHS = N->getOperand(0);
5760   SDValue RHS = N->getOperand(1);
5761   SDValue Carry = N->getOperand(2);
5762   SDValue Cond = N->getOperand(3);
5763
5764   // If Carry is false, fold to a regular SETCC.
5765   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5766     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5767
5768   return SDValue();
5769 }
5770
5771 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5772 /// a build_vector of constants.
5773 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5774 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5775 /// Vector extends are not folded if operations are legal; this is to
5776 /// avoid introducing illegal build_vector dag nodes.
5777 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5778                                          SelectionDAG &DAG, bool LegalTypes,
5779                                          bool LegalOperations) {
5780   unsigned Opcode = N->getOpcode();
5781   SDValue N0 = N->getOperand(0);
5782   EVT VT = N->getValueType(0);
5783
5784   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5785          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5786          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5787          && "Expected EXTEND dag node in input!");
5788
5789   // fold (sext c1) -> c1
5790   // fold (zext c1) -> c1
5791   // fold (aext c1) -> c1
5792   if (isa<ConstantSDNode>(N0))
5793     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5794
5795   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5796   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5797   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5798   EVT SVT = VT.getScalarType();
5799   if (!(VT.isVector() &&
5800       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5801       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5802     return nullptr;
5803
5804   // We can fold this node into a build_vector.
5805   unsigned VTBits = SVT.getSizeInBits();
5806   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5807   SmallVector<SDValue, 8> Elts;
5808   unsigned NumElts = VT.getVectorNumElements();
5809   SDLoc DL(N);
5810
5811   for (unsigned i=0; i != NumElts; ++i) {
5812     SDValue Op = N0->getOperand(i);
5813     if (Op->isUndef()) {
5814       Elts.push_back(DAG.getUNDEF(SVT));
5815       continue;
5816     }
5817
5818     SDLoc DL(Op);
5819     // Get the constant value and if needed trunc it to the size of the type.
5820     // Nodes like build_vector might have constants wider than the scalar type.
5821     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5822     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5823       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5824     else
5825       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5826   }
5827
5828   return DAG.getBuildVector(VT, DL, Elts).getNode();
5829 }
5830
5831 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5832 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5833 // transformation. Returns true if extension are possible and the above
5834 // mentioned transformation is profitable.
5835 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5836                                     unsigned ExtOpc,
5837                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5838                                     const TargetLowering &TLI) {
5839   bool HasCopyToRegUses = false;
5840   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5841   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5842                             UE = N0.getNode()->use_end();
5843        UI != UE; ++UI) {
5844     SDNode *User = *UI;
5845     if (User == N)
5846       continue;
5847     if (UI.getUse().getResNo() != N0.getResNo())
5848       continue;
5849     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5850     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5851       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5852       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5853         // Sign bits will be lost after a zext.
5854         return false;
5855       bool Add = false;
5856       for (unsigned i = 0; i != 2; ++i) {
5857         SDValue UseOp = User->getOperand(i);
5858         if (UseOp == N0)
5859           continue;
5860         if (!isa<ConstantSDNode>(UseOp))
5861           return false;
5862         Add = true;
5863       }
5864       if (Add)
5865         ExtendNodes.push_back(User);
5866       continue;
5867     }
5868     // If truncates aren't free and there are users we can't
5869     // extend, it isn't worthwhile.
5870     if (!isTruncFree)
5871       return false;
5872     // Remember if this value is live-out.
5873     if (User->getOpcode() == ISD::CopyToReg)
5874       HasCopyToRegUses = true;
5875   }
5876
5877   if (HasCopyToRegUses) {
5878     bool BothLiveOut = false;
5879     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5880          UI != UE; ++UI) {
5881       SDUse &Use = UI.getUse();
5882       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5883         BothLiveOut = true;
5884         break;
5885       }
5886     }
5887     if (BothLiveOut)
5888       // Both unextended and extended values are live out. There had better be
5889       // a good reason for the transformation.
5890       return ExtendNodes.size();
5891   }
5892   return true;
5893 }
5894
5895 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5896                                   SDValue Trunc, SDValue ExtLoad,
5897                                   const SDLoc &DL, ISD::NodeType ExtType) {
5898   // Extend SetCC uses if necessary.
5899   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5900     SDNode *SetCC = SetCCs[i];
5901     SmallVector<SDValue, 4> Ops;
5902
5903     for (unsigned j = 0; j != 2; ++j) {
5904       SDValue SOp = SetCC->getOperand(j);
5905       if (SOp == Trunc)
5906         Ops.push_back(ExtLoad);
5907       else
5908         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5909     }
5910
5911     Ops.push_back(SetCC->getOperand(2));
5912     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5913   }
5914 }
5915
5916 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5917 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5918   SDValue N0 = N->getOperand(0);
5919   EVT DstVT = N->getValueType(0);
5920   EVT SrcVT = N0.getValueType();
5921
5922   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5923           N->getOpcode() == ISD::ZERO_EXTEND) &&
5924          "Unexpected node type (not an extend)!");
5925
5926   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5927   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5928   //   (v8i32 (sext (v8i16 (load x))))
5929   // into:
5930   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5931   //                          (v4i32 (sextload (x + 16)))))
5932   // Where uses of the original load, i.e.:
5933   //   (v8i16 (load x))
5934   // are replaced with:
5935   //   (v8i16 (truncate
5936   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5937   //                            (v4i32 (sextload (x + 16)))))))
5938   //
5939   // This combine is only applicable to illegal, but splittable, vectors.
5940   // All legal types, and illegal non-vector types, are handled elsewhere.
5941   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5942   //
5943   if (N0->getOpcode() != ISD::LOAD)
5944     return SDValue();
5945
5946   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5947
5948   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5949       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5950       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5951     return SDValue();
5952
5953   SmallVector<SDNode *, 4> SetCCs;
5954   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5955     return SDValue();
5956
5957   ISD::LoadExtType ExtType =
5958       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5959
5960   // Try to split the vector types to get down to legal types.
5961   EVT SplitSrcVT = SrcVT;
5962   EVT SplitDstVT = DstVT;
5963   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5964          SplitSrcVT.getVectorNumElements() > 1) {
5965     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5966     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5967   }
5968
5969   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5970     return SDValue();
5971
5972   SDLoc DL(N);
5973   const unsigned NumSplits =
5974       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5975   const unsigned Stride = SplitSrcVT.getStoreSize();
5976   SmallVector<SDValue, 4> Loads;
5977   SmallVector<SDValue, 4> Chains;
5978
5979   SDValue BasePtr = LN0->getBasePtr();
5980   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5981     const unsigned Offset = Idx * Stride;
5982     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5983
5984     SDValue SplitLoad = DAG.getExtLoad(
5985         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5986         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
5987         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
5988
5989     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5990                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5991
5992     Loads.push_back(SplitLoad.getValue(0));
5993     Chains.push_back(SplitLoad.getValue(1));
5994   }
5995
5996   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5997   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5998
5999   CombineTo(N, NewValue);
6000
6001   // Replace uses of the original load (before extension)
6002   // with a truncate of the concatenated sextloaded vectors.
6003   SDValue Trunc =
6004       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6005   CombineTo(N0.getNode(), Trunc, NewChain);
6006   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6007                   (ISD::NodeType)N->getOpcode());
6008   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6009 }
6010
6011 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6012   SDValue N0 = N->getOperand(0);
6013   EVT VT = N->getValueType(0);
6014
6015   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6016                                               LegalOperations))
6017     return SDValue(Res, 0);
6018
6019   // fold (sext (sext x)) -> (sext x)
6020   // fold (sext (aext x)) -> (sext x)
6021   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6022     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6023                        N0.getOperand(0));
6024
6025   if (N0.getOpcode() == ISD::TRUNCATE) {
6026     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6027     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6028     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6029       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6030       if (NarrowLoad.getNode() != N0.getNode()) {
6031         CombineTo(N0.getNode(), NarrowLoad);
6032         // CombineTo deleted the truncate, if needed, but not what's under it.
6033         AddToWorklist(oye);
6034       }
6035       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6036     }
6037
6038     // See if the value being truncated is already sign extended.  If so, just
6039     // eliminate the trunc/sext pair.
6040     SDValue Op = N0.getOperand(0);
6041     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
6042     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
6043     unsigned DestBits = VT.getScalarType().getSizeInBits();
6044     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6045
6046     if (OpBits == DestBits) {
6047       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6048       // bits, it is already ready.
6049       if (NumSignBits > DestBits-MidBits)
6050         return Op;
6051     } else if (OpBits < DestBits) {
6052       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6053       // bits, just sext from i32.
6054       if (NumSignBits > OpBits-MidBits)
6055         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6056     } else {
6057       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6058       // bits, just truncate to i32.
6059       if (NumSignBits > OpBits-MidBits)
6060         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6061     }
6062
6063     // fold (sext (truncate x)) -> (sextinreg x).
6064     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6065                                                  N0.getValueType())) {
6066       if (OpBits < DestBits)
6067         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6068       else if (OpBits > DestBits)
6069         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6070       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6071                          DAG.getValueType(N0.getValueType()));
6072     }
6073   }
6074
6075   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6076   // Only generate vector extloads when 1) they're legal, and 2) they are
6077   // deemed desirable by the target.
6078   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6079       ((!LegalOperations && !VT.isVector() &&
6080         !cast<LoadSDNode>(N0)->isVolatile()) ||
6081        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6082     bool DoXform = true;
6083     SmallVector<SDNode*, 4> SetCCs;
6084     if (!N0.hasOneUse())
6085       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6086     if (VT.isVector())
6087       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6088     if (DoXform) {
6089       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6090       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6091                                        LN0->getChain(),
6092                                        LN0->getBasePtr(), N0.getValueType(),
6093                                        LN0->getMemOperand());
6094       CombineTo(N, ExtLoad);
6095       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6096                                   N0.getValueType(), ExtLoad);
6097       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6098       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6099                       ISD::SIGN_EXTEND);
6100       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6101     }
6102   }
6103
6104   // fold (sext (load x)) to multiple smaller sextloads.
6105   // Only on illegal but splittable vectors.
6106   if (SDValue ExtLoad = CombineExtLoad(N))
6107     return ExtLoad;
6108
6109   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6110   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6111   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6112       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6113     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6114     EVT MemVT = LN0->getMemoryVT();
6115     if ((!LegalOperations && !LN0->isVolatile()) ||
6116         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6117       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6118                                        LN0->getChain(),
6119                                        LN0->getBasePtr(), MemVT,
6120                                        LN0->getMemOperand());
6121       CombineTo(N, ExtLoad);
6122       CombineTo(N0.getNode(),
6123                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6124                             N0.getValueType(), ExtLoad),
6125                 ExtLoad.getValue(1));
6126       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6127     }
6128   }
6129
6130   // fold (sext (and/or/xor (load x), cst)) ->
6131   //      (and/or/xor (sextload x), (sext cst))
6132   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6133        N0.getOpcode() == ISD::XOR) &&
6134       isa<LoadSDNode>(N0.getOperand(0)) &&
6135       N0.getOperand(1).getOpcode() == ISD::Constant &&
6136       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6137       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6138     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6139     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6140       bool DoXform = true;
6141       SmallVector<SDNode*, 4> SetCCs;
6142       if (!N0.hasOneUse())
6143         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6144                                           SetCCs, TLI);
6145       if (DoXform) {
6146         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6147                                          LN0->getChain(), LN0->getBasePtr(),
6148                                          LN0->getMemoryVT(),
6149                                          LN0->getMemOperand());
6150         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6151         Mask = Mask.sext(VT.getSizeInBits());
6152         SDLoc DL(N);
6153         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6154                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6155         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6156                                     SDLoc(N0.getOperand(0)),
6157                                     N0.getOperand(0).getValueType(), ExtLoad);
6158         CombineTo(N, And);
6159         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6160         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6161                         ISD::SIGN_EXTEND);
6162         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6163       }
6164     }
6165   }
6166
6167   if (N0.getOpcode() == ISD::SETCC) {
6168     EVT N0VT = N0.getOperand(0).getValueType();
6169     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6170     // Only do this before legalize for now.
6171     if (VT.isVector() && !LegalOperations &&
6172         TLI.getBooleanContents(N0VT) ==
6173             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6174       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6175       // of the same size as the compared operands. Only optimize sext(setcc())
6176       // if this is the case.
6177       EVT SVT = getSetCCResultType(N0VT);
6178
6179       // We know that the # elements of the results is the same as the
6180       // # elements of the compare (and the # elements of the compare result
6181       // for that matter).  Check to see that they are the same size.  If so,
6182       // we know that the element size of the sext'd result matches the
6183       // element size of the compare operands.
6184       if (VT.getSizeInBits() == SVT.getSizeInBits())
6185         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6186                              N0.getOperand(1),
6187                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6188
6189       // If the desired elements are smaller or larger than the source
6190       // elements we can use a matching integer vector type and then
6191       // truncate/sign extend
6192       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6193       if (SVT == MatchingVectorType) {
6194         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6195                                N0.getOperand(0), N0.getOperand(1),
6196                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6197         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6198       }
6199     }
6200
6201     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6202     // Here, T can be 1 or -1, depending on the type of the setcc and
6203     // getBooleanContents().
6204     unsigned SetCCWidth = N0.getValueType().getScalarSizeInBits();
6205
6206     SDLoc DL(N);
6207     // To determine the "true" side of the select, we need to know the high bit
6208     // of the value returned by the setcc if it evaluates to true.
6209     // If the type of the setcc is i1, then the true case of the select is just
6210     // sext(i1 1), that is, -1.
6211     // If the type of the setcc is larger (say, i8) then the value of the high
6212     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6213     // of the appropriate width.
6214     SDValue ExtTrueVal =
6215         (SetCCWidth == 1)
6216             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6217                               DL, VT)
6218             : TLI.getConstTrueVal(DAG, VT, DL);
6219
6220     if (SDValue SCC = SimplifySelectCC(
6221             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6222             DAG.getConstant(0, DL, VT),
6223             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6224       return SCC;
6225
6226     if (!VT.isVector()) {
6227       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6228       if (!LegalOperations ||
6229           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6230         SDLoc DL(N);
6231         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6232         SDValue SetCC =
6233             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6234         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6235                              DAG.getConstant(0, DL, VT));
6236       }
6237     }
6238   }
6239
6240   // fold (sext x) -> (zext x) if the sign bit is known zero.
6241   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6242       DAG.SignBitIsZero(N0))
6243     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6244
6245   return SDValue();
6246 }
6247
6248 // isTruncateOf - If N is a truncate of some other value, return true, record
6249 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6250 // This function computes KnownZero to avoid a duplicated call to
6251 // computeKnownBits in the caller.
6252 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6253                          APInt &KnownZero) {
6254   APInt KnownOne;
6255   if (N->getOpcode() == ISD::TRUNCATE) {
6256     Op = N->getOperand(0);
6257     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6258     return true;
6259   }
6260
6261   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6262       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6263     return false;
6264
6265   SDValue Op0 = N->getOperand(0);
6266   SDValue Op1 = N->getOperand(1);
6267   assert(Op0.getValueType() == Op1.getValueType());
6268
6269   if (isNullConstant(Op0))
6270     Op = Op1;
6271   else if (isNullConstant(Op1))
6272     Op = Op0;
6273   else
6274     return false;
6275
6276   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6277
6278   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6279     return false;
6280
6281   return true;
6282 }
6283
6284 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6285   SDValue N0 = N->getOperand(0);
6286   EVT VT = N->getValueType(0);
6287
6288   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6289                                               LegalOperations))
6290     return SDValue(Res, 0);
6291
6292   // fold (zext (zext x)) -> (zext x)
6293   // fold (zext (aext x)) -> (zext x)
6294   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6295     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6296                        N0.getOperand(0));
6297
6298   // fold (zext (truncate x)) -> (zext x) or
6299   //      (zext (truncate x)) -> (truncate x)
6300   // This is valid when the truncated bits of x are already zero.
6301   // FIXME: We should extend this to work for vectors too.
6302   SDValue Op;
6303   APInt KnownZero;
6304   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6305     APInt TruncatedBits =
6306       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6307       APInt(Op.getValueSizeInBits(), 0) :
6308       APInt::getBitsSet(Op.getValueSizeInBits(),
6309                         N0.getValueSizeInBits(),
6310                         std::min(Op.getValueSizeInBits(),
6311                                  VT.getSizeInBits()));
6312     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6313       if (VT.bitsGT(Op.getValueType()))
6314         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6315       if (VT.bitsLT(Op.getValueType()))
6316         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6317
6318       return Op;
6319     }
6320   }
6321
6322   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6323   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6324   if (N0.getOpcode() == ISD::TRUNCATE) {
6325     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6326       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6327       if (NarrowLoad.getNode() != N0.getNode()) {
6328         CombineTo(N0.getNode(), NarrowLoad);
6329         // CombineTo deleted the truncate, if needed, but not what's under it.
6330         AddToWorklist(oye);
6331       }
6332       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6333     }
6334   }
6335
6336   // fold (zext (truncate x)) -> (and x, mask)
6337   if (N0.getOpcode() == ISD::TRUNCATE) {
6338     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6339     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6340     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6341       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6342       if (NarrowLoad.getNode() != N0.getNode()) {
6343         CombineTo(N0.getNode(), NarrowLoad);
6344         // CombineTo deleted the truncate, if needed, but not what's under it.
6345         AddToWorklist(oye);
6346       }
6347       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6348     }
6349
6350     EVT SrcVT = N0.getOperand(0).getValueType();
6351     EVT MinVT = N0.getValueType();
6352
6353     // Try to mask before the extension to avoid having to generate a larger mask,
6354     // possibly over several sub-vectors.
6355     if (SrcVT.bitsLT(VT)) {
6356       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6357                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6358         SDValue Op = N0.getOperand(0);
6359         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6360         AddToWorklist(Op.getNode());
6361         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6362       }
6363     }
6364
6365     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6366       SDValue Op = N0.getOperand(0);
6367       if (SrcVT.bitsLT(VT)) {
6368         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6369         AddToWorklist(Op.getNode());
6370       } else if (SrcVT.bitsGT(VT)) {
6371         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6372         AddToWorklist(Op.getNode());
6373       }
6374       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6375     }
6376   }
6377
6378   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6379   // if either of the casts is not free.
6380   if (N0.getOpcode() == ISD::AND &&
6381       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6382       N0.getOperand(1).getOpcode() == ISD::Constant &&
6383       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6384                            N0.getValueType()) ||
6385        !TLI.isZExtFree(N0.getValueType(), VT))) {
6386     SDValue X = N0.getOperand(0).getOperand(0);
6387     if (X.getValueType().bitsLT(VT)) {
6388       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6389     } else if (X.getValueType().bitsGT(VT)) {
6390       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6391     }
6392     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6393     Mask = Mask.zext(VT.getSizeInBits());
6394     SDLoc DL(N);
6395     return DAG.getNode(ISD::AND, DL, VT,
6396                        X, DAG.getConstant(Mask, DL, VT));
6397   }
6398
6399   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6400   // Only generate vector extloads when 1) they're legal, and 2) they are
6401   // deemed desirable by the target.
6402   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6403       ((!LegalOperations && !VT.isVector() &&
6404         !cast<LoadSDNode>(N0)->isVolatile()) ||
6405        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6406     bool DoXform = true;
6407     SmallVector<SDNode*, 4> SetCCs;
6408     if (!N0.hasOneUse())
6409       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6410     if (VT.isVector())
6411       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6412     if (DoXform) {
6413       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6414       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6415                                        LN0->getChain(),
6416                                        LN0->getBasePtr(), N0.getValueType(),
6417                                        LN0->getMemOperand());
6418       CombineTo(N, ExtLoad);
6419       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6420                                   N0.getValueType(), ExtLoad);
6421       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6422
6423       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6424                       ISD::ZERO_EXTEND);
6425       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6426     }
6427   }
6428
6429   // fold (zext (load x)) to multiple smaller zextloads.
6430   // Only on illegal but splittable vectors.
6431   if (SDValue ExtLoad = CombineExtLoad(N))
6432     return ExtLoad;
6433
6434   // fold (zext (and/or/xor (load x), cst)) ->
6435   //      (and/or/xor (zextload x), (zext cst))
6436   // Unless (and (load x) cst) will match as a zextload already and has
6437   // additional users.
6438   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6439        N0.getOpcode() == ISD::XOR) &&
6440       isa<LoadSDNode>(N0.getOperand(0)) &&
6441       N0.getOperand(1).getOpcode() == ISD::Constant &&
6442       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6443       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6444     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6445     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6446       bool DoXform = true;
6447       SmallVector<SDNode*, 4> SetCCs;
6448       if (!N0.hasOneUse()) {
6449         if (N0.getOpcode() == ISD::AND) {
6450           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6451           auto NarrowLoad = false;
6452           EVT LoadResultTy = AndC->getValueType(0);
6453           EVT ExtVT, LoadedVT;
6454           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6455                                NarrowLoad))
6456             DoXform = false;
6457         }
6458         if (DoXform)
6459           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6460                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6461       }
6462       if (DoXform) {
6463         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6464                                          LN0->getChain(), LN0->getBasePtr(),
6465                                          LN0->getMemoryVT(),
6466                                          LN0->getMemOperand());
6467         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6468         Mask = Mask.zext(VT.getSizeInBits());
6469         SDLoc DL(N);
6470         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6471                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6472         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6473                                     SDLoc(N0.getOperand(0)),
6474                                     N0.getOperand(0).getValueType(), ExtLoad);
6475         CombineTo(N, And);
6476         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6477         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6478                         ISD::ZERO_EXTEND);
6479         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6480       }
6481     }
6482   }
6483
6484   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6485   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6486   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6487       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6488     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6489     EVT MemVT = LN0->getMemoryVT();
6490     if ((!LegalOperations && !LN0->isVolatile()) ||
6491         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6492       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6493                                        LN0->getChain(),
6494                                        LN0->getBasePtr(), MemVT,
6495                                        LN0->getMemOperand());
6496       CombineTo(N, ExtLoad);
6497       CombineTo(N0.getNode(),
6498                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6499                             ExtLoad),
6500                 ExtLoad.getValue(1));
6501       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6502     }
6503   }
6504
6505   if (N0.getOpcode() == ISD::SETCC) {
6506     // Only do this before legalize for now.
6507     if (!LegalOperations && VT.isVector() &&
6508         N0.getValueType().getVectorElementType() == MVT::i1) {
6509       EVT N00VT = N0.getOperand(0).getValueType();
6510       if (getSetCCResultType(N00VT) == N0.getValueType())
6511         return SDValue();
6512
6513       // We know that the # elements of the results is the same as the #
6514       // elements of the compare (and the # elements of the compare result for
6515       // that matter). Check to see that they are the same size. If so, we know
6516       // that the element size of the sext'd result matches the element size of
6517       // the compare operands.
6518       SDLoc DL(N);
6519       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6520       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6521         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6522         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6523                                      N0.getOperand(1), N0.getOperand(2));
6524         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6525       }
6526
6527       // If the desired elements are smaller or larger than the source
6528       // elements we can use a matching integer vector type and then
6529       // truncate/sign extend.
6530       EVT MatchingElementType = EVT::getIntegerVT(
6531           *DAG.getContext(), N00VT.getScalarType().getSizeInBits());
6532       EVT MatchingVectorType = EVT::getVectorVT(
6533           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6534       SDValue VsetCC =
6535           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6536                       N0.getOperand(1), N0.getOperand(2));
6537       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6538                          VecOnes);
6539     }
6540
6541     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6542     SDLoc DL(N);
6543     if (SDValue SCC = SimplifySelectCC(
6544             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6545             DAG.getConstant(0, DL, VT),
6546             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6547       return SCC;
6548   }
6549
6550   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6551   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6552       isa<ConstantSDNode>(N0.getOperand(1)) &&
6553       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6554       N0.hasOneUse()) {
6555     SDValue ShAmt = N0.getOperand(1);
6556     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6557     if (N0.getOpcode() == ISD::SHL) {
6558       SDValue InnerZExt = N0.getOperand(0);
6559       // If the original shl may be shifting out bits, do not perform this
6560       // transformation.
6561       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6562         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6563       if (ShAmtVal > KnownZeroBits)
6564         return SDValue();
6565     }
6566
6567     SDLoc DL(N);
6568
6569     // Ensure that the shift amount is wide enough for the shifted value.
6570     if (VT.getSizeInBits() >= 256)
6571       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6572
6573     return DAG.getNode(N0.getOpcode(), DL, VT,
6574                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6575                        ShAmt);
6576   }
6577
6578   return SDValue();
6579 }
6580
6581 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6582   SDValue N0 = N->getOperand(0);
6583   EVT VT = N->getValueType(0);
6584
6585   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6586                                               LegalOperations))
6587     return SDValue(Res, 0);
6588
6589   // fold (aext (aext x)) -> (aext x)
6590   // fold (aext (zext x)) -> (zext x)
6591   // fold (aext (sext x)) -> (sext x)
6592   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6593       N0.getOpcode() == ISD::ZERO_EXTEND ||
6594       N0.getOpcode() == ISD::SIGN_EXTEND)
6595     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6596
6597   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6598   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6599   if (N0.getOpcode() == ISD::TRUNCATE) {
6600     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6601       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6602       if (NarrowLoad.getNode() != N0.getNode()) {
6603         CombineTo(N0.getNode(), NarrowLoad);
6604         // CombineTo deleted the truncate, if needed, but not what's under it.
6605         AddToWorklist(oye);
6606       }
6607       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6608     }
6609   }
6610
6611   // fold (aext (truncate x))
6612   if (N0.getOpcode() == ISD::TRUNCATE) {
6613     SDValue TruncOp = N0.getOperand(0);
6614     if (TruncOp.getValueType() == VT)
6615       return TruncOp; // x iff x size == zext size.
6616     if (TruncOp.getValueType().bitsGT(VT))
6617       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6618     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6619   }
6620
6621   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6622   // if the trunc is not free.
6623   if (N0.getOpcode() == ISD::AND &&
6624       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6625       N0.getOperand(1).getOpcode() == ISD::Constant &&
6626       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6627                           N0.getValueType())) {
6628     SDValue X = N0.getOperand(0).getOperand(0);
6629     if (X.getValueType().bitsLT(VT)) {
6630       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6631     } else if (X.getValueType().bitsGT(VT)) {
6632       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6633     }
6634     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6635     Mask = Mask.zext(VT.getSizeInBits());
6636     SDLoc DL(N);
6637     return DAG.getNode(ISD::AND, DL, VT,
6638                        X, DAG.getConstant(Mask, DL, VT));
6639   }
6640
6641   // fold (aext (load x)) -> (aext (truncate (extload x)))
6642   // None of the supported targets knows how to perform load and any_ext
6643   // on vectors in one instruction.  We only perform this transformation on
6644   // scalars.
6645   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6646       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6647       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6648     bool DoXform = true;
6649     SmallVector<SDNode*, 4> SetCCs;
6650     if (!N0.hasOneUse())
6651       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6652     if (DoXform) {
6653       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6654       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6655                                        LN0->getChain(),
6656                                        LN0->getBasePtr(), N0.getValueType(),
6657                                        LN0->getMemOperand());
6658       CombineTo(N, ExtLoad);
6659       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6660                                   N0.getValueType(), ExtLoad);
6661       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6662       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6663                       ISD::ANY_EXTEND);
6664       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6665     }
6666   }
6667
6668   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6669   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6670   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6671   if (N0.getOpcode() == ISD::LOAD &&
6672       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6673       N0.hasOneUse()) {
6674     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6675     ISD::LoadExtType ExtType = LN0->getExtensionType();
6676     EVT MemVT = LN0->getMemoryVT();
6677     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6678       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6679                                        VT, LN0->getChain(), LN0->getBasePtr(),
6680                                        MemVT, LN0->getMemOperand());
6681       CombineTo(N, ExtLoad);
6682       CombineTo(N0.getNode(),
6683                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6684                             N0.getValueType(), ExtLoad),
6685                 ExtLoad.getValue(1));
6686       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6687     }
6688   }
6689
6690   if (N0.getOpcode() == ISD::SETCC) {
6691     // For vectors:
6692     // aext(setcc) -> vsetcc
6693     // aext(setcc) -> truncate(vsetcc)
6694     // aext(setcc) -> aext(vsetcc)
6695     // Only do this before legalize for now.
6696     if (VT.isVector() && !LegalOperations) {
6697       EVT N0VT = N0.getOperand(0).getValueType();
6698         // We know that the # elements of the results is the same as the
6699         // # elements of the compare (and the # elements of the compare result
6700         // for that matter).  Check to see that they are the same size.  If so,
6701         // we know that the element size of the sext'd result matches the
6702         // element size of the compare operands.
6703       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6704         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6705                              N0.getOperand(1),
6706                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6707       // If the desired elements are smaller or larger than the source
6708       // elements we can use a matching integer vector type and then
6709       // truncate/any extend
6710       else {
6711         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6712         SDValue VsetCC =
6713           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6714                         N0.getOperand(1),
6715                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6716         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6717       }
6718     }
6719
6720     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6721     SDLoc DL(N);
6722     if (SDValue SCC = SimplifySelectCC(
6723             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6724             DAG.getConstant(0, DL, VT),
6725             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6726       return SCC;
6727   }
6728
6729   return SDValue();
6730 }
6731
6732 /// See if the specified operand can be simplified with the knowledge that only
6733 /// the bits specified by Mask are used.  If so, return the simpler operand,
6734 /// otherwise return a null SDValue.
6735 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6736   switch (V.getOpcode()) {
6737   default: break;
6738   case ISD::Constant: {
6739     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6740     assert(CV && "Const value should be ConstSDNode.");
6741     const APInt &CVal = CV->getAPIntValue();
6742     APInt NewVal = CVal & Mask;
6743     if (NewVal != CVal)
6744       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6745     break;
6746   }
6747   case ISD::OR:
6748   case ISD::XOR:
6749     // If the LHS or RHS don't contribute bits to the or, drop them.
6750     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6751       return V.getOperand(1);
6752     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6753       return V.getOperand(0);
6754     break;
6755   case ISD::SRL:
6756     // Only look at single-use SRLs.
6757     if (!V.getNode()->hasOneUse())
6758       break;
6759     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6760       // See if we can recursively simplify the LHS.
6761       unsigned Amt = RHSC->getZExtValue();
6762
6763       // Watch out for shift count overflow though.
6764       if (Amt >= Mask.getBitWidth()) break;
6765       APInt NewMask = Mask << Amt;
6766       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6767         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6768                            SimplifyLHS, V.getOperand(1));
6769     }
6770   }
6771   return SDValue();
6772 }
6773
6774 /// If the result of a wider load is shifted to right of N  bits and then
6775 /// truncated to a narrower type and where N is a multiple of number of bits of
6776 /// the narrower type, transform it to a narrower load from address + N / num of
6777 /// bits of new type. If the result is to be extended, also fold the extension
6778 /// to form a extending load.
6779 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6780   unsigned Opc = N->getOpcode();
6781
6782   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6783   SDValue N0 = N->getOperand(0);
6784   EVT VT = N->getValueType(0);
6785   EVT ExtVT = VT;
6786
6787   // This transformation isn't valid for vector loads.
6788   if (VT.isVector())
6789     return SDValue();
6790
6791   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6792   // extended to VT.
6793   if (Opc == ISD::SIGN_EXTEND_INREG) {
6794     ExtType = ISD::SEXTLOAD;
6795     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6796   } else if (Opc == ISD::SRL) {
6797     // Another special-case: SRL is basically zero-extending a narrower value.
6798     ExtType = ISD::ZEXTLOAD;
6799     N0 = SDValue(N, 0);
6800     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6801     if (!N01) return SDValue();
6802     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6803                               VT.getSizeInBits() - N01->getZExtValue());
6804   }
6805   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6806     return SDValue();
6807
6808   unsigned EVTBits = ExtVT.getSizeInBits();
6809
6810   // Do not generate loads of non-round integer types since these can
6811   // be expensive (and would be wrong if the type is not byte sized).
6812   if (!ExtVT.isRound())
6813     return SDValue();
6814
6815   unsigned ShAmt = 0;
6816   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6817     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6818       ShAmt = N01->getZExtValue();
6819       // Is the shift amount a multiple of size of VT?
6820       if ((ShAmt & (EVTBits-1)) == 0) {
6821         N0 = N0.getOperand(0);
6822         // Is the load width a multiple of size of VT?
6823         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6824           return SDValue();
6825       }
6826
6827       // At this point, we must have a load or else we can't do the transform.
6828       if (!isa<LoadSDNode>(N0)) return SDValue();
6829
6830       // Because a SRL must be assumed to *need* to zero-extend the high bits
6831       // (as opposed to anyext the high bits), we can't combine the zextload
6832       // lowering of SRL and an sextload.
6833       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6834         return SDValue();
6835
6836       // If the shift amount is larger than the input type then we're not
6837       // accessing any of the loaded bytes.  If the load was a zextload/extload
6838       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6839       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6840         return SDValue();
6841     }
6842   }
6843
6844   // If the load is shifted left (and the result isn't shifted back right),
6845   // we can fold the truncate through the shift.
6846   unsigned ShLeftAmt = 0;
6847   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6848       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6849     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6850       ShLeftAmt = N01->getZExtValue();
6851       N0 = N0.getOperand(0);
6852     }
6853   }
6854
6855   // If we haven't found a load, we can't narrow it.  Don't transform one with
6856   // multiple uses, this would require adding a new load.
6857   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6858     return SDValue();
6859
6860   // Don't change the width of a volatile load.
6861   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6862   if (LN0->isVolatile())
6863     return SDValue();
6864
6865   // Verify that we are actually reducing a load width here.
6866   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6867     return SDValue();
6868
6869   // For the transform to be legal, the load must produce only two values
6870   // (the value loaded and the chain).  Don't transform a pre-increment
6871   // load, for example, which produces an extra value.  Otherwise the
6872   // transformation is not equivalent, and the downstream logic to replace
6873   // uses gets things wrong.
6874   if (LN0->getNumValues() > 2)
6875     return SDValue();
6876
6877   // If the load that we're shrinking is an extload and we're not just
6878   // discarding the extension we can't simply shrink the load. Bail.
6879   // TODO: It would be possible to merge the extensions in some cases.
6880   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6881       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6882     return SDValue();
6883
6884   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6885     return SDValue();
6886
6887   EVT PtrType = N0.getOperand(1).getValueType();
6888
6889   if (PtrType == MVT::Untyped || PtrType.isExtended())
6890     // It's not possible to generate a constant of extended or untyped type.
6891     return SDValue();
6892
6893   // For big endian targets, we need to adjust the offset to the pointer to
6894   // load the correct bytes.
6895   if (DAG.getDataLayout().isBigEndian()) {
6896     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6897     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6898     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6899   }
6900
6901   uint64_t PtrOff = ShAmt / 8;
6902   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6903   SDLoc DL(LN0);
6904   // The original load itself didn't wrap, so an offset within it doesn't.
6905   SDNodeFlags Flags;
6906   Flags.setNoUnsignedWrap(true);
6907   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6908                                PtrType, LN0->getBasePtr(),
6909                                DAG.getConstant(PtrOff, DL, PtrType),
6910                                &Flags);
6911   AddToWorklist(NewPtr.getNode());
6912
6913   SDValue Load;
6914   if (ExtType == ISD::NON_EXTLOAD)
6915     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6916                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
6917                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6918   else
6919     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
6920                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
6921                           NewAlign, LN0->getMemOperand()->getFlags(),
6922                           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(), LD1->getBasePtr(),
7341                          LD1->getPointerInfo(), Align);
7342   }
7343
7344   return SDValue();
7345 }
7346
7347 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7348   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7349   // and Lo parts; on big-endian machines it doesn't.
7350   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7351 }
7352
7353 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7354                                     const TargetLowering &TLI) {
7355   // If this is not a bitcast to an FP type or if the target doesn't have
7356   // IEEE754-compliant FP logic, we're done.
7357   EVT VT = N->getValueType(0);
7358   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7359     return SDValue();
7360
7361   // TODO: Use splat values for the constant-checking below and remove this
7362   // restriction.
7363   SDValue N0 = N->getOperand(0);
7364   EVT SourceVT = N0.getValueType();
7365   if (SourceVT.isVector())
7366     return SDValue();
7367
7368   unsigned FPOpcode;
7369   APInt SignMask;
7370   switch (N0.getOpcode()) {
7371   case ISD::AND:
7372     FPOpcode = ISD::FABS;
7373     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7374     break;
7375   case ISD::XOR:
7376     FPOpcode = ISD::FNEG;
7377     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7378     break;
7379   // TODO: ISD::OR --> ISD::FNABS?
7380   default:
7381     return SDValue();
7382   }
7383
7384   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7385   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7386   SDValue LogicOp0 = N0.getOperand(0);
7387   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7388   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7389       LogicOp0.getOpcode() == ISD::BITCAST &&
7390       LogicOp0->getOperand(0).getValueType() == VT)
7391     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7392
7393   return SDValue();
7394 }
7395
7396 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7397   SDValue N0 = N->getOperand(0);
7398   EVT VT = N->getValueType(0);
7399
7400   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7401   // Only do this before legalize, since afterward the target may be depending
7402   // on the bitconvert.
7403   // First check to see if this is all constant.
7404   if (!LegalTypes &&
7405       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7406       VT.isVector()) {
7407     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7408
7409     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7410     assert(!DestEltVT.isVector() &&
7411            "Element type of vector ValueType must not be vector!");
7412     if (isSimple)
7413       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7414   }
7415
7416   // If the input is a constant, let getNode fold it.
7417   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7418     // If we can't allow illegal operations, we need to check that this is just
7419     // a fp -> int or int -> conversion and that the resulting operation will
7420     // be legal.
7421     if (!LegalOperations ||
7422         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7423          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7424         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7425          TLI.isOperationLegal(ISD::Constant, VT)))
7426       return DAG.getBitcast(VT, N0);
7427   }
7428
7429   // (conv (conv x, t1), t2) -> (conv x, t2)
7430   if (N0.getOpcode() == ISD::BITCAST)
7431     return DAG.getBitcast(VT, N0.getOperand(0));
7432
7433   // fold (conv (load x)) -> (load (conv*)x)
7434   // If the resultant load doesn't need a higher alignment than the original!
7435   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7436       // Do not change the width of a volatile load.
7437       !cast<LoadSDNode>(N0)->isVolatile() &&
7438       // Do not remove the cast if the types differ in endian layout.
7439       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7440           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7441       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7442       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7443     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7444     unsigned OrigAlign = LN0->getAlignment();
7445
7446     bool Fast = false;
7447     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7448                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7449         Fast) {
7450       SDValue Load =
7451           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7452                       LN0->getPointerInfo(), OrigAlign,
7453                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7454       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7455       return Load;
7456     }
7457   }
7458
7459   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7460     return V;
7461
7462   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7463   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7464   //
7465   // For ppc_fp128:
7466   // fold (bitcast (fneg x)) ->
7467   //     flipbit = signbit
7468   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7469   //
7470   // fold (bitcast (fabs x)) ->
7471   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7472   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7473   // This often reduces constant pool loads.
7474   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7475        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7476       N0.getNode()->hasOneUse() && VT.isInteger() &&
7477       !VT.isVector() && !N0.getValueType().isVector()) {
7478     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7479     AddToWorklist(NewConv.getNode());
7480
7481     SDLoc DL(N);
7482     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7483       assert(VT.getSizeInBits() == 128);
7484       SDValue SignBit = DAG.getConstant(
7485           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7486       SDValue FlipBit;
7487       if (N0.getOpcode() == ISD::FNEG) {
7488         FlipBit = SignBit;
7489         AddToWorklist(FlipBit.getNode());
7490       } else {
7491         assert(N0.getOpcode() == ISD::FABS);
7492         SDValue Hi =
7493             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7494                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7495                                               SDLoc(NewConv)));
7496         AddToWorklist(Hi.getNode());
7497         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7498         AddToWorklist(FlipBit.getNode());
7499       }
7500       SDValue FlipBits =
7501           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7502       AddToWorklist(FlipBits.getNode());
7503       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7504     }
7505     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7506     if (N0.getOpcode() == ISD::FNEG)
7507       return DAG.getNode(ISD::XOR, DL, VT,
7508                          NewConv, DAG.getConstant(SignBit, DL, VT));
7509     assert(N0.getOpcode() == ISD::FABS);
7510     return DAG.getNode(ISD::AND, DL, VT,
7511                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7512   }
7513
7514   // fold (bitconvert (fcopysign cst, x)) ->
7515   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7516   // Note that we don't handle (copysign x, cst) because this can always be
7517   // folded to an fneg or fabs.
7518   //
7519   // For ppc_fp128:
7520   // fold (bitcast (fcopysign cst, x)) ->
7521   //     flipbit = (and (extract_element
7522   //                     (xor (bitcast cst), (bitcast x)), 0),
7523   //                    signbit)
7524   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7525   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7526       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7527       VT.isInteger() && !VT.isVector()) {
7528     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7529     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7530     if (isTypeLegal(IntXVT)) {
7531       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7532       AddToWorklist(X.getNode());
7533
7534       // If X has a different width than the result/lhs, sext it or truncate it.
7535       unsigned VTWidth = VT.getSizeInBits();
7536       if (OrigXWidth < VTWidth) {
7537         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7538         AddToWorklist(X.getNode());
7539       } else if (OrigXWidth > VTWidth) {
7540         // To get the sign bit in the right place, we have to shift it right
7541         // before truncating.
7542         SDLoc DL(X);
7543         X = DAG.getNode(ISD::SRL, DL,
7544                         X.getValueType(), X,
7545                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7546                                         X.getValueType()));
7547         AddToWorklist(X.getNode());
7548         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7549         AddToWorklist(X.getNode());
7550       }
7551
7552       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7553         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7554         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7555         AddToWorklist(Cst.getNode());
7556         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7557         AddToWorklist(X.getNode());
7558         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7559         AddToWorklist(XorResult.getNode());
7560         SDValue XorResult64 = DAG.getNode(
7561             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7562             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7563                                   SDLoc(XorResult)));
7564         AddToWorklist(XorResult64.getNode());
7565         SDValue FlipBit =
7566             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7567                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7568         AddToWorklist(FlipBit.getNode());
7569         SDValue FlipBits =
7570             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7571         AddToWorklist(FlipBits.getNode());
7572         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7573       }
7574       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7575       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7576                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7577       AddToWorklist(X.getNode());
7578
7579       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7580       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7581                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7582       AddToWorklist(Cst.getNode());
7583
7584       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7585     }
7586   }
7587
7588   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7589   if (N0.getOpcode() == ISD::BUILD_PAIR)
7590     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7591       return CombineLD;
7592
7593   // Remove double bitcasts from shuffles - this is often a legacy of
7594   // XformToShuffleWithZero being used to combine bitmaskings (of
7595   // float vectors bitcast to integer vectors) into shuffles.
7596   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7597   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7598       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7599       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7600       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7601     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7602
7603     // If operands are a bitcast, peek through if it casts the original VT.
7604     // If operands are a constant, just bitcast back to original VT.
7605     auto PeekThroughBitcast = [&](SDValue Op) {
7606       if (Op.getOpcode() == ISD::BITCAST &&
7607           Op.getOperand(0).getValueType() == VT)
7608         return SDValue(Op.getOperand(0));
7609       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7610           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7611         return DAG.getBitcast(VT, Op);
7612       return SDValue();
7613     };
7614
7615     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7616     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7617     if (!(SV0 && SV1))
7618       return SDValue();
7619
7620     int MaskScale =
7621         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7622     SmallVector<int, 8> NewMask;
7623     for (int M : SVN->getMask())
7624       for (int i = 0; i != MaskScale; ++i)
7625         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7626
7627     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7628     if (!LegalMask) {
7629       std::swap(SV0, SV1);
7630       ShuffleVectorSDNode::commuteMask(NewMask);
7631       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7632     }
7633
7634     if (LegalMask)
7635       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7636   }
7637
7638   return SDValue();
7639 }
7640
7641 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7642   EVT VT = N->getValueType(0);
7643   return CombineConsecutiveLoads(N, VT);
7644 }
7645
7646 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7647 /// operands. DstEltVT indicates the destination element value type.
7648 SDValue DAGCombiner::
7649 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7650   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7651
7652   // If this is already the right type, we're done.
7653   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7654
7655   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7656   unsigned DstBitSize = DstEltVT.getSizeInBits();
7657
7658   // If this is a conversion of N elements of one type to N elements of another
7659   // type, convert each element.  This handles FP<->INT cases.
7660   if (SrcBitSize == DstBitSize) {
7661     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7662                               BV->getValueType(0).getVectorNumElements());
7663
7664     // Due to the FP element handling below calling this routine recursively,
7665     // we can end up with a scalar-to-vector node here.
7666     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7667       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7668                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7669
7670     SmallVector<SDValue, 8> Ops;
7671     for (SDValue Op : BV->op_values()) {
7672       // If the vector element type is not legal, the BUILD_VECTOR operands
7673       // are promoted and implicitly truncated.  Make that explicit here.
7674       if (Op.getValueType() != SrcEltVT)
7675         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7676       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7677       AddToWorklist(Ops.back().getNode());
7678     }
7679     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7680   }
7681
7682   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7683   // handle annoying details of growing/shrinking FP values, we convert them to
7684   // int first.
7685   if (SrcEltVT.isFloatingPoint()) {
7686     // Convert the input float vector to a int vector where the elements are the
7687     // same sizes.
7688     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7689     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7690     SrcEltVT = IntVT;
7691   }
7692
7693   // Now we know the input is an integer vector.  If the output is a FP type,
7694   // convert to integer first, then to FP of the right size.
7695   if (DstEltVT.isFloatingPoint()) {
7696     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7697     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7698
7699     // Next, convert to FP elements of the same size.
7700     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7701   }
7702
7703   SDLoc DL(BV);
7704
7705   // Okay, we know the src/dst types are both integers of differing types.
7706   // Handling growing first.
7707   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7708   if (SrcBitSize < DstBitSize) {
7709     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7710
7711     SmallVector<SDValue, 8> Ops;
7712     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7713          i += NumInputsPerOutput) {
7714       bool isLE = DAG.getDataLayout().isLittleEndian();
7715       APInt NewBits = APInt(DstBitSize, 0);
7716       bool EltIsUndef = true;
7717       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7718         // Shift the previously computed bits over.
7719         NewBits <<= SrcBitSize;
7720         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7721         if (Op.isUndef()) continue;
7722         EltIsUndef = false;
7723
7724         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7725                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7726       }
7727
7728       if (EltIsUndef)
7729         Ops.push_back(DAG.getUNDEF(DstEltVT));
7730       else
7731         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7732     }
7733
7734     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7735     return DAG.getBuildVector(VT, DL, Ops);
7736   }
7737
7738   // Finally, this must be the case where we are shrinking elements: each input
7739   // turns into multiple outputs.
7740   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7741   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7742                             NumOutputsPerInput*BV->getNumOperands());
7743   SmallVector<SDValue, 8> Ops;
7744
7745   for (const SDValue &Op : BV->op_values()) {
7746     if (Op.isUndef()) {
7747       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7748       continue;
7749     }
7750
7751     APInt OpVal = cast<ConstantSDNode>(Op)->
7752                   getAPIntValue().zextOrTrunc(SrcBitSize);
7753
7754     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7755       APInt ThisVal = OpVal.trunc(DstBitSize);
7756       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7757       OpVal = OpVal.lshr(DstBitSize);
7758     }
7759
7760     // For big endian targets, swap the order of the pieces of each element.
7761     if (DAG.getDataLayout().isBigEndian())
7762       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7763   }
7764
7765   return DAG.getBuildVector(VT, DL, Ops);
7766 }
7767
7768 /// Try to perform FMA combining on a given FADD node.
7769 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7770   SDValue N0 = N->getOperand(0);
7771   SDValue N1 = N->getOperand(1);
7772   EVT VT = N->getValueType(0);
7773   SDLoc SL(N);
7774
7775   const TargetOptions &Options = DAG.getTarget().Options;
7776   bool AllowFusion =
7777       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7778
7779   // Floating-point multiply-add with intermediate rounding.
7780   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7781
7782   // Floating-point multiply-add without intermediate rounding.
7783   bool HasFMA =
7784       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7785       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7786
7787   // No valid opcode, do not combine.
7788   if (!HasFMAD && !HasFMA)
7789     return SDValue();
7790
7791   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7792   ;
7793   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7794     return SDValue();
7795
7796   // Always prefer FMAD to FMA for precision.
7797   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7798   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7799   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7800
7801   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7802   // prefer to fold the multiply with fewer uses.
7803   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7804       N1.getOpcode() == ISD::FMUL) {
7805     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7806       std::swap(N0, N1);
7807   }
7808
7809   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7810   if (N0.getOpcode() == ISD::FMUL &&
7811       (Aggressive || N0->hasOneUse())) {
7812     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7813                        N0.getOperand(0), N0.getOperand(1), N1);
7814   }
7815
7816   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7817   // Note: Commutes FADD operands.
7818   if (N1.getOpcode() == ISD::FMUL &&
7819       (Aggressive || N1->hasOneUse())) {
7820     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7821                        N1.getOperand(0), N1.getOperand(1), N0);
7822   }
7823
7824   // Look through FP_EXTEND nodes to do more combining.
7825   if (AllowFusion && LookThroughFPExt) {
7826     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7827     if (N0.getOpcode() == ISD::FP_EXTEND) {
7828       SDValue N00 = N0.getOperand(0);
7829       if (N00.getOpcode() == ISD::FMUL)
7830         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7831                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7832                                        N00.getOperand(0)),
7833                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7834                                        N00.getOperand(1)), N1);
7835     }
7836
7837     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7838     // Note: Commutes FADD operands.
7839     if (N1.getOpcode() == ISD::FP_EXTEND) {
7840       SDValue N10 = N1.getOperand(0);
7841       if (N10.getOpcode() == ISD::FMUL)
7842         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7843                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7844                                        N10.getOperand(0)),
7845                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7846                                        N10.getOperand(1)), N0);
7847     }
7848   }
7849
7850   // More folding opportunities when target permits.
7851   if ((AllowFusion || HasFMAD)  && Aggressive) {
7852     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7853     if (N0.getOpcode() == PreferredFusedOpcode &&
7854         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7855       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7856                          N0.getOperand(0), N0.getOperand(1),
7857                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7858                                      N0.getOperand(2).getOperand(0),
7859                                      N0.getOperand(2).getOperand(1),
7860                                      N1));
7861     }
7862
7863     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7864     if (N1->getOpcode() == PreferredFusedOpcode &&
7865         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7866       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7867                          N1.getOperand(0), N1.getOperand(1),
7868                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7869                                      N1.getOperand(2).getOperand(0),
7870                                      N1.getOperand(2).getOperand(1),
7871                                      N0));
7872     }
7873
7874     if (AllowFusion && LookThroughFPExt) {
7875       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7876       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7877       auto FoldFAddFMAFPExtFMul = [&] (
7878           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7879         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7880                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7881                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7882                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7883                                        Z));
7884       };
7885       if (N0.getOpcode() == PreferredFusedOpcode) {
7886         SDValue N02 = N0.getOperand(2);
7887         if (N02.getOpcode() == ISD::FP_EXTEND) {
7888           SDValue N020 = N02.getOperand(0);
7889           if (N020.getOpcode() == ISD::FMUL)
7890             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7891                                         N020.getOperand(0), N020.getOperand(1),
7892                                         N1);
7893         }
7894       }
7895
7896       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7897       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7898       // FIXME: This turns two single-precision and one double-precision
7899       // operation into two double-precision operations, which might not be
7900       // interesting for all targets, especially GPUs.
7901       auto FoldFAddFPExtFMAFMul = [&] (
7902           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7903         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7904                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7905                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7906                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7907                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7908                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7909                                        Z));
7910       };
7911       if (N0.getOpcode() == ISD::FP_EXTEND) {
7912         SDValue N00 = N0.getOperand(0);
7913         if (N00.getOpcode() == PreferredFusedOpcode) {
7914           SDValue N002 = N00.getOperand(2);
7915           if (N002.getOpcode() == ISD::FMUL)
7916             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7917                                         N002.getOperand(0), N002.getOperand(1),
7918                                         N1);
7919         }
7920       }
7921
7922       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7923       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7924       if (N1.getOpcode() == PreferredFusedOpcode) {
7925         SDValue N12 = N1.getOperand(2);
7926         if (N12.getOpcode() == ISD::FP_EXTEND) {
7927           SDValue N120 = N12.getOperand(0);
7928           if (N120.getOpcode() == ISD::FMUL)
7929             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7930                                         N120.getOperand(0), N120.getOperand(1),
7931                                         N0);
7932         }
7933       }
7934
7935       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7936       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7937       // FIXME: This turns two single-precision and one double-precision
7938       // operation into two double-precision operations, which might not be
7939       // interesting for all targets, especially GPUs.
7940       if (N1.getOpcode() == ISD::FP_EXTEND) {
7941         SDValue N10 = N1.getOperand(0);
7942         if (N10.getOpcode() == PreferredFusedOpcode) {
7943           SDValue N102 = N10.getOperand(2);
7944           if (N102.getOpcode() == ISD::FMUL)
7945             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7946                                         N102.getOperand(0), N102.getOperand(1),
7947                                         N0);
7948         }
7949       }
7950     }
7951   }
7952
7953   return SDValue();
7954 }
7955
7956 /// Try to perform FMA combining on a given FSUB node.
7957 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7958   SDValue N0 = N->getOperand(0);
7959   SDValue N1 = N->getOperand(1);
7960   EVT VT = N->getValueType(0);
7961   SDLoc SL(N);
7962
7963   const TargetOptions &Options = DAG.getTarget().Options;
7964   bool AllowFusion =
7965       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7966
7967   // Floating-point multiply-add with intermediate rounding.
7968   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7969
7970   // Floating-point multiply-add without intermediate rounding.
7971   bool HasFMA =
7972       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7973       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7974
7975   // No valid opcode, do not combine.
7976   if (!HasFMAD && !HasFMA)
7977     return SDValue();
7978
7979   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7980   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7981     return SDValue();
7982
7983   // Always prefer FMAD to FMA for precision.
7984   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7985   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7986   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7987
7988   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7989   if (N0.getOpcode() == ISD::FMUL &&
7990       (Aggressive || N0->hasOneUse())) {
7991     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7992                        N0.getOperand(0), N0.getOperand(1),
7993                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7994   }
7995
7996   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7997   // Note: Commutes FSUB operands.
7998   if (N1.getOpcode() == ISD::FMUL &&
7999       (Aggressive || N1->hasOneUse()))
8000     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8001                        DAG.getNode(ISD::FNEG, SL, VT,
8002                                    N1.getOperand(0)),
8003                        N1.getOperand(1), N0);
8004
8005   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8006   if (N0.getOpcode() == ISD::FNEG &&
8007       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8008       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8009     SDValue N00 = N0.getOperand(0).getOperand(0);
8010     SDValue N01 = N0.getOperand(0).getOperand(1);
8011     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8012                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8013                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8014   }
8015
8016   // Look through FP_EXTEND nodes to do more combining.
8017   if (AllowFusion && LookThroughFPExt) {
8018     // fold (fsub (fpext (fmul x, y)), z)
8019     //   -> (fma (fpext x), (fpext y), (fneg z))
8020     if (N0.getOpcode() == ISD::FP_EXTEND) {
8021       SDValue N00 = N0.getOperand(0);
8022       if (N00.getOpcode() == ISD::FMUL)
8023         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8024                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8025                                        N00.getOperand(0)),
8026                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8027                                        N00.getOperand(1)),
8028                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8029     }
8030
8031     // fold (fsub x, (fpext (fmul y, z)))
8032     //   -> (fma (fneg (fpext y)), (fpext z), x)
8033     // Note: Commutes FSUB operands.
8034     if (N1.getOpcode() == ISD::FP_EXTEND) {
8035       SDValue N10 = N1.getOperand(0);
8036       if (N10.getOpcode() == ISD::FMUL)
8037         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8038                            DAG.getNode(ISD::FNEG, SL, VT,
8039                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8040                                                    N10.getOperand(0))),
8041                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8042                                        N10.getOperand(1)),
8043                            N0);
8044     }
8045
8046     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8047     //   -> (fneg (fma (fpext x), (fpext y), z))
8048     // Note: This could be removed with appropriate canonicalization of the
8049     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8050     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8051     // from implementing the canonicalization in visitFSUB.
8052     if (N0.getOpcode() == ISD::FP_EXTEND) {
8053       SDValue N00 = N0.getOperand(0);
8054       if (N00.getOpcode() == ISD::FNEG) {
8055         SDValue N000 = N00.getOperand(0);
8056         if (N000.getOpcode() == ISD::FMUL) {
8057           return DAG.getNode(ISD::FNEG, SL, VT,
8058                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8059                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8060                                                      N000.getOperand(0)),
8061                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8062                                                      N000.getOperand(1)),
8063                                          N1));
8064         }
8065       }
8066     }
8067
8068     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8069     //   -> (fneg (fma (fpext x)), (fpext y), z)
8070     // Note: This could be removed with appropriate canonicalization of the
8071     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8072     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8073     // from implementing the canonicalization in visitFSUB.
8074     if (N0.getOpcode() == ISD::FNEG) {
8075       SDValue N00 = N0.getOperand(0);
8076       if (N00.getOpcode() == ISD::FP_EXTEND) {
8077         SDValue N000 = N00.getOperand(0);
8078         if (N000.getOpcode() == ISD::FMUL) {
8079           return DAG.getNode(ISD::FNEG, SL, VT,
8080                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8081                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8082                                                      N000.getOperand(0)),
8083                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8084                                                      N000.getOperand(1)),
8085                                          N1));
8086         }
8087       }
8088     }
8089
8090   }
8091
8092   // More folding opportunities when target permits.
8093   if ((AllowFusion || HasFMAD) && Aggressive) {
8094     // fold (fsub (fma x, y, (fmul u, v)), z)
8095     //   -> (fma x, y (fma u, v, (fneg z)))
8096     if (N0.getOpcode() == PreferredFusedOpcode &&
8097         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8098       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8099                          N0.getOperand(0), N0.getOperand(1),
8100                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8101                                      N0.getOperand(2).getOperand(0),
8102                                      N0.getOperand(2).getOperand(1),
8103                                      DAG.getNode(ISD::FNEG, SL, VT,
8104                                                  N1)));
8105     }
8106
8107     // fold (fsub x, (fma y, z, (fmul u, v)))
8108     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8109     if (N1.getOpcode() == PreferredFusedOpcode &&
8110         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8111       SDValue N20 = N1.getOperand(2).getOperand(0);
8112       SDValue N21 = N1.getOperand(2).getOperand(1);
8113       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8114                          DAG.getNode(ISD::FNEG, SL, VT,
8115                                      N1.getOperand(0)),
8116                          N1.getOperand(1),
8117                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8118                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8119
8120                                      N21, N0));
8121     }
8122
8123     if (AllowFusion && LookThroughFPExt) {
8124       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8125       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8126       if (N0.getOpcode() == PreferredFusedOpcode) {
8127         SDValue N02 = N0.getOperand(2);
8128         if (N02.getOpcode() == ISD::FP_EXTEND) {
8129           SDValue N020 = N02.getOperand(0);
8130           if (N020.getOpcode() == ISD::FMUL)
8131             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8132                                N0.getOperand(0), N0.getOperand(1),
8133                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8134                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8135                                                        N020.getOperand(0)),
8136                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8137                                                        N020.getOperand(1)),
8138                                            DAG.getNode(ISD::FNEG, SL, VT,
8139                                                        N1)));
8140         }
8141       }
8142
8143       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8144       //   -> (fma (fpext x), (fpext y),
8145       //           (fma (fpext u), (fpext v), (fneg z)))
8146       // FIXME: This turns two single-precision and one double-precision
8147       // operation into two double-precision operations, which might not be
8148       // interesting for all targets, especially GPUs.
8149       if (N0.getOpcode() == ISD::FP_EXTEND) {
8150         SDValue N00 = N0.getOperand(0);
8151         if (N00.getOpcode() == PreferredFusedOpcode) {
8152           SDValue N002 = N00.getOperand(2);
8153           if (N002.getOpcode() == ISD::FMUL)
8154             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8155                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8156                                            N00.getOperand(0)),
8157                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8158                                            N00.getOperand(1)),
8159                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8160                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8161                                                        N002.getOperand(0)),
8162                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8163                                                        N002.getOperand(1)),
8164                                            DAG.getNode(ISD::FNEG, SL, VT,
8165                                                        N1)));
8166         }
8167       }
8168
8169       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8170       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8171       if (N1.getOpcode() == PreferredFusedOpcode &&
8172         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8173         SDValue N120 = N1.getOperand(2).getOperand(0);
8174         if (N120.getOpcode() == ISD::FMUL) {
8175           SDValue N1200 = N120.getOperand(0);
8176           SDValue N1201 = N120.getOperand(1);
8177           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8178                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8179                              N1.getOperand(1),
8180                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8181                                          DAG.getNode(ISD::FNEG, SL, VT,
8182                                              DAG.getNode(ISD::FP_EXTEND, SL,
8183                                                          VT, N1200)),
8184                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8185                                                      N1201),
8186                                          N0));
8187         }
8188       }
8189
8190       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8191       //   -> (fma (fneg (fpext y)), (fpext z),
8192       //           (fma (fneg (fpext u)), (fpext v), x))
8193       // FIXME: This turns two single-precision and one double-precision
8194       // operation into two double-precision operations, which might not be
8195       // interesting for all targets, especially GPUs.
8196       if (N1.getOpcode() == ISD::FP_EXTEND &&
8197         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8198         SDValue N100 = N1.getOperand(0).getOperand(0);
8199         SDValue N101 = N1.getOperand(0).getOperand(1);
8200         SDValue N102 = N1.getOperand(0).getOperand(2);
8201         if (N102.getOpcode() == ISD::FMUL) {
8202           SDValue N1020 = N102.getOperand(0);
8203           SDValue N1021 = N102.getOperand(1);
8204           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8205                              DAG.getNode(ISD::FNEG, SL, VT,
8206                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8207                                                      N100)),
8208                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8209                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8210                                          DAG.getNode(ISD::FNEG, SL, VT,
8211                                              DAG.getNode(ISD::FP_EXTEND, SL,
8212                                                          VT, N1020)),
8213                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8214                                                      N1021),
8215                                          N0));
8216         }
8217       }
8218     }
8219   }
8220
8221   return SDValue();
8222 }
8223
8224 /// Try to perform FMA combining on a given FMUL node.
8225 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8226   SDValue N0 = N->getOperand(0);
8227   SDValue N1 = N->getOperand(1);
8228   EVT VT = N->getValueType(0);
8229   SDLoc SL(N);
8230
8231   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8232
8233   const TargetOptions &Options = DAG.getTarget().Options;
8234   bool AllowFusion =
8235       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8236
8237   // Floating-point multiply-add with intermediate rounding.
8238   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8239
8240   // Floating-point multiply-add without intermediate rounding.
8241   bool HasFMA =
8242       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8243       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8244
8245   // No valid opcode, do not combine.
8246   if (!HasFMAD && !HasFMA)
8247     return SDValue();
8248
8249   // Always prefer FMAD to FMA for precision.
8250   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8251   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8252
8253   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8254   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8255   auto FuseFADD = [&](SDValue X, SDValue Y) {
8256     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8257       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8258       if (XC1 && XC1->isExactlyValue(+1.0))
8259         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8260       if (XC1 && XC1->isExactlyValue(-1.0))
8261         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8262                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8263     }
8264     return SDValue();
8265   };
8266
8267   if (SDValue FMA = FuseFADD(N0, N1))
8268     return FMA;
8269   if (SDValue FMA = FuseFADD(N1, N0))
8270     return FMA;
8271
8272   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8273   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8274   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8275   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8276   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8277     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8278       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8279       if (XC0 && XC0->isExactlyValue(+1.0))
8280         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8281                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8282                            Y);
8283       if (XC0 && XC0->isExactlyValue(-1.0))
8284         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8285                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8286                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8287
8288       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8289       if (XC1 && XC1->isExactlyValue(+1.0))
8290         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8291                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8292       if (XC1 && XC1->isExactlyValue(-1.0))
8293         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8294     }
8295     return SDValue();
8296   };
8297
8298   if (SDValue FMA = FuseFSUB(N0, N1))
8299     return FMA;
8300   if (SDValue FMA = FuseFSUB(N1, N0))
8301     return FMA;
8302
8303   return SDValue();
8304 }
8305
8306 SDValue DAGCombiner::visitFADD(SDNode *N) {
8307   SDValue N0 = N->getOperand(0);
8308   SDValue N1 = N->getOperand(1);
8309   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8310   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8311   EVT VT = N->getValueType(0);
8312   SDLoc DL(N);
8313   const TargetOptions &Options = DAG.getTarget().Options;
8314   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8315
8316   // fold vector ops
8317   if (VT.isVector())
8318     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8319       return FoldedVOp;
8320
8321   // fold (fadd c1, c2) -> c1 + c2
8322   if (N0CFP && N1CFP)
8323     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8324
8325   // canonicalize constant to RHS
8326   if (N0CFP && !N1CFP)
8327     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8328
8329   // fold (fadd A, (fneg B)) -> (fsub A, B)
8330   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8331       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8332     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8333                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8334
8335   // fold (fadd (fneg A), B) -> (fsub B, A)
8336   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8337       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8338     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8339                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8340
8341   // If 'unsafe math' is enabled, fold lots of things.
8342   if (Options.UnsafeFPMath) {
8343     // No FP constant should be created after legalization as Instruction
8344     // Selection pass has a hard time dealing with FP constants.
8345     bool AllowNewConst = (Level < AfterLegalizeDAG);
8346
8347     // fold (fadd A, 0) -> A
8348     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8349       if (N1C->isZero())
8350         return N0;
8351
8352     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8353     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8354         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8355       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8356                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8357                                      Flags),
8358                          Flags);
8359
8360     // If allowed, fold (fadd (fneg x), x) -> 0.0
8361     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8362       return DAG.getConstantFP(0.0, DL, VT);
8363
8364     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8365     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8366       return DAG.getConstantFP(0.0, DL, VT);
8367
8368     // We can fold chains of FADD's of the same value into multiplications.
8369     // This transform is not safe in general because we are reducing the number
8370     // of rounding steps.
8371     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8372       if (N0.getOpcode() == ISD::FMUL) {
8373         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8374         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8375
8376         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8377         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8378           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8379                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8380           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8381         }
8382
8383         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8384         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8385             N1.getOperand(0) == N1.getOperand(1) &&
8386             N0.getOperand(0) == N1.getOperand(0)) {
8387           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8388                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8389           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8390         }
8391       }
8392
8393       if (N1.getOpcode() == ISD::FMUL) {
8394         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8395         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8396
8397         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8398         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8399           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8400                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8401           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8402         }
8403
8404         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8405         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8406             N0.getOperand(0) == N0.getOperand(1) &&
8407             N1.getOperand(0) == N0.getOperand(0)) {
8408           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8409                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8410           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8411         }
8412       }
8413
8414       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8415         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8416         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8417         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8418             (N0.getOperand(0) == N1)) {
8419           return DAG.getNode(ISD::FMUL, DL, VT,
8420                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8421         }
8422       }
8423
8424       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8425         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8426         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8427         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8428             N1.getOperand(0) == N0) {
8429           return DAG.getNode(ISD::FMUL, DL, VT,
8430                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8431         }
8432       }
8433
8434       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8435       if (AllowNewConst &&
8436           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8437           N0.getOperand(0) == N0.getOperand(1) &&
8438           N1.getOperand(0) == N1.getOperand(1) &&
8439           N0.getOperand(0) == N1.getOperand(0)) {
8440         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8441                            DAG.getConstantFP(4.0, DL, VT), Flags);
8442       }
8443     }
8444   } // enable-unsafe-fp-math
8445
8446   // FADD -> FMA combines:
8447   if (SDValue Fused = visitFADDForFMACombine(N)) {
8448     AddToWorklist(Fused.getNode());
8449     return Fused;
8450   }
8451   return SDValue();
8452 }
8453
8454 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8455   SDValue N0 = N->getOperand(0);
8456   SDValue N1 = N->getOperand(1);
8457   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8458   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8459   EVT VT = N->getValueType(0);
8460   SDLoc dl(N);
8461   const TargetOptions &Options = DAG.getTarget().Options;
8462   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8463
8464   // fold vector ops
8465   if (VT.isVector())
8466     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8467       return FoldedVOp;
8468
8469   // fold (fsub c1, c2) -> c1-c2
8470   if (N0CFP && N1CFP)
8471     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8472
8473   // fold (fsub A, (fneg B)) -> (fadd A, B)
8474   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8475     return DAG.getNode(ISD::FADD, dl, VT, N0,
8476                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8477
8478   // If 'unsafe math' is enabled, fold lots of things.
8479   if (Options.UnsafeFPMath) {
8480     // (fsub A, 0) -> A
8481     if (N1CFP && N1CFP->isZero())
8482       return N0;
8483
8484     // (fsub 0, B) -> -B
8485     if (N0CFP && N0CFP->isZero()) {
8486       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8487         return GetNegatedExpression(N1, DAG, LegalOperations);
8488       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8489         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8490     }
8491
8492     // (fsub x, x) -> 0.0
8493     if (N0 == N1)
8494       return DAG.getConstantFP(0.0f, dl, VT);
8495
8496     // (fsub x, (fadd x, y)) -> (fneg y)
8497     // (fsub x, (fadd y, x)) -> (fneg y)
8498     if (N1.getOpcode() == ISD::FADD) {
8499       SDValue N10 = N1->getOperand(0);
8500       SDValue N11 = N1->getOperand(1);
8501
8502       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8503         return GetNegatedExpression(N11, DAG, LegalOperations);
8504
8505       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8506         return GetNegatedExpression(N10, DAG, LegalOperations);
8507     }
8508   }
8509
8510   // FSUB -> FMA combines:
8511   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8512     AddToWorklist(Fused.getNode());
8513     return Fused;
8514   }
8515
8516   return SDValue();
8517 }
8518
8519 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8520   SDValue N0 = N->getOperand(0);
8521   SDValue N1 = N->getOperand(1);
8522   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8523   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8524   EVT VT = N->getValueType(0);
8525   SDLoc DL(N);
8526   const TargetOptions &Options = DAG.getTarget().Options;
8527   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8528
8529   // fold vector ops
8530   if (VT.isVector()) {
8531     // This just handles C1 * C2 for vectors. Other vector folds are below.
8532     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8533       return FoldedVOp;
8534   }
8535
8536   // fold (fmul c1, c2) -> c1*c2
8537   if (N0CFP && N1CFP)
8538     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8539
8540   // canonicalize constant to RHS
8541   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8542      !isConstantFPBuildVectorOrConstantFP(N1))
8543     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8544
8545   // fold (fmul A, 1.0) -> A
8546   if (N1CFP && N1CFP->isExactlyValue(1.0))
8547     return N0;
8548
8549   if (Options.UnsafeFPMath) {
8550     // fold (fmul A, 0) -> 0
8551     if (N1CFP && N1CFP->isZero())
8552       return N1;
8553
8554     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8555     if (N0.getOpcode() == ISD::FMUL) {
8556       // Fold scalars or any vector constants (not just splats).
8557       // This fold is done in general by InstCombine, but extra fmul insts
8558       // may have been generated during lowering.
8559       SDValue N00 = N0.getOperand(0);
8560       SDValue N01 = N0.getOperand(1);
8561       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8562       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8563       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8564
8565       // Check 1: Make sure that the first operand of the inner multiply is NOT
8566       // a constant. Otherwise, we may induce infinite looping.
8567       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8568         // Check 2: Make sure that the second operand of the inner multiply and
8569         // the second operand of the outer multiply are constants.
8570         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8571             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8572           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8573           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8574         }
8575       }
8576     }
8577
8578     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8579     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8580     // during an early run of DAGCombiner can prevent folding with fmuls
8581     // inserted during lowering.
8582     if (N0.getOpcode() == ISD::FADD &&
8583         (N0.getOperand(0) == N0.getOperand(1)) &&
8584         N0.hasOneUse()) {
8585       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8586       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8587       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8588     }
8589   }
8590
8591   // fold (fmul X, 2.0) -> (fadd X, X)
8592   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8593     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8594
8595   // fold (fmul X, -1.0) -> (fneg X)
8596   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8597     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8598       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8599
8600   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8601   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8602     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8603       // Both can be negated for free, check to see if at least one is cheaper
8604       // negated.
8605       if (LHSNeg == 2 || RHSNeg == 2)
8606         return DAG.getNode(ISD::FMUL, DL, VT,
8607                            GetNegatedExpression(N0, DAG, LegalOperations),
8608                            GetNegatedExpression(N1, DAG, LegalOperations),
8609                            Flags);
8610     }
8611   }
8612
8613   // FMUL -> FMA combines:
8614   if (SDValue Fused = visitFMULForFMACombine(N)) {
8615     AddToWorklist(Fused.getNode());
8616     return Fused;
8617   }
8618
8619   return SDValue();
8620 }
8621
8622 SDValue DAGCombiner::visitFMA(SDNode *N) {
8623   SDValue N0 = N->getOperand(0);
8624   SDValue N1 = N->getOperand(1);
8625   SDValue N2 = N->getOperand(2);
8626   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8627   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8628   EVT VT = N->getValueType(0);
8629   SDLoc dl(N);
8630   const TargetOptions &Options = DAG.getTarget().Options;
8631
8632   // Constant fold FMA.
8633   if (isa<ConstantFPSDNode>(N0) &&
8634       isa<ConstantFPSDNode>(N1) &&
8635       isa<ConstantFPSDNode>(N2)) {
8636     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8637   }
8638
8639   if (Options.UnsafeFPMath) {
8640     if (N0CFP && N0CFP->isZero())
8641       return N2;
8642     if (N1CFP && N1CFP->isZero())
8643       return N2;
8644   }
8645   // TODO: The FMA node should have flags that propagate to these nodes.
8646   if (N0CFP && N0CFP->isExactlyValue(1.0))
8647     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8648   if (N1CFP && N1CFP->isExactlyValue(1.0))
8649     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8650
8651   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8652   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8653      !isConstantFPBuildVectorOrConstantFP(N1))
8654     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8655
8656   // TODO: FMA nodes should have flags that propagate to the created nodes.
8657   // For now, create a Flags object for use with all unsafe math transforms.
8658   SDNodeFlags Flags;
8659   Flags.setUnsafeAlgebra(true);
8660
8661   if (Options.UnsafeFPMath) {
8662     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8663     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8664         isConstantFPBuildVectorOrConstantFP(N1) &&
8665         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8666       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8667                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8668                                      &Flags), &Flags);
8669     }
8670
8671     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8672     if (N0.getOpcode() == ISD::FMUL &&
8673         isConstantFPBuildVectorOrConstantFP(N1) &&
8674         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8675       return DAG.getNode(ISD::FMA, dl, VT,
8676                          N0.getOperand(0),
8677                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8678                                      &Flags),
8679                          N2);
8680     }
8681   }
8682
8683   // (fma x, 1, y) -> (fadd x, y)
8684   // (fma x, -1, y) -> (fadd (fneg x), y)
8685   if (N1CFP) {
8686     if (N1CFP->isExactlyValue(1.0))
8687       // TODO: The FMA node should have flags that propagate to this node.
8688       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8689
8690     if (N1CFP->isExactlyValue(-1.0) &&
8691         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8692       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8693       AddToWorklist(RHSNeg.getNode());
8694       // TODO: The FMA node should have flags that propagate to this node.
8695       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8696     }
8697   }
8698
8699   if (Options.UnsafeFPMath) {
8700     // (fma x, c, x) -> (fmul x, (c+1))
8701     if (N1CFP && N0 == N2) {
8702     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8703                          DAG.getNode(ISD::FADD, dl, VT,
8704                                      N1, DAG.getConstantFP(1.0, dl, VT),
8705                                      &Flags), &Flags);
8706     }
8707
8708     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8709     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8710       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8711                          DAG.getNode(ISD::FADD, dl, VT,
8712                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8713                                      &Flags), &Flags);
8714     }
8715   }
8716
8717   return SDValue();
8718 }
8719
8720 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8721 // reciprocal.
8722 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8723 // Notice that this is not always beneficial. One reason is different target
8724 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8725 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8726 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8727 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8728   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8729   const SDNodeFlags *Flags = N->getFlags();
8730   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8731     return SDValue();
8732
8733   // Skip if current node is a reciprocal.
8734   SDValue N0 = N->getOperand(0);
8735   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8736   if (N0CFP && N0CFP->isExactlyValue(1.0))
8737     return SDValue();
8738
8739   // Exit early if the target does not want this transform or if there can't
8740   // possibly be enough uses of the divisor to make the transform worthwhile.
8741   SDValue N1 = N->getOperand(1);
8742   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8743   if (!MinUses || N1->use_size() < MinUses)
8744     return SDValue();
8745
8746   // Find all FDIV users of the same divisor.
8747   // Use a set because duplicates may be present in the user list.
8748   SetVector<SDNode *> Users;
8749   for (auto *U : N1->uses()) {
8750     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8751       // This division is eligible for optimization only if global unsafe math
8752       // is enabled or if this division allows reciprocal formation.
8753       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8754         Users.insert(U);
8755     }
8756   }
8757
8758   // Now that we have the actual number of divisor uses, make sure it meets
8759   // the minimum threshold specified by the target.
8760   if (Users.size() < MinUses)
8761     return SDValue();
8762
8763   EVT VT = N->getValueType(0);
8764   SDLoc DL(N);
8765   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8766   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8767
8768   // Dividend / Divisor -> Dividend * Reciprocal
8769   for (auto *U : Users) {
8770     SDValue Dividend = U->getOperand(0);
8771     if (Dividend != FPOne) {
8772       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8773                                     Reciprocal, Flags);
8774       CombineTo(U, NewNode);
8775     } else if (U != Reciprocal.getNode()) {
8776       // In the absence of fast-math-flags, this user node is always the
8777       // same node as Reciprocal, but with FMF they may be different nodes.
8778       CombineTo(U, Reciprocal);
8779     }
8780   }
8781   return SDValue(N, 0);  // N was replaced.
8782 }
8783
8784 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8785   SDValue N0 = N->getOperand(0);
8786   SDValue N1 = N->getOperand(1);
8787   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8788   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8789   EVT VT = N->getValueType(0);
8790   SDLoc DL(N);
8791   const TargetOptions &Options = DAG.getTarget().Options;
8792   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8793
8794   // fold vector ops
8795   if (VT.isVector())
8796     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8797       return FoldedVOp;
8798
8799   // fold (fdiv c1, c2) -> c1/c2
8800   if (N0CFP && N1CFP)
8801     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8802
8803   if (Options.UnsafeFPMath) {
8804     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8805     if (N1CFP) {
8806       // Compute the reciprocal 1.0 / c2.
8807       const APFloat &N1APF = N1CFP->getValueAPF();
8808       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8809       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8810       // Only do the transform if the reciprocal is a legal fp immediate that
8811       // isn't too nasty (eg NaN, denormal, ...).
8812       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8813           (!LegalOperations ||
8814            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8815            // backend)... we should handle this gracefully after Legalize.
8816            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8817            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8818            TLI.isFPImmLegal(Recip, VT)))
8819         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8820                            DAG.getConstantFP(Recip, DL, VT), Flags);
8821     }
8822
8823     // If this FDIV is part of a reciprocal square root, it may be folded
8824     // into a target-specific square root estimate instruction.
8825     if (N1.getOpcode() == ISD::FSQRT) {
8826       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8827         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8828       }
8829     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8830                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8831       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8832                                           Flags)) {
8833         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8834         AddToWorklist(RV.getNode());
8835         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8836       }
8837     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8838                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8839       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8840                                           Flags)) {
8841         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8842         AddToWorklist(RV.getNode());
8843         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8844       }
8845     } else if (N1.getOpcode() == ISD::FMUL) {
8846       // Look through an FMUL. Even though this won't remove the FDIV directly,
8847       // it's still worthwhile to get rid of the FSQRT if possible.
8848       SDValue SqrtOp;
8849       SDValue OtherOp;
8850       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8851         SqrtOp = N1.getOperand(0);
8852         OtherOp = N1.getOperand(1);
8853       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8854         SqrtOp = N1.getOperand(1);
8855         OtherOp = N1.getOperand(0);
8856       }
8857       if (SqrtOp.getNode()) {
8858         // We found a FSQRT, so try to make this fold:
8859         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8860         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8861           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8862           AddToWorklist(RV.getNode());
8863           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8864         }
8865       }
8866     }
8867
8868     // Fold into a reciprocal estimate and multiply instead of a real divide.
8869     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8870       AddToWorklist(RV.getNode());
8871       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8872     }
8873   }
8874
8875   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8876   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8877     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8878       // Both can be negated for free, check to see if at least one is cheaper
8879       // negated.
8880       if (LHSNeg == 2 || RHSNeg == 2)
8881         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8882                            GetNegatedExpression(N0, DAG, LegalOperations),
8883                            GetNegatedExpression(N1, DAG, LegalOperations),
8884                            Flags);
8885     }
8886   }
8887
8888   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8889     return CombineRepeatedDivisors;
8890
8891   return SDValue();
8892 }
8893
8894 SDValue DAGCombiner::visitFREM(SDNode *N) {
8895   SDValue N0 = N->getOperand(0);
8896   SDValue N1 = N->getOperand(1);
8897   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8898   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8899   EVT VT = N->getValueType(0);
8900
8901   // fold (frem c1, c2) -> fmod(c1,c2)
8902   if (N0CFP && N1CFP)
8903     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8904                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8905
8906   return SDValue();
8907 }
8908
8909 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8910   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8911     return SDValue();
8912
8913   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8914   // For now, create a Flags object for use with all unsafe math transforms.
8915   SDNodeFlags Flags;
8916   Flags.setUnsafeAlgebra(true);
8917   return buildSqrtEstimate(N->getOperand(0), &Flags);
8918 }
8919
8920 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8921 /// copysign(x, fp_round(y)) -> copysign(x, y)
8922 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8923   SDValue N1 = N->getOperand(1);
8924   if ((N1.getOpcode() == ISD::FP_EXTEND ||
8925        N1.getOpcode() == ISD::FP_ROUND)) {
8926     // Do not optimize out type conversion of f128 type yet.
8927     // For some targets like x86_64, configuration is changed to keep one f128
8928     // value in one SSE register, but instruction selection cannot handle
8929     // FCOPYSIGN on SSE registers yet.
8930     EVT N1VT = N1->getValueType(0);
8931     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8932     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8933   }
8934   return false;
8935 }
8936
8937 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8938   SDValue N0 = N->getOperand(0);
8939   SDValue N1 = N->getOperand(1);
8940   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8941   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8942   EVT VT = N->getValueType(0);
8943
8944   if (N0CFP && N1CFP)  // Constant fold
8945     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8946
8947   if (N1CFP) {
8948     const APFloat& V = N1CFP->getValueAPF();
8949     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8950     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8951     if (!V.isNegative()) {
8952       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8953         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8954     } else {
8955       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8956         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8957                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8958     }
8959   }
8960
8961   // copysign(fabs(x), y) -> copysign(x, y)
8962   // copysign(fneg(x), y) -> copysign(x, y)
8963   // copysign(copysign(x,z), y) -> copysign(x, y)
8964   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8965       N0.getOpcode() == ISD::FCOPYSIGN)
8966     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8967                        N0.getOperand(0), N1);
8968
8969   // copysign(x, abs(y)) -> abs(x)
8970   if (N1.getOpcode() == ISD::FABS)
8971     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8972
8973   // copysign(x, copysign(y,z)) -> copysign(x, z)
8974   if (N1.getOpcode() == ISD::FCOPYSIGN)
8975     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8976                        N0, N1.getOperand(1));
8977
8978   // copysign(x, fp_extend(y)) -> copysign(x, y)
8979   // copysign(x, fp_round(y)) -> copysign(x, y)
8980   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8981     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8982                        N0, N1.getOperand(0));
8983
8984   return SDValue();
8985 }
8986
8987 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8988   SDValue N0 = N->getOperand(0);
8989   EVT VT = N->getValueType(0);
8990   EVT OpVT = N0.getValueType();
8991
8992   // fold (sint_to_fp c1) -> c1fp
8993   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
8994       // ...but only if the target supports immediate floating-point values
8995       (!LegalOperations ||
8996        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8997     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8998
8999   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9000   // but UINT_TO_FP is legal on this target, try to convert.
9001   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9002       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9003     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9004     if (DAG.SignBitIsZero(N0))
9005       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9006   }
9007
9008   // The next optimizations are desirable only if SELECT_CC can be lowered.
9009   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9010     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9011     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9012         !VT.isVector() &&
9013         (!LegalOperations ||
9014          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9015       SDLoc DL(N);
9016       SDValue Ops[] =
9017         { N0.getOperand(0), N0.getOperand(1),
9018           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9019           N0.getOperand(2) };
9020       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9021     }
9022
9023     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9024     //      (select_cc x, y, 1.0, 0.0,, cc)
9025     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9026         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9027         (!LegalOperations ||
9028          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9029       SDLoc DL(N);
9030       SDValue Ops[] =
9031         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9032           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9033           N0.getOperand(0).getOperand(2) };
9034       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9035     }
9036   }
9037
9038   return SDValue();
9039 }
9040
9041 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9042   SDValue N0 = N->getOperand(0);
9043   EVT VT = N->getValueType(0);
9044   EVT OpVT = N0.getValueType();
9045
9046   // fold (uint_to_fp c1) -> c1fp
9047   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9048       // ...but only if the target supports immediate floating-point values
9049       (!LegalOperations ||
9050        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9051     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9052
9053   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9054   // but SINT_TO_FP is legal on this target, try to convert.
9055   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9056       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9057     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9058     if (DAG.SignBitIsZero(N0))
9059       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9060   }
9061
9062   // The next optimizations are desirable only if SELECT_CC can be lowered.
9063   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9064     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9065
9066     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9067         (!LegalOperations ||
9068          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9069       SDLoc DL(N);
9070       SDValue Ops[] =
9071         { N0.getOperand(0), N0.getOperand(1),
9072           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9073           N0.getOperand(2) };
9074       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9075     }
9076   }
9077
9078   return SDValue();
9079 }
9080
9081 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9082 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9083   SDValue N0 = N->getOperand(0);
9084   EVT VT = N->getValueType(0);
9085
9086   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9087     return SDValue();
9088
9089   SDValue Src = N0.getOperand(0);
9090   EVT SrcVT = Src.getValueType();
9091   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9092   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9093
9094   // We can safely assume the conversion won't overflow the output range,
9095   // because (for example) (uint8_t)18293.f is undefined behavior.
9096
9097   // Since we can assume the conversion won't overflow, our decision as to
9098   // whether the input will fit in the float should depend on the minimum
9099   // of the input range and output range.
9100
9101   // This means this is also safe for a signed input and unsigned output, since
9102   // a negative input would lead to undefined behavior.
9103   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9104   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9105   unsigned ActualSize = std::min(InputSize, OutputSize);
9106   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9107
9108   // We can only fold away the float conversion if the input range can be
9109   // represented exactly in the float range.
9110   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9111     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9112       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9113                                                        : ISD::ZERO_EXTEND;
9114       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9115     }
9116     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9117       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9118     return DAG.getBitcast(VT, Src);
9119   }
9120   return SDValue();
9121 }
9122
9123 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9124   SDValue N0 = N->getOperand(0);
9125   EVT VT = N->getValueType(0);
9126
9127   // fold (fp_to_sint c1fp) -> c1
9128   if (isConstantFPBuildVectorOrConstantFP(N0))
9129     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9130
9131   return FoldIntToFPToInt(N, DAG);
9132 }
9133
9134 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9135   SDValue N0 = N->getOperand(0);
9136   EVT VT = N->getValueType(0);
9137
9138   // fold (fp_to_uint c1fp) -> c1
9139   if (isConstantFPBuildVectorOrConstantFP(N0))
9140     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9141
9142   return FoldIntToFPToInt(N, DAG);
9143 }
9144
9145 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9146   SDValue N0 = N->getOperand(0);
9147   SDValue N1 = N->getOperand(1);
9148   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9149   EVT VT = N->getValueType(0);
9150
9151   // fold (fp_round c1fp) -> c1fp
9152   if (N0CFP)
9153     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9154
9155   // fold (fp_round (fp_extend x)) -> x
9156   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9157     return N0.getOperand(0);
9158
9159   // fold (fp_round (fp_round x)) -> (fp_round x)
9160   if (N0.getOpcode() == ISD::FP_ROUND) {
9161     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9162     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9163
9164     // Skip this folding if it results in an fp_round from f80 to f16.
9165     //
9166     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9167     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9168     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9169     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9170     // x86.
9171     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9172       return SDValue();
9173
9174     // If the first fp_round isn't a value preserving truncation, it might
9175     // introduce a tie in the second fp_round, that wouldn't occur in the
9176     // single-step fp_round we want to fold to.
9177     // In other words, double rounding isn't the same as rounding.
9178     // Also, this is a value preserving truncation iff both fp_round's are.
9179     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9180       SDLoc DL(N);
9181       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9182                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9183     }
9184   }
9185
9186   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9187   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9188     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9189                               N0.getOperand(0), N1);
9190     AddToWorklist(Tmp.getNode());
9191     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9192                        Tmp, N0.getOperand(1));
9193   }
9194
9195   return SDValue();
9196 }
9197
9198 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9199   SDValue N0 = N->getOperand(0);
9200   EVT VT = N->getValueType(0);
9201   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9202   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9203
9204   // fold (fp_round_inreg c1fp) -> c1fp
9205   if (N0CFP && isTypeLegal(EVT)) {
9206     SDLoc DL(N);
9207     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9208     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9209   }
9210
9211   return SDValue();
9212 }
9213
9214 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9215   SDValue N0 = N->getOperand(0);
9216   EVT VT = N->getValueType(0);
9217
9218   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9219   if (N->hasOneUse() &&
9220       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9221     return SDValue();
9222
9223   // fold (fp_extend c1fp) -> c1fp
9224   if (isConstantFPBuildVectorOrConstantFP(N0))
9225     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9226
9227   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9228   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9229       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9230     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9231
9232   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9233   // value of X.
9234   if (N0.getOpcode() == ISD::FP_ROUND
9235       && N0.getNode()->getConstantOperandVal(1) == 1) {
9236     SDValue In = N0.getOperand(0);
9237     if (In.getValueType() == VT) return In;
9238     if (VT.bitsLT(In.getValueType()))
9239       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9240                          In, N0.getOperand(1));
9241     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9242   }
9243
9244   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9245   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9246        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9247     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9248     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9249                                      LN0->getChain(),
9250                                      LN0->getBasePtr(), N0.getValueType(),
9251                                      LN0->getMemOperand());
9252     CombineTo(N, ExtLoad);
9253     CombineTo(N0.getNode(),
9254               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9255                           N0.getValueType(), ExtLoad,
9256                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9257               ExtLoad.getValue(1));
9258     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9259   }
9260
9261   return SDValue();
9262 }
9263
9264 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9265   SDValue N0 = N->getOperand(0);
9266   EVT VT = N->getValueType(0);
9267
9268   // fold (fceil c1) -> fceil(c1)
9269   if (isConstantFPBuildVectorOrConstantFP(N0))
9270     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9271
9272   return SDValue();
9273 }
9274
9275 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9276   SDValue N0 = N->getOperand(0);
9277   EVT VT = N->getValueType(0);
9278
9279   // fold (ftrunc c1) -> ftrunc(c1)
9280   if (isConstantFPBuildVectorOrConstantFP(N0))
9281     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9282
9283   return SDValue();
9284 }
9285
9286 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9287   SDValue N0 = N->getOperand(0);
9288   EVT VT = N->getValueType(0);
9289
9290   // fold (ffloor c1) -> ffloor(c1)
9291   if (isConstantFPBuildVectorOrConstantFP(N0))
9292     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9293
9294   return SDValue();
9295 }
9296
9297 // FIXME: FNEG and FABS have a lot in common; refactor.
9298 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9299   SDValue N0 = N->getOperand(0);
9300   EVT VT = N->getValueType(0);
9301
9302   // Constant fold FNEG.
9303   if (isConstantFPBuildVectorOrConstantFP(N0))
9304     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9305
9306   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9307                          &DAG.getTarget().Options))
9308     return GetNegatedExpression(N0, DAG, LegalOperations);
9309
9310   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9311   // constant pool values.
9312   if (!TLI.isFNegFree(VT) &&
9313       N0.getOpcode() == ISD::BITCAST &&
9314       N0.getNode()->hasOneUse()) {
9315     SDValue Int = N0.getOperand(0);
9316     EVT IntVT = Int.getValueType();
9317     if (IntVT.isInteger() && !IntVT.isVector()) {
9318       APInt SignMask;
9319       if (N0.getValueType().isVector()) {
9320         // For a vector, get a mask such as 0x80... per scalar element
9321         // and splat it.
9322         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9323         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9324       } else {
9325         // For a scalar, just generate 0x80...
9326         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9327       }
9328       SDLoc DL0(N0);
9329       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9330                         DAG.getConstant(SignMask, DL0, IntVT));
9331       AddToWorklist(Int.getNode());
9332       return DAG.getBitcast(VT, Int);
9333     }
9334   }
9335
9336   // (fneg (fmul c, x)) -> (fmul -c, x)
9337   if (N0.getOpcode() == ISD::FMUL &&
9338       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9339     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9340     if (CFP1) {
9341       APFloat CVal = CFP1->getValueAPF();
9342       CVal.changeSign();
9343       if (Level >= AfterLegalizeDAG &&
9344           (TLI.isFPImmLegal(CVal, VT) ||
9345            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9346         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9347                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9348                                        N0.getOperand(1)),
9349                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9350     }
9351   }
9352
9353   return SDValue();
9354 }
9355
9356 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9357   SDValue N0 = N->getOperand(0);
9358   SDValue N1 = N->getOperand(1);
9359   EVT VT = N->getValueType(0);
9360   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9361   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9362
9363   if (N0CFP && N1CFP) {
9364     const APFloat &C0 = N0CFP->getValueAPF();
9365     const APFloat &C1 = N1CFP->getValueAPF();
9366     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9367   }
9368
9369   // Canonicalize to constant on RHS.
9370   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9371      !isConstantFPBuildVectorOrConstantFP(N1))
9372     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9373
9374   return SDValue();
9375 }
9376
9377 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9378   SDValue N0 = N->getOperand(0);
9379   SDValue N1 = N->getOperand(1);
9380   EVT VT = N->getValueType(0);
9381   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9382   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9383
9384   if (N0CFP && N1CFP) {
9385     const APFloat &C0 = N0CFP->getValueAPF();
9386     const APFloat &C1 = N1CFP->getValueAPF();
9387     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9388   }
9389
9390   // Canonicalize to constant on RHS.
9391   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9392      !isConstantFPBuildVectorOrConstantFP(N1))
9393     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9394
9395   return SDValue();
9396 }
9397
9398 SDValue DAGCombiner::visitFABS(SDNode *N) {
9399   SDValue N0 = N->getOperand(0);
9400   EVT VT = N->getValueType(0);
9401
9402   // fold (fabs c1) -> fabs(c1)
9403   if (isConstantFPBuildVectorOrConstantFP(N0))
9404     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9405
9406   // fold (fabs (fabs x)) -> (fabs x)
9407   if (N0.getOpcode() == ISD::FABS)
9408     return N->getOperand(0);
9409
9410   // fold (fabs (fneg x)) -> (fabs x)
9411   // fold (fabs (fcopysign x, y)) -> (fabs x)
9412   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9413     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9414
9415   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9416   // constant pool values.
9417   if (!TLI.isFAbsFree(VT) &&
9418       N0.getOpcode() == ISD::BITCAST &&
9419       N0.getNode()->hasOneUse()) {
9420     SDValue Int = N0.getOperand(0);
9421     EVT IntVT = Int.getValueType();
9422     if (IntVT.isInteger() && !IntVT.isVector()) {
9423       APInt SignMask;
9424       if (N0.getValueType().isVector()) {
9425         // For a vector, get a mask such as 0x7f... per scalar element
9426         // and splat it.
9427         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9428         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9429       } else {
9430         // For a scalar, just generate 0x7f...
9431         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9432       }
9433       SDLoc DL(N0);
9434       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9435                         DAG.getConstant(SignMask, DL, IntVT));
9436       AddToWorklist(Int.getNode());
9437       return DAG.getBitcast(N->getValueType(0), Int);
9438     }
9439   }
9440
9441   return SDValue();
9442 }
9443
9444 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9445   SDValue Chain = N->getOperand(0);
9446   SDValue N1 = N->getOperand(1);
9447   SDValue N2 = N->getOperand(2);
9448
9449   // If N is a constant we could fold this into a fallthrough or unconditional
9450   // branch. However that doesn't happen very often in normal code, because
9451   // Instcombine/SimplifyCFG should have handled the available opportunities.
9452   // If we did this folding here, it would be necessary to update the
9453   // MachineBasicBlock CFG, which is awkward.
9454
9455   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9456   // on the target.
9457   if (N1.getOpcode() == ISD::SETCC &&
9458       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9459                                    N1.getOperand(0).getValueType())) {
9460     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9461                        Chain, N1.getOperand(2),
9462                        N1.getOperand(0), N1.getOperand(1), N2);
9463   }
9464
9465   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9466       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9467        (N1.getOperand(0).hasOneUse() &&
9468         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9469     SDNode *Trunc = nullptr;
9470     if (N1.getOpcode() == ISD::TRUNCATE) {
9471       // Look pass the truncate.
9472       Trunc = N1.getNode();
9473       N1 = N1.getOperand(0);
9474     }
9475
9476     // Match this pattern so that we can generate simpler code:
9477     //
9478     //   %a = ...
9479     //   %b = and i32 %a, 2
9480     //   %c = srl i32 %b, 1
9481     //   brcond i32 %c ...
9482     //
9483     // into
9484     //
9485     //   %a = ...
9486     //   %b = and i32 %a, 2
9487     //   %c = setcc eq %b, 0
9488     //   brcond %c ...
9489     //
9490     // This applies only when the AND constant value has one bit set and the
9491     // SRL constant is equal to the log2 of the AND constant. The back-end is
9492     // smart enough to convert the result into a TEST/JMP sequence.
9493     SDValue Op0 = N1.getOperand(0);
9494     SDValue Op1 = N1.getOperand(1);
9495
9496     if (Op0.getOpcode() == ISD::AND &&
9497         Op1.getOpcode() == ISD::Constant) {
9498       SDValue AndOp1 = Op0.getOperand(1);
9499
9500       if (AndOp1.getOpcode() == ISD::Constant) {
9501         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9502
9503         if (AndConst.isPowerOf2() &&
9504             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9505           SDLoc DL(N);
9506           SDValue SetCC =
9507             DAG.getSetCC(DL,
9508                          getSetCCResultType(Op0.getValueType()),
9509                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9510                          ISD::SETNE);
9511
9512           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9513                                           MVT::Other, Chain, SetCC, N2);
9514           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9515           // will convert it back to (X & C1) >> C2.
9516           CombineTo(N, NewBRCond, false);
9517           // Truncate is dead.
9518           if (Trunc)
9519             deleteAndRecombine(Trunc);
9520           // Replace the uses of SRL with SETCC
9521           WorklistRemover DeadNodes(*this);
9522           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9523           deleteAndRecombine(N1.getNode());
9524           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9525         }
9526       }
9527     }
9528
9529     if (Trunc)
9530       // Restore N1 if the above transformation doesn't match.
9531       N1 = N->getOperand(1);
9532   }
9533
9534   // Transform br(xor(x, y)) -> br(x != y)
9535   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9536   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9537     SDNode *TheXor = N1.getNode();
9538     SDValue Op0 = TheXor->getOperand(0);
9539     SDValue Op1 = TheXor->getOperand(1);
9540     if (Op0.getOpcode() == Op1.getOpcode()) {
9541       // Avoid missing important xor optimizations.
9542       if (SDValue Tmp = visitXOR(TheXor)) {
9543         if (Tmp.getNode() != TheXor) {
9544           DEBUG(dbgs() << "\nReplacing.8 ";
9545                 TheXor->dump(&DAG);
9546                 dbgs() << "\nWith: ";
9547                 Tmp.getNode()->dump(&DAG);
9548                 dbgs() << '\n');
9549           WorklistRemover DeadNodes(*this);
9550           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9551           deleteAndRecombine(TheXor);
9552           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9553                              MVT::Other, Chain, Tmp, N2);
9554         }
9555
9556         // visitXOR has changed XOR's operands or replaced the XOR completely,
9557         // bail out.
9558         return SDValue(N, 0);
9559       }
9560     }
9561
9562     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9563       bool Equal = false;
9564       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9565           Op0.getOpcode() == ISD::XOR) {
9566         TheXor = Op0.getNode();
9567         Equal = true;
9568       }
9569
9570       EVT SetCCVT = N1.getValueType();
9571       if (LegalTypes)
9572         SetCCVT = getSetCCResultType(SetCCVT);
9573       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9574                                    SetCCVT,
9575                                    Op0, Op1,
9576                                    Equal ? ISD::SETEQ : ISD::SETNE);
9577       // Replace the uses of XOR with SETCC
9578       WorklistRemover DeadNodes(*this);
9579       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9580       deleteAndRecombine(N1.getNode());
9581       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9582                          MVT::Other, Chain, SetCC, N2);
9583     }
9584   }
9585
9586   return SDValue();
9587 }
9588
9589 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9590 //
9591 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9592   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9593   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9594
9595   // If N is a constant we could fold this into a fallthrough or unconditional
9596   // branch. However that doesn't happen very often in normal code, because
9597   // Instcombine/SimplifyCFG should have handled the available opportunities.
9598   // If we did this folding here, it would be necessary to update the
9599   // MachineBasicBlock CFG, which is awkward.
9600
9601   // Use SimplifySetCC to simplify SETCC's.
9602   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9603                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9604                                false);
9605   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9606
9607   // fold to a simpler setcc
9608   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9609     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9610                        N->getOperand(0), Simp.getOperand(2),
9611                        Simp.getOperand(0), Simp.getOperand(1),
9612                        N->getOperand(4));
9613
9614   return SDValue();
9615 }
9616
9617 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9618 /// and that N may be folded in the load / store addressing mode.
9619 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9620                                     SelectionDAG &DAG,
9621                                     const TargetLowering &TLI) {
9622   EVT VT;
9623   unsigned AS;
9624
9625   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9626     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9627       return false;
9628     VT = LD->getMemoryVT();
9629     AS = LD->getAddressSpace();
9630   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9631     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9632       return false;
9633     VT = ST->getMemoryVT();
9634     AS = ST->getAddressSpace();
9635   } else
9636     return false;
9637
9638   TargetLowering::AddrMode AM;
9639   if (N->getOpcode() == ISD::ADD) {
9640     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9641     if (Offset)
9642       // [reg +/- imm]
9643       AM.BaseOffs = Offset->getSExtValue();
9644     else
9645       // [reg +/- reg]
9646       AM.Scale = 1;
9647   } else if (N->getOpcode() == ISD::SUB) {
9648     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9649     if (Offset)
9650       // [reg +/- imm]
9651       AM.BaseOffs = -Offset->getSExtValue();
9652     else
9653       // [reg +/- reg]
9654       AM.Scale = 1;
9655   } else
9656     return false;
9657
9658   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9659                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9660 }
9661
9662 /// Try turning a load/store into a pre-indexed load/store when the base
9663 /// pointer is an add or subtract and it has other uses besides the load/store.
9664 /// After the transformation, the new indexed load/store has effectively folded
9665 /// the add/subtract in and all of its other uses are redirected to the
9666 /// new load/store.
9667 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9668   if (Level < AfterLegalizeDAG)
9669     return false;
9670
9671   bool isLoad = true;
9672   SDValue Ptr;
9673   EVT VT;
9674   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9675     if (LD->isIndexed())
9676       return false;
9677     VT = LD->getMemoryVT();
9678     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9679         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9680       return false;
9681     Ptr = LD->getBasePtr();
9682   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9683     if (ST->isIndexed())
9684       return false;
9685     VT = ST->getMemoryVT();
9686     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9687         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9688       return false;
9689     Ptr = ST->getBasePtr();
9690     isLoad = false;
9691   } else {
9692     return false;
9693   }
9694
9695   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9696   // out.  There is no reason to make this a preinc/predec.
9697   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9698       Ptr.getNode()->hasOneUse())
9699     return false;
9700
9701   // Ask the target to do addressing mode selection.
9702   SDValue BasePtr;
9703   SDValue Offset;
9704   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9705   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9706     return false;
9707
9708   // Backends without true r+i pre-indexed forms may need to pass a
9709   // constant base with a variable offset so that constant coercion
9710   // will work with the patterns in canonical form.
9711   bool Swapped = false;
9712   if (isa<ConstantSDNode>(BasePtr)) {
9713     std::swap(BasePtr, Offset);
9714     Swapped = true;
9715   }
9716
9717   // Don't create a indexed load / store with zero offset.
9718   if (isNullConstant(Offset))
9719     return false;
9720
9721   // Try turning it into a pre-indexed load / store except when:
9722   // 1) The new base ptr is a frame index.
9723   // 2) If N is a store and the new base ptr is either the same as or is a
9724   //    predecessor of the value being stored.
9725   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9726   //    that would create a cycle.
9727   // 4) All uses are load / store ops that use it as old base ptr.
9728
9729   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9730   // (plus the implicit offset) to a register to preinc anyway.
9731   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9732     return false;
9733
9734   // Check #2.
9735   if (!isLoad) {
9736     SDValue Val = cast<StoreSDNode>(N)->getValue();
9737     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9738       return false;
9739   }
9740
9741   // Caches for hasPredecessorHelper.
9742   SmallPtrSet<const SDNode *, 32> Visited;
9743   SmallVector<const SDNode *, 16> Worklist;
9744   Worklist.push_back(N);
9745
9746   // If the offset is a constant, there may be other adds of constants that
9747   // can be folded with this one. We should do this to avoid having to keep
9748   // a copy of the original base pointer.
9749   SmallVector<SDNode *, 16> OtherUses;
9750   if (isa<ConstantSDNode>(Offset))
9751     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9752                               UE = BasePtr.getNode()->use_end();
9753          UI != UE; ++UI) {
9754       SDUse &Use = UI.getUse();
9755       // Skip the use that is Ptr and uses of other results from BasePtr's
9756       // node (important for nodes that return multiple results).
9757       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9758         continue;
9759
9760       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9761         continue;
9762
9763       if (Use.getUser()->getOpcode() != ISD::ADD &&
9764           Use.getUser()->getOpcode() != ISD::SUB) {
9765         OtherUses.clear();
9766         break;
9767       }
9768
9769       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9770       if (!isa<ConstantSDNode>(Op1)) {
9771         OtherUses.clear();
9772         break;
9773       }
9774
9775       // FIXME: In some cases, we can be smarter about this.
9776       if (Op1.getValueType() != Offset.getValueType()) {
9777         OtherUses.clear();
9778         break;
9779       }
9780
9781       OtherUses.push_back(Use.getUser());
9782     }
9783
9784   if (Swapped)
9785     std::swap(BasePtr, Offset);
9786
9787   // Now check for #3 and #4.
9788   bool RealUse = false;
9789
9790   for (SDNode *Use : Ptr.getNode()->uses()) {
9791     if (Use == N)
9792       continue;
9793     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9794       return false;
9795
9796     // If Ptr may be folded in addressing mode of other use, then it's
9797     // not profitable to do this transformation.
9798     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9799       RealUse = true;
9800   }
9801
9802   if (!RealUse)
9803     return false;
9804
9805   SDValue Result;
9806   if (isLoad)
9807     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9808                                 BasePtr, Offset, AM);
9809   else
9810     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9811                                  BasePtr, Offset, AM);
9812   ++PreIndexedNodes;
9813   ++NodesCombined;
9814   DEBUG(dbgs() << "\nReplacing.4 ";
9815         N->dump(&DAG);
9816         dbgs() << "\nWith: ";
9817         Result.getNode()->dump(&DAG);
9818         dbgs() << '\n');
9819   WorklistRemover DeadNodes(*this);
9820   if (isLoad) {
9821     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9822     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9823   } else {
9824     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9825   }
9826
9827   // Finally, since the node is now dead, remove it from the graph.
9828   deleteAndRecombine(N);
9829
9830   if (Swapped)
9831     std::swap(BasePtr, Offset);
9832
9833   // Replace other uses of BasePtr that can be updated to use Ptr
9834   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9835     unsigned OffsetIdx = 1;
9836     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9837       OffsetIdx = 0;
9838     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9839            BasePtr.getNode() && "Expected BasePtr operand");
9840
9841     // We need to replace ptr0 in the following expression:
9842     //   x0 * offset0 + y0 * ptr0 = t0
9843     // knowing that
9844     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9845     //
9846     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9847     // indexed load/store and the expresion that needs to be re-written.
9848     //
9849     // Therefore, we have:
9850     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9851
9852     ConstantSDNode *CN =
9853       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9854     int X0, X1, Y0, Y1;
9855     const APInt &Offset0 = CN->getAPIntValue();
9856     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9857
9858     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9859     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9860     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9861     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9862
9863     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9864
9865     APInt CNV = Offset0;
9866     if (X0 < 0) CNV = -CNV;
9867     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9868     else CNV = CNV - Offset1;
9869
9870     SDLoc DL(OtherUses[i]);
9871
9872     // We can now generate the new expression.
9873     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9874     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9875
9876     SDValue NewUse = DAG.getNode(Opcode,
9877                                  DL,
9878                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9879     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9880     deleteAndRecombine(OtherUses[i]);
9881   }
9882
9883   // Replace the uses of Ptr with uses of the updated base value.
9884   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9885   deleteAndRecombine(Ptr.getNode());
9886
9887   return true;
9888 }
9889
9890 /// Try to combine a load/store with a add/sub of the base pointer node into a
9891 /// post-indexed load/store. The transformation folded the add/subtract into the
9892 /// new indexed load/store effectively and all of its uses are redirected to the
9893 /// new load/store.
9894 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9895   if (Level < AfterLegalizeDAG)
9896     return false;
9897
9898   bool isLoad = true;
9899   SDValue Ptr;
9900   EVT VT;
9901   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9902     if (LD->isIndexed())
9903       return false;
9904     VT = LD->getMemoryVT();
9905     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9906         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9907       return false;
9908     Ptr = LD->getBasePtr();
9909   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9910     if (ST->isIndexed())
9911       return false;
9912     VT = ST->getMemoryVT();
9913     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9914         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9915       return false;
9916     Ptr = ST->getBasePtr();
9917     isLoad = false;
9918   } else {
9919     return false;
9920   }
9921
9922   if (Ptr.getNode()->hasOneUse())
9923     return false;
9924
9925   for (SDNode *Op : Ptr.getNode()->uses()) {
9926     if (Op == N ||
9927         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9928       continue;
9929
9930     SDValue BasePtr;
9931     SDValue Offset;
9932     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9933     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9934       // Don't create a indexed load / store with zero offset.
9935       if (isNullConstant(Offset))
9936         continue;
9937
9938       // Try turning it into a post-indexed load / store except when
9939       // 1) All uses are load / store ops that use it as base ptr (and
9940       //    it may be folded as addressing mmode).
9941       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9942       //    nor a successor of N. Otherwise, if Op is folded that would
9943       //    create a cycle.
9944
9945       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9946         continue;
9947
9948       // Check for #1.
9949       bool TryNext = false;
9950       for (SDNode *Use : BasePtr.getNode()->uses()) {
9951         if (Use == Ptr.getNode())
9952           continue;
9953
9954         // If all the uses are load / store addresses, then don't do the
9955         // transformation.
9956         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9957           bool RealUse = false;
9958           for (SDNode *UseUse : Use->uses()) {
9959             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9960               RealUse = true;
9961           }
9962
9963           if (!RealUse) {
9964             TryNext = true;
9965             break;
9966           }
9967         }
9968       }
9969
9970       if (TryNext)
9971         continue;
9972
9973       // Check for #2
9974       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9975         SDValue Result = isLoad
9976           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9977                                BasePtr, Offset, AM)
9978           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9979                                 BasePtr, Offset, AM);
9980         ++PostIndexedNodes;
9981         ++NodesCombined;
9982         DEBUG(dbgs() << "\nReplacing.5 ";
9983               N->dump(&DAG);
9984               dbgs() << "\nWith: ";
9985               Result.getNode()->dump(&DAG);
9986               dbgs() << '\n');
9987         WorklistRemover DeadNodes(*this);
9988         if (isLoad) {
9989           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9990           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9991         } else {
9992           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9993         }
9994
9995         // Finally, since the node is now dead, remove it from the graph.
9996         deleteAndRecombine(N);
9997
9998         // Replace the uses of Use with uses of the updated base value.
9999         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10000                                       Result.getValue(isLoad ? 1 : 0));
10001         deleteAndRecombine(Op);
10002         return true;
10003       }
10004     }
10005   }
10006
10007   return false;
10008 }
10009
10010 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10011 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10012   ISD::MemIndexedMode AM = LD->getAddressingMode();
10013   assert(AM != ISD::UNINDEXED);
10014   SDValue BP = LD->getOperand(1);
10015   SDValue Inc = LD->getOperand(2);
10016
10017   // Some backends use TargetConstants for load offsets, but don't expect
10018   // TargetConstants in general ADD nodes. We can convert these constants into
10019   // regular Constants (if the constant is not opaque).
10020   assert((Inc.getOpcode() != ISD::TargetConstant ||
10021           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10022          "Cannot split out indexing using opaque target constants");
10023   if (Inc.getOpcode() == ISD::TargetConstant) {
10024     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10025     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10026                           ConstInc->getValueType(0));
10027   }
10028
10029   unsigned Opc =
10030       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10031   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10032 }
10033
10034 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10035   LoadSDNode *LD  = cast<LoadSDNode>(N);
10036   SDValue Chain = LD->getChain();
10037   SDValue Ptr   = LD->getBasePtr();
10038
10039   // If load is not volatile and there are no uses of the loaded value (and
10040   // the updated indexed value in case of indexed loads), change uses of the
10041   // chain value into uses of the chain input (i.e. delete the dead load).
10042   if (!LD->isVolatile()) {
10043     if (N->getValueType(1) == MVT::Other) {
10044       // Unindexed loads.
10045       if (!N->hasAnyUseOfValue(0)) {
10046         // It's not safe to use the two value CombineTo variant here. e.g.
10047         // v1, chain2 = load chain1, loc
10048         // v2, chain3 = load chain2, loc
10049         // v3         = add v2, c
10050         // Now we replace use of chain2 with chain1.  This makes the second load
10051         // isomorphic to the one we are deleting, and thus makes this load live.
10052         DEBUG(dbgs() << "\nReplacing.6 ";
10053               N->dump(&DAG);
10054               dbgs() << "\nWith chain: ";
10055               Chain.getNode()->dump(&DAG);
10056               dbgs() << "\n");
10057         WorklistRemover DeadNodes(*this);
10058         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10059
10060         if (N->use_empty())
10061           deleteAndRecombine(N);
10062
10063         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10064       }
10065     } else {
10066       // Indexed loads.
10067       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10068
10069       // If this load has an opaque TargetConstant offset, then we cannot split
10070       // the indexing into an add/sub directly (that TargetConstant may not be
10071       // valid for a different type of node, and we cannot convert an opaque
10072       // target constant into a regular constant).
10073       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10074                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10075
10076       if (!N->hasAnyUseOfValue(0) &&
10077           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10078         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10079         SDValue Index;
10080         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10081           Index = SplitIndexingFromLoad(LD);
10082           // Try to fold the base pointer arithmetic into subsequent loads and
10083           // stores.
10084           AddUsersToWorklist(N);
10085         } else
10086           Index = DAG.getUNDEF(N->getValueType(1));
10087         DEBUG(dbgs() << "\nReplacing.7 ";
10088               N->dump(&DAG);
10089               dbgs() << "\nWith: ";
10090               Undef.getNode()->dump(&DAG);
10091               dbgs() << " and 2 other values\n");
10092         WorklistRemover DeadNodes(*this);
10093         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10094         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10095         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10096         deleteAndRecombine(N);
10097         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10098       }
10099     }
10100   }
10101
10102   // If this load is directly stored, replace the load value with the stored
10103   // value.
10104   // TODO: Handle store large -> read small portion.
10105   // TODO: Handle TRUNCSTORE/LOADEXT
10106   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10107     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10108       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10109       if (PrevST->getBasePtr() == Ptr &&
10110           PrevST->getValue().getValueType() == N->getValueType(0))
10111       return CombineTo(N, Chain.getOperand(1), Chain);
10112     }
10113   }
10114
10115   // Try to infer better alignment information than the load already has.
10116   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10117     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10118       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10119         SDValue NewLoad = DAG.getExtLoad(
10120             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10121             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10122             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10123         if (NewLoad.getNode() != N)
10124           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10125       }
10126     }
10127   }
10128
10129   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10130                                                   : DAG.getSubtarget().useAA();
10131 #ifndef NDEBUG
10132   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10133       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10134     UseAA = false;
10135 #endif
10136   if (UseAA && LD->isUnindexed()) {
10137     // Walk up chain skipping non-aliasing memory nodes.
10138     SDValue BetterChain = FindBetterChain(N, Chain);
10139
10140     // If there is a better chain.
10141     if (Chain != BetterChain) {
10142       SDValue ReplLoad;
10143
10144       // Replace the chain to void dependency.
10145       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10146         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10147                                BetterChain, Ptr, LD->getMemOperand());
10148       } else {
10149         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10150                                   LD->getValueType(0),
10151                                   BetterChain, Ptr, LD->getMemoryVT(),
10152                                   LD->getMemOperand());
10153       }
10154
10155       // Create token factor to keep old chain connected.
10156       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10157                                   MVT::Other, Chain, ReplLoad.getValue(1));
10158
10159       // Make sure the new and old chains are cleaned up.
10160       AddToWorklist(Token.getNode());
10161
10162       // Replace uses with load result and token factor. Don't add users
10163       // to work list.
10164       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10165     }
10166   }
10167
10168   // Try transforming N to an indexed load.
10169   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10170     return SDValue(N, 0);
10171
10172   // Try to slice up N to more direct loads if the slices are mapped to
10173   // different register banks or pairing can take place.
10174   if (SliceUpLoad(N))
10175     return SDValue(N, 0);
10176
10177   return SDValue();
10178 }
10179
10180 namespace {
10181 /// \brief Helper structure used to slice a load in smaller loads.
10182 /// Basically a slice is obtained from the following sequence:
10183 /// Origin = load Ty1, Base
10184 /// Shift = srl Ty1 Origin, CstTy Amount
10185 /// Inst = trunc Shift to Ty2
10186 ///
10187 /// Then, it will be rewriten into:
10188 /// Slice = load SliceTy, Base + SliceOffset
10189 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10190 ///
10191 /// SliceTy is deduced from the number of bits that are actually used to
10192 /// build Inst.
10193 struct LoadedSlice {
10194   /// \brief Helper structure used to compute the cost of a slice.
10195   struct Cost {
10196     /// Are we optimizing for code size.
10197     bool ForCodeSize;
10198     /// Various cost.
10199     unsigned Loads;
10200     unsigned Truncates;
10201     unsigned CrossRegisterBanksCopies;
10202     unsigned ZExts;
10203     unsigned Shift;
10204
10205     Cost(bool ForCodeSize = false)
10206         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10207           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10208
10209     /// \brief Get the cost of one isolated slice.
10210     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10211         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10212           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10213       EVT TruncType = LS.Inst->getValueType(0);
10214       EVT LoadedType = LS.getLoadedType();
10215       if (TruncType != LoadedType &&
10216           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10217         ZExts = 1;
10218     }
10219
10220     /// \brief Account for slicing gain in the current cost.
10221     /// Slicing provide a few gains like removing a shift or a
10222     /// truncate. This method allows to grow the cost of the original
10223     /// load with the gain from this slice.
10224     void addSliceGain(const LoadedSlice &LS) {
10225       // Each slice saves a truncate.
10226       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10227       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10228                               LS.Inst->getValueType(0)))
10229         ++Truncates;
10230       // If there is a shift amount, this slice gets rid of it.
10231       if (LS.Shift)
10232         ++Shift;
10233       // If this slice can merge a cross register bank copy, account for it.
10234       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10235         ++CrossRegisterBanksCopies;
10236     }
10237
10238     Cost &operator+=(const Cost &RHS) {
10239       Loads += RHS.Loads;
10240       Truncates += RHS.Truncates;
10241       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10242       ZExts += RHS.ZExts;
10243       Shift += RHS.Shift;
10244       return *this;
10245     }
10246
10247     bool operator==(const Cost &RHS) const {
10248       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10249              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10250              ZExts == RHS.ZExts && Shift == RHS.Shift;
10251     }
10252
10253     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10254
10255     bool operator<(const Cost &RHS) const {
10256       // Assume cross register banks copies are as expensive as loads.
10257       // FIXME: Do we want some more target hooks?
10258       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10259       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10260       // Unless we are optimizing for code size, consider the
10261       // expensive operation first.
10262       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10263         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10264       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10265              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10266     }
10267
10268     bool operator>(const Cost &RHS) const { return RHS < *this; }
10269
10270     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10271
10272     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10273   };
10274   // The last instruction that represent the slice. This should be a
10275   // truncate instruction.
10276   SDNode *Inst;
10277   // The original load instruction.
10278   LoadSDNode *Origin;
10279   // The right shift amount in bits from the original load.
10280   unsigned Shift;
10281   // The DAG from which Origin came from.
10282   // This is used to get some contextual information about legal types, etc.
10283   SelectionDAG *DAG;
10284
10285   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10286               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10287       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10288
10289   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10290   /// \return Result is \p BitWidth and has used bits set to 1 and
10291   ///         not used bits set to 0.
10292   APInt getUsedBits() const {
10293     // Reproduce the trunc(lshr) sequence:
10294     // - Start from the truncated value.
10295     // - Zero extend to the desired bit width.
10296     // - Shift left.
10297     assert(Origin && "No original load to compare against.");
10298     unsigned BitWidth = Origin->getValueSizeInBits(0);
10299     assert(Inst && "This slice is not bound to an instruction");
10300     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10301            "Extracted slice is bigger than the whole type!");
10302     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10303     UsedBits.setAllBits();
10304     UsedBits = UsedBits.zext(BitWidth);
10305     UsedBits <<= Shift;
10306     return UsedBits;
10307   }
10308
10309   /// \brief Get the size of the slice to be loaded in bytes.
10310   unsigned getLoadedSize() const {
10311     unsigned SliceSize = getUsedBits().countPopulation();
10312     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10313     return SliceSize / 8;
10314   }
10315
10316   /// \brief Get the type that will be loaded for this slice.
10317   /// Note: This may not be the final type for the slice.
10318   EVT getLoadedType() const {
10319     assert(DAG && "Missing context");
10320     LLVMContext &Ctxt = *DAG->getContext();
10321     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10322   }
10323
10324   /// \brief Get the alignment of the load used for this slice.
10325   unsigned getAlignment() const {
10326     unsigned Alignment = Origin->getAlignment();
10327     unsigned Offset = getOffsetFromBase();
10328     if (Offset != 0)
10329       Alignment = MinAlign(Alignment, Alignment + Offset);
10330     return Alignment;
10331   }
10332
10333   /// \brief Check if this slice can be rewritten with legal operations.
10334   bool isLegal() const {
10335     // An invalid slice is not legal.
10336     if (!Origin || !Inst || !DAG)
10337       return false;
10338
10339     // Offsets are for indexed load only, we do not handle that.
10340     if (!Origin->getOffset().isUndef())
10341       return false;
10342
10343     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10344
10345     // Check that the type is legal.
10346     EVT SliceType = getLoadedType();
10347     if (!TLI.isTypeLegal(SliceType))
10348       return false;
10349
10350     // Check that the load is legal for this type.
10351     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10352       return false;
10353
10354     // Check that the offset can be computed.
10355     // 1. Check its type.
10356     EVT PtrType = Origin->getBasePtr().getValueType();
10357     if (PtrType == MVT::Untyped || PtrType.isExtended())
10358       return false;
10359
10360     // 2. Check that it fits in the immediate.
10361     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10362       return false;
10363
10364     // 3. Check that the computation is legal.
10365     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10366       return false;
10367
10368     // Check that the zext is legal if it needs one.
10369     EVT TruncateType = Inst->getValueType(0);
10370     if (TruncateType != SliceType &&
10371         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10372       return false;
10373
10374     return true;
10375   }
10376
10377   /// \brief Get the offset in bytes of this slice in the original chunk of
10378   /// bits.
10379   /// \pre DAG != nullptr.
10380   uint64_t getOffsetFromBase() const {
10381     assert(DAG && "Missing context.");
10382     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10383     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10384     uint64_t Offset = Shift / 8;
10385     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10386     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10387            "The size of the original loaded type is not a multiple of a"
10388            " byte.");
10389     // If Offset is bigger than TySizeInBytes, it means we are loading all
10390     // zeros. This should have been optimized before in the process.
10391     assert(TySizeInBytes > Offset &&
10392            "Invalid shift amount for given loaded size");
10393     if (IsBigEndian)
10394       Offset = TySizeInBytes - Offset - getLoadedSize();
10395     return Offset;
10396   }
10397
10398   /// \brief Generate the sequence of instructions to load the slice
10399   /// represented by this object and redirect the uses of this slice to
10400   /// this new sequence of instructions.
10401   /// \pre this->Inst && this->Origin are valid Instructions and this
10402   /// object passed the legal check: LoadedSlice::isLegal returned true.
10403   /// \return The last instruction of the sequence used to load the slice.
10404   SDValue loadSlice() const {
10405     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10406     const SDValue &OldBaseAddr = Origin->getBasePtr();
10407     SDValue BaseAddr = OldBaseAddr;
10408     // Get the offset in that chunk of bytes w.r.t. the endianess.
10409     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10410     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10411     if (Offset) {
10412       // BaseAddr = BaseAddr + Offset.
10413       EVT ArithType = BaseAddr.getValueType();
10414       SDLoc DL(Origin);
10415       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10416                               DAG->getConstant(Offset, DL, ArithType));
10417     }
10418
10419     // Create the type of the loaded slice according to its size.
10420     EVT SliceType = getLoadedType();
10421
10422     // Create the load for the slice.
10423     SDValue LastInst =
10424         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10425                      Origin->getPointerInfo().getWithOffset(Offset),
10426                      getAlignment(), Origin->getMemOperand()->getFlags());
10427     // If the final type is not the same as the loaded type, this means that
10428     // we have to pad with zero. Create a zero extend for that.
10429     EVT FinalType = Inst->getValueType(0);
10430     if (SliceType != FinalType)
10431       LastInst =
10432           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10433     return LastInst;
10434   }
10435
10436   /// \brief Check if this slice can be merged with an expensive cross register
10437   /// bank copy. E.g.,
10438   /// i = load i32
10439   /// f = bitcast i32 i to float
10440   bool canMergeExpensiveCrossRegisterBankCopy() const {
10441     if (!Inst || !Inst->hasOneUse())
10442       return false;
10443     SDNode *Use = *Inst->use_begin();
10444     if (Use->getOpcode() != ISD::BITCAST)
10445       return false;
10446     assert(DAG && "Missing context");
10447     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10448     EVT ResVT = Use->getValueType(0);
10449     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10450     const TargetRegisterClass *ArgRC =
10451         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10452     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10453       return false;
10454
10455     // At this point, we know that we perform a cross-register-bank copy.
10456     // Check if it is expensive.
10457     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10458     // Assume bitcasts are cheap, unless both register classes do not
10459     // explicitly share a common sub class.
10460     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10461       return false;
10462
10463     // Check if it will be merged with the load.
10464     // 1. Check the alignment constraint.
10465     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10466         ResVT.getTypeForEVT(*DAG->getContext()));
10467
10468     if (RequiredAlignment > getAlignment())
10469       return false;
10470
10471     // 2. Check that the load is a legal operation for that type.
10472     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10473       return false;
10474
10475     // 3. Check that we do not have a zext in the way.
10476     if (Inst->getValueType(0) != getLoadedType())
10477       return false;
10478
10479     return true;
10480   }
10481 };
10482 }
10483
10484 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10485 /// \p UsedBits looks like 0..0 1..1 0..0.
10486 static bool areUsedBitsDense(const APInt &UsedBits) {
10487   // If all the bits are one, this is dense!
10488   if (UsedBits.isAllOnesValue())
10489     return true;
10490
10491   // Get rid of the unused bits on the right.
10492   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10493   // Get rid of the unused bits on the left.
10494   if (NarrowedUsedBits.countLeadingZeros())
10495     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10496   // Check that the chunk of bits is completely used.
10497   return NarrowedUsedBits.isAllOnesValue();
10498 }
10499
10500 /// \brief Check whether or not \p First and \p Second are next to each other
10501 /// in memory. This means that there is no hole between the bits loaded
10502 /// by \p First and the bits loaded by \p Second.
10503 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10504                                      const LoadedSlice &Second) {
10505   assert(First.Origin == Second.Origin && First.Origin &&
10506          "Unable to match different memory origins.");
10507   APInt UsedBits = First.getUsedBits();
10508   assert((UsedBits & Second.getUsedBits()) == 0 &&
10509          "Slices are not supposed to overlap.");
10510   UsedBits |= Second.getUsedBits();
10511   return areUsedBitsDense(UsedBits);
10512 }
10513
10514 /// \brief Adjust the \p GlobalLSCost according to the target
10515 /// paring capabilities and the layout of the slices.
10516 /// \pre \p GlobalLSCost should account for at least as many loads as
10517 /// there is in the slices in \p LoadedSlices.
10518 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10519                                  LoadedSlice::Cost &GlobalLSCost) {
10520   unsigned NumberOfSlices = LoadedSlices.size();
10521   // If there is less than 2 elements, no pairing is possible.
10522   if (NumberOfSlices < 2)
10523     return;
10524
10525   // Sort the slices so that elements that are likely to be next to each
10526   // other in memory are next to each other in the list.
10527   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10528             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10529     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10530     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10531   });
10532   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10533   // First (resp. Second) is the first (resp. Second) potentially candidate
10534   // to be placed in a paired load.
10535   const LoadedSlice *First = nullptr;
10536   const LoadedSlice *Second = nullptr;
10537   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10538                 // Set the beginning of the pair.
10539                                                            First = Second) {
10540
10541     Second = &LoadedSlices[CurrSlice];
10542
10543     // If First is NULL, it means we start a new pair.
10544     // Get to the next slice.
10545     if (!First)
10546       continue;
10547
10548     EVT LoadedType = First->getLoadedType();
10549
10550     // If the types of the slices are different, we cannot pair them.
10551     if (LoadedType != Second->getLoadedType())
10552       continue;
10553
10554     // Check if the target supplies paired loads for this type.
10555     unsigned RequiredAlignment = 0;
10556     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10557       // move to the next pair, this type is hopeless.
10558       Second = nullptr;
10559       continue;
10560     }
10561     // Check if we meet the alignment requirement.
10562     if (RequiredAlignment > First->getAlignment())
10563       continue;
10564
10565     // Check that both loads are next to each other in memory.
10566     if (!areSlicesNextToEachOther(*First, *Second))
10567       continue;
10568
10569     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10570     --GlobalLSCost.Loads;
10571     // Move to the next pair.
10572     Second = nullptr;
10573   }
10574 }
10575
10576 /// \brief Check the profitability of all involved LoadedSlice.
10577 /// Currently, it is considered profitable if there is exactly two
10578 /// involved slices (1) which are (2) next to each other in memory, and
10579 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10580 ///
10581 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10582 /// the elements themselves.
10583 ///
10584 /// FIXME: When the cost model will be mature enough, we can relax
10585 /// constraints (1) and (2).
10586 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10587                                 const APInt &UsedBits, bool ForCodeSize) {
10588   unsigned NumberOfSlices = LoadedSlices.size();
10589   if (StressLoadSlicing)
10590     return NumberOfSlices > 1;
10591
10592   // Check (1).
10593   if (NumberOfSlices != 2)
10594     return false;
10595
10596   // Check (2).
10597   if (!areUsedBitsDense(UsedBits))
10598     return false;
10599
10600   // Check (3).
10601   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10602   // The original code has one big load.
10603   OrigCost.Loads = 1;
10604   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10605     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10606     // Accumulate the cost of all the slices.
10607     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10608     GlobalSlicingCost += SliceCost;
10609
10610     // Account as cost in the original configuration the gain obtained
10611     // with the current slices.
10612     OrigCost.addSliceGain(LS);
10613   }
10614
10615   // If the target supports paired load, adjust the cost accordingly.
10616   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10617   return OrigCost > GlobalSlicingCost;
10618 }
10619
10620 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10621 /// operations, split it in the various pieces being extracted.
10622 ///
10623 /// This sort of thing is introduced by SROA.
10624 /// This slicing takes care not to insert overlapping loads.
10625 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10626 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10627   if (Level < AfterLegalizeDAG)
10628     return false;
10629
10630   LoadSDNode *LD = cast<LoadSDNode>(N);
10631   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10632       !LD->getValueType(0).isInteger())
10633     return false;
10634
10635   // Keep track of already used bits to detect overlapping values.
10636   // In that case, we will just abort the transformation.
10637   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10638
10639   SmallVector<LoadedSlice, 4> LoadedSlices;
10640
10641   // Check if this load is used as several smaller chunks of bits.
10642   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10643   // of computation for each trunc.
10644   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10645        UI != UIEnd; ++UI) {
10646     // Skip the uses of the chain.
10647     if (UI.getUse().getResNo() != 0)
10648       continue;
10649
10650     SDNode *User = *UI;
10651     unsigned Shift = 0;
10652
10653     // Check if this is a trunc(lshr).
10654     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10655         isa<ConstantSDNode>(User->getOperand(1))) {
10656       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10657       User = *User->use_begin();
10658     }
10659
10660     // At this point, User is a Truncate, iff we encountered, trunc or
10661     // trunc(lshr).
10662     if (User->getOpcode() != ISD::TRUNCATE)
10663       return false;
10664
10665     // The width of the type must be a power of 2 and greater than 8-bits.
10666     // Otherwise the load cannot be represented in LLVM IR.
10667     // Moreover, if we shifted with a non-8-bits multiple, the slice
10668     // will be across several bytes. We do not support that.
10669     unsigned Width = User->getValueSizeInBits(0);
10670     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10671       return 0;
10672
10673     // Build the slice for this chain of computations.
10674     LoadedSlice LS(User, LD, Shift, &DAG);
10675     APInt CurrentUsedBits = LS.getUsedBits();
10676
10677     // Check if this slice overlaps with another.
10678     if ((CurrentUsedBits & UsedBits) != 0)
10679       return false;
10680     // Update the bits used globally.
10681     UsedBits |= CurrentUsedBits;
10682
10683     // Check if the new slice would be legal.
10684     if (!LS.isLegal())
10685       return false;
10686
10687     // Record the slice.
10688     LoadedSlices.push_back(LS);
10689   }
10690
10691   // Abort slicing if it does not seem to be profitable.
10692   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10693     return false;
10694
10695   ++SlicedLoads;
10696
10697   // Rewrite each chain to use an independent load.
10698   // By construction, each chain can be represented by a unique load.
10699
10700   // Prepare the argument for the new token factor for all the slices.
10701   SmallVector<SDValue, 8> ArgChains;
10702   for (SmallVectorImpl<LoadedSlice>::const_iterator
10703            LSIt = LoadedSlices.begin(),
10704            LSItEnd = LoadedSlices.end();
10705        LSIt != LSItEnd; ++LSIt) {
10706     SDValue SliceInst = LSIt->loadSlice();
10707     CombineTo(LSIt->Inst, SliceInst, true);
10708     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10709       SliceInst = SliceInst.getOperand(0);
10710     assert(SliceInst->getOpcode() == ISD::LOAD &&
10711            "It takes more than a zext to get to the loaded slice!!");
10712     ArgChains.push_back(SliceInst.getValue(1));
10713   }
10714
10715   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10716                               ArgChains);
10717   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10718   return true;
10719 }
10720
10721 /// Check to see if V is (and load (ptr), imm), where the load is having
10722 /// specific bytes cleared out.  If so, return the byte size being masked out
10723 /// and the shift amount.
10724 static std::pair<unsigned, unsigned>
10725 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10726   std::pair<unsigned, unsigned> Result(0, 0);
10727
10728   // Check for the structure we're looking for.
10729   if (V->getOpcode() != ISD::AND ||
10730       !isa<ConstantSDNode>(V->getOperand(1)) ||
10731       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10732     return Result;
10733
10734   // Check the chain and pointer.
10735   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10736   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10737
10738   // The store should be chained directly to the load or be an operand of a
10739   // tokenfactor.
10740   if (LD == Chain.getNode())
10741     ; // ok.
10742   else if (Chain->getOpcode() != ISD::TokenFactor)
10743     return Result; // Fail.
10744   else {
10745     bool isOk = false;
10746     for (const SDValue &ChainOp : Chain->op_values())
10747       if (ChainOp.getNode() == LD) {
10748         isOk = true;
10749         break;
10750       }
10751     if (!isOk) return Result;
10752   }
10753
10754   // This only handles simple types.
10755   if (V.getValueType() != MVT::i16 &&
10756       V.getValueType() != MVT::i32 &&
10757       V.getValueType() != MVT::i64)
10758     return Result;
10759
10760   // Check the constant mask.  Invert it so that the bits being masked out are
10761   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10762   // follow the sign bit for uniformity.
10763   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10764   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10765   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10766   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10767   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10768   if (NotMaskLZ == 64) return Result;  // All zero mask.
10769
10770   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10771   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10772     return Result;
10773
10774   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10775   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10776     NotMaskLZ -= 64-V.getValueSizeInBits();
10777
10778   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10779   switch (MaskedBytes) {
10780   case 1:
10781   case 2:
10782   case 4: break;
10783   default: return Result; // All one mask, or 5-byte mask.
10784   }
10785
10786   // Verify that the first bit starts at a multiple of mask so that the access
10787   // is aligned the same as the access width.
10788   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10789
10790   Result.first = MaskedBytes;
10791   Result.second = NotMaskTZ/8;
10792   return Result;
10793 }
10794
10795
10796 /// Check to see if IVal is something that provides a value as specified by
10797 /// MaskInfo. If so, replace the specified store with a narrower store of
10798 /// truncated IVal.
10799 static SDNode *
10800 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10801                                 SDValue IVal, StoreSDNode *St,
10802                                 DAGCombiner *DC) {
10803   unsigned NumBytes = MaskInfo.first;
10804   unsigned ByteShift = MaskInfo.second;
10805   SelectionDAG &DAG = DC->getDAG();
10806
10807   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10808   // that uses this.  If not, this is not a replacement.
10809   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10810                                   ByteShift*8, (ByteShift+NumBytes)*8);
10811   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10812
10813   // Check that it is legal on the target to do this.  It is legal if the new
10814   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10815   // legalization.
10816   MVT VT = MVT::getIntegerVT(NumBytes*8);
10817   if (!DC->isTypeLegal(VT))
10818     return nullptr;
10819
10820   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10821   // shifted by ByteShift and truncated down to NumBytes.
10822   if (ByteShift) {
10823     SDLoc DL(IVal);
10824     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10825                        DAG.getConstant(ByteShift*8, DL,
10826                                     DC->getShiftAmountTy(IVal.getValueType())));
10827   }
10828
10829   // Figure out the offset for the store and the alignment of the access.
10830   unsigned StOffset;
10831   unsigned NewAlign = St->getAlignment();
10832
10833   if (DAG.getDataLayout().isLittleEndian())
10834     StOffset = ByteShift;
10835   else
10836     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10837
10838   SDValue Ptr = St->getBasePtr();
10839   if (StOffset) {
10840     SDLoc DL(IVal);
10841     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10842                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10843     NewAlign = MinAlign(NewAlign, StOffset);
10844   }
10845
10846   // Truncate down to the new size.
10847   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10848
10849   ++OpsNarrowed;
10850   return DAG
10851       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10852                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
10853       .getNode();
10854 }
10855
10856
10857 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10858 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10859 /// narrowing the load and store if it would end up being a win for performance
10860 /// or code size.
10861 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10862   StoreSDNode *ST  = cast<StoreSDNode>(N);
10863   if (ST->isVolatile())
10864     return SDValue();
10865
10866   SDValue Chain = ST->getChain();
10867   SDValue Value = ST->getValue();
10868   SDValue Ptr   = ST->getBasePtr();
10869   EVT VT = Value.getValueType();
10870
10871   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10872     return SDValue();
10873
10874   unsigned Opc = Value.getOpcode();
10875
10876   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10877   // is a byte mask indicating a consecutive number of bytes, check to see if
10878   // Y is known to provide just those bytes.  If so, we try to replace the
10879   // load + replace + store sequence with a single (narrower) store, which makes
10880   // the load dead.
10881   if (Opc == ISD::OR) {
10882     std::pair<unsigned, unsigned> MaskedLoad;
10883     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10884     if (MaskedLoad.first)
10885       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10886                                                   Value.getOperand(1), ST,this))
10887         return SDValue(NewST, 0);
10888
10889     // Or is commutative, so try swapping X and Y.
10890     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10891     if (MaskedLoad.first)
10892       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10893                                                   Value.getOperand(0), ST,this))
10894         return SDValue(NewST, 0);
10895   }
10896
10897   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10898       Value.getOperand(1).getOpcode() != ISD::Constant)
10899     return SDValue();
10900
10901   SDValue N0 = Value.getOperand(0);
10902   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10903       Chain == SDValue(N0.getNode(), 1)) {
10904     LoadSDNode *LD = cast<LoadSDNode>(N0);
10905     if (LD->getBasePtr() != Ptr ||
10906         LD->getPointerInfo().getAddrSpace() !=
10907         ST->getPointerInfo().getAddrSpace())
10908       return SDValue();
10909
10910     // Find the type to narrow it the load / op / store to.
10911     SDValue N1 = Value.getOperand(1);
10912     unsigned BitWidth = N1.getValueSizeInBits();
10913     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10914     if (Opc == ISD::AND)
10915       Imm ^= APInt::getAllOnesValue(BitWidth);
10916     if (Imm == 0 || Imm.isAllOnesValue())
10917       return SDValue();
10918     unsigned ShAmt = Imm.countTrailingZeros();
10919     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10920     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10921     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10922     // The narrowing should be profitable, the load/store operation should be
10923     // legal (or custom) and the store size should be equal to the NewVT width.
10924     while (NewBW < BitWidth &&
10925            (NewVT.getStoreSizeInBits() != NewBW ||
10926             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10927             !TLI.isNarrowingProfitable(VT, NewVT))) {
10928       NewBW = NextPowerOf2(NewBW);
10929       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10930     }
10931     if (NewBW >= BitWidth)
10932       return SDValue();
10933
10934     // If the lsb changed does not start at the type bitwidth boundary,
10935     // start at the previous one.
10936     if (ShAmt % NewBW)
10937       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10938     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10939                                    std::min(BitWidth, ShAmt + NewBW));
10940     if ((Imm & Mask) == Imm) {
10941       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10942       if (Opc == ISD::AND)
10943         NewImm ^= APInt::getAllOnesValue(NewBW);
10944       uint64_t PtrOff = ShAmt / 8;
10945       // For big endian targets, we need to adjust the offset to the pointer to
10946       // load the correct bytes.
10947       if (DAG.getDataLayout().isBigEndian())
10948         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10949
10950       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10951       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10952       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10953         return SDValue();
10954
10955       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10956                                    Ptr.getValueType(), Ptr,
10957                                    DAG.getConstant(PtrOff, SDLoc(LD),
10958                                                    Ptr.getValueType()));
10959       SDValue NewLD =
10960           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
10961                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
10962                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
10963       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10964                                    DAG.getConstant(NewImm, SDLoc(Value),
10965                                                    NewVT));
10966       SDValue NewST =
10967           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
10968                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
10969
10970       AddToWorklist(NewPtr.getNode());
10971       AddToWorklist(NewLD.getNode());
10972       AddToWorklist(NewVal.getNode());
10973       WorklistRemover DeadNodes(*this);
10974       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10975       ++OpsNarrowed;
10976       return NewST;
10977     }
10978   }
10979
10980   return SDValue();
10981 }
10982
10983 /// For a given floating point load / store pair, if the load value isn't used
10984 /// by any other operations, then consider transforming the pair to integer
10985 /// load / store operations if the target deems the transformation profitable.
10986 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10987   StoreSDNode *ST  = cast<StoreSDNode>(N);
10988   SDValue Chain = ST->getChain();
10989   SDValue Value = ST->getValue();
10990   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10991       Value.hasOneUse() &&
10992       Chain == SDValue(Value.getNode(), 1)) {
10993     LoadSDNode *LD = cast<LoadSDNode>(Value);
10994     EVT VT = LD->getMemoryVT();
10995     if (!VT.isFloatingPoint() ||
10996         VT != ST->getMemoryVT() ||
10997         LD->isNonTemporal() ||
10998         ST->isNonTemporal() ||
10999         LD->getPointerInfo().getAddrSpace() != 0 ||
11000         ST->getPointerInfo().getAddrSpace() != 0)
11001       return SDValue();
11002
11003     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11004     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11005         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11006         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11007         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11008       return SDValue();
11009
11010     unsigned LDAlign = LD->getAlignment();
11011     unsigned STAlign = ST->getAlignment();
11012     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11013     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11014     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11015       return SDValue();
11016
11017     SDValue NewLD =
11018         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11019                     LD->getPointerInfo(), LDAlign);
11020
11021     SDValue NewST =
11022         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11023                      ST->getPointerInfo(), STAlign);
11024
11025     AddToWorklist(NewLD.getNode());
11026     AddToWorklist(NewST.getNode());
11027     WorklistRemover DeadNodes(*this);
11028     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11029     ++LdStFP2Int;
11030     return NewST;
11031   }
11032
11033   return SDValue();
11034 }
11035
11036 namespace {
11037 /// Helper struct to parse and store a memory address as base + index + offset.
11038 /// We ignore sign extensions when it is safe to do so.
11039 /// The following two expressions are not equivalent. To differentiate we need
11040 /// to store whether there was a sign extension involved in the index
11041 /// computation.
11042 ///  (load (i64 add (i64 copyfromreg %c)
11043 ///                 (i64 signextend (add (i8 load %index)
11044 ///                                      (i8 1))))
11045 /// vs
11046 ///
11047 /// (load (i64 add (i64 copyfromreg %c)
11048 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11049 ///                                         (i32 1)))))
11050 struct BaseIndexOffset {
11051   SDValue Base;
11052   SDValue Index;
11053   int64_t Offset;
11054   bool IsIndexSignExt;
11055
11056   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11057
11058   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11059                   bool IsIndexSignExt) :
11060     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11061
11062   bool equalBaseIndex(const BaseIndexOffset &Other) {
11063     return Other.Base == Base && Other.Index == Index &&
11064       Other.IsIndexSignExt == IsIndexSignExt;
11065   }
11066
11067   /// Parses tree in Ptr for base, index, offset addresses.
11068   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11069     bool IsIndexSignExt = false;
11070
11071     // Split up a folded GlobalAddress+Offset into its component parts.
11072     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11073       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11074         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11075                                                     SDLoc(GA),
11076                                                     GA->getValueType(0),
11077                                                     /*Offset=*/0,
11078                                                     /*isTargetGA=*/false,
11079                                                     GA->getTargetFlags()),
11080                                SDValue(),
11081                                GA->getOffset(),
11082                                IsIndexSignExt);
11083       }
11084
11085     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11086     // instruction, then it could be just the BASE or everything else we don't
11087     // know how to handle. Just use Ptr as BASE and give up.
11088     if (Ptr->getOpcode() != ISD::ADD)
11089       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11090
11091     // We know that we have at least an ADD instruction. Try to pattern match
11092     // the simple case of BASE + OFFSET.
11093     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11094       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11095       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11096                               IsIndexSignExt);
11097     }
11098
11099     // Inside a loop the current BASE pointer is calculated using an ADD and a
11100     // MUL instruction. In this case Ptr is the actual BASE pointer.
11101     // (i64 add (i64 %array_ptr)
11102     //          (i64 mul (i64 %induction_var)
11103     //                   (i64 %element_size)))
11104     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11105       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11106
11107     // Look at Base + Index + Offset cases.
11108     SDValue Base = Ptr->getOperand(0);
11109     SDValue IndexOffset = Ptr->getOperand(1);
11110
11111     // Skip signextends.
11112     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11113       IndexOffset = IndexOffset->getOperand(0);
11114       IsIndexSignExt = true;
11115     }
11116
11117     // Either the case of Base + Index (no offset) or something else.
11118     if (IndexOffset->getOpcode() != ISD::ADD)
11119       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11120
11121     // Now we have the case of Base + Index + offset.
11122     SDValue Index = IndexOffset->getOperand(0);
11123     SDValue Offset = IndexOffset->getOperand(1);
11124
11125     if (!isa<ConstantSDNode>(Offset))
11126       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11127
11128     // Ignore signextends.
11129     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11130       Index = Index->getOperand(0);
11131       IsIndexSignExt = true;
11132     } else IsIndexSignExt = false;
11133
11134     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11135     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11136   }
11137 };
11138 } // namespace
11139
11140 // This is a helper function for visitMUL to check the profitability
11141 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11142 // MulNode is the original multiply, AddNode is (add x, c1),
11143 // and ConstNode is c2.
11144 //
11145 // If the (add x, c1) has multiple uses, we could increase
11146 // the number of adds if we make this transformation.
11147 // It would only be worth doing this if we can remove a
11148 // multiply in the process. Check for that here.
11149 // To illustrate:
11150 //     (A + c1) * c3
11151 //     (A + c2) * c3
11152 // We're checking for cases where we have common "c3 * A" expressions.
11153 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11154                                               SDValue &AddNode,
11155                                               SDValue &ConstNode) {
11156   APInt Val;
11157
11158   // If the add only has one use, this would be OK to do.
11159   if (AddNode.getNode()->hasOneUse())
11160     return true;
11161
11162   // Walk all the users of the constant with which we're multiplying.
11163   for (SDNode *Use : ConstNode->uses()) {
11164
11165     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11166       continue;
11167
11168     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11169       SDNode *OtherOp;
11170       SDNode *MulVar = AddNode.getOperand(0).getNode();
11171
11172       // OtherOp is what we're multiplying against the constant.
11173       if (Use->getOperand(0) == ConstNode)
11174         OtherOp = Use->getOperand(1).getNode();
11175       else
11176         OtherOp = Use->getOperand(0).getNode();
11177
11178       // Check to see if multiply is with the same operand of our "add".
11179       //
11180       //     ConstNode  = CONST
11181       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11182       //     ...
11183       //     AddNode  = (A + c1)  <-- MulVar is A.
11184       //         = AddNode * ConstNode   <-- current visiting instruction.
11185       //
11186       // If we make this transformation, we will have a common
11187       // multiply (ConstNode * A) that we can save.
11188       if (OtherOp == MulVar)
11189         return true;
11190
11191       // Now check to see if a future expansion will give us a common
11192       // multiply.
11193       //
11194       //     ConstNode  = CONST
11195       //     AddNode    = (A + c1)
11196       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11197       //     ...
11198       //     OtherOp = (A + c2)
11199       //     Use     = OtherOp * ConstNode <-- visiting Use.
11200       //
11201       // If we make this transformation, we will have a common
11202       // multiply (CONST * A) after we also do the same transformation
11203       // to the "t2" instruction.
11204       if (OtherOp->getOpcode() == ISD::ADD &&
11205           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11206           OtherOp->getOperand(0).getNode() == MulVar)
11207         return true;
11208     }
11209   }
11210
11211   // Didn't find a case where this would be profitable.
11212   return false;
11213 }
11214
11215 SDValue DAGCombiner::getMergedConstantVectorStore(
11216     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11217     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11218   SmallVector<SDValue, 8> BuildVector;
11219
11220   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11221     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11222     Chains.push_back(St->getChain());
11223     BuildVector.push_back(St->getValue());
11224   }
11225
11226   return DAG.getBuildVector(Ty, SL, BuildVector);
11227 }
11228
11229 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11230                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11231                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11232   // Make sure we have something to merge.
11233   if (NumStores < 2)
11234     return false;
11235
11236   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11237   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11238   unsigned LatestNodeUsed = 0;
11239
11240   for (unsigned i=0; i < NumStores; ++i) {
11241     // Find a chain for the new wide-store operand. Notice that some
11242     // of the store nodes that we found may not be selected for inclusion
11243     // in the wide store. The chain we use needs to be the chain of the
11244     // latest store node which is *used* and replaced by the wide store.
11245     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11246       LatestNodeUsed = i;
11247   }
11248
11249   SmallVector<SDValue, 8> Chains;
11250
11251   // The latest Node in the DAG.
11252   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11253   SDLoc DL(StoreNodes[0].MemNode);
11254
11255   SDValue StoredVal;
11256   if (UseVector) {
11257     bool IsVec = MemVT.isVector();
11258     unsigned Elts = NumStores;
11259     if (IsVec) {
11260       // When merging vector stores, get the total number of elements.
11261       Elts *= MemVT.getVectorNumElements();
11262     }
11263     // Get the type for the merged vector store.
11264     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11265     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11266
11267     if (IsConstantSrc) {
11268       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11269     } else {
11270       SmallVector<SDValue, 8> Ops;
11271       for (unsigned i = 0; i < NumStores; ++i) {
11272         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11273         SDValue Val = St->getValue();
11274         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11275         if (Val.getValueType() != MemVT)
11276           return false;
11277         Ops.push_back(Val);
11278         Chains.push_back(St->getChain());
11279       }
11280
11281       // Build the extracted vector elements back into a vector.
11282       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11283                               DL, Ty, Ops);    }
11284   } else {
11285     // We should always use a vector store when merging extracted vector
11286     // elements, so this path implies a store of constants.
11287     assert(IsConstantSrc && "Merged vector elements should use vector store");
11288
11289     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11290     APInt StoreInt(SizeInBits, 0);
11291
11292     // Construct a single integer constant which is made of the smaller
11293     // constant inputs.
11294     bool IsLE = DAG.getDataLayout().isLittleEndian();
11295     for (unsigned i = 0; i < NumStores; ++i) {
11296       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11297       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11298       Chains.push_back(St->getChain());
11299
11300       SDValue Val = St->getValue();
11301       StoreInt <<= ElementSizeBytes * 8;
11302       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11303         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11304       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11305         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11306       } else {
11307         llvm_unreachable("Invalid constant element type");
11308       }
11309     }
11310
11311     // Create the new Load and Store operations.
11312     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11313     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11314   }
11315
11316   assert(!Chains.empty());
11317
11318   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11319   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11320                                   FirstInChain->getBasePtr(),
11321                                   FirstInChain->getPointerInfo(),
11322                                   FirstInChain->getAlignment());
11323
11324   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11325                                                   : DAG.getSubtarget().useAA();
11326   if (UseAA) {
11327     // Replace all merged stores with the new store.
11328     for (unsigned i = 0; i < NumStores; ++i)
11329       CombineTo(StoreNodes[i].MemNode, NewStore);
11330   } else {
11331     // Replace the last store with the new store.
11332     CombineTo(LatestOp, NewStore);
11333     // Erase all other stores.
11334     for (unsigned i = 0; i < NumStores; ++i) {
11335       if (StoreNodes[i].MemNode == LatestOp)
11336         continue;
11337       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11338       // ReplaceAllUsesWith will replace all uses that existed when it was
11339       // called, but graph optimizations may cause new ones to appear. For
11340       // example, the case in pr14333 looks like
11341       //
11342       //  St's chain -> St -> another store -> X
11343       //
11344       // And the only difference from St to the other store is the chain.
11345       // When we change it's chain to be St's chain they become identical,
11346       // get CSEed and the net result is that X is now a use of St.
11347       // Since we know that St is redundant, just iterate.
11348       while (!St->use_empty())
11349         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11350       deleteAndRecombine(St);
11351     }
11352   }
11353
11354   return true;
11355 }
11356
11357 void DAGCombiner::getStoreMergeAndAliasCandidates(
11358     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11359     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11360   // This holds the base pointer, index, and the offset in bytes from the base
11361   // pointer.
11362   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11363
11364   // We must have a base and an offset.
11365   if (!BasePtr.Base.getNode())
11366     return;
11367
11368   // Do not handle stores to undef base pointers.
11369   if (BasePtr.Base.isUndef())
11370     return;
11371
11372   // Walk up the chain and look for nodes with offsets from the same
11373   // base pointer. Stop when reaching an instruction with a different kind
11374   // or instruction which has a different base pointer.
11375   EVT MemVT = St->getMemoryVT();
11376   unsigned Seq = 0;
11377   StoreSDNode *Index = St;
11378
11379
11380   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11381                                                   : DAG.getSubtarget().useAA();
11382
11383   if (UseAA) {
11384     // Look at other users of the same chain. Stores on the same chain do not
11385     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11386     // to be on the same chain, so don't bother looking at adjacent chains.
11387
11388     SDValue Chain = St->getChain();
11389     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11390       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11391         if (I.getOperandNo() != 0)
11392           continue;
11393
11394         if (OtherST->isVolatile() || OtherST->isIndexed())
11395           continue;
11396
11397         if (OtherST->getMemoryVT() != MemVT)
11398           continue;
11399
11400         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11401
11402         if (Ptr.equalBaseIndex(BasePtr))
11403           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11404       }
11405     }
11406
11407     return;
11408   }
11409
11410   while (Index) {
11411     // If the chain has more than one use, then we can't reorder the mem ops.
11412     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11413       break;
11414
11415     // Find the base pointer and offset for this memory node.
11416     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11417
11418     // Check that the base pointer is the same as the original one.
11419     if (!Ptr.equalBaseIndex(BasePtr))
11420       break;
11421
11422     // The memory operands must not be volatile.
11423     if (Index->isVolatile() || Index->isIndexed())
11424       break;
11425
11426     // No truncation.
11427     if (Index->isTruncatingStore())
11428       break;
11429
11430     // The stored memory type must be the same.
11431     if (Index->getMemoryVT() != MemVT)
11432       break;
11433
11434     // We do not allow under-aligned stores in order to prevent
11435     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11436     // be irrelevant here; what MATTERS is that we not move memory
11437     // operations that potentially overlap past each-other.
11438     if (Index->getAlignment() < MemVT.getStoreSize())
11439       break;
11440
11441     // We found a potential memory operand to merge.
11442     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11443
11444     // Find the next memory operand in the chain. If the next operand in the
11445     // chain is a store then move up and continue the scan with the next
11446     // memory operand. If the next operand is a load save it and use alias
11447     // information to check if it interferes with anything.
11448     SDNode *NextInChain = Index->getChain().getNode();
11449     while (1) {
11450       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11451         // We found a store node. Use it for the next iteration.
11452         Index = STn;
11453         break;
11454       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11455         if (Ldn->isVolatile()) {
11456           Index = nullptr;
11457           break;
11458         }
11459
11460         // Save the load node for later. Continue the scan.
11461         AliasLoadNodes.push_back(Ldn);
11462         NextInChain = Ldn->getChain().getNode();
11463         continue;
11464       } else {
11465         Index = nullptr;
11466         break;
11467       }
11468     }
11469   }
11470 }
11471
11472 // We need to check that merging these stores does not cause a loop
11473 // in the DAG. Any store candidate may depend on another candidate
11474 // indirectly through its operand (we already consider dependencies
11475 // through the chain). Check in parallel by searching up from
11476 // non-chain operands of candidates.
11477 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11478     SmallVectorImpl<MemOpLink> &StoreNodes) {
11479   SmallPtrSet<const SDNode *, 16> Visited;
11480   SmallVector<const SDNode *, 8> Worklist;
11481   // search ops of store candidates
11482   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11483     SDNode *n = StoreNodes[i].MemNode;
11484     // Potential loops may happen only through non-chain operands
11485     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11486       Worklist.push_back(n->getOperand(j).getNode());
11487   }
11488   // search through DAG. We can stop early if we find a storenode
11489   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11490     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11491       return false;
11492   }
11493   return true;
11494 }
11495
11496 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11497   if (OptLevel == CodeGenOpt::None)
11498     return false;
11499
11500   EVT MemVT = St->getMemoryVT();
11501   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11502   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11503       Attribute::NoImplicitFloat);
11504
11505   // This function cannot currently deal with non-byte-sized memory sizes.
11506   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11507     return false;
11508
11509   if (!MemVT.isSimple())
11510     return false;
11511
11512   // Perform an early exit check. Do not bother looking at stored values that
11513   // are not constants, loads, or extracted vector elements.
11514   SDValue StoredVal = St->getValue();
11515   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11516   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11517                        isa<ConstantFPSDNode>(StoredVal);
11518   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11519                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11520
11521   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11522     return false;
11523
11524   // Don't merge vectors into wider vectors if the source data comes from loads.
11525   // TODO: This restriction can be lifted by using logic similar to the
11526   // ExtractVecSrc case.
11527   if (MemVT.isVector() && IsLoadSrc)
11528     return false;
11529
11530   // Only look at ends of store sequences.
11531   SDValue Chain = SDValue(St, 0);
11532   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11533     return false;
11534
11535   // Save the LoadSDNodes that we find in the chain.
11536   // We need to make sure that these nodes do not interfere with
11537   // any of the store nodes.
11538   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11539
11540   // Save the StoreSDNodes that we find in the chain.
11541   SmallVector<MemOpLink, 8> StoreNodes;
11542
11543   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11544
11545   // Check if there is anything to merge.
11546   if (StoreNodes.size() < 2)
11547     return false;
11548
11549   // only do dep endence check in AA case
11550   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11551                                                   : DAG.getSubtarget().useAA();
11552   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11553     return false;
11554
11555   // Sort the memory operands according to their distance from the
11556   // base pointer.  As a secondary criteria: make sure stores coming
11557   // later in the code come first in the list. This is important for
11558   // the non-UseAA case, because we're merging stores into the FINAL
11559   // store along a chain which potentially contains aliasing stores.
11560   // Thus, if there are multiple stores to the same address, the last
11561   // one can be considered for merging but not the others.
11562   std::sort(StoreNodes.begin(), StoreNodes.end(),
11563             [](MemOpLink LHS, MemOpLink RHS) {
11564     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11565            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11566             LHS.SequenceNum < RHS.SequenceNum);
11567   });
11568
11569   // Scan the memory operations on the chain and find the first non-consecutive
11570   // store memory address.
11571   unsigned LastConsecutiveStore = 0;
11572   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11573   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11574
11575     // Check that the addresses are consecutive starting from the second
11576     // element in the list of stores.
11577     if (i > 0) {
11578       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11579       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11580         break;
11581     }
11582
11583     // Check if this store interferes with any of the loads that we found.
11584     // If we find a load that alias with this store. Stop the sequence.
11585     if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11586                     [&](LSBaseSDNode* Ldn) {
11587                       return isAlias(Ldn, StoreNodes[i].MemNode);
11588                     }))
11589       break;
11590
11591     // Mark this node as useful.
11592     LastConsecutiveStore = i;
11593   }
11594
11595   // The node with the lowest store address.
11596   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11597   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11598   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11599   LLVMContext &Context = *DAG.getContext();
11600   const DataLayout &DL = DAG.getDataLayout();
11601
11602   // Store the constants into memory as one consecutive store.
11603   if (IsConstantSrc) {
11604     unsigned LastLegalType = 0;
11605     unsigned LastLegalVectorType = 0;
11606     bool NonZero = false;
11607     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11608       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11609       SDValue StoredVal = St->getValue();
11610
11611       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11612         NonZero |= !C->isNullValue();
11613       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11614         NonZero |= !C->getConstantFPValue()->isNullValue();
11615       } else {
11616         // Non-constant.
11617         break;
11618       }
11619
11620       // Find a legal type for the constant store.
11621       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11622       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11623       bool IsFast;
11624       if (TLI.isTypeLegal(StoreTy) &&
11625           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11626                                  FirstStoreAlign, &IsFast) && IsFast) {
11627         LastLegalType = i+1;
11628       // Or check whether a truncstore is legal.
11629       } else if (TLI.getTypeAction(Context, StoreTy) ==
11630                  TargetLowering::TypePromoteInteger) {
11631         EVT LegalizedStoredValueTy =
11632           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11633         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11634             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11635                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11636             IsFast) {
11637           LastLegalType = i + 1;
11638         }
11639       }
11640
11641       // We only use vectors if the constant is known to be zero or the target
11642       // allows it and the function is not marked with the noimplicitfloat
11643       // attribute.
11644       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11645                                                         FirstStoreAS)) &&
11646           !NoVectors) {
11647         // Find a legal type for the vector store.
11648         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11649         if (TLI.isTypeLegal(Ty) &&
11650             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11651                                    FirstStoreAlign, &IsFast) && IsFast)
11652           LastLegalVectorType = i + 1;
11653       }
11654     }
11655
11656     // Check if we found a legal integer type to store.
11657     if (LastLegalType == 0 && LastLegalVectorType == 0)
11658       return false;
11659
11660     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11661     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11662
11663     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11664                                            true, UseVector);
11665   }
11666
11667   // When extracting multiple vector elements, try to store them
11668   // in one vector store rather than a sequence of scalar stores.
11669   if (IsExtractVecSrc) {
11670     unsigned NumStoresToMerge = 0;
11671     bool IsVec = MemVT.isVector();
11672     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11673       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11674       unsigned StoreValOpcode = St->getValue().getOpcode();
11675       // This restriction could be loosened.
11676       // Bail out if any stored values are not elements extracted from a vector.
11677       // It should be possible to handle mixed sources, but load sources need
11678       // more careful handling (see the block of code below that handles
11679       // consecutive loads).
11680       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11681           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11682         return false;
11683
11684       // Find a legal type for the vector store.
11685       unsigned Elts = i + 1;
11686       if (IsVec) {
11687         // When merging vector stores, get the total number of elements.
11688         Elts *= MemVT.getVectorNumElements();
11689       }
11690       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11691       bool IsFast;
11692       if (TLI.isTypeLegal(Ty) &&
11693           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11694                                  FirstStoreAlign, &IsFast) && IsFast)
11695         NumStoresToMerge = i + 1;
11696     }
11697
11698     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11699                                            false, true);
11700   }
11701
11702   // Below we handle the case of multiple consecutive stores that
11703   // come from multiple consecutive loads. We merge them into a single
11704   // wide load and a single wide store.
11705
11706   // Look for load nodes which are used by the stored values.
11707   SmallVector<MemOpLink, 8> LoadNodes;
11708
11709   // Find acceptable loads. Loads need to have the same chain (token factor),
11710   // must not be zext, volatile, indexed, and they must be consecutive.
11711   BaseIndexOffset LdBasePtr;
11712   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11713     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11714     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11715     if (!Ld) break;
11716
11717     // Loads must only have one use.
11718     if (!Ld->hasNUsesOfValue(1, 0))
11719       break;
11720
11721     // The memory operands must not be volatile.
11722     if (Ld->isVolatile() || Ld->isIndexed())
11723       break;
11724
11725     // We do not accept ext loads.
11726     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11727       break;
11728
11729     // The stored memory type must be the same.
11730     if (Ld->getMemoryVT() != MemVT)
11731       break;
11732
11733     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11734     // If this is not the first ptr that we check.
11735     if (LdBasePtr.Base.getNode()) {
11736       // The base ptr must be the same.
11737       if (!LdPtr.equalBaseIndex(LdBasePtr))
11738         break;
11739     } else {
11740       // Check that all other base pointers are the same as this one.
11741       LdBasePtr = LdPtr;
11742     }
11743
11744     // We found a potential memory operand to merge.
11745     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11746   }
11747
11748   if (LoadNodes.size() < 2)
11749     return false;
11750
11751   // If we have load/store pair instructions and we only have two values,
11752   // don't bother.
11753   unsigned RequiredAlignment;
11754   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11755       St->getAlignment() >= RequiredAlignment)
11756     return false;
11757
11758   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11759   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11760   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11761
11762   // Scan the memory operations on the chain and find the first non-consecutive
11763   // load memory address. These variables hold the index in the store node
11764   // array.
11765   unsigned LastConsecutiveLoad = 0;
11766   // This variable refers to the size and not index in the array.
11767   unsigned LastLegalVectorType = 0;
11768   unsigned LastLegalIntegerType = 0;
11769   StartAddress = LoadNodes[0].OffsetFromBase;
11770   SDValue FirstChain = FirstLoad->getChain();
11771   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11772     // All loads must share the same chain.
11773     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11774       break;
11775
11776     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11777     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11778       break;
11779     LastConsecutiveLoad = i;
11780     // Find a legal type for the vector store.
11781     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11782     bool IsFastSt, IsFastLd;
11783     if (TLI.isTypeLegal(StoreTy) &&
11784         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11785                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11786         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11787                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11788       LastLegalVectorType = i + 1;
11789     }
11790
11791     // Find a legal type for the integer store.
11792     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11793     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11794     if (TLI.isTypeLegal(StoreTy) &&
11795         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11796                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11797         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11798                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11799       LastLegalIntegerType = i + 1;
11800     // Or check whether a truncstore and extload is legal.
11801     else if (TLI.getTypeAction(Context, StoreTy) ==
11802              TargetLowering::TypePromoteInteger) {
11803       EVT LegalizedStoredValueTy =
11804         TLI.getTypeToTransformTo(Context, StoreTy);
11805       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11806           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11807           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11808           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11809           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11810                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11811           IsFastSt &&
11812           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11813                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11814           IsFastLd)
11815         LastLegalIntegerType = i+1;
11816     }
11817   }
11818
11819   // Only use vector types if the vector type is larger than the integer type.
11820   // If they are the same, use integers.
11821   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11822   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11823
11824   // We add +1 here because the LastXXX variables refer to location while
11825   // the NumElem refers to array/index size.
11826   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11827   NumElem = std::min(LastLegalType, NumElem);
11828
11829   if (NumElem < 2)
11830     return false;
11831
11832   // Collect the chains from all merged stores.
11833   SmallVector<SDValue, 8> MergeStoreChains;
11834   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11835
11836   // The latest Node in the DAG.
11837   unsigned LatestNodeUsed = 0;
11838   for (unsigned i=1; i<NumElem; ++i) {
11839     // Find a chain for the new wide-store operand. Notice that some
11840     // of the store nodes that we found may not be selected for inclusion
11841     // in the wide store. The chain we use needs to be the chain of the
11842     // latest store node which is *used* and replaced by the wide store.
11843     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11844       LatestNodeUsed = i;
11845
11846     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11847   }
11848
11849   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11850
11851   // Find if it is better to use vectors or integers to load and store
11852   // to memory.
11853   EVT JointMemOpVT;
11854   if (UseVectorTy) {
11855     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11856   } else {
11857     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11858     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11859   }
11860
11861   SDLoc LoadDL(LoadNodes[0].MemNode);
11862   SDLoc StoreDL(StoreNodes[0].MemNode);
11863
11864   // The merged loads are required to have the same incoming chain, so
11865   // using the first's chain is acceptable.
11866   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
11867                                 FirstLoad->getBasePtr(),
11868                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
11869
11870   SDValue NewStoreChain =
11871     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11872
11873   SDValue NewStore =
11874       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11875                    FirstInChain->getPointerInfo(), FirstStoreAlign);
11876
11877   // Transfer chain users from old loads to the new load.
11878   for (unsigned i = 0; i < NumElem; ++i) {
11879     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11880     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11881                                   SDValue(NewLoad.getNode(), 1));
11882   }
11883
11884   if (UseAA) {
11885     // Replace the all stores with the new store.
11886     for (unsigned i = 0; i < NumElem; ++i)
11887       CombineTo(StoreNodes[i].MemNode, NewStore);
11888   } else {
11889     // Replace the last store with the new store.
11890     CombineTo(LatestOp, NewStore);
11891     // Erase all other stores.
11892     for (unsigned i = 0; i < NumElem; ++i) {
11893       // Remove all Store nodes.
11894       if (StoreNodes[i].MemNode == LatestOp)
11895         continue;
11896       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11897       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11898       deleteAndRecombine(St);
11899     }
11900   }
11901
11902   return true;
11903 }
11904
11905 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11906   SDLoc SL(ST);
11907   SDValue ReplStore;
11908
11909   // Replace the chain to avoid dependency.
11910   if (ST->isTruncatingStore()) {
11911     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11912                                   ST->getBasePtr(), ST->getMemoryVT(),
11913                                   ST->getMemOperand());
11914   } else {
11915     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11916                              ST->getMemOperand());
11917   }
11918
11919   // Create token to keep both nodes around.
11920   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11921                               MVT::Other, ST->getChain(), ReplStore);
11922
11923   // Make sure the new and old chains are cleaned up.
11924   AddToWorklist(Token.getNode());
11925
11926   // Don't add users to work list.
11927   return CombineTo(ST, Token, false);
11928 }
11929
11930 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11931   SDValue Value = ST->getValue();
11932   if (Value.getOpcode() == ISD::TargetConstantFP)
11933     return SDValue();
11934
11935   SDLoc DL(ST);
11936
11937   SDValue Chain = ST->getChain();
11938   SDValue Ptr = ST->getBasePtr();
11939
11940   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11941
11942   // NOTE: If the original store is volatile, this transform must not increase
11943   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11944   // processor operation but an i64 (which is not legal) requires two.  So the
11945   // transform should not be done in this case.
11946
11947   SDValue Tmp;
11948   switch (CFP->getSimpleValueType(0).SimpleTy) {
11949   default:
11950     llvm_unreachable("Unknown FP type");
11951   case MVT::f16:    // We don't do this for these yet.
11952   case MVT::f80:
11953   case MVT::f128:
11954   case MVT::ppcf128:
11955     return SDValue();
11956   case MVT::f32:
11957     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11958         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11959       ;
11960       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11961                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11962                             MVT::i32);
11963       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11964     }
11965
11966     return SDValue();
11967   case MVT::f64:
11968     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11969          !ST->isVolatile()) ||
11970         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11971       ;
11972       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11973                             getZExtValue(), SDLoc(CFP), MVT::i64);
11974       return DAG.getStore(Chain, DL, Tmp,
11975                           Ptr, ST->getMemOperand());
11976     }
11977
11978     if (!ST->isVolatile() &&
11979         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11980       // Many FP stores are not made apparent until after legalize, e.g. for
11981       // argument passing.  Since this is so common, custom legalize the
11982       // 64-bit integer store into two 32-bit stores.
11983       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11984       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11985       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11986       if (DAG.getDataLayout().isBigEndian())
11987         std::swap(Lo, Hi);
11988
11989       unsigned Alignment = ST->getAlignment();
11990       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
11991       AAMDNodes AAInfo = ST->getAAInfo();
11992
11993       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
11994                                  ST->getAlignment(), MMOFlags, AAInfo);
11995       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11996                         DAG.getConstant(4, DL, Ptr.getValueType()));
11997       Alignment = MinAlign(Alignment, 4U);
11998       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
11999                                  ST->getPointerInfo().getWithOffset(4),
12000                                  Alignment, MMOFlags, AAInfo);
12001       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12002                          St0, St1);
12003     }
12004
12005     return SDValue();
12006   }
12007 }
12008
12009 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12010   StoreSDNode *ST  = cast<StoreSDNode>(N);
12011   SDValue Chain = ST->getChain();
12012   SDValue Value = ST->getValue();
12013   SDValue Ptr   = ST->getBasePtr();
12014
12015   // If this is a store of a bit convert, store the input value if the
12016   // resultant store does not need a higher alignment than the original.
12017   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12018       ST->isUnindexed()) {
12019     EVT SVT = Value.getOperand(0).getValueType();
12020     if (((!LegalOperations && !ST->isVolatile()) ||
12021          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12022         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12023       unsigned OrigAlign = ST->getAlignment();
12024       bool Fast = false;
12025       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12026                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12027           Fast) {
12028         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12029                             ST->getPointerInfo(), OrigAlign,
12030                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12031       }
12032     }
12033   }
12034
12035   // Turn 'store undef, Ptr' -> nothing.
12036   if (Value.isUndef() && ST->isUnindexed())
12037     return Chain;
12038
12039   // Try to infer better alignment information than the store already has.
12040   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12041     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12042       if (Align > ST->getAlignment()) {
12043         SDValue NewStore =
12044             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12045                               ST->getMemoryVT(), Align,
12046                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12047         if (NewStore.getNode() != N)
12048           return CombineTo(ST, NewStore, true);
12049       }
12050     }
12051   }
12052
12053   // Try transforming a pair floating point load / store ops to integer
12054   // load / store ops.
12055   if (SDValue NewST = TransformFPLoadStorePair(N))
12056     return NewST;
12057
12058   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12059                                                   : DAG.getSubtarget().useAA();
12060 #ifndef NDEBUG
12061   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12062       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12063     UseAA = false;
12064 #endif
12065   if (UseAA && ST->isUnindexed()) {
12066     // FIXME: We should do this even without AA enabled. AA will just allow
12067     // FindBetterChain to work in more situations. The problem with this is that
12068     // any combine that expects memory operations to be on consecutive chains
12069     // first needs to be updated to look for users of the same chain.
12070
12071     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12072     // adjacent stores.
12073     if (findBetterNeighborChains(ST)) {
12074       // replaceStoreChain uses CombineTo, which handled all of the worklist
12075       // manipulation. Return the original node to not do anything else.
12076       return SDValue(ST, 0);
12077     }
12078     Chain = ST->getChain();
12079   }
12080
12081   // Try transforming N to an indexed store.
12082   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12083     return SDValue(N, 0);
12084
12085   // FIXME: is there such a thing as a truncating indexed store?
12086   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12087       Value.getValueType().isInteger()) {
12088     // See if we can simplify the input to this truncstore with knowledge that
12089     // only the low bits are being used.  For example:
12090     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12091     SDValue Shorter =
12092       GetDemandedBits(Value,
12093                       APInt::getLowBitsSet(
12094                         Value.getValueType().getScalarType().getSizeInBits(),
12095                         ST->getMemoryVT().getScalarType().getSizeInBits()));
12096     AddToWorklist(Value.getNode());
12097     if (Shorter.getNode())
12098       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12099                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12100
12101     // Otherwise, see if we can simplify the operation with
12102     // SimplifyDemandedBits, which only works if the value has a single use.
12103     if (SimplifyDemandedBits(Value,
12104                         APInt::getLowBitsSet(
12105                           Value.getValueType().getScalarType().getSizeInBits(),
12106                           ST->getMemoryVT().getScalarType().getSizeInBits())))
12107       return SDValue(N, 0);
12108   }
12109
12110   // If this is a load followed by a store to the same location, then the store
12111   // is dead/noop.
12112   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12113     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12114         ST->isUnindexed() && !ST->isVolatile() &&
12115         // There can't be any side effects between the load and store, such as
12116         // a call or store.
12117         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12118       // The store is dead, remove it.
12119       return Chain;
12120     }
12121   }
12122
12123   // If this is a store followed by a store with the same value to the same
12124   // location, then the store is dead/noop.
12125   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12126     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12127         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12128         ST1->isUnindexed() && !ST1->isVolatile()) {
12129       // The store is dead, remove it.
12130       return Chain;
12131     }
12132   }
12133
12134   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12135   // truncating store.  We can do this even if this is already a truncstore.
12136   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12137       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12138       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12139                             ST->getMemoryVT())) {
12140     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12141                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12142   }
12143
12144   // Only perform this optimization before the types are legal, because we
12145   // don't want to perform this optimization on every DAGCombine invocation.
12146   if (!LegalTypes) {
12147     bool EverChanged = false;
12148
12149     do {
12150       // There can be multiple store sequences on the same chain.
12151       // Keep trying to merge store sequences until we are unable to do so
12152       // or until we merge the last store on the chain.
12153       bool Changed = MergeConsecutiveStores(ST);
12154       EverChanged |= Changed;
12155       if (!Changed) break;
12156     } while (ST->getOpcode() != ISD::DELETED_NODE);
12157
12158     if (EverChanged)
12159       return SDValue(N, 0);
12160   }
12161
12162   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12163   //
12164   // Make sure to do this only after attempting to merge stores in order to
12165   //  avoid changing the types of some subset of stores due to visit order,
12166   //  preventing their merging.
12167   if (isa<ConstantFPSDNode>(Value)) {
12168     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12169       return NewSt;
12170   }
12171
12172   return ReduceLoadOpStoreWidth(N);
12173 }
12174
12175 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12176   SDValue InVec = N->getOperand(0);
12177   SDValue InVal = N->getOperand(1);
12178   SDValue EltNo = N->getOperand(2);
12179   SDLoc dl(N);
12180
12181   // If the inserted element is an UNDEF, just use the input vector.
12182   if (InVal.isUndef())
12183     return InVec;
12184
12185   EVT VT = InVec.getValueType();
12186
12187   // If we can't generate a legal BUILD_VECTOR, exit
12188   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12189     return SDValue();
12190
12191   // Check that we know which element is being inserted
12192   if (!isa<ConstantSDNode>(EltNo))
12193     return SDValue();
12194   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12195
12196   // Canonicalize insert_vector_elt dag nodes.
12197   // Example:
12198   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12199   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12200   //
12201   // Do this only if the child insert_vector node has one use; also
12202   // do this only if indices are both constants and Idx1 < Idx0.
12203   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12204       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12205     unsigned OtherElt =
12206       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12207     if (Elt < OtherElt) {
12208       // Swap nodes.
12209       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12210                                   InVec.getOperand(0), InVal, EltNo);
12211       AddToWorklist(NewOp.getNode());
12212       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12213                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12214     }
12215   }
12216
12217   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12218   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12219   // vector elements.
12220   SmallVector<SDValue, 8> Ops;
12221   // Do not combine these two vectors if the output vector will not replace
12222   // the input vector.
12223   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12224     Ops.append(InVec.getNode()->op_begin(),
12225                InVec.getNode()->op_end());
12226   } else if (InVec.isUndef()) {
12227     unsigned NElts = VT.getVectorNumElements();
12228     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12229   } else {
12230     return SDValue();
12231   }
12232
12233   // Insert the element
12234   if (Elt < Ops.size()) {
12235     // All the operands of BUILD_VECTOR must have the same type;
12236     // we enforce that here.
12237     EVT OpVT = Ops[0].getValueType();
12238     if (InVal.getValueType() != OpVT)
12239       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12240                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12241                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12242     Ops[Elt] = InVal;
12243   }
12244
12245   // Return the new vector
12246   return DAG.getBuildVector(VT, dl, Ops);
12247 }
12248
12249 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12250     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12251   assert(!OriginalLoad->isVolatile());
12252
12253   EVT ResultVT = EVE->getValueType(0);
12254   EVT VecEltVT = InVecVT.getVectorElementType();
12255   unsigned Align = OriginalLoad->getAlignment();
12256   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12257       VecEltVT.getTypeForEVT(*DAG.getContext()));
12258
12259   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12260     return SDValue();
12261
12262   Align = NewAlign;
12263
12264   SDValue NewPtr = OriginalLoad->getBasePtr();
12265   SDValue Offset;
12266   EVT PtrType = NewPtr.getValueType();
12267   MachinePointerInfo MPI;
12268   SDLoc DL(EVE);
12269   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12270     int Elt = ConstEltNo->getZExtValue();
12271     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12272     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12273     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12274   } else {
12275     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12276     Offset = DAG.getNode(
12277         ISD::MUL, DL, PtrType, Offset,
12278         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12279     MPI = OriginalLoad->getPointerInfo();
12280   }
12281   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12282
12283   // The replacement we need to do here is a little tricky: we need to
12284   // replace an extractelement of a load with a load.
12285   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12286   // Note that this replacement assumes that the extractvalue is the only
12287   // use of the load; that's okay because we don't want to perform this
12288   // transformation in other cases anyway.
12289   SDValue Load;
12290   SDValue Chain;
12291   if (ResultVT.bitsGT(VecEltVT)) {
12292     // If the result type of vextract is wider than the load, then issue an
12293     // extending load instead.
12294     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12295                                                   VecEltVT)
12296                                    ? ISD::ZEXTLOAD
12297                                    : ISD::EXTLOAD;
12298     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12299                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12300                           Align, OriginalLoad->getMemOperand()->getFlags(),
12301                           OriginalLoad->getAAInfo());
12302     Chain = Load.getValue(1);
12303   } else {
12304     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12305                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12306                        OriginalLoad->getAAInfo());
12307     Chain = Load.getValue(1);
12308     if (ResultVT.bitsLT(VecEltVT))
12309       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12310     else
12311       Load = DAG.getBitcast(ResultVT, Load);
12312   }
12313   WorklistRemover DeadNodes(*this);
12314   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12315   SDValue To[] = { Load, Chain };
12316   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12317   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12318   // worklist explicitly as well.
12319   AddToWorklist(Load.getNode());
12320   AddUsersToWorklist(Load.getNode()); // Add users too
12321   // Make sure to revisit this node to clean it up; it will usually be dead.
12322   AddToWorklist(EVE);
12323   ++OpsNarrowed;
12324   return SDValue(EVE, 0);
12325 }
12326
12327 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12328   // (vextract (scalar_to_vector val, 0) -> val
12329   SDValue InVec = N->getOperand(0);
12330   EVT VT = InVec.getValueType();
12331   EVT NVT = N->getValueType(0);
12332
12333   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12334     // Check if the result type doesn't match the inserted element type. A
12335     // SCALAR_TO_VECTOR may truncate the inserted element and the
12336     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12337     SDValue InOp = InVec.getOperand(0);
12338     if (InOp.getValueType() != NVT) {
12339       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12340       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12341     }
12342     return InOp;
12343   }
12344
12345   SDValue EltNo = N->getOperand(1);
12346   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12347
12348   // extract_vector_elt (build_vector x, y), 1 -> y
12349   if (ConstEltNo &&
12350       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12351       TLI.isTypeLegal(VT) &&
12352       (InVec.hasOneUse() ||
12353        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12354     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12355     EVT InEltVT = Elt.getValueType();
12356
12357     // Sometimes build_vector's scalar input types do not match result type.
12358     if (NVT == InEltVT)
12359       return Elt;
12360
12361     // TODO: It may be useful to truncate if free if the build_vector implicitly
12362     // converts.
12363   }
12364
12365   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12366   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12367       ConstEltNo->isNullValue() && VT.isInteger()) {
12368     SDValue BCSrc = InVec.getOperand(0);
12369     if (BCSrc.getValueType().isScalarInteger())
12370       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12371   }
12372
12373   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12374   //
12375   // This only really matters if the index is non-constant since other combines
12376   // on the constant elements already work.
12377   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12378       EltNo == InVec.getOperand(2)) {
12379     SDValue Elt = InVec.getOperand(1);
12380     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12381   }
12382
12383   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12384   // We only perform this optimization before the op legalization phase because
12385   // we may introduce new vector instructions which are not backed by TD
12386   // patterns. For example on AVX, extracting elements from a wide vector
12387   // without using extract_subvector. However, if we can find an underlying
12388   // scalar value, then we can always use that.
12389   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12390     int NumElem = VT.getVectorNumElements();
12391     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12392     // Find the new index to extract from.
12393     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12394
12395     // Extracting an undef index is undef.
12396     if (OrigElt == -1)
12397       return DAG.getUNDEF(NVT);
12398
12399     // Select the right vector half to extract from.
12400     SDValue SVInVec;
12401     if (OrigElt < NumElem) {
12402       SVInVec = InVec->getOperand(0);
12403     } else {
12404       SVInVec = InVec->getOperand(1);
12405       OrigElt -= NumElem;
12406     }
12407
12408     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12409       SDValue InOp = SVInVec.getOperand(OrigElt);
12410       if (InOp.getValueType() != NVT) {
12411         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12412         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12413       }
12414
12415       return InOp;
12416     }
12417
12418     // FIXME: We should handle recursing on other vector shuffles and
12419     // scalar_to_vector here as well.
12420
12421     if (!LegalOperations) {
12422       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12423       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12424                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12425     }
12426   }
12427
12428   bool BCNumEltsChanged = false;
12429   EVT ExtVT = VT.getVectorElementType();
12430   EVT LVT = ExtVT;
12431
12432   // If the result of load has to be truncated, then it's not necessarily
12433   // profitable.
12434   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12435     return SDValue();
12436
12437   if (InVec.getOpcode() == ISD::BITCAST) {
12438     // Don't duplicate a load with other uses.
12439     if (!InVec.hasOneUse())
12440       return SDValue();
12441
12442     EVT BCVT = InVec.getOperand(0).getValueType();
12443     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12444       return SDValue();
12445     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12446       BCNumEltsChanged = true;
12447     InVec = InVec.getOperand(0);
12448     ExtVT = BCVT.getVectorElementType();
12449   }
12450
12451   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12452   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12453       ISD::isNormalLoad(InVec.getNode()) &&
12454       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12455     SDValue Index = N->getOperand(1);
12456     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12457       if (!OrigLoad->isVolatile()) {
12458         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12459                                                              OrigLoad);
12460       }
12461     }
12462   }
12463
12464   // Perform only after legalization to ensure build_vector / vector_shuffle
12465   // optimizations have already been done.
12466   if (!LegalOperations) return SDValue();
12467
12468   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12469   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12470   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12471
12472   if (ConstEltNo) {
12473     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12474
12475     LoadSDNode *LN0 = nullptr;
12476     const ShuffleVectorSDNode *SVN = nullptr;
12477     if (ISD::isNormalLoad(InVec.getNode())) {
12478       LN0 = cast<LoadSDNode>(InVec);
12479     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12480                InVec.getOperand(0).getValueType() == ExtVT &&
12481                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12482       // Don't duplicate a load with other uses.
12483       if (!InVec.hasOneUse())
12484         return SDValue();
12485
12486       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12487     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12488       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12489       // =>
12490       // (load $addr+1*size)
12491
12492       // Don't duplicate a load with other uses.
12493       if (!InVec.hasOneUse())
12494         return SDValue();
12495
12496       // If the bit convert changed the number of elements, it is unsafe
12497       // to examine the mask.
12498       if (BCNumEltsChanged)
12499         return SDValue();
12500
12501       // Select the input vector, guarding against out of range extract vector.
12502       unsigned NumElems = VT.getVectorNumElements();
12503       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12504       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12505
12506       if (InVec.getOpcode() == ISD::BITCAST) {
12507         // Don't duplicate a load with other uses.
12508         if (!InVec.hasOneUse())
12509           return SDValue();
12510
12511         InVec = InVec.getOperand(0);
12512       }
12513       if (ISD::isNormalLoad(InVec.getNode())) {
12514         LN0 = cast<LoadSDNode>(InVec);
12515         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12516         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12517       }
12518     }
12519
12520     // Make sure we found a non-volatile load and the extractelement is
12521     // the only use.
12522     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12523       return SDValue();
12524
12525     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12526     if (Elt == -1)
12527       return DAG.getUNDEF(LVT);
12528
12529     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12530   }
12531
12532   return SDValue();
12533 }
12534
12535 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12536 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12537   // We perform this optimization post type-legalization because
12538   // the type-legalizer often scalarizes integer-promoted vectors.
12539   // Performing this optimization before may create bit-casts which
12540   // will be type-legalized to complex code sequences.
12541   // We perform this optimization only before the operation legalizer because we
12542   // may introduce illegal operations.
12543   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12544     return SDValue();
12545
12546   unsigned NumInScalars = N->getNumOperands();
12547   SDLoc dl(N);
12548   EVT VT = N->getValueType(0);
12549
12550   // Check to see if this is a BUILD_VECTOR of a bunch of values
12551   // which come from any_extend or zero_extend nodes. If so, we can create
12552   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12553   // optimizations. We do not handle sign-extend because we can't fill the sign
12554   // using shuffles.
12555   EVT SourceType = MVT::Other;
12556   bool AllAnyExt = true;
12557
12558   for (unsigned i = 0; i != NumInScalars; ++i) {
12559     SDValue In = N->getOperand(i);
12560     // Ignore undef inputs.
12561     if (In.isUndef()) continue;
12562
12563     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12564     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12565
12566     // Abort if the element is not an extension.
12567     if (!ZeroExt && !AnyExt) {
12568       SourceType = MVT::Other;
12569       break;
12570     }
12571
12572     // The input is a ZeroExt or AnyExt. Check the original type.
12573     EVT InTy = In.getOperand(0).getValueType();
12574
12575     // Check that all of the widened source types are the same.
12576     if (SourceType == MVT::Other)
12577       // First time.
12578       SourceType = InTy;
12579     else if (InTy != SourceType) {
12580       // Multiple income types. Abort.
12581       SourceType = MVT::Other;
12582       break;
12583     }
12584
12585     // Check if all of the extends are ANY_EXTENDs.
12586     AllAnyExt &= AnyExt;
12587   }
12588
12589   // In order to have valid types, all of the inputs must be extended from the
12590   // same source type and all of the inputs must be any or zero extend.
12591   // Scalar sizes must be a power of two.
12592   EVT OutScalarTy = VT.getScalarType();
12593   bool ValidTypes = SourceType != MVT::Other &&
12594                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12595                  isPowerOf2_32(SourceType.getSizeInBits());
12596
12597   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12598   // turn into a single shuffle instruction.
12599   if (!ValidTypes)
12600     return SDValue();
12601
12602   bool isLE = DAG.getDataLayout().isLittleEndian();
12603   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12604   assert(ElemRatio > 1 && "Invalid element size ratio");
12605   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12606                                DAG.getConstant(0, SDLoc(N), SourceType);
12607
12608   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12609   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12610
12611   // Populate the new build_vector
12612   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12613     SDValue Cast = N->getOperand(i);
12614     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12615             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12616             Cast.isUndef()) && "Invalid cast opcode");
12617     SDValue In;
12618     if (Cast.isUndef())
12619       In = DAG.getUNDEF(SourceType);
12620     else
12621       In = Cast->getOperand(0);
12622     unsigned Index = isLE ? (i * ElemRatio) :
12623                             (i * ElemRatio + (ElemRatio - 1));
12624
12625     assert(Index < Ops.size() && "Invalid index");
12626     Ops[Index] = In;
12627   }
12628
12629   // The type of the new BUILD_VECTOR node.
12630   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12631   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12632          "Invalid vector size");
12633   // Check if the new vector type is legal.
12634   if (!isTypeLegal(VecVT)) return SDValue();
12635
12636   // Make the new BUILD_VECTOR.
12637   SDValue BV = DAG.getBuildVector(VecVT, dl, Ops);
12638
12639   // The new BUILD_VECTOR node has the potential to be further optimized.
12640   AddToWorklist(BV.getNode());
12641   // Bitcast to the desired type.
12642   return DAG.getBitcast(VT, BV);
12643 }
12644
12645 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12646   EVT VT = N->getValueType(0);
12647
12648   unsigned NumInScalars = N->getNumOperands();
12649   SDLoc dl(N);
12650
12651   EVT SrcVT = MVT::Other;
12652   unsigned Opcode = ISD::DELETED_NODE;
12653   unsigned NumDefs = 0;
12654
12655   for (unsigned i = 0; i != NumInScalars; ++i) {
12656     SDValue In = N->getOperand(i);
12657     unsigned Opc = In.getOpcode();
12658
12659     if (Opc == ISD::UNDEF)
12660       continue;
12661
12662     // If all scalar values are floats and converted from integers.
12663     if (Opcode == ISD::DELETED_NODE &&
12664         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12665       Opcode = Opc;
12666     }
12667
12668     if (Opc != Opcode)
12669       return SDValue();
12670
12671     EVT InVT = In.getOperand(0).getValueType();
12672
12673     // If all scalar values are typed differently, bail out. It's chosen to
12674     // simplify BUILD_VECTOR of integer types.
12675     if (SrcVT == MVT::Other)
12676       SrcVT = InVT;
12677     if (SrcVT != InVT)
12678       return SDValue();
12679     NumDefs++;
12680   }
12681
12682   // If the vector has just one element defined, it's not worth to fold it into
12683   // a vectorized one.
12684   if (NumDefs < 2)
12685     return SDValue();
12686
12687   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12688          && "Should only handle conversion from integer to float.");
12689   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12690
12691   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12692
12693   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12694     return SDValue();
12695
12696   // Just because the floating-point vector type is legal does not necessarily
12697   // mean that the corresponding integer vector type is.
12698   if (!isTypeLegal(NVT))
12699     return SDValue();
12700
12701   SmallVector<SDValue, 8> Opnds;
12702   for (unsigned i = 0; i != NumInScalars; ++i) {
12703     SDValue In = N->getOperand(i);
12704
12705     if (In.isUndef())
12706       Opnds.push_back(DAG.getUNDEF(SrcVT));
12707     else
12708       Opnds.push_back(In.getOperand(0));
12709   }
12710   SDValue BV = DAG.getBuildVector(NVT, dl, Opnds);
12711   AddToWorklist(BV.getNode());
12712
12713   return DAG.getNode(Opcode, dl, VT, BV);
12714 }
12715
12716 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12717   unsigned NumInScalars = N->getNumOperands();
12718   SDLoc dl(N);
12719   EVT VT = N->getValueType(0);
12720
12721   // A vector built entirely of undefs is undef.
12722   if (ISD::allOperandsUndef(N))
12723     return DAG.getUNDEF(VT);
12724
12725   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12726     return V;
12727
12728   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12729     return V;
12730
12731   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12732   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12733   // at most two distinct vectors, turn this into a shuffle node.
12734
12735   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12736   if (!isTypeLegal(VT))
12737     return SDValue();
12738
12739   // May only combine to shuffle after legalize if shuffle is legal.
12740   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12741     return SDValue();
12742
12743   SDValue VecIn1, VecIn2;
12744   bool UsesZeroVector = false;
12745   for (unsigned i = 0; i != NumInScalars; ++i) {
12746     SDValue Op = N->getOperand(i);
12747     // Ignore undef inputs.
12748     if (Op.isUndef()) continue;
12749
12750     // See if we can combine this build_vector into a blend with a zero vector.
12751     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12752       UsesZeroVector = true;
12753       continue;
12754     }
12755
12756     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12757     // constant index, bail out.
12758     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12759         !isa<ConstantSDNode>(Op.getOperand(1))) {
12760       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12761       break;
12762     }
12763
12764     // We allow up to two distinct input vectors.
12765     SDValue ExtractedFromVec = Op.getOperand(0);
12766     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12767       continue;
12768
12769     if (!VecIn1.getNode()) {
12770       VecIn1 = ExtractedFromVec;
12771     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12772       VecIn2 = ExtractedFromVec;
12773     } else {
12774       // Too many inputs.
12775       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12776       break;
12777     }
12778   }
12779
12780   // If everything is good, we can make a shuffle operation.
12781   if (VecIn1.getNode()) {
12782     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12783     SmallVector<int, 8> Mask;
12784     for (unsigned i = 0; i != NumInScalars; ++i) {
12785       unsigned Opcode = N->getOperand(i).getOpcode();
12786       if (Opcode == ISD::UNDEF) {
12787         Mask.push_back(-1);
12788         continue;
12789       }
12790
12791       // Operands can also be zero.
12792       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12793         assert(UsesZeroVector &&
12794                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12795                "Unexpected node found!");
12796         Mask.push_back(NumInScalars+i);
12797         continue;
12798       }
12799
12800       // If extracting from the first vector, just use the index directly.
12801       SDValue Extract = N->getOperand(i);
12802       SDValue ExtVal = Extract.getOperand(1);
12803       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12804       if (Extract.getOperand(0) == VecIn1) {
12805         Mask.push_back(ExtIndex);
12806         continue;
12807       }
12808
12809       // Otherwise, use InIdx + InputVecSize
12810       Mask.push_back(InNumElements + ExtIndex);
12811     }
12812
12813     // Avoid introducing illegal shuffles with zero.
12814     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12815       return SDValue();
12816
12817     // We can't generate a shuffle node with mismatched input and output types.
12818     // Attempt to transform a single input vector to the correct type.
12819     if ((VT != VecIn1.getValueType())) {
12820       // If the input vector type has a different base type to the output
12821       // vector type, bail out.
12822       EVT VTElemType = VT.getVectorElementType();
12823       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12824           (VecIn2.getNode() &&
12825            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12826         return SDValue();
12827
12828       // If the input vector is too small, widen it.
12829       // We only support widening of vectors which are half the size of the
12830       // output registers. For example XMM->YMM widening on X86 with AVX.
12831       EVT VecInT = VecIn1.getValueType();
12832       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12833         // If we only have one small input, widen it by adding undef values.
12834         if (!VecIn2.getNode())
12835           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12836                                DAG.getUNDEF(VecIn1.getValueType()));
12837         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12838           // If we have two small inputs of the same type, try to concat them.
12839           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12840           VecIn2 = SDValue(nullptr, 0);
12841         } else
12842           return SDValue();
12843       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12844         // If the input vector is too large, try to split it.
12845         // We don't support having two input vectors that are too large.
12846         // If the zero vector was used, we can not split the vector,
12847         // since we'd need 3 inputs.
12848         if (UsesZeroVector || VecIn2.getNode())
12849           return SDValue();
12850
12851         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12852           return SDValue();
12853
12854         // Try to replace VecIn1 with two extract_subvectors
12855         // No need to update the masks, they should still be correct.
12856         VecIn2 = DAG.getNode(
12857             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12858             DAG.getConstant(VT.getVectorNumElements(), dl,
12859                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12860         VecIn1 = DAG.getNode(
12861             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12862             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12863       } else
12864         return SDValue();
12865     }
12866
12867     if (UsesZeroVector)
12868       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12869                                 DAG.getConstantFP(0.0, dl, VT);
12870     else
12871       // If VecIn2 is unused then change it to undef.
12872       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12873
12874     // Check that we were able to transform all incoming values to the same
12875     // type.
12876     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12877         VecIn1.getValueType() != VT)
12878           return SDValue();
12879
12880     // Return the new VECTOR_SHUFFLE node.
12881     SDValue Ops[2];
12882     Ops[0] = VecIn1;
12883     Ops[1] = VecIn2;
12884     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], Mask);
12885   }
12886
12887   return SDValue();
12888 }
12889
12890 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12892   EVT OpVT = N->getOperand(0).getValueType();
12893
12894   // If the operands are legal vectors, leave them alone.
12895   if (TLI.isTypeLegal(OpVT))
12896     return SDValue();
12897
12898   SDLoc DL(N);
12899   EVT VT = N->getValueType(0);
12900   SmallVector<SDValue, 8> Ops;
12901
12902   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12903   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12904
12905   // Keep track of what we encounter.
12906   bool AnyInteger = false;
12907   bool AnyFP = false;
12908   for (const SDValue &Op : N->ops()) {
12909     if (ISD::BITCAST == Op.getOpcode() &&
12910         !Op.getOperand(0).getValueType().isVector())
12911       Ops.push_back(Op.getOperand(0));
12912     else if (ISD::UNDEF == Op.getOpcode())
12913       Ops.push_back(ScalarUndef);
12914     else
12915       return SDValue();
12916
12917     // Note whether we encounter an integer or floating point scalar.
12918     // If it's neither, bail out, it could be something weird like x86mmx.
12919     EVT LastOpVT = Ops.back().getValueType();
12920     if (LastOpVT.isFloatingPoint())
12921       AnyFP = true;
12922     else if (LastOpVT.isInteger())
12923       AnyInteger = true;
12924     else
12925       return SDValue();
12926   }
12927
12928   // If any of the operands is a floating point scalar bitcast to a vector,
12929   // use floating point types throughout, and bitcast everything.
12930   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12931   if (AnyFP) {
12932     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12933     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12934     if (AnyInteger) {
12935       for (SDValue &Op : Ops) {
12936         if (Op.getValueType() == SVT)
12937           continue;
12938         if (Op.isUndef())
12939           Op = ScalarUndef;
12940         else
12941           Op = DAG.getBitcast(SVT, Op);
12942       }
12943     }
12944   }
12945
12946   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12947                                VT.getSizeInBits() / SVT.getSizeInBits());
12948   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
12949 }
12950
12951 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12952 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12953 // most two distinct vectors the same size as the result, attempt to turn this
12954 // into a legal shuffle.
12955 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12956   EVT VT = N->getValueType(0);
12957   EVT OpVT = N->getOperand(0).getValueType();
12958   int NumElts = VT.getVectorNumElements();
12959   int NumOpElts = OpVT.getVectorNumElements();
12960
12961   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12962   SmallVector<int, 8> Mask;
12963
12964   for (SDValue Op : N->ops()) {
12965     // Peek through any bitcast.
12966     while (Op.getOpcode() == ISD::BITCAST)
12967       Op = Op.getOperand(0);
12968
12969     // UNDEF nodes convert to UNDEF shuffle mask values.
12970     if (Op.isUndef()) {
12971       Mask.append((unsigned)NumOpElts, -1);
12972       continue;
12973     }
12974
12975     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12976       return SDValue();
12977
12978     // What vector are we extracting the subvector from and at what index?
12979     SDValue ExtVec = Op.getOperand(0);
12980
12981     // We want the EVT of the original extraction to correctly scale the
12982     // extraction index.
12983     EVT ExtVT = ExtVec.getValueType();
12984
12985     // Peek through any bitcast.
12986     while (ExtVec.getOpcode() == ISD::BITCAST)
12987       ExtVec = ExtVec.getOperand(0);
12988
12989     // UNDEF nodes convert to UNDEF shuffle mask values.
12990     if (ExtVec.isUndef()) {
12991       Mask.append((unsigned)NumOpElts, -1);
12992       continue;
12993     }
12994
12995     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12996       return SDValue();
12997     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12998
12999     // Ensure that we are extracting a subvector from a vector the same
13000     // size as the result.
13001     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13002       return SDValue();
13003
13004     // Scale the subvector index to account for any bitcast.
13005     int NumExtElts = ExtVT.getVectorNumElements();
13006     if (0 == (NumExtElts % NumElts))
13007       ExtIdx /= (NumExtElts / NumElts);
13008     else if (0 == (NumElts % NumExtElts))
13009       ExtIdx *= (NumElts / NumExtElts);
13010     else
13011       return SDValue();
13012
13013     // At most we can reference 2 inputs in the final shuffle.
13014     if (SV0.isUndef() || SV0 == ExtVec) {
13015       SV0 = ExtVec;
13016       for (int i = 0; i != NumOpElts; ++i)
13017         Mask.push_back(i + ExtIdx);
13018     } else if (SV1.isUndef() || SV1 == ExtVec) {
13019       SV1 = ExtVec;
13020       for (int i = 0; i != NumOpElts; ++i)
13021         Mask.push_back(i + ExtIdx + NumElts);
13022     } else {
13023       return SDValue();
13024     }
13025   }
13026
13027   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13028     return SDValue();
13029
13030   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13031                               DAG.getBitcast(VT, SV1), Mask);
13032 }
13033
13034 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13035   // If we only have one input vector, we don't need to do any concatenation.
13036   if (N->getNumOperands() == 1)
13037     return N->getOperand(0);
13038
13039   // Check if all of the operands are undefs.
13040   EVT VT = N->getValueType(0);
13041   if (ISD::allOperandsUndef(N))
13042     return DAG.getUNDEF(VT);
13043
13044   // Optimize concat_vectors where all but the first of the vectors are undef.
13045   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13046         return Op.isUndef();
13047       })) {
13048     SDValue In = N->getOperand(0);
13049     assert(In.getValueType().isVector() && "Must concat vectors");
13050
13051     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13052     if (In->getOpcode() == ISD::BITCAST &&
13053         !In->getOperand(0)->getValueType(0).isVector()) {
13054       SDValue Scalar = In->getOperand(0);
13055
13056       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13057       // look through the trunc so we can still do the transform:
13058       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13059       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13060           !TLI.isTypeLegal(Scalar.getValueType()) &&
13061           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13062         Scalar = Scalar->getOperand(0);
13063
13064       EVT SclTy = Scalar->getValueType(0);
13065
13066       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13067         return SDValue();
13068
13069       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13070                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13071       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13072         return SDValue();
13073
13074       SDLoc dl = SDLoc(N);
13075       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
13076       return DAG.getBitcast(VT, Res);
13077     }
13078   }
13079
13080   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13081   // We have already tested above for an UNDEF only concatenation.
13082   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13083   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13084   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13085     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13086   };
13087   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13088     SmallVector<SDValue, 8> Opnds;
13089     EVT SVT = VT.getScalarType();
13090
13091     EVT MinVT = SVT;
13092     if (!SVT.isFloatingPoint()) {
13093       // If BUILD_VECTOR are from built from integer, they may have different
13094       // operand types. Get the smallest type and truncate all operands to it.
13095       bool FoundMinVT = false;
13096       for (const SDValue &Op : N->ops())
13097         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13098           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13099           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13100           FoundMinVT = true;
13101         }
13102       assert(FoundMinVT && "Concat vector type mismatch");
13103     }
13104
13105     for (const SDValue &Op : N->ops()) {
13106       EVT OpVT = Op.getValueType();
13107       unsigned NumElts = OpVT.getVectorNumElements();
13108
13109       if (ISD::UNDEF == Op.getOpcode())
13110         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13111
13112       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13113         if (SVT.isFloatingPoint()) {
13114           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13115           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13116         } else {
13117           for (unsigned i = 0; i != NumElts; ++i)
13118             Opnds.push_back(
13119                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13120         }
13121       }
13122     }
13123
13124     assert(VT.getVectorNumElements() == Opnds.size() &&
13125            "Concat vector type mismatch");
13126     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13127   }
13128
13129   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13130   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13131     return V;
13132
13133   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13134   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13135     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13136       return V;
13137
13138   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13139   // nodes often generate nop CONCAT_VECTOR nodes.
13140   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13141   // place the incoming vectors at the exact same location.
13142   SDValue SingleSource = SDValue();
13143   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13144
13145   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13146     SDValue Op = N->getOperand(i);
13147
13148     if (Op.isUndef())
13149       continue;
13150
13151     // Check if this is the identity extract:
13152     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13153       return SDValue();
13154
13155     // Find the single incoming vector for the extract_subvector.
13156     if (SingleSource.getNode()) {
13157       if (Op.getOperand(0) != SingleSource)
13158         return SDValue();
13159     } else {
13160       SingleSource = Op.getOperand(0);
13161
13162       // Check the source type is the same as the type of the result.
13163       // If not, this concat may extend the vector, so we can not
13164       // optimize it away.
13165       if (SingleSource.getValueType() != N->getValueType(0))
13166         return SDValue();
13167     }
13168
13169     unsigned IdentityIndex = i * PartNumElem;
13170     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13171     // The extract index must be constant.
13172     if (!CS)
13173       return SDValue();
13174
13175     // Check that we are reading from the identity index.
13176     if (CS->getZExtValue() != IdentityIndex)
13177       return SDValue();
13178   }
13179
13180   if (SingleSource.getNode())
13181     return SingleSource;
13182
13183   return SDValue();
13184 }
13185
13186 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13187   EVT NVT = N->getValueType(0);
13188   SDValue V = N->getOperand(0);
13189
13190   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13191     // Combine:
13192     //    (extract_subvec (concat V1, V2, ...), i)
13193     // Into:
13194     //    Vi if possible
13195     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13196     // type.
13197     if (V->getOperand(0).getValueType() != NVT)
13198       return SDValue();
13199     unsigned Idx = N->getConstantOperandVal(1);
13200     unsigned NumElems = NVT.getVectorNumElements();
13201     assert((Idx % NumElems) == 0 &&
13202            "IDX in concat is not a multiple of the result vector length.");
13203     return V->getOperand(Idx / NumElems);
13204   }
13205
13206   // Skip bitcasting
13207   if (V->getOpcode() == ISD::BITCAST)
13208     V = V.getOperand(0);
13209
13210   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13211     SDLoc dl(N);
13212     // Handle only simple case where vector being inserted and vector
13213     // being extracted are of same type, and are half size of larger vectors.
13214     EVT BigVT = V->getOperand(0).getValueType();
13215     EVT SmallVT = V->getOperand(1).getValueType();
13216     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13217       return SDValue();
13218
13219     // Only handle cases where both indexes are constants with the same type.
13220     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13221     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13222
13223     if (InsIdx && ExtIdx &&
13224         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13225         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13226       // Combine:
13227       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13228       // Into:
13229       //    indices are equal or bit offsets are equal => V1
13230       //    otherwise => (extract_subvec V1, ExtIdx)
13231       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13232           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13233         return DAG.getBitcast(NVT, V->getOperand(1));
13234       return DAG.getNode(
13235           ISD::EXTRACT_SUBVECTOR, dl, NVT,
13236           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13237           N->getOperand(1));
13238     }
13239   }
13240
13241   return SDValue();
13242 }
13243
13244 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13245                                                  SDValue V, SelectionDAG &DAG) {
13246   SDLoc DL(V);
13247   EVT VT = V.getValueType();
13248
13249   switch (V.getOpcode()) {
13250   default:
13251     return V;
13252
13253   case ISD::CONCAT_VECTORS: {
13254     EVT OpVT = V->getOperand(0).getValueType();
13255     int OpSize = OpVT.getVectorNumElements();
13256     SmallBitVector OpUsedElements(OpSize, false);
13257     bool FoundSimplification = false;
13258     SmallVector<SDValue, 4> NewOps;
13259     NewOps.reserve(V->getNumOperands());
13260     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13261       SDValue Op = V->getOperand(i);
13262       bool OpUsed = false;
13263       for (int j = 0; j < OpSize; ++j)
13264         if (UsedElements[i * OpSize + j]) {
13265           OpUsedElements[j] = true;
13266           OpUsed = true;
13267         }
13268       NewOps.push_back(
13269           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13270                  : DAG.getUNDEF(OpVT));
13271       FoundSimplification |= Op == NewOps.back();
13272       OpUsedElements.reset();
13273     }
13274     if (FoundSimplification)
13275       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13276     return V;
13277   }
13278
13279   case ISD::INSERT_SUBVECTOR: {
13280     SDValue BaseV = V->getOperand(0);
13281     SDValue SubV = V->getOperand(1);
13282     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13283     if (!IdxN)
13284       return V;
13285
13286     int SubSize = SubV.getValueType().getVectorNumElements();
13287     int Idx = IdxN->getZExtValue();
13288     bool SubVectorUsed = false;
13289     SmallBitVector SubUsedElements(SubSize, false);
13290     for (int i = 0; i < SubSize; ++i)
13291       if (UsedElements[i + Idx]) {
13292         SubVectorUsed = true;
13293         SubUsedElements[i] = true;
13294         UsedElements[i + Idx] = false;
13295       }
13296
13297     // Now recurse on both the base and sub vectors.
13298     SDValue SimplifiedSubV =
13299         SubVectorUsed
13300             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13301             : DAG.getUNDEF(SubV.getValueType());
13302     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13303     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13304       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13305                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13306     return V;
13307   }
13308   }
13309 }
13310
13311 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13312                                        SDValue N1, SelectionDAG &DAG) {
13313   EVT VT = SVN->getValueType(0);
13314   int NumElts = VT.getVectorNumElements();
13315   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13316   for (int M : SVN->getMask())
13317     if (M >= 0 && M < NumElts)
13318       N0UsedElements[M] = true;
13319     else if (M >= NumElts)
13320       N1UsedElements[M - NumElts] = true;
13321
13322   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13323   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13324   if (S0 == N0 && S1 == N1)
13325     return SDValue();
13326
13327   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13328 }
13329
13330 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13331 // or turn a shuffle of a single concat into simpler shuffle then concat.
13332 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13333   EVT VT = N->getValueType(0);
13334   unsigned NumElts = VT.getVectorNumElements();
13335
13336   SDValue N0 = N->getOperand(0);
13337   SDValue N1 = N->getOperand(1);
13338   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13339
13340   SmallVector<SDValue, 4> Ops;
13341   EVT ConcatVT = N0.getOperand(0).getValueType();
13342   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13343   unsigned NumConcats = NumElts / NumElemsPerConcat;
13344
13345   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13346   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13347   // half vector elements.
13348   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13349       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13350                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13351     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13352                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13353     N1 = DAG.getUNDEF(ConcatVT);
13354     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13355   }
13356
13357   // Look at every vector that's inserted. We're looking for exact
13358   // subvector-sized copies from a concatenated vector
13359   for (unsigned I = 0; I != NumConcats; ++I) {
13360     // Make sure we're dealing with a copy.
13361     unsigned Begin = I * NumElemsPerConcat;
13362     bool AllUndef = true, NoUndef = true;
13363     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13364       if (SVN->getMaskElt(J) >= 0)
13365         AllUndef = false;
13366       else
13367         NoUndef = false;
13368     }
13369
13370     if (NoUndef) {
13371       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13372         return SDValue();
13373
13374       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13375         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13376           return SDValue();
13377
13378       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13379       if (FirstElt < N0.getNumOperands())
13380         Ops.push_back(N0.getOperand(FirstElt));
13381       else
13382         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13383
13384     } else if (AllUndef) {
13385       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13386     } else { // Mixed with general masks and undefs, can't do optimization.
13387       return SDValue();
13388     }
13389   }
13390
13391   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13392 }
13393
13394 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13395   EVT VT = N->getValueType(0);
13396   unsigned NumElts = VT.getVectorNumElements();
13397
13398   SDValue N0 = N->getOperand(0);
13399   SDValue N1 = N->getOperand(1);
13400
13401   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13402
13403   // Canonicalize shuffle undef, undef -> undef
13404   if (N0.isUndef() && N1.isUndef())
13405     return DAG.getUNDEF(VT);
13406
13407   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13408
13409   // Canonicalize shuffle v, v -> v, undef
13410   if (N0 == N1) {
13411     SmallVector<int, 8> NewMask;
13412     for (unsigned i = 0; i != NumElts; ++i) {
13413       int Idx = SVN->getMaskElt(i);
13414       if (Idx >= (int)NumElts) Idx -= NumElts;
13415       NewMask.push_back(Idx);
13416     }
13417     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13418   }
13419
13420   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13421   if (N0.isUndef())
13422     return DAG.getCommutedVectorShuffle(*SVN);
13423
13424   // Remove references to rhs if it is undef
13425   if (N1.isUndef()) {
13426     bool Changed = false;
13427     SmallVector<int, 8> NewMask;
13428     for (unsigned i = 0; i != NumElts; ++i) {
13429       int Idx = SVN->getMaskElt(i);
13430       if (Idx >= (int)NumElts) {
13431         Idx = -1;
13432         Changed = true;
13433       }
13434       NewMask.push_back(Idx);
13435     }
13436     if (Changed)
13437       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13438   }
13439
13440   // If it is a splat, check if the argument vector is another splat or a
13441   // build_vector.
13442   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13443     SDNode *V = N0.getNode();
13444
13445     // If this is a bit convert that changes the element type of the vector but
13446     // not the number of vector elements, look through it.  Be careful not to
13447     // look though conversions that change things like v4f32 to v2f64.
13448     if (V->getOpcode() == ISD::BITCAST) {
13449       SDValue ConvInput = V->getOperand(0);
13450       if (ConvInput.getValueType().isVector() &&
13451           ConvInput.getValueType().getVectorNumElements() == NumElts)
13452         V = ConvInput.getNode();
13453     }
13454
13455     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13456       assert(V->getNumOperands() == NumElts &&
13457              "BUILD_VECTOR has wrong number of operands");
13458       SDValue Base;
13459       bool AllSame = true;
13460       for (unsigned i = 0; i != NumElts; ++i) {
13461         if (!V->getOperand(i).isUndef()) {
13462           Base = V->getOperand(i);
13463           break;
13464         }
13465       }
13466       // Splat of <u, u, u, u>, return <u, u, u, u>
13467       if (!Base.getNode())
13468         return N0;
13469       for (unsigned i = 0; i != NumElts; ++i) {
13470         if (V->getOperand(i) != Base) {
13471           AllSame = false;
13472           break;
13473         }
13474       }
13475       // Splat of <x, x, x, x>, return <x, x, x, x>
13476       if (AllSame)
13477         return N0;
13478
13479       // Canonicalize any other splat as a build_vector.
13480       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13481       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13482       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13483
13484       // We may have jumped through bitcasts, so the type of the
13485       // BUILD_VECTOR may not match the type of the shuffle.
13486       if (V->getValueType(0) != VT)
13487         NewBV = DAG.getBitcast(VT, NewBV);
13488       return NewBV;
13489     }
13490   }
13491
13492   // There are various patterns used to build up a vector from smaller vectors,
13493   // subvectors, or elements. Scan chains of these and replace unused insertions
13494   // or components with undef.
13495   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13496     return S;
13497
13498   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13499       Level < AfterLegalizeVectorOps &&
13500       (N1.isUndef() ||
13501       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13502        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13503     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13504       return V;
13505   }
13506
13507   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13508   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13509   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13510     SmallVector<SDValue, 8> Ops;
13511     for (int M : SVN->getMask()) {
13512       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13513       if (M >= 0) {
13514         int Idx = M % NumElts;
13515         SDValue &S = (M < (int)NumElts ? N0 : N1);
13516         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13517           Op = S.getOperand(Idx);
13518         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13519           if (Idx == 0)
13520             Op = S.getOperand(0);
13521         } else {
13522           // Operand can't be combined - bail out.
13523           break;
13524         }
13525       }
13526       Ops.push_back(Op);
13527     }
13528     if (Ops.size() == VT.getVectorNumElements()) {
13529       // BUILD_VECTOR requires all inputs to be of the same type, find the
13530       // maximum type and extend them all.
13531       EVT SVT = VT.getScalarType();
13532       if (SVT.isInteger())
13533         for (SDValue &Op : Ops)
13534           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13535       if (SVT != VT.getScalarType())
13536         for (SDValue &Op : Ops)
13537           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13538                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13539                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13540       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13541     }
13542   }
13543
13544   // If this shuffle only has a single input that is a bitcasted shuffle,
13545   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13546   // back to their original types.
13547   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13548       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13549       TLI.isTypeLegal(VT)) {
13550
13551     // Peek through the bitcast only if there is one user.
13552     SDValue BC0 = N0;
13553     while (BC0.getOpcode() == ISD::BITCAST) {
13554       if (!BC0.hasOneUse())
13555         break;
13556       BC0 = BC0.getOperand(0);
13557     }
13558
13559     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13560       if (Scale == 1)
13561         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13562
13563       SmallVector<int, 8> NewMask;
13564       for (int M : Mask)
13565         for (int s = 0; s != Scale; ++s)
13566           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13567       return NewMask;
13568     };
13569
13570     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13571       EVT SVT = VT.getScalarType();
13572       EVT InnerVT = BC0->getValueType(0);
13573       EVT InnerSVT = InnerVT.getScalarType();
13574
13575       // Determine which shuffle works with the smaller scalar type.
13576       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13577       EVT ScaleSVT = ScaleVT.getScalarType();
13578
13579       if (TLI.isTypeLegal(ScaleVT) &&
13580           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13581           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13582
13583         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13584         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13585
13586         // Scale the shuffle masks to the smaller scalar type.
13587         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13588         SmallVector<int, 8> InnerMask =
13589             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13590         SmallVector<int, 8> OuterMask =
13591             ScaleShuffleMask(SVN->getMask(), OuterScale);
13592
13593         // Merge the shuffle masks.
13594         SmallVector<int, 8> NewMask;
13595         for (int M : OuterMask)
13596           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13597
13598         // Test for shuffle mask legality over both commutations.
13599         SDValue SV0 = BC0->getOperand(0);
13600         SDValue SV1 = BC0->getOperand(1);
13601         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13602         if (!LegalMask) {
13603           std::swap(SV0, SV1);
13604           ShuffleVectorSDNode::commuteMask(NewMask);
13605           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13606         }
13607
13608         if (LegalMask) {
13609           SV0 = DAG.getBitcast(ScaleVT, SV0);
13610           SV1 = DAG.getBitcast(ScaleVT, SV1);
13611           return DAG.getBitcast(
13612               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13613         }
13614       }
13615     }
13616   }
13617
13618   // Canonicalize shuffles according to rules:
13619   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13620   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13621   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13622   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13623       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13624       TLI.isTypeLegal(VT)) {
13625     // The incoming shuffle must be of the same type as the result of the
13626     // current shuffle.
13627     assert(N1->getOperand(0).getValueType() == VT &&
13628            "Shuffle types don't match");
13629
13630     SDValue SV0 = N1->getOperand(0);
13631     SDValue SV1 = N1->getOperand(1);
13632     bool HasSameOp0 = N0 == SV0;
13633     bool IsSV1Undef = SV1.isUndef();
13634     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13635       // Commute the operands of this shuffle so that next rule
13636       // will trigger.
13637       return DAG.getCommutedVectorShuffle(*SVN);
13638   }
13639
13640   // Try to fold according to rules:
13641   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13642   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13643   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13644   // Don't try to fold shuffles with illegal type.
13645   // Only fold if this shuffle is the only user of the other shuffle.
13646   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13647       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13648     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13649
13650     // The incoming shuffle must be of the same type as the result of the
13651     // current shuffle.
13652     assert(OtherSV->getOperand(0).getValueType() == VT &&
13653            "Shuffle types don't match");
13654
13655     SDValue SV0, SV1;
13656     SmallVector<int, 4> Mask;
13657     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13658     // operand, and SV1 as the second operand.
13659     for (unsigned i = 0; i != NumElts; ++i) {
13660       int Idx = SVN->getMaskElt(i);
13661       if (Idx < 0) {
13662         // Propagate Undef.
13663         Mask.push_back(Idx);
13664         continue;
13665       }
13666
13667       SDValue CurrentVec;
13668       if (Idx < (int)NumElts) {
13669         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13670         // shuffle mask to identify which vector is actually referenced.
13671         Idx = OtherSV->getMaskElt(Idx);
13672         if (Idx < 0) {
13673           // Propagate Undef.
13674           Mask.push_back(Idx);
13675           continue;
13676         }
13677
13678         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13679                                            : OtherSV->getOperand(1);
13680       } else {
13681         // This shuffle index references an element within N1.
13682         CurrentVec = N1;
13683       }
13684
13685       // Simple case where 'CurrentVec' is UNDEF.
13686       if (CurrentVec.isUndef()) {
13687         Mask.push_back(-1);
13688         continue;
13689       }
13690
13691       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13692       // will be the first or second operand of the combined shuffle.
13693       Idx = Idx % NumElts;
13694       if (!SV0.getNode() || SV0 == CurrentVec) {
13695         // Ok. CurrentVec is the left hand side.
13696         // Update the mask accordingly.
13697         SV0 = CurrentVec;
13698         Mask.push_back(Idx);
13699         continue;
13700       }
13701
13702       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13703       if (SV1.getNode() && SV1 != CurrentVec)
13704         return SDValue();
13705
13706       // Ok. CurrentVec is the right hand side.
13707       // Update the mask accordingly.
13708       SV1 = CurrentVec;
13709       Mask.push_back(Idx + NumElts);
13710     }
13711
13712     // Check if all indices in Mask are Undef. In case, propagate Undef.
13713     bool isUndefMask = true;
13714     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13715       isUndefMask &= Mask[i] < 0;
13716
13717     if (isUndefMask)
13718       return DAG.getUNDEF(VT);
13719
13720     if (!SV0.getNode())
13721       SV0 = DAG.getUNDEF(VT);
13722     if (!SV1.getNode())
13723       SV1 = DAG.getUNDEF(VT);
13724
13725     // Avoid introducing shuffles with illegal mask.
13726     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13727       ShuffleVectorSDNode::commuteMask(Mask);
13728
13729       if (!TLI.isShuffleMaskLegal(Mask, VT))
13730         return SDValue();
13731
13732       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13733       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13734       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13735       std::swap(SV0, SV1);
13736     }
13737
13738     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13739     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13740     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13741     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
13742   }
13743
13744   return SDValue();
13745 }
13746
13747 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13748   SDValue InVal = N->getOperand(0);
13749   EVT VT = N->getValueType(0);
13750
13751   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13752   // with a VECTOR_SHUFFLE.
13753   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13754     SDValue InVec = InVal->getOperand(0);
13755     SDValue EltNo = InVal->getOperand(1);
13756
13757     // FIXME: We could support implicit truncation if the shuffle can be
13758     // scaled to a smaller vector scalar type.
13759     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13760     if (C0 && VT == InVec.getValueType() &&
13761         VT.getScalarType() == InVal.getValueType()) {
13762       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13763       int Elt = C0->getZExtValue();
13764       NewMask[0] = Elt;
13765
13766       if (TLI.isShuffleMaskLegal(NewMask, VT))
13767         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13768                                     NewMask);
13769     }
13770   }
13771
13772   return SDValue();
13773 }
13774
13775 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13776   SDValue N0 = N->getOperand(0);
13777   SDValue N1 = N->getOperand(1);
13778   SDValue N2 = N->getOperand(2);
13779
13780   if (N0.getValueType() != N1.getValueType())
13781     return SDValue();
13782
13783   // If the input vector is a concatenation, and the insert replaces
13784   // one of the halves, we can optimize into a single concat_vectors.
13785   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
13786       N2.getOpcode() == ISD::Constant) {
13787     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13788     EVT VT = N->getValueType(0);
13789
13790     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13791     // (concat_vectors Z, Y)
13792     if (InsIdx == 0)
13793       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
13794                          N0.getOperand(1));
13795
13796     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13797     // (concat_vectors X, Z)
13798     if (InsIdx == VT.getVectorNumElements() / 2)
13799       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
13800                          N1);
13801   }
13802
13803   return SDValue();
13804 }
13805
13806 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13807   SDValue N0 = N->getOperand(0);
13808
13809   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13810   if (N0->getOpcode() == ISD::FP16_TO_FP)
13811     return N0->getOperand(0);
13812
13813   return SDValue();
13814 }
13815
13816 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13817   SDValue N0 = N->getOperand(0);
13818
13819   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13820   if (N0->getOpcode() == ISD::AND) {
13821     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13822     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13823       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13824                          N0.getOperand(0));
13825     }
13826   }
13827
13828   return SDValue();
13829 }
13830
13831 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13832 /// with the destination vector and a zero vector.
13833 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13834 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13835 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13836   EVT VT = N->getValueType(0);
13837   SDValue LHS = N->getOperand(0);
13838   SDValue RHS = N->getOperand(1);
13839   SDLoc dl(N);
13840
13841   // Make sure we're not running after operation legalization where it
13842   // may have custom lowered the vector shuffles.
13843   if (LegalOperations)
13844     return SDValue();
13845
13846   if (N->getOpcode() != ISD::AND)
13847     return SDValue();
13848
13849   if (RHS.getOpcode() == ISD::BITCAST)
13850     RHS = RHS.getOperand(0);
13851
13852   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13853     return SDValue();
13854
13855   EVT RVT = RHS.getValueType();
13856   unsigned NumElts = RHS.getNumOperands();
13857
13858   // Attempt to create a valid clear mask, splitting the mask into
13859   // sub elements and checking to see if each is
13860   // all zeros or all ones - suitable for shuffle masking.
13861   auto BuildClearMask = [&](int Split) {
13862     int NumSubElts = NumElts * Split;
13863     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13864
13865     SmallVector<int, 8> Indices;
13866     for (int i = 0; i != NumSubElts; ++i) {
13867       int EltIdx = i / Split;
13868       int SubIdx = i % Split;
13869       SDValue Elt = RHS.getOperand(EltIdx);
13870       if (Elt.isUndef()) {
13871         Indices.push_back(-1);
13872         continue;
13873       }
13874
13875       APInt Bits;
13876       if (isa<ConstantSDNode>(Elt))
13877         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13878       else if (isa<ConstantFPSDNode>(Elt))
13879         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13880       else
13881         return SDValue();
13882
13883       // Extract the sub element from the constant bit mask.
13884       if (DAG.getDataLayout().isBigEndian()) {
13885         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13886       } else {
13887         Bits = Bits.lshr(SubIdx * NumSubBits);
13888       }
13889
13890       if (Split > 1)
13891         Bits = Bits.trunc(NumSubBits);
13892
13893       if (Bits.isAllOnesValue())
13894         Indices.push_back(i);
13895       else if (Bits == 0)
13896         Indices.push_back(i + NumSubElts);
13897       else
13898         return SDValue();
13899     }
13900
13901     // Let's see if the target supports this vector_shuffle.
13902     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13903     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13904     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13905       return SDValue();
13906
13907     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13908     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13909                                                    DAG.getBitcast(ClearVT, LHS),
13910                                                    Zero, Indices));
13911   };
13912
13913   // Determine maximum split level (byte level masking).
13914   int MaxSplit = 1;
13915   if (RVT.getScalarSizeInBits() % 8 == 0)
13916     MaxSplit = RVT.getScalarSizeInBits() / 8;
13917
13918   for (int Split = 1; Split <= MaxSplit; ++Split)
13919     if (RVT.getScalarSizeInBits() % Split == 0)
13920       if (SDValue S = BuildClearMask(Split))
13921         return S;
13922
13923   return SDValue();
13924 }
13925
13926 /// Visit a binary vector operation, like ADD.
13927 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13928   assert(N->getValueType(0).isVector() &&
13929          "SimplifyVBinOp only works on vectors!");
13930
13931   SDValue LHS = N->getOperand(0);
13932   SDValue RHS = N->getOperand(1);
13933   SDValue Ops[] = {LHS, RHS};
13934
13935   // See if we can constant fold the vector operation.
13936   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13937           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13938     return Fold;
13939
13940   // Try to convert a constant mask AND into a shuffle clear mask.
13941   if (SDValue Shuffle = XformToShuffleWithZero(N))
13942     return Shuffle;
13943
13944   // Type legalization might introduce new shuffles in the DAG.
13945   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13946   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13947   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13948       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13949       LHS.getOperand(1).isUndef() &&
13950       RHS.getOperand(1).isUndef()) {
13951     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13952     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13953
13954     if (SVN0->getMask().equals(SVN1->getMask())) {
13955       EVT VT = N->getValueType(0);
13956       SDValue UndefVector = LHS.getOperand(1);
13957       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13958                                      LHS.getOperand(0), RHS.getOperand(0),
13959                                      N->getFlags());
13960       AddUsersToWorklist(N);
13961       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13962                                   SVN0->getMask());
13963     }
13964   }
13965
13966   return SDValue();
13967 }
13968
13969 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
13970                                     SDValue N2) {
13971   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13972
13973   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13974                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13975
13976   // If we got a simplified select_cc node back from SimplifySelectCC, then
13977   // break it down into a new SETCC node, and a new SELECT node, and then return
13978   // the SELECT node, since we were called with a SELECT node.
13979   if (SCC.getNode()) {
13980     // Check to see if we got a select_cc back (to turn into setcc/select).
13981     // Otherwise, just return whatever node we got back, like fabs.
13982     if (SCC.getOpcode() == ISD::SELECT_CC) {
13983       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13984                                   N0.getValueType(),
13985                                   SCC.getOperand(0), SCC.getOperand(1),
13986                                   SCC.getOperand(4));
13987       AddToWorklist(SETCC.getNode());
13988       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13989                            SCC.getOperand(2), SCC.getOperand(3));
13990     }
13991
13992     return SCC;
13993   }
13994   return SDValue();
13995 }
13996
13997 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13998 /// being selected between, see if we can simplify the select.  Callers of this
13999 /// should assume that TheSelect is deleted if this returns true.  As such, they
14000 /// should return the appropriate thing (e.g. the node) back to the top-level of
14001 /// the DAG combiner loop to avoid it being looked at.
14002 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14003                                     SDValue RHS) {
14004
14005   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14006   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14007   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14008     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14009       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14010       SDValue Sqrt = RHS;
14011       ISD::CondCode CC;
14012       SDValue CmpLHS;
14013       const ConstantFPSDNode *Zero = nullptr;
14014
14015       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14016         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14017         CmpLHS = TheSelect->getOperand(0);
14018         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14019       } else {
14020         // SELECT or VSELECT
14021         SDValue Cmp = TheSelect->getOperand(0);
14022         if (Cmp.getOpcode() == ISD::SETCC) {
14023           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14024           CmpLHS = Cmp.getOperand(0);
14025           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14026         }
14027       }
14028       if (Zero && Zero->isZero() &&
14029           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14030           CC == ISD::SETULT || CC == ISD::SETLT)) {
14031         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14032         CombineTo(TheSelect, Sqrt);
14033         return true;
14034       }
14035     }
14036   }
14037   // Cannot simplify select with vector condition
14038   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14039
14040   // If this is a select from two identical things, try to pull the operation
14041   // through the select.
14042   if (LHS.getOpcode() != RHS.getOpcode() ||
14043       !LHS.hasOneUse() || !RHS.hasOneUse())
14044     return false;
14045
14046   // If this is a load and the token chain is identical, replace the select
14047   // of two loads with a load through a select of the address to load from.
14048   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14049   // constants have been dropped into the constant pool.
14050   if (LHS.getOpcode() == ISD::LOAD) {
14051     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14052     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14053
14054     // Token chains must be identical.
14055     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14056         // Do not let this transformation reduce the number of volatile loads.
14057         LLD->isVolatile() || RLD->isVolatile() ||
14058         // FIXME: If either is a pre/post inc/dec load,
14059         // we'd need to split out the address adjustment.
14060         LLD->isIndexed() || RLD->isIndexed() ||
14061         // If this is an EXTLOAD, the VT's must match.
14062         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14063         // If this is an EXTLOAD, the kind of extension must match.
14064         (LLD->getExtensionType() != RLD->getExtensionType() &&
14065          // The only exception is if one of the extensions is anyext.
14066          LLD->getExtensionType() != ISD::EXTLOAD &&
14067          RLD->getExtensionType() != ISD::EXTLOAD) ||
14068         // FIXME: this discards src value information.  This is
14069         // over-conservative. It would be beneficial to be able to remember
14070         // both potential memory locations.  Since we are discarding
14071         // src value info, don't do the transformation if the memory
14072         // locations are not in the default address space.
14073         LLD->getPointerInfo().getAddrSpace() != 0 ||
14074         RLD->getPointerInfo().getAddrSpace() != 0 ||
14075         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14076                                       LLD->getBasePtr().getValueType()))
14077       return false;
14078
14079     // Check that the select condition doesn't reach either load.  If so,
14080     // folding this will induce a cycle into the DAG.  If not, this is safe to
14081     // xform, so create a select of the addresses.
14082     SDValue Addr;
14083     if (TheSelect->getOpcode() == ISD::SELECT) {
14084       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14085       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14086           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14087         return false;
14088       // The loads must not depend on one another.
14089       if (LLD->isPredecessorOf(RLD) ||
14090           RLD->isPredecessorOf(LLD))
14091         return false;
14092       Addr = DAG.getSelect(SDLoc(TheSelect),
14093                            LLD->getBasePtr().getValueType(),
14094                            TheSelect->getOperand(0), LLD->getBasePtr(),
14095                            RLD->getBasePtr());
14096     } else {  // Otherwise SELECT_CC
14097       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14098       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14099
14100       if ((LLD->hasAnyUseOfValue(1) &&
14101            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14102           (RLD->hasAnyUseOfValue(1) &&
14103            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14104         return false;
14105
14106       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14107                          LLD->getBasePtr().getValueType(),
14108                          TheSelect->getOperand(0),
14109                          TheSelect->getOperand(1),
14110                          LLD->getBasePtr(), RLD->getBasePtr(),
14111                          TheSelect->getOperand(4));
14112     }
14113
14114     SDValue Load;
14115     // It is safe to replace the two loads if they have different alignments,
14116     // but the new load must be the minimum (most restrictive) alignment of the
14117     // inputs.
14118     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14119     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14120     if (!RLD->isInvariant())
14121       MMOFlags &= ~MachineMemOperand::MOInvariant;
14122     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14123       // FIXME: Discards pointer and AA info.
14124       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14125                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14126                          MMOFlags);
14127     } else {
14128       // FIXME: Discards pointer and AA info.
14129       Load = DAG.getExtLoad(
14130           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14131                                                   : LLD->getExtensionType(),
14132           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14133           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14134     }
14135
14136     // Users of the select now use the result of the load.
14137     CombineTo(TheSelect, Load);
14138
14139     // Users of the old loads now use the new load's chain.  We know the
14140     // old-load value is dead now.
14141     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14142     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14143     return true;
14144   }
14145
14146   return false;
14147 }
14148
14149 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14150 /// where 'cond' is the comparison specified by CC.
14151 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14152                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14153                                       bool NotExtCompare) {
14154   // (x ? y : y) -> y.
14155   if (N2 == N3) return N2;
14156
14157   EVT VT = N2.getValueType();
14158   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14159   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14160
14161   // Determine if the condition we're dealing with is constant
14162   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14163                               N0, N1, CC, DL, false);
14164   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14165
14166   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14167     // fold select_cc true, x, y -> x
14168     // fold select_cc false, x, y -> y
14169     return !SCCC->isNullValue() ? N2 : N3;
14170   }
14171
14172   // Check to see if we can simplify the select into an fabs node
14173   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14174     // Allow either -0.0 or 0.0
14175     if (CFP->isZero()) {
14176       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14177       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14178           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14179           N2 == N3.getOperand(0))
14180         return DAG.getNode(ISD::FABS, DL, VT, N0);
14181
14182       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14183       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14184           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14185           N2.getOperand(0) == N3)
14186         return DAG.getNode(ISD::FABS, DL, VT, N3);
14187     }
14188   }
14189
14190   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14191   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14192   // in it.  This is a win when the constant is not otherwise available because
14193   // it replaces two constant pool loads with one.  We only do this if the FP
14194   // type is known to be legal, because if it isn't, then we are before legalize
14195   // types an we want the other legalization to happen first (e.g. to avoid
14196   // messing with soft float) and if the ConstantFP is not legal, because if
14197   // it is legal, we may not need to store the FP constant in a constant pool.
14198   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14199     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14200       if (TLI.isTypeLegal(N2.getValueType()) &&
14201           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14202                TargetLowering::Legal &&
14203            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14204            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14205           // If both constants have multiple uses, then we won't need to do an
14206           // extra load, they are likely around in registers for other users.
14207           (TV->hasOneUse() || FV->hasOneUse())) {
14208         Constant *Elts[] = {
14209           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14210           const_cast<ConstantFP*>(TV->getConstantFPValue())
14211         };
14212         Type *FPTy = Elts[0]->getType();
14213         const DataLayout &TD = DAG.getDataLayout();
14214
14215         // Create a ConstantArray of the two constants.
14216         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14217         SDValue CPIdx =
14218             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14219                                 TD.getPrefTypeAlignment(FPTy));
14220         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14221
14222         // Get the offsets to the 0 and 1 element of the array so that we can
14223         // select between them.
14224         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14225         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14226         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14227
14228         SDValue Cond = DAG.getSetCC(DL,
14229                                     getSetCCResultType(N0.getValueType()),
14230                                     N0, N1, CC);
14231         AddToWorklist(Cond.getNode());
14232         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14233                                           Cond, One, Zero);
14234         AddToWorklist(CstOffset.getNode());
14235         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14236                             CstOffset);
14237         AddToWorklist(CPIdx.getNode());
14238         return DAG.getLoad(
14239             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14240             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14241             Alignment);
14242       }
14243     }
14244
14245   // Check to see if we can perform the "gzip trick", transforming
14246   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14247   if (isNullConstant(N3) && CC == ISD::SETLT &&
14248       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14249        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14250     EVT XType = N0.getValueType();
14251     EVT AType = N2.getValueType();
14252     if (XType.bitsGE(AType)) {
14253       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14254       // single-bit constant.
14255       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14256         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14257         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14258         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14259                                        getShiftAmountTy(N0.getValueType()));
14260         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14261                                     XType, N0, ShCt);
14262         AddToWorklist(Shift.getNode());
14263
14264         if (XType.bitsGT(AType)) {
14265           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14266           AddToWorklist(Shift.getNode());
14267         }
14268
14269         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14270       }
14271
14272       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14273                                   XType, N0,
14274                                   DAG.getConstant(XType.getSizeInBits() - 1,
14275                                                   SDLoc(N0),
14276                                          getShiftAmountTy(N0.getValueType())));
14277       AddToWorklist(Shift.getNode());
14278
14279       if (XType.bitsGT(AType)) {
14280         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14281         AddToWorklist(Shift.getNode());
14282       }
14283
14284       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14285     }
14286   }
14287
14288   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14289   // where y is has a single bit set.
14290   // A plaintext description would be, we can turn the SELECT_CC into an AND
14291   // when the condition can be materialized as an all-ones register.  Any
14292   // single bit-test can be materialized as an all-ones register with
14293   // shift-left and shift-right-arith.
14294   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14295       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14296     SDValue AndLHS = N0->getOperand(0);
14297     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14298     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14299       // Shift the tested bit over the sign bit.
14300       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14301       SDValue ShlAmt =
14302         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14303                         getShiftAmountTy(AndLHS.getValueType()));
14304       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14305
14306       // Now arithmetic right shift it all the way over, so the result is either
14307       // all-ones, or zero.
14308       SDValue ShrAmt =
14309         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14310                         getShiftAmountTy(Shl.getValueType()));
14311       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14312
14313       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14314     }
14315   }
14316
14317   // fold select C, 16, 0 -> shl C, 4
14318   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14319       TLI.getBooleanContents(N0.getValueType()) ==
14320           TargetLowering::ZeroOrOneBooleanContent) {
14321
14322     // If the caller doesn't want us to simplify this into a zext of a compare,
14323     // don't do it.
14324     if (NotExtCompare && N2C->isOne())
14325       return SDValue();
14326
14327     // Get a SetCC of the condition
14328     // NOTE: Don't create a SETCC if it's not legal on this target.
14329     if (!LegalOperations ||
14330         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14331       SDValue Temp, SCC;
14332       // cast from setcc result type to select result type
14333       if (LegalTypes) {
14334         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14335                             N0, N1, CC);
14336         if (N2.getValueType().bitsLT(SCC.getValueType()))
14337           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14338                                         N2.getValueType());
14339         else
14340           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14341                              N2.getValueType(), SCC);
14342       } else {
14343         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14344         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14345                            N2.getValueType(), SCC);
14346       }
14347
14348       AddToWorklist(SCC.getNode());
14349       AddToWorklist(Temp.getNode());
14350
14351       if (N2C->isOne())
14352         return Temp;
14353
14354       // shl setcc result by log2 n2c
14355       return DAG.getNode(
14356           ISD::SHL, DL, N2.getValueType(), Temp,
14357           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14358                           getShiftAmountTy(Temp.getValueType())));
14359     }
14360   }
14361
14362   // Check to see if this is an integer abs.
14363   // select_cc setg[te] X,  0,  X, -X ->
14364   // select_cc setgt    X, -1,  X, -X ->
14365   // select_cc setl[te] X,  0, -X,  X ->
14366   // select_cc setlt    X,  1, -X,  X ->
14367   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14368   if (N1C) {
14369     ConstantSDNode *SubC = nullptr;
14370     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14371          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14372         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14373       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14374     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14375               (N1C->isOne() && CC == ISD::SETLT)) &&
14376              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14377       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14378
14379     EVT XType = N0.getValueType();
14380     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14381       SDLoc DL(N0);
14382       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14383                                   N0,
14384                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14385                                          getShiftAmountTy(N0.getValueType())));
14386       SDValue Add = DAG.getNode(ISD::ADD, DL,
14387                                 XType, N0, Shift);
14388       AddToWorklist(Shift.getNode());
14389       AddToWorklist(Add.getNode());
14390       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14391     }
14392   }
14393
14394   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14395   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14396   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14397   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14398   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14399   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14400   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14401   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14402   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14403     SDValue ValueOnZero = N2;
14404     SDValue Count = N3;
14405     // If the condition is NE instead of E, swap the operands.
14406     if (CC == ISD::SETNE)
14407       std::swap(ValueOnZero, Count);
14408     // Check if the value on zero is a constant equal to the bits in the type.
14409     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14410       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14411         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14412         // legal, combine to just cttz.
14413         if ((Count.getOpcode() == ISD::CTTZ ||
14414              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14415             N0 == Count.getOperand(0) &&
14416             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14417           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14418         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14419         // legal, combine to just ctlz.
14420         if ((Count.getOpcode() == ISD::CTLZ ||
14421              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14422             N0 == Count.getOperand(0) &&
14423             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14424           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14425       }
14426     }
14427   }
14428
14429   return SDValue();
14430 }
14431
14432 /// This is a stub for TargetLowering::SimplifySetCC.
14433 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14434                                    ISD::CondCode Cond, const SDLoc &DL,
14435                                    bool foldBooleans) {
14436   TargetLowering::DAGCombinerInfo
14437     DagCombineInfo(DAG, Level, false, this);
14438   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14439 }
14440
14441 /// Given an ISD::SDIV node expressing a divide by constant, return
14442 /// a DAG expression to select that will generate the same value by multiplying
14443 /// by a magic number.
14444 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14445 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14446   // when optimising for minimum size, we don't want to expand a div to a mul
14447   // and a shift.
14448   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14449     return SDValue();
14450
14451   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14452   if (!C)
14453     return SDValue();
14454
14455   // Avoid division by zero.
14456   if (C->isNullValue())
14457     return SDValue();
14458
14459   std::vector<SDNode*> Built;
14460   SDValue S =
14461       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14462
14463   for (SDNode *N : Built)
14464     AddToWorklist(N);
14465   return S;
14466 }
14467
14468 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14469 /// DAG expression that will generate the same value by right shifting.
14470 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14471   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14472   if (!C)
14473     return SDValue();
14474
14475   // Avoid division by zero.
14476   if (C->isNullValue())
14477     return SDValue();
14478
14479   std::vector<SDNode *> Built;
14480   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14481
14482   for (SDNode *N : Built)
14483     AddToWorklist(N);
14484   return S;
14485 }
14486
14487 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14488 /// expression that will generate the same value by multiplying by a magic
14489 /// number.
14490 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14491 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14492   // when optimising for minimum size, we don't want to expand a div to a mul
14493   // and a shift.
14494   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14495     return SDValue();
14496
14497   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14498   if (!C)
14499     return SDValue();
14500
14501   // Avoid division by zero.
14502   if (C->isNullValue())
14503     return SDValue();
14504
14505   std::vector<SDNode*> Built;
14506   SDValue S =
14507       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14508
14509   for (SDNode *N : Built)
14510     AddToWorklist(N);
14511   return S;
14512 }
14513
14514 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14515   if (Level >= AfterLegalizeDAG)
14516     return SDValue();
14517
14518   // Expose the DAG combiner to the target combiner implementations.
14519   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14520
14521   unsigned Iterations = 0;
14522   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14523     if (Iterations) {
14524       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14525       // For the reciprocal, we need to find the zero of the function:
14526       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14527       //     =>
14528       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14529       //     does not require additional intermediate precision]
14530       EVT VT = Op.getValueType();
14531       SDLoc DL(Op);
14532       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14533
14534       AddToWorklist(Est.getNode());
14535
14536       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14537       for (unsigned i = 0; i < Iterations; ++i) {
14538         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14539         AddToWorklist(NewEst.getNode());
14540
14541         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14542         AddToWorklist(NewEst.getNode());
14543
14544         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14545         AddToWorklist(NewEst.getNode());
14546
14547         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14548         AddToWorklist(Est.getNode());
14549       }
14550     }
14551     return Est;
14552   }
14553
14554   return SDValue();
14555 }
14556
14557 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14558 /// For the reciprocal sqrt, we need to find the zero of the function:
14559 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14560 ///     =>
14561 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14562 /// As a result, we precompute A/2 prior to the iteration loop.
14563 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14564                                          unsigned Iterations,
14565                                          SDNodeFlags *Flags, bool Reciprocal) {
14566   EVT VT = Arg.getValueType();
14567   SDLoc DL(Arg);
14568   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14569
14570   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14571   // this entire sequence requires only one FP constant.
14572   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14573   AddToWorklist(HalfArg.getNode());
14574
14575   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14576   AddToWorklist(HalfArg.getNode());
14577
14578   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14579   for (unsigned i = 0; i < Iterations; ++i) {
14580     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14581     AddToWorklist(NewEst.getNode());
14582
14583     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14584     AddToWorklist(NewEst.getNode());
14585
14586     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14587     AddToWorklist(NewEst.getNode());
14588
14589     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14590     AddToWorklist(Est.getNode());
14591   }
14592
14593   // If non-reciprocal square root is requested, multiply the result by Arg.
14594   if (!Reciprocal) {
14595     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14596     AddToWorklist(Est.getNode());
14597   }
14598
14599   return Est;
14600 }
14601
14602 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14603 /// For the reciprocal sqrt, we need to find the zero of the function:
14604 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14605 ///     =>
14606 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14607 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
14608                                          unsigned Iterations,
14609                                          SDNodeFlags *Flags, bool Reciprocal) {
14610   EVT VT = Arg.getValueType();
14611   SDLoc DL(Arg);
14612   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14613   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14614
14615   // This routine must enter the loop below to work correctly
14616   // when (Reciprocal == false).
14617   assert(Iterations > 0);
14618
14619   // Newton iterations for reciprocal square root:
14620   // E = (E * -0.5) * ((A * E) * E + -3.0)
14621   for (unsigned i = 0; i < Iterations; ++i) {
14622     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
14623     AddToWorklist(AE.getNode());
14624
14625     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
14626     AddToWorklist(AEE.getNode());
14627
14628     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
14629     AddToWorklist(RHS.getNode());
14630
14631     // When calculating a square root at the last iteration build:
14632     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
14633     // (notice a common subexpression)
14634     SDValue LHS;
14635     if (Reciprocal || (i + 1) < Iterations) {
14636       // RSQRT: LHS = (E * -0.5)
14637       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14638     } else {
14639       // SQRT: LHS = (A * E) * -0.5
14640       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
14641     }
14642     AddToWorklist(LHS.getNode());
14643
14644     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
14645     AddToWorklist(Est.getNode());
14646   }
14647
14648   return Est;
14649 }
14650
14651 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
14652 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
14653 /// Op can be zero.
14654 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
14655                                            bool Reciprocal) {
14656   if (Level >= AfterLegalizeDAG)
14657     return SDValue();
14658
14659   // Expose the DAG combiner to the target combiner implementations.
14660   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14661   unsigned Iterations = 0;
14662   bool UseOneConstNR = false;
14663   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14664     AddToWorklist(Est.getNode());
14665     if (Iterations) {
14666       Est = UseOneConstNR
14667                 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
14668                 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
14669     }
14670     return Est;
14671   }
14672
14673   return SDValue();
14674 }
14675
14676 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14677   return buildSqrtEstimateImpl(Op, Flags, true);
14678 }
14679
14680 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14681   SDValue Est = buildSqrtEstimateImpl(Op, Flags, false);
14682   if (!Est)
14683     return SDValue();
14684
14685   // Unfortunately, Est is now NaN if the input was exactly 0.
14686   // Select out this case and force the answer to 0.
14687   EVT VT = Est.getValueType();
14688   SDLoc DL(Op);
14689   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
14690   EVT CCVT = getSetCCResultType(VT);
14691   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ);
14692   AddToWorklist(ZeroCmp.getNode());
14693
14694   Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp,
14695                     Zero, Est);
14696   AddToWorklist(Est.getNode());
14697   return Est;
14698 }
14699
14700 /// Return true if base is a frame index, which is known not to alias with
14701 /// anything but itself.  Provides base object and offset as results.
14702 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14703                            const GlobalValue *&GV, const void *&CV) {
14704   // Assume it is a primitive operation.
14705   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14706
14707   // If it's an adding a simple constant then integrate the offset.
14708   if (Base.getOpcode() == ISD::ADD) {
14709     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14710       Base = Base.getOperand(0);
14711       Offset += C->getZExtValue();
14712     }
14713   }
14714
14715   // Return the underlying GlobalValue, and update the Offset.  Return false
14716   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14717   // by multiple nodes with different offsets.
14718   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14719     GV = G->getGlobal();
14720     Offset += G->getOffset();
14721     return false;
14722   }
14723
14724   // Return the underlying Constant value, and update the Offset.  Return false
14725   // for ConstantSDNodes since the same constant pool entry may be represented
14726   // by multiple nodes with different offsets.
14727   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14728     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14729                                          : (const void *)C->getConstVal();
14730     Offset += C->getOffset();
14731     return false;
14732   }
14733   // If it's any of the following then it can't alias with anything but itself.
14734   return isa<FrameIndexSDNode>(Base);
14735 }
14736
14737 /// Return true if there is any possibility that the two addresses overlap.
14738 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14739   // If they are the same then they must be aliases.
14740   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14741
14742   // If they are both volatile then they cannot be reordered.
14743   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14744
14745   // If one operation reads from invariant memory, and the other may store, they
14746   // cannot alias. These should really be checking the equivalent of mayWrite,
14747   // but it only matters for memory nodes other than load /store.
14748   if (Op0->isInvariant() && Op1->writeMem())
14749     return false;
14750
14751   if (Op1->isInvariant() && Op0->writeMem())
14752     return false;
14753
14754   // Gather base node and offset information.
14755   SDValue Base1, Base2;
14756   int64_t Offset1, Offset2;
14757   const GlobalValue *GV1, *GV2;
14758   const void *CV1, *CV2;
14759   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14760                                       Base1, Offset1, GV1, CV1);
14761   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14762                                       Base2, Offset2, GV2, CV2);
14763
14764   // If they have a same base address then check to see if they overlap.
14765   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14766     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14767              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14768
14769   // It is possible for different frame indices to alias each other, mostly
14770   // when tail call optimization reuses return address slots for arguments.
14771   // To catch this case, look up the actual index of frame indices to compute
14772   // the real alias relationship.
14773   if (isFrameIndex1 && isFrameIndex2) {
14774     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14775     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14776     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14777     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14778              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14779   }
14780
14781   // Otherwise, if we know what the bases are, and they aren't identical, then
14782   // we know they cannot alias.
14783   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14784     return false;
14785
14786   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14787   // compared to the size and offset of the access, we may be able to prove they
14788   // do not alias.  This check is conservative for now to catch cases created by
14789   // splitting vector types.
14790   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14791       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14792       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14793        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14794       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
14795     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14796     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14797
14798     // There is no overlap between these relatively aligned accesses of similar
14799     // size, return no alias.
14800     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14801         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14802       return false;
14803   }
14804
14805   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14806                    ? CombinerGlobalAA
14807                    : DAG.getSubtarget().useAA();
14808 #ifndef NDEBUG
14809   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14810       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14811     UseAA = false;
14812 #endif
14813   if (UseAA &&
14814       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14815     // Use alias analysis information.
14816     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14817                                  Op1->getSrcValueOffset());
14818     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14819         Op0->getSrcValueOffset() - MinOffset;
14820     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14821         Op1->getSrcValueOffset() - MinOffset;
14822     AliasResult AAResult =
14823         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14824                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14825                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14826                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14827     if (AAResult == NoAlias)
14828       return false;
14829   }
14830
14831   // Otherwise we have to assume they alias.
14832   return true;
14833 }
14834
14835 /// Walk up chain skipping non-aliasing memory nodes,
14836 /// looking for aliasing nodes and adding them to the Aliases vector.
14837 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14838                                    SmallVectorImpl<SDValue> &Aliases) {
14839   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14840   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14841
14842   // Get alias information for node.
14843   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14844
14845   // Starting off.
14846   Chains.push_back(OriginalChain);
14847   unsigned Depth = 0;
14848
14849   // Look at each chain and determine if it is an alias.  If so, add it to the
14850   // aliases list.  If not, then continue up the chain looking for the next
14851   // candidate.
14852   while (!Chains.empty()) {
14853     SDValue Chain = Chains.pop_back_val();
14854
14855     // For TokenFactor nodes, look at each operand and only continue up the
14856     // chain until we reach the depth limit.
14857     //
14858     // FIXME: The depth check could be made to return the last non-aliasing
14859     // chain we found before we hit a tokenfactor rather than the original
14860     // chain.
14861     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14862       Aliases.clear();
14863       Aliases.push_back(OriginalChain);
14864       return;
14865     }
14866
14867     // Don't bother if we've been before.
14868     if (!Visited.insert(Chain.getNode()).second)
14869       continue;
14870
14871     switch (Chain.getOpcode()) {
14872     case ISD::EntryToken:
14873       // Entry token is ideal chain operand, but handled in FindBetterChain.
14874       break;
14875
14876     case ISD::LOAD:
14877     case ISD::STORE: {
14878       // Get alias information for Chain.
14879       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14880           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14881
14882       // If chain is alias then stop here.
14883       if (!(IsLoad && IsOpLoad) &&
14884           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14885         Aliases.push_back(Chain);
14886       } else {
14887         // Look further up the chain.
14888         Chains.push_back(Chain.getOperand(0));
14889         ++Depth;
14890       }
14891       break;
14892     }
14893
14894     case ISD::TokenFactor:
14895       // We have to check each of the operands of the token factor for "small"
14896       // token factors, so we queue them up.  Adding the operands to the queue
14897       // (stack) in reverse order maintains the original order and increases the
14898       // likelihood that getNode will find a matching token factor (CSE.)
14899       if (Chain.getNumOperands() > 16) {
14900         Aliases.push_back(Chain);
14901         break;
14902       }
14903       for (unsigned n = Chain.getNumOperands(); n;)
14904         Chains.push_back(Chain.getOperand(--n));
14905       ++Depth;
14906       break;
14907
14908     default:
14909       // For all other instructions we will just have to take what we can get.
14910       Aliases.push_back(Chain);
14911       break;
14912     }
14913   }
14914 }
14915
14916 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14917 /// (aliasing node.)
14918 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14919   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14920
14921   // Accumulate all the aliases to this node.
14922   GatherAllAliases(N, OldChain, Aliases);
14923
14924   // If no operands then chain to entry token.
14925   if (Aliases.size() == 0)
14926     return DAG.getEntryNode();
14927
14928   // If a single operand then chain to it.  We don't need to revisit it.
14929   if (Aliases.size() == 1)
14930     return Aliases[0];
14931
14932   // Construct a custom tailored token factor.
14933   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14934 }
14935
14936 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
14937   // This holds the base pointer, index, and the offset in bytes from the base
14938   // pointer.
14939   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
14940
14941   // We must have a base and an offset.
14942   if (!BasePtr.Base.getNode())
14943     return false;
14944
14945   // Do not handle stores to undef base pointers.
14946   if (BasePtr.Base.isUndef())
14947     return false;
14948
14949   SmallVector<StoreSDNode *, 8> ChainedStores;
14950   ChainedStores.push_back(St);
14951
14952   // Walk up the chain and look for nodes with offsets from the same
14953   // base pointer. Stop when reaching an instruction with a different kind
14954   // or instruction which has a different base pointer.
14955   StoreSDNode *Index = St;
14956   while (Index) {
14957     // If the chain has more than one use, then we can't reorder the mem ops.
14958     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14959       break;
14960
14961     if (Index->isVolatile() || Index->isIndexed())
14962       break;
14963
14964     // Find the base pointer and offset for this memory node.
14965     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
14966
14967     // Check that the base pointer is the same as the original one.
14968     if (!Ptr.equalBaseIndex(BasePtr))
14969       break;
14970
14971     // Find the next memory operand in the chain. If the next operand in the
14972     // chain is a store then move up and continue the scan with the next
14973     // memory operand. If the next operand is a load save it and use alias
14974     // information to check if it interferes with anything.
14975     SDNode *NextInChain = Index->getChain().getNode();
14976     while (true) {
14977       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14978         // We found a store node. Use it for the next iteration.
14979         if (STn->isVolatile() || STn->isIndexed()) {
14980           Index = nullptr;
14981           break;
14982         }
14983         ChainedStores.push_back(STn);
14984         Index = STn;
14985         break;
14986       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14987         NextInChain = Ldn->getChain().getNode();
14988         continue;
14989       } else {
14990         Index = nullptr;
14991         break;
14992       }
14993     }
14994   }
14995
14996   bool MadeChangeToSt = false;
14997   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14998
14999   for (StoreSDNode *ChainedStore : ChainedStores) {
15000     SDValue Chain = ChainedStore->getChain();
15001     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15002
15003     if (Chain != BetterChain) {
15004       if (ChainedStore == St)
15005         MadeChangeToSt = true;
15006       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15007     }
15008   }
15009
15010   // Do all replacements after finding the replacements to make to avoid making
15011   // the chains more complicated by introducing new TokenFactors.
15012   for (auto Replacement : BetterChains)
15013     replaceStoreChain(Replacement.first, Replacement.second);
15014
15015   return MadeChangeToSt;
15016 }
15017
15018 /// This is the entry point for the file.
15019 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15020                            CodeGenOpt::Level OptLevel) {
15021   /// This is the main entry point to this class.
15022   DAGCombiner(*this, AA, OptLevel).Run(Level);
15023 }