]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[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/ADT/SetVector.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include <algorithm>
43 using namespace llvm;
44
45 #define DEBUG_TYPE "dagcombine"
46
47 STATISTIC(NodesCombined   , "Number of dag nodes combined");
48 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
49 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
50 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
51 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
52 STATISTIC(SlicedLoads, "Number of load sliced");
53
54 namespace {
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Enable DAG combiner's use of IR alias analysis"));
58
59   static cl::opt<bool>
60     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
61                cl::desc("Enable DAG combiner's use of TBAA"));
62
63 #ifndef NDEBUG
64   static cl::opt<std::string>
65     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
66                cl::desc("Only use DAG-combiner alias analysis in this"
67                         " function"));
68 #endif
69
70   /// Hidden option to stress test load slicing, i.e., when this option
71   /// is enabled, load slicing bypasses most of its profitability guards.
72   static cl::opt<bool>
73   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
74                     cl::desc("Bypass the profitability model of load "
75                              "slicing"),
76                     cl::init(false));
77
78   static cl::opt<bool>
79     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
80                       cl::desc("DAG combiner may split indexing from loads"));
81
82 //------------------------------ DAGCombiner ---------------------------------//
83
84   class DAGCombiner {
85     SelectionDAG &DAG;
86     const TargetLowering &TLI;
87     CombineLevel Level;
88     CodeGenOpt::Level OptLevel;
89     bool LegalOperations;
90     bool LegalTypes;
91     bool ForCodeSize;
92
93     /// \brief Worklist of all of the nodes that need to be simplified.
94     ///
95     /// This must behave as a stack -- new nodes to process are pushed onto the
96     /// back and when processing we pop off of the back.
97     ///
98     /// The worklist will not contain duplicates but may contain null entries
99     /// due to nodes being deleted from the underlying DAG.
100     SmallVector<SDNode *, 64> Worklist;
101
102     /// \brief Mapping from an SDNode to its position on the worklist.
103     ///
104     /// This is used to find and remove nodes from the worklist (by nulling
105     /// them) when they are deleted from the underlying DAG. It relies on
106     /// stable indices of nodes within the worklist.
107     DenseMap<SDNode *, unsigned> WorklistMap;
108
109     /// \brief Set of nodes which have been combined (at least once).
110     ///
111     /// This is used to allow us to reliably add any operands of a DAG node
112     /// which have not yet been combined to the worklist.
113     SmallPtrSet<SDNode *, 32> CombinedNodes;
114
115     // AA - Used for DAG load/store alias analysis.
116     AliasAnalysis &AA;
117
118     /// When an instruction is simplified, add all users of the instruction to
119     /// the work lists because they might get more simplified now.
120     void AddUsersToWorklist(SDNode *N) {
121       for (SDNode *Node : N->uses())
122         AddToWorklist(Node);
123     }
124
125     /// Call the node-specific routine that folds each particular type of node.
126     SDValue visit(SDNode *N);
127
128   public:
129     /// Add to the worklist making sure its instance is at the back (next to be
130     /// processed.)
131     void AddToWorklist(SDNode *N) {
132       assert(N->getOpcode() != ISD::DELETED_NODE &&
133              "Deleted Node added to Worklist");
134
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     unsigned MaximumLegalStoreInBits;
180
181     /// Check the specified integer node value to see if it can be simplified or
182     /// if things it uses can be simplified by bit propagation.
183     /// If so, return true.
184     bool SimplifyDemandedBits(SDValue Op) {
185       unsigned BitWidth = Op.getScalarValueSizeInBits();
186       APInt Demanded = APInt::getAllOnesValue(BitWidth);
187       return SimplifyDemandedBits(Op, Demanded);
188     }
189
190     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
191
192     bool CombineToPreIndexedLoadStore(SDNode *N);
193     bool CombineToPostIndexedLoadStore(SDNode *N);
194     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
195     bool SliceUpLoad(SDNode *N);
196
197     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
198     ///   load.
199     ///
200     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
201     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
202     /// \param EltNo index of the vector element to load.
203     /// \param OriginalLoad load that EVE came from to be replaced.
204     /// \returns EVE on success SDValue() on failure.
205     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
206         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
207     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
208     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
209     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
211     SDValue PromoteIntBinOp(SDValue Op);
212     SDValue PromoteIntShiftOp(SDValue Op);
213     SDValue PromoteExtend(SDValue Op);
214     bool PromoteLoad(SDValue Op);
215
216     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
217                          SDValue ExtLoad, const SDLoc &DL,
218                          ISD::NodeType ExtType);
219
220     /// Call the node-specific routine that knows how to fold each
221     /// particular type of node. If that doesn't do anything, try the
222     /// target-specific DAG combines.
223     SDValue combine(SDNode *N);
224
225     // Visitation implementation - Implement dag node combining for different
226     // node types.  The semantics are as follows:
227     // Return Value:
228     //   SDValue.getNode() == 0 - No change was made
229     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
230     //   otherwise              - N should be replaced by the returned Operand.
231     //
232     SDValue visitTokenFactor(SDNode *N);
233     SDValue visitMERGE_VALUES(SDNode *N);
234     SDValue visitADD(SDNode *N);
235     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
236     SDValue visitSUB(SDNode *N);
237     SDValue visitADDC(SDNode *N);
238     SDValue visitUADDO(SDNode *N);
239     SDValue visitSUBC(SDNode *N);
240     SDValue visitUSUBO(SDNode *N);
241     SDValue visitADDE(SDNode *N);
242     SDValue visitSUBE(SDNode *N);
243     SDValue visitMUL(SDNode *N);
244     SDValue useDivRem(SDNode *N);
245     SDValue visitSDIV(SDNode *N);
246     SDValue visitUDIV(SDNode *N);
247     SDValue visitREM(SDNode *N);
248     SDValue visitMULHU(SDNode *N);
249     SDValue visitMULHS(SDNode *N);
250     SDValue visitSMUL_LOHI(SDNode *N);
251     SDValue visitUMUL_LOHI(SDNode *N);
252     SDValue visitSMULO(SDNode *N);
253     SDValue visitUMULO(SDNode *N);
254     SDValue visitIMINMAX(SDNode *N);
255     SDValue visitAND(SDNode *N);
256     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
257     SDValue visitOR(SDNode *N);
258     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
259     SDValue visitXOR(SDNode *N);
260     SDValue SimplifyVBinOp(SDNode *N);
261     SDValue visitSHL(SDNode *N);
262     SDValue visitSRA(SDNode *N);
263     SDValue visitSRL(SDNode *N);
264     SDValue visitRotate(SDNode *N);
265     SDValue visitABS(SDNode *N);
266     SDValue visitBSWAP(SDNode *N);
267     SDValue visitBITREVERSE(SDNode *N);
268     SDValue visitCTLZ(SDNode *N);
269     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
270     SDValue visitCTTZ(SDNode *N);
271     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
272     SDValue visitCTPOP(SDNode *N);
273     SDValue visitSELECT(SDNode *N);
274     SDValue visitVSELECT(SDNode *N);
275     SDValue visitSELECT_CC(SDNode *N);
276     SDValue visitSETCC(SDNode *N);
277     SDValue visitSETCCE(SDNode *N);
278     SDValue visitSIGN_EXTEND(SDNode *N);
279     SDValue visitZERO_EXTEND(SDNode *N);
280     SDValue visitANY_EXTEND(SDNode *N);
281     SDValue visitAssertZext(SDNode *N);
282     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
283     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
284     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
285     SDValue visitTRUNCATE(SDNode *N);
286     SDValue visitBITCAST(SDNode *N);
287     SDValue visitBUILD_PAIR(SDNode *N);
288     SDValue visitFADD(SDNode *N);
289     SDValue visitFSUB(SDNode *N);
290     SDValue visitFMUL(SDNode *N);
291     SDValue visitFMA(SDNode *N);
292     SDValue visitFDIV(SDNode *N);
293     SDValue visitFREM(SDNode *N);
294     SDValue visitFSQRT(SDNode *N);
295     SDValue visitFCOPYSIGN(SDNode *N);
296     SDValue visitSINT_TO_FP(SDNode *N);
297     SDValue visitUINT_TO_FP(SDNode *N);
298     SDValue visitFP_TO_SINT(SDNode *N);
299     SDValue visitFP_TO_UINT(SDNode *N);
300     SDValue visitFP_ROUND(SDNode *N);
301     SDValue visitFP_ROUND_INREG(SDNode *N);
302     SDValue visitFP_EXTEND(SDNode *N);
303     SDValue visitFNEG(SDNode *N);
304     SDValue visitFABS(SDNode *N);
305     SDValue visitFCEIL(SDNode *N);
306     SDValue visitFTRUNC(SDNode *N);
307     SDValue visitFFLOOR(SDNode *N);
308     SDValue visitFMINNUM(SDNode *N);
309     SDValue visitFMAXNUM(SDNode *N);
310     SDValue visitBRCOND(SDNode *N);
311     SDValue visitBR_CC(SDNode *N);
312     SDValue visitLOAD(SDNode *N);
313
314     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
315     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
316
317     SDValue visitSTORE(SDNode *N);
318     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
319     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
320     SDValue visitBUILD_VECTOR(SDNode *N);
321     SDValue visitCONCAT_VECTORS(SDNode *N);
322     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
323     SDValue visitVECTOR_SHUFFLE(SDNode *N);
324     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
325     SDValue visitINSERT_SUBVECTOR(SDNode *N);
326     SDValue visitMLOAD(SDNode *N);
327     SDValue visitMSTORE(SDNode *N);
328     SDValue visitMGATHER(SDNode *N);
329     SDValue visitMSCATTER(SDNode *N);
330     SDValue visitFP_TO_FP16(SDNode *N);
331     SDValue visitFP16_TO_FP(SDNode *N);
332
333     SDValue visitFADDForFMACombine(SDNode *N);
334     SDValue visitFSUBForFMACombine(SDNode *N);
335     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
336
337     SDValue XformToShuffleWithZero(SDNode *N);
338     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
339                            SDValue RHS);
340
341     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
342
343     SDValue foldSelectOfConstants(SDNode *N);
344     SDValue foldBinOpIntoSelect(SDNode *BO);
345     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
346     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
347     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
348     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
349                              SDValue N2, SDValue N3, ISD::CondCode CC,
350                              bool NotExtCompare = false);
351     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
352                                    SDValue N2, SDValue N3, ISD::CondCode CC);
353     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
354                               const SDLoc &DL);
355     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
356                           const SDLoc &DL, bool foldBooleans = true);
357
358     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
359                            SDValue &CC) const;
360     bool isOneUseSetCC(SDValue N) const;
361
362     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
363                                          unsigned HiOp);
364     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
365     SDValue CombineExtLoad(SDNode *N);
366     SDValue combineRepeatedFPDivisors(SDNode *N);
367     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
368     SDValue BuildSDIV(SDNode *N);
369     SDValue BuildSDIVPow2(SDNode *N);
370     SDValue BuildUDIV(SDNode *N);
371     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
372     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
373     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
374     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
375     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
376     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
377                                 SDNodeFlags *Flags, bool Reciprocal);
378     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
379                                 SDNodeFlags *Flags, bool Reciprocal);
380     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
381                                bool DemandHighBits = true);
382     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
383     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
384                               SDValue InnerPos, SDValue InnerNeg,
385                               unsigned PosOpcode, unsigned NegOpcode,
386                               const SDLoc &DL);
387     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
388     SDValue MatchLoadCombine(SDNode *N);
389     SDValue ReduceLoadWidth(SDNode *N);
390     SDValue ReduceLoadOpStoreWidth(SDNode *N);
391     SDValue splitMergedValStore(StoreSDNode *ST);
392     SDValue TransformFPLoadStorePair(SDNode *N);
393     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
394     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
395     SDValue reduceBuildVecToShuffle(SDNode *N);
396     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
397                                   ArrayRef<int> VectorMask, SDValue VecIn1,
398                                   SDValue VecIn2, unsigned LeftIdx);
399
400     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
401
402     /// Walk up chain skipping non-aliasing memory nodes,
403     /// looking for aliasing nodes and adding them to the Aliases vector.
404     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
405                           SmallVectorImpl<SDValue> &Aliases);
406
407     /// Return true if there is any possibility that the two addresses overlap.
408     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
409
410     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
411     /// chain (aliasing node.)
412     SDValue FindBetterChain(SDNode *N, SDValue Chain);
413
414     /// Try to replace a store and any possibly adjacent stores on
415     /// consecutive chains with better chains. Return true only if St is
416     /// replaced.
417     ///
418     /// Notice that other chains may still be replaced even if the function
419     /// returns false.
420     bool findBetterNeighborChains(StoreSDNode *St);
421
422     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
423     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
424
425     /// Holds a pointer to an LSBaseSDNode as well as information on where it
426     /// is located in a sequence of memory operations connected by a chain.
427     struct MemOpLink {
428       MemOpLink(LSBaseSDNode *N, int64_t Offset)
429           : MemNode(N), OffsetFromBase(Offset) {}
430       // Ptr to the mem node.
431       LSBaseSDNode *MemNode;
432       // Offset from the base ptr.
433       int64_t OffsetFromBase;
434     };
435
436     /// This is a helper function for visitMUL to check the profitability
437     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
438     /// MulNode is the original multiply, AddNode is (add x, c1),
439     /// and ConstNode is c2.
440     bool isMulAddWithConstProfitable(SDNode *MulNode,
441                                      SDValue &AddNode,
442                                      SDValue &ConstNode);
443
444
445     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
446     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
447     /// the type of the loaded value to be extended.  LoadedVT returns the type
448     /// of the original loaded value.  NarrowLoad returns whether the load would
449     /// need to be narrowed in order to match.
450     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
451                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
452                           bool &NarrowLoad);
453
454     /// Helper function for MergeConsecutiveStores which merges the
455     /// component store chains.
456     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
457                                 unsigned NumStores);
458
459     /// This is a helper function for MergeConsecutiveStores. When the source
460     /// elements of the consecutive stores are all constants or all extracted
461     /// vector elements, try to merge them into one larger store.
462     /// \return True if a merged store was created.
463     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
464                                          EVT MemVT, unsigned NumStores,
465                                          bool IsConstantSrc, bool UseVector);
466
467     /// This is a helper function for MergeConsecutiveStores.
468     /// Stores that may be merged are placed in StoreNodes.
469     void getStoreMergeCandidates(StoreSDNode *St,
470                                  SmallVectorImpl<MemOpLink> &StoreNodes);
471
472     /// Helper function for MergeConsecutiveStores. Checks if
473     /// Candidate stores have indirect dependency through their
474     /// operands. \return True if safe to merge
475     bool checkMergeStoreCandidatesForDependencies(
476         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
477
478     /// Merge consecutive store operations into a wide store.
479     /// This optimization uses wide integers or vectors when possible.
480     /// \return number of stores that were merged into a merged store (the
481     /// affected nodes are stored as a prefix in \p StoreNodes).
482     bool MergeConsecutiveStores(StoreSDNode *N);
483
484     /// \brief Try to transform a truncation where C is a constant:
485     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
486     ///
487     /// \p N needs to be a truncation and its first operand an AND. Other
488     /// requirements are checked by the function (e.g. that trunc is
489     /// single-use) and if missed an empty SDValue is returned.
490     SDValue distributeTruncateThroughAnd(SDNode *N);
491
492   public:
493     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
494         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
495           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
496       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
497
498       MaximumLegalStoreInBits = 0;
499       for (MVT VT : MVT::all_valuetypes())
500         if (EVT(VT).isSimple() && VT != MVT::Other &&
501             TLI.isTypeLegal(EVT(VT)) &&
502             VT.getSizeInBits() >= MaximumLegalStoreInBits)
503           MaximumLegalStoreInBits = VT.getSizeInBits();
504     }
505
506     /// Runs the dag combiner on all nodes in the work list
507     void Run(CombineLevel AtLevel);
508
509     SelectionDAG &getDAG() const { return DAG; }
510
511     /// Returns a type large enough to hold any valid shift amount - before type
512     /// legalization these can be huge.
513     EVT getShiftAmountTy(EVT LHSTy) {
514       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
515       if (LHSTy.isVector())
516         return LHSTy;
517       auto &DL = DAG.getDataLayout();
518       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
519                         : TLI.getPointerTy(DL);
520     }
521
522     /// This method returns true if we are running before type legalization or
523     /// if the specified VT is legal.
524     bool isTypeLegal(const EVT &VT) {
525       if (!LegalTypes) return true;
526       return TLI.isTypeLegal(VT);
527     }
528
529     /// Convenience wrapper around TargetLowering::getSetCCResultType
530     EVT getSetCCResultType(EVT VT) const {
531       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
532     }
533   };
534 }
535
536
537 namespace {
538 /// This class is a DAGUpdateListener that removes any deleted
539 /// nodes from the worklist.
540 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
541   DAGCombiner &DC;
542 public:
543   explicit WorklistRemover(DAGCombiner &dc)
544     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
545
546   void NodeDeleted(SDNode *N, SDNode *E) override {
547     DC.removeFromWorklist(N);
548   }
549 };
550 }
551
552 //===----------------------------------------------------------------------===//
553 //  TargetLowering::DAGCombinerInfo implementation
554 //===----------------------------------------------------------------------===//
555
556 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
557   ((DAGCombiner*)DC)->AddToWorklist(N);
558 }
559
560 SDValue TargetLowering::DAGCombinerInfo::
561 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
562   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
563 }
564
565 SDValue TargetLowering::DAGCombinerInfo::
566 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
567   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
568 }
569
570
571 SDValue TargetLowering::DAGCombinerInfo::
572 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
573   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
574 }
575
576 void TargetLowering::DAGCombinerInfo::
577 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
578   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
579 }
580
581 //===----------------------------------------------------------------------===//
582 // Helper Functions
583 //===----------------------------------------------------------------------===//
584
585 void DAGCombiner::deleteAndRecombine(SDNode *N) {
586   removeFromWorklist(N);
587
588   // If the operands of this node are only used by the node, they will now be
589   // dead. Make sure to re-visit them and recursively delete dead nodes.
590   for (const SDValue &Op : N->ops())
591     // For an operand generating multiple values, one of the values may
592     // become dead allowing further simplification (e.g. split index
593     // arithmetic from an indexed load).
594     if (Op->hasOneUse() || Op->getNumValues() > 1)
595       AddToWorklist(Op.getNode());
596
597   DAG.DeleteNode(N);
598 }
599
600 /// Return 1 if we can compute the negated form of the specified expression for
601 /// the same cost as the expression itself, or 2 if we can compute the negated
602 /// form more cheaply than the expression itself.
603 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
604                                const TargetLowering &TLI,
605                                const TargetOptions *Options,
606                                unsigned Depth = 0) {
607   // fneg is removable even if it has multiple uses.
608   if (Op.getOpcode() == ISD::FNEG) return 2;
609
610   // Don't allow anything with multiple uses.
611   if (!Op.hasOneUse()) return 0;
612
613   // Don't recurse exponentially.
614   if (Depth > 6) return 0;
615
616   switch (Op.getOpcode()) {
617   default: return false;
618   case ISD::ConstantFP: {
619     if (!LegalOperations)
620       return 1;
621
622     // Don't invert constant FP values after legalization unless the target says
623     // the negated constant is legal.
624     EVT VT = Op.getValueType();
625     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
626       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
627   }
628   case ISD::FADD:
629     // FIXME: determine better conditions for this xform.
630     if (!Options->UnsafeFPMath) return 0;
631
632     // After operation legalization, it might not be legal to create new FSUBs.
633     if (LegalOperations &&
634         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
635       return 0;
636
637     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
638     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
639                                     Options, Depth + 1))
640       return V;
641     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
642     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
643                               Depth + 1);
644   case ISD::FSUB:
645     // We can't turn -(A-B) into B-A when we honor signed zeros.
646     if (!Options->NoSignedZerosFPMath &&
647         !Op.getNode()->getFlags()->hasNoSignedZeros())
648       return 0;
649
650     // fold (fneg (fsub A, B)) -> (fsub B, A)
651     return 1;
652
653   case ISD::FMUL:
654   case ISD::FDIV:
655     if (Options->HonorSignDependentRoundingFPMath()) return 0;
656
657     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
658     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
659                                     Options, Depth + 1))
660       return V;
661
662     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
663                               Depth + 1);
664
665   case ISD::FP_EXTEND:
666   case ISD::FP_ROUND:
667   case ISD::FSIN:
668     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
669                               Depth + 1);
670   }
671 }
672
673 /// If isNegatibleForFree returns true, return the newly negated expression.
674 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
675                                     bool LegalOperations, unsigned Depth = 0) {
676   const TargetOptions &Options = DAG.getTarget().Options;
677   // fneg is removable even if it has multiple uses.
678   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
679
680   // Don't allow anything with multiple uses.
681   assert(Op.hasOneUse() && "Unknown reuse!");
682
683   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
684
685   const SDNodeFlags *Flags = Op.getNode()->getFlags();
686
687   switch (Op.getOpcode()) {
688   default: llvm_unreachable("Unknown code");
689   case ISD::ConstantFP: {
690     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
691     V.changeSign();
692     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
693   }
694   case ISD::FADD:
695     // FIXME: determine better conditions for this xform.
696     assert(Options.UnsafeFPMath);
697
698     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
699     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
700                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
701       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
702                          GetNegatedExpression(Op.getOperand(0), DAG,
703                                               LegalOperations, Depth+1),
704                          Op.getOperand(1), Flags);
705     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
706     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
707                        GetNegatedExpression(Op.getOperand(1), DAG,
708                                             LegalOperations, Depth+1),
709                        Op.getOperand(0), Flags);
710   case ISD::FSUB:
711     // fold (fneg (fsub 0, B)) -> B
712     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
713       if (N0CFP->isZero())
714         return Op.getOperand(1);
715
716     // fold (fneg (fsub A, B)) -> (fsub B, A)
717     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
718                        Op.getOperand(1), Op.getOperand(0), Flags);
719
720   case ISD::FMUL:
721   case ISD::FDIV:
722     assert(!Options.HonorSignDependentRoundingFPMath());
723
724     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
725     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
726                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
727       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
728                          GetNegatedExpression(Op.getOperand(0), DAG,
729                                               LegalOperations, Depth+1),
730                          Op.getOperand(1), Flags);
731
732     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
733     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
734                        Op.getOperand(0),
735                        GetNegatedExpression(Op.getOperand(1), DAG,
736                                             LegalOperations, Depth+1), Flags);
737
738   case ISD::FP_EXTEND:
739   case ISD::FSIN:
740     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
741                        GetNegatedExpression(Op.getOperand(0), DAG,
742                                             LegalOperations, Depth+1));
743   case ISD::FP_ROUND:
744       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
745                          GetNegatedExpression(Op.getOperand(0), DAG,
746                                               LegalOperations, Depth+1),
747                          Op.getOperand(1));
748   }
749 }
750
751 // APInts must be the same size for most operations, this helper
752 // function zero extends the shorter of the pair so that they match.
753 // We provide an Offset so that we can create bitwidths that won't overflow.
754 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
755   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
756   LHS = LHS.zextOrSelf(Bits);
757   RHS = RHS.zextOrSelf(Bits);
758 }
759
760 // Return true if this node is a setcc, or is a select_cc
761 // that selects between the target values used for true and false, making it
762 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
763 // the appropriate nodes based on the type of node we are checking. This
764 // simplifies life a bit for the callers.
765 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
766                                     SDValue &CC) const {
767   if (N.getOpcode() == ISD::SETCC) {
768     LHS = N.getOperand(0);
769     RHS = N.getOperand(1);
770     CC  = N.getOperand(2);
771     return true;
772   }
773
774   if (N.getOpcode() != ISD::SELECT_CC ||
775       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
776       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
777     return false;
778
779   if (TLI.getBooleanContents(N.getValueType()) ==
780       TargetLowering::UndefinedBooleanContent)
781     return false;
782
783   LHS = N.getOperand(0);
784   RHS = N.getOperand(1);
785   CC  = N.getOperand(4);
786   return true;
787 }
788
789 /// Return true if this is a SetCC-equivalent operation with only one use.
790 /// If this is true, it allows the users to invert the operation for free when
791 /// it is profitable to do so.
792 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
793   SDValue N0, N1, N2;
794   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
795     return true;
796   return false;
797 }
798
799 // \brief Returns the SDNode if it is a constant float BuildVector
800 // or constant float.
801 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
802   if (isa<ConstantFPSDNode>(N))
803     return N.getNode();
804   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
805     return N.getNode();
806   return nullptr;
807 }
808
809 // Determines if it is a constant integer or a build vector of constant
810 // integers (and undefs).
811 // Do not permit build vector implicit truncation.
812 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
813   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
814     return !(Const->isOpaque() && NoOpaques);
815   if (N.getOpcode() != ISD::BUILD_VECTOR)
816     return false;
817   unsigned BitWidth = N.getScalarValueSizeInBits();
818   for (const SDValue &Op : N->op_values()) {
819     if (Op.isUndef())
820       continue;
821     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
822     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
823         (Const->isOpaque() && NoOpaques))
824       return false;
825   }
826   return true;
827 }
828
829 // Determines if it is a constant null integer or a splatted vector of a
830 // constant null integer (with no undefs).
831 // Build vector implicit truncation is not an issue for null values.
832 static bool isNullConstantOrNullSplatConstant(SDValue N) {
833   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
834     return Splat->isNullValue();
835   return false;
836 }
837
838 // Determines if it is a constant integer of one or a splatted vector of a
839 // constant integer of one (with no undefs).
840 // Do not permit build vector implicit truncation.
841 static bool isOneConstantOrOneSplatConstant(SDValue N) {
842   unsigned BitWidth = N.getScalarValueSizeInBits();
843   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
844     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
845   return false;
846 }
847
848 // Determines if it is a constant integer of all ones or a splatted vector of a
849 // constant integer of all ones (with no undefs).
850 // Do not permit build vector implicit truncation.
851 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
852   unsigned BitWidth = N.getScalarValueSizeInBits();
853   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
854     return Splat->isAllOnesValue() &&
855            Splat->getAPIntValue().getBitWidth() == BitWidth;
856   return false;
857 }
858
859 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
860 // undef's.
861 static bool isAnyConstantBuildVector(const SDNode *N) {
862   return ISD::isBuildVectorOfConstantSDNodes(N) ||
863          ISD::isBuildVectorOfConstantFPSDNodes(N);
864 }
865
866 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
867                                     SDValue N1) {
868   EVT VT = N0.getValueType();
869   if (N0.getOpcode() == Opc) {
870     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
871       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
872         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
873         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
874           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
875         return SDValue();
876       }
877       if (N0.hasOneUse()) {
878         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
879         // use
880         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
881         if (!OpNode.getNode())
882           return SDValue();
883         AddToWorklist(OpNode.getNode());
884         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
885       }
886     }
887   }
888
889   if (N1.getOpcode() == Opc) {
890     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
891       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
892         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
893         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
894           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
895         return SDValue();
896       }
897       if (N1.hasOneUse()) {
898         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
899         // use
900         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
901         if (!OpNode.getNode())
902           return SDValue();
903         AddToWorklist(OpNode.getNode());
904         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
905       }
906     }
907   }
908
909   return SDValue();
910 }
911
912 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
913                                bool AddTo) {
914   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
915   ++NodesCombined;
916   DEBUG(dbgs() << "\nReplacing.1 ";
917         N->dump(&DAG);
918         dbgs() << "\nWith: ";
919         To[0].getNode()->dump(&DAG);
920         dbgs() << " and " << NumTo-1 << " other values\n");
921   for (unsigned i = 0, e = NumTo; i != e; ++i)
922     assert((!To[i].getNode() ||
923             N->getValueType(i) == To[i].getValueType()) &&
924            "Cannot combine value to value of different type!");
925
926   WorklistRemover DeadNodes(*this);
927   DAG.ReplaceAllUsesWith(N, To);
928   if (AddTo) {
929     // Push the new nodes and any users onto the worklist
930     for (unsigned i = 0, e = NumTo; i != e; ++i) {
931       if (To[i].getNode()) {
932         AddToWorklist(To[i].getNode());
933         AddUsersToWorklist(To[i].getNode());
934       }
935     }
936   }
937
938   // Finally, if the node is now dead, remove it from the graph.  The node
939   // may not be dead if the replacement process recursively simplified to
940   // something else needing this node.
941   if (N->use_empty())
942     deleteAndRecombine(N);
943   return SDValue(N, 0);
944 }
945
946 void DAGCombiner::
947 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
948   // Replace all uses.  If any nodes become isomorphic to other nodes and
949   // are deleted, make sure to remove them from our worklist.
950   WorklistRemover DeadNodes(*this);
951   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
952
953   // Push the new node and any (possibly new) users onto the worklist.
954   AddToWorklist(TLO.New.getNode());
955   AddUsersToWorklist(TLO.New.getNode());
956
957   // Finally, if the node is now dead, remove it from the graph.  The node
958   // may not be dead if the replacement process recursively simplified to
959   // something else needing this node.
960   if (TLO.Old.getNode()->use_empty())
961     deleteAndRecombine(TLO.Old.getNode());
962 }
963
964 /// Check the specified integer node value to see if it can be simplified or if
965 /// things it uses can be simplified by bit propagation. If so, return true.
966 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
967   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
968   APInt KnownZero, KnownOne;
969   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
970     return false;
971
972   // Revisit the node.
973   AddToWorklist(Op.getNode());
974
975   // Replace the old value with the new one.
976   ++NodesCombined;
977   DEBUG(dbgs() << "\nReplacing.2 ";
978         TLO.Old.getNode()->dump(&DAG);
979         dbgs() << "\nWith: ";
980         TLO.New.getNode()->dump(&DAG);
981         dbgs() << '\n');
982
983   CommitTargetLoweringOpt(TLO);
984   return true;
985 }
986
987 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
988   SDLoc DL(Load);
989   EVT VT = Load->getValueType(0);
990   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
991
992   DEBUG(dbgs() << "\nReplacing.9 ";
993         Load->dump(&DAG);
994         dbgs() << "\nWith: ";
995         Trunc.getNode()->dump(&DAG);
996         dbgs() << '\n');
997   WorklistRemover DeadNodes(*this);
998   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
999   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1000   deleteAndRecombine(Load);
1001   AddToWorklist(Trunc.getNode());
1002 }
1003
1004 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1005   Replace = false;
1006   SDLoc DL(Op);
1007   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1008     LoadSDNode *LD = cast<LoadSDNode>(Op);
1009     EVT MemVT = LD->getMemoryVT();
1010     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1011       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1012                                                        : ISD::EXTLOAD)
1013       : LD->getExtensionType();
1014     Replace = true;
1015     return DAG.getExtLoad(ExtType, DL, PVT,
1016                           LD->getChain(), LD->getBasePtr(),
1017                           MemVT, LD->getMemOperand());
1018   }
1019
1020   unsigned Opc = Op.getOpcode();
1021   switch (Opc) {
1022   default: break;
1023   case ISD::AssertSext:
1024     return DAG.getNode(ISD::AssertSext, DL, PVT,
1025                        SExtPromoteOperand(Op.getOperand(0), PVT),
1026                        Op.getOperand(1));
1027   case ISD::AssertZext:
1028     return DAG.getNode(ISD::AssertZext, DL, PVT,
1029                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1030                        Op.getOperand(1));
1031   case ISD::Constant: {
1032     unsigned ExtOpc =
1033       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1034     return DAG.getNode(ExtOpc, DL, PVT, Op);
1035   }
1036   }
1037
1038   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1039     return SDValue();
1040   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1041 }
1042
1043 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1044   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1045     return SDValue();
1046   EVT OldVT = Op.getValueType();
1047   SDLoc DL(Op);
1048   bool Replace = false;
1049   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1050   if (!NewOp.getNode())
1051     return SDValue();
1052   AddToWorklist(NewOp.getNode());
1053
1054   if (Replace)
1055     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1056   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1057                      DAG.getValueType(OldVT));
1058 }
1059
1060 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1061   EVT OldVT = Op.getValueType();
1062   SDLoc DL(Op);
1063   bool Replace = false;
1064   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1065   if (!NewOp.getNode())
1066     return SDValue();
1067   AddToWorklist(NewOp.getNode());
1068
1069   if (Replace)
1070     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1071   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1072 }
1073
1074 /// Promote the specified integer binary operation if the target indicates it is
1075 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1076 /// i32 since i16 instructions are longer.
1077 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1078   if (!LegalOperations)
1079     return SDValue();
1080
1081   EVT VT = Op.getValueType();
1082   if (VT.isVector() || !VT.isInteger())
1083     return SDValue();
1084
1085   // If operation type is 'undesirable', e.g. i16 on x86, consider
1086   // promoting it.
1087   unsigned Opc = Op.getOpcode();
1088   if (TLI.isTypeDesirableForOp(Opc, VT))
1089     return SDValue();
1090
1091   EVT PVT = VT;
1092   // Consult target whether it is a good idea to promote this operation and
1093   // what's the right type to promote it to.
1094   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1095     assert(PVT != VT && "Don't know what type to promote to!");
1096
1097     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1098
1099     bool Replace0 = false;
1100     SDValue N0 = Op.getOperand(0);
1101     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1102
1103     bool Replace1 = false;
1104     SDValue N1 = Op.getOperand(1);
1105     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1106     SDLoc DL(Op);
1107
1108     SDValue RV =
1109         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1110
1111     // New replace instances of N0 and N1
1112     if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1113         NN0.getOpcode() != ISD::DELETED_NODE) {
1114       AddToWorklist(NN0.getNode());
1115       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1116     }
1117
1118     if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1119         NN1.getOpcode() != ISD::DELETED_NODE) {
1120       AddToWorklist(NN1.getNode());
1121       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1122     }
1123
1124     // Deal with Op being deleted.
1125     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1126       return RV;
1127   }
1128   return SDValue();
1129 }
1130
1131 /// Promote the specified integer shift operation if the target indicates it is
1132 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1133 /// i32 since i16 instructions are longer.
1134 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1135   if (!LegalOperations)
1136     return SDValue();
1137
1138   EVT VT = Op.getValueType();
1139   if (VT.isVector() || !VT.isInteger())
1140     return SDValue();
1141
1142   // If operation type is 'undesirable', e.g. i16 on x86, consider
1143   // promoting it.
1144   unsigned Opc = Op.getOpcode();
1145   if (TLI.isTypeDesirableForOp(Opc, VT))
1146     return SDValue();
1147
1148   EVT PVT = VT;
1149   // Consult target whether it is a good idea to promote this operation and
1150   // what's the right type to promote it to.
1151   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1152     assert(PVT != VT && "Don't know what type to promote to!");
1153
1154     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1155
1156     bool Replace = false;
1157     SDValue N0 = Op.getOperand(0);
1158     SDValue N1 = Op.getOperand(1);
1159     if (Opc == ISD::SRA)
1160       N0 = SExtPromoteOperand(N0, PVT);
1161     else if (Opc == ISD::SRL)
1162       N0 = ZExtPromoteOperand(N0, PVT);
1163     else
1164       N0 = PromoteOperand(N0, PVT, Replace);
1165
1166     if (!N0.getNode())
1167       return SDValue();
1168
1169     SDLoc DL(Op);
1170     SDValue RV =
1171         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1172
1173     AddToWorklist(N0.getNode());
1174     if (Replace)
1175       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1176
1177     // Deal with Op being deleted.
1178     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1179       return RV;
1180   }
1181   return SDValue();
1182 }
1183
1184 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1185   if (!LegalOperations)
1186     return SDValue();
1187
1188   EVT VT = Op.getValueType();
1189   if (VT.isVector() || !VT.isInteger())
1190     return SDValue();
1191
1192   // If operation type is 'undesirable', e.g. i16 on x86, consider
1193   // promoting it.
1194   unsigned Opc = Op.getOpcode();
1195   if (TLI.isTypeDesirableForOp(Opc, VT))
1196     return SDValue();
1197
1198   EVT PVT = VT;
1199   // Consult target whether it is a good idea to promote this operation and
1200   // what's the right type to promote it to.
1201   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1202     assert(PVT != VT && "Don't know what type to promote to!");
1203     // fold (aext (aext x)) -> (aext x)
1204     // fold (aext (zext x)) -> (zext x)
1205     // fold (aext (sext x)) -> (sext x)
1206     DEBUG(dbgs() << "\nPromoting ";
1207           Op.getNode()->dump(&DAG));
1208     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1209   }
1210   return SDValue();
1211 }
1212
1213 bool DAGCombiner::PromoteLoad(SDValue Op) {
1214   if (!LegalOperations)
1215     return false;
1216
1217   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1218     return false;
1219
1220   EVT VT = Op.getValueType();
1221   if (VT.isVector() || !VT.isInteger())
1222     return false;
1223
1224   // If operation type is 'undesirable', e.g. i16 on x86, consider
1225   // promoting it.
1226   unsigned Opc = Op.getOpcode();
1227   if (TLI.isTypeDesirableForOp(Opc, VT))
1228     return false;
1229
1230   EVT PVT = VT;
1231   // Consult target whether it is a good idea to promote this operation and
1232   // what's the right type to promote it to.
1233   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1234     assert(PVT != VT && "Don't know what type to promote to!");
1235
1236     SDLoc DL(Op);
1237     SDNode *N = Op.getNode();
1238     LoadSDNode *LD = cast<LoadSDNode>(N);
1239     EVT MemVT = LD->getMemoryVT();
1240     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1241       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1242                                                        : ISD::EXTLOAD)
1243       : LD->getExtensionType();
1244     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1245                                    LD->getChain(), LD->getBasePtr(),
1246                                    MemVT, LD->getMemOperand());
1247     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1248
1249     DEBUG(dbgs() << "\nPromoting ";
1250           N->dump(&DAG);
1251           dbgs() << "\nTo: ";
1252           Result.getNode()->dump(&DAG);
1253           dbgs() << '\n');
1254     WorklistRemover DeadNodes(*this);
1255     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1256     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1257     deleteAndRecombine(N);
1258     AddToWorklist(Result.getNode());
1259     return true;
1260   }
1261   return false;
1262 }
1263
1264 /// \brief Recursively delete a node which has no uses and any operands for
1265 /// which it is the only use.
1266 ///
1267 /// Note that this both deletes the nodes and removes them from the worklist.
1268 /// It also adds any nodes who have had a user deleted to the worklist as they
1269 /// may now have only one use and subject to other combines.
1270 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1271   if (!N->use_empty())
1272     return false;
1273
1274   SmallSetVector<SDNode *, 16> Nodes;
1275   Nodes.insert(N);
1276   do {
1277     N = Nodes.pop_back_val();
1278     if (!N)
1279       continue;
1280
1281     if (N->use_empty()) {
1282       for (const SDValue &ChildN : N->op_values())
1283         Nodes.insert(ChildN.getNode());
1284
1285       removeFromWorklist(N);
1286       DAG.DeleteNode(N);
1287     } else {
1288       AddToWorklist(N);
1289     }
1290   } while (!Nodes.empty());
1291   return true;
1292 }
1293
1294 //===----------------------------------------------------------------------===//
1295 //  Main DAG Combiner implementation
1296 //===----------------------------------------------------------------------===//
1297
1298 void DAGCombiner::Run(CombineLevel AtLevel) {
1299   // set the instance variables, so that the various visit routines may use it.
1300   Level = AtLevel;
1301   LegalOperations = Level >= AfterLegalizeVectorOps;
1302   LegalTypes = Level >= AfterLegalizeTypes;
1303
1304   // Add all the dag nodes to the worklist.
1305   for (SDNode &Node : DAG.allnodes())
1306     AddToWorklist(&Node);
1307
1308   // Create a dummy node (which is not added to allnodes), that adds a reference
1309   // to the root node, preventing it from being deleted, and tracking any
1310   // changes of the root.
1311   HandleSDNode Dummy(DAG.getRoot());
1312
1313   // While the worklist isn't empty, find a node and try to combine it.
1314   while (!WorklistMap.empty()) {
1315     SDNode *N;
1316     // The Worklist holds the SDNodes in order, but it may contain null entries.
1317     do {
1318       N = Worklist.pop_back_val();
1319     } while (!N);
1320
1321     bool GoodWorklistEntry = WorklistMap.erase(N);
1322     (void)GoodWorklistEntry;
1323     assert(GoodWorklistEntry &&
1324            "Found a worklist entry without a corresponding map entry!");
1325
1326     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1327     // N is deleted from the DAG, since they too may now be dead or may have a
1328     // reduced number of uses, allowing other xforms.
1329     if (recursivelyDeleteUnusedNodes(N))
1330       continue;
1331
1332     WorklistRemover DeadNodes(*this);
1333
1334     // If this combine is running after legalizing the DAG, re-legalize any
1335     // nodes pulled off the worklist.
1336     if (Level == AfterLegalizeDAG) {
1337       SmallSetVector<SDNode *, 16> UpdatedNodes;
1338       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1339
1340       for (SDNode *LN : UpdatedNodes) {
1341         AddToWorklist(LN);
1342         AddUsersToWorklist(LN);
1343       }
1344       if (!NIsValid)
1345         continue;
1346     }
1347
1348     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1349
1350     // Add any operands of the new node which have not yet been combined to the
1351     // worklist as well. Because the worklist uniques things already, this
1352     // won't repeatedly process the same operand.
1353     CombinedNodes.insert(N);
1354     for (const SDValue &ChildN : N->op_values())
1355       if (!CombinedNodes.count(ChildN.getNode()))
1356         AddToWorklist(ChildN.getNode());
1357
1358     SDValue RV = combine(N);
1359
1360     if (!RV.getNode())
1361       continue;
1362
1363     ++NodesCombined;
1364
1365     // If we get back the same node we passed in, rather than a new node or
1366     // zero, we know that the node must have defined multiple values and
1367     // CombineTo was used.  Since CombineTo takes care of the worklist
1368     // mechanics for us, we have no work to do in this case.
1369     if (RV.getNode() == N)
1370       continue;
1371
1372     assert(N->getOpcode() != ISD::DELETED_NODE &&
1373            RV.getOpcode() != ISD::DELETED_NODE &&
1374            "Node was deleted but visit returned new node!");
1375
1376     DEBUG(dbgs() << " ... into: ";
1377           RV.getNode()->dump(&DAG));
1378
1379     if (N->getNumValues() == RV.getNode()->getNumValues())
1380       DAG.ReplaceAllUsesWith(N, RV.getNode());
1381     else {
1382       assert(N->getValueType(0) == RV.getValueType() &&
1383              N->getNumValues() == 1 && "Type mismatch");
1384       DAG.ReplaceAllUsesWith(N, &RV);
1385     }
1386
1387     // Push the new node and any users onto the worklist
1388     AddToWorklist(RV.getNode());
1389     AddUsersToWorklist(RV.getNode());
1390
1391     // Finally, if the node is now dead, remove it from the graph.  The node
1392     // may not be dead if the replacement process recursively simplified to
1393     // something else needing this node. This will also take care of adding any
1394     // operands which have lost a user to the worklist.
1395     recursivelyDeleteUnusedNodes(N);
1396   }
1397
1398   // If the root changed (e.g. it was a dead load, update the root).
1399   DAG.setRoot(Dummy.getValue());
1400   DAG.RemoveDeadNodes();
1401 }
1402
1403 SDValue DAGCombiner::visit(SDNode *N) {
1404   switch (N->getOpcode()) {
1405   default: break;
1406   case ISD::TokenFactor:        return visitTokenFactor(N);
1407   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1408   case ISD::ADD:                return visitADD(N);
1409   case ISD::SUB:                return visitSUB(N);
1410   case ISD::ADDC:               return visitADDC(N);
1411   case ISD::UADDO:              return visitUADDO(N);
1412   case ISD::SUBC:               return visitSUBC(N);
1413   case ISD::USUBO:              return visitUSUBO(N);
1414   case ISD::ADDE:               return visitADDE(N);
1415   case ISD::SUBE:               return visitSUBE(N);
1416   case ISD::MUL:                return visitMUL(N);
1417   case ISD::SDIV:               return visitSDIV(N);
1418   case ISD::UDIV:               return visitUDIV(N);
1419   case ISD::SREM:
1420   case ISD::UREM:               return visitREM(N);
1421   case ISD::MULHU:              return visitMULHU(N);
1422   case ISD::MULHS:              return visitMULHS(N);
1423   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1424   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1425   case ISD::SMULO:              return visitSMULO(N);
1426   case ISD::UMULO:              return visitUMULO(N);
1427   case ISD::SMIN:
1428   case ISD::SMAX:
1429   case ISD::UMIN:
1430   case ISD::UMAX:               return visitIMINMAX(N);
1431   case ISD::AND:                return visitAND(N);
1432   case ISD::OR:                 return visitOR(N);
1433   case ISD::XOR:                return visitXOR(N);
1434   case ISD::SHL:                return visitSHL(N);
1435   case ISD::SRA:                return visitSRA(N);
1436   case ISD::SRL:                return visitSRL(N);
1437   case ISD::ROTR:
1438   case ISD::ROTL:               return visitRotate(N);
1439   case ISD::ABS:                return visitABS(N);
1440   case ISD::BSWAP:              return visitBSWAP(N);
1441   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1442   case ISD::CTLZ:               return visitCTLZ(N);
1443   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1444   case ISD::CTTZ:               return visitCTTZ(N);
1445   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1446   case ISD::CTPOP:              return visitCTPOP(N);
1447   case ISD::SELECT:             return visitSELECT(N);
1448   case ISD::VSELECT:            return visitVSELECT(N);
1449   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1450   case ISD::SETCC:              return visitSETCC(N);
1451   case ISD::SETCCE:             return visitSETCCE(N);
1452   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1453   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1454   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1455   case ISD::AssertZext:         return visitAssertZext(N);
1456   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1457   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1458   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1459   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1460   case ISD::BITCAST:            return visitBITCAST(N);
1461   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1462   case ISD::FADD:               return visitFADD(N);
1463   case ISD::FSUB:               return visitFSUB(N);
1464   case ISD::FMUL:               return visitFMUL(N);
1465   case ISD::FMA:                return visitFMA(N);
1466   case ISD::FDIV:               return visitFDIV(N);
1467   case ISD::FREM:               return visitFREM(N);
1468   case ISD::FSQRT:              return visitFSQRT(N);
1469   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1470   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1471   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1472   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1473   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1474   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1475   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1476   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1477   case ISD::FNEG:               return visitFNEG(N);
1478   case ISD::FABS:               return visitFABS(N);
1479   case ISD::FFLOOR:             return visitFFLOOR(N);
1480   case ISD::FMINNUM:            return visitFMINNUM(N);
1481   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1482   case ISD::FCEIL:              return visitFCEIL(N);
1483   case ISD::FTRUNC:             return visitFTRUNC(N);
1484   case ISD::BRCOND:             return visitBRCOND(N);
1485   case ISD::BR_CC:              return visitBR_CC(N);
1486   case ISD::LOAD:               return visitLOAD(N);
1487   case ISD::STORE:              return visitSTORE(N);
1488   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1489   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1490   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1491   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1492   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1493   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1494   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1495   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1496   case ISD::MGATHER:            return visitMGATHER(N);
1497   case ISD::MLOAD:              return visitMLOAD(N);
1498   case ISD::MSCATTER:           return visitMSCATTER(N);
1499   case ISD::MSTORE:             return visitMSTORE(N);
1500   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1501   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1502   }
1503   return SDValue();
1504 }
1505
1506 SDValue DAGCombiner::combine(SDNode *N) {
1507   SDValue RV = visit(N);
1508
1509   // If nothing happened, try a target-specific DAG combine.
1510   if (!RV.getNode()) {
1511     assert(N->getOpcode() != ISD::DELETED_NODE &&
1512            "Node was deleted but visit returned NULL!");
1513
1514     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1515         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1516
1517       // Expose the DAG combiner to the target combiner impls.
1518       TargetLowering::DAGCombinerInfo
1519         DagCombineInfo(DAG, Level, false, this);
1520
1521       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1522     }
1523   }
1524
1525   // If nothing happened still, try promoting the operation.
1526   if (!RV.getNode()) {
1527     switch (N->getOpcode()) {
1528     default: break;
1529     case ISD::ADD:
1530     case ISD::SUB:
1531     case ISD::MUL:
1532     case ISD::AND:
1533     case ISD::OR:
1534     case ISD::XOR:
1535       RV = PromoteIntBinOp(SDValue(N, 0));
1536       break;
1537     case ISD::SHL:
1538     case ISD::SRA:
1539     case ISD::SRL:
1540       RV = PromoteIntShiftOp(SDValue(N, 0));
1541       break;
1542     case ISD::SIGN_EXTEND:
1543     case ISD::ZERO_EXTEND:
1544     case ISD::ANY_EXTEND:
1545       RV = PromoteExtend(SDValue(N, 0));
1546       break;
1547     case ISD::LOAD:
1548       if (PromoteLoad(SDValue(N, 0)))
1549         RV = SDValue(N, 0);
1550       break;
1551     }
1552   }
1553
1554   // If N is a commutative binary node, try commuting it to enable more
1555   // sdisel CSE.
1556   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1557       N->getNumValues() == 1) {
1558     SDValue N0 = N->getOperand(0);
1559     SDValue N1 = N->getOperand(1);
1560
1561     // Constant operands are canonicalized to RHS.
1562     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1563       SDValue Ops[] = {N1, N0};
1564       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1565                                             N->getFlags());
1566       if (CSENode)
1567         return SDValue(CSENode, 0);
1568     }
1569   }
1570
1571   return RV;
1572 }
1573
1574 /// Given a node, return its input chain if it has one, otherwise return a null
1575 /// sd operand.
1576 static SDValue getInputChainForNode(SDNode *N) {
1577   if (unsigned NumOps = N->getNumOperands()) {
1578     if (N->getOperand(0).getValueType() == MVT::Other)
1579       return N->getOperand(0);
1580     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1581       return N->getOperand(NumOps-1);
1582     for (unsigned i = 1; i < NumOps-1; ++i)
1583       if (N->getOperand(i).getValueType() == MVT::Other)
1584         return N->getOperand(i);
1585   }
1586   return SDValue();
1587 }
1588
1589 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1590   // If N has two operands, where one has an input chain equal to the other,
1591   // the 'other' chain is redundant.
1592   if (N->getNumOperands() == 2) {
1593     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1594       return N->getOperand(0);
1595     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1596       return N->getOperand(1);
1597   }
1598
1599   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1600   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1601   SmallPtrSet<SDNode*, 16> SeenOps;
1602   bool Changed = false;             // If we should replace this token factor.
1603
1604   // Start out with this token factor.
1605   TFs.push_back(N);
1606
1607   // Iterate through token factors.  The TFs grows when new token factors are
1608   // encountered.
1609   for (unsigned i = 0; i < TFs.size(); ++i) {
1610     SDNode *TF = TFs[i];
1611
1612     // Check each of the operands.
1613     for (const SDValue &Op : TF->op_values()) {
1614
1615       switch (Op.getOpcode()) {
1616       case ISD::EntryToken:
1617         // Entry tokens don't need to be added to the list. They are
1618         // redundant.
1619         Changed = true;
1620         break;
1621
1622       case ISD::TokenFactor:
1623         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1624           // Queue up for processing.
1625           TFs.push_back(Op.getNode());
1626           // Clean up in case the token factor is removed.
1627           AddToWorklist(Op.getNode());
1628           Changed = true;
1629           break;
1630         }
1631         LLVM_FALLTHROUGH;
1632
1633       default:
1634         // Only add if it isn't already in the list.
1635         if (SeenOps.insert(Op.getNode()).second)
1636           Ops.push_back(Op);
1637         else
1638           Changed = true;
1639         break;
1640       }
1641     }
1642   }
1643
1644   // Remove Nodes that are chained to another node in the list. Do so
1645   // by walking up chains breath-first stopping when we've seen
1646   // another operand. In general we must climb to the EntryNode, but we can exit
1647   // early if we find all remaining work is associated with just one operand as
1648   // no further pruning is possible.
1649
1650   // List of nodes to search through and original Ops from which they originate.
1651   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1652   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1653   SmallPtrSet<SDNode *, 16> SeenChains;
1654   bool DidPruneOps = false;
1655
1656   unsigned NumLeftToConsider = 0;
1657   for (const SDValue &Op : Ops) {
1658     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1659     OpWorkCount.push_back(1);
1660   }
1661
1662   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1663     // If this is an Op, we can remove the op from the list. Remark any
1664     // search associated with it as from the current OpNumber.
1665     if (SeenOps.count(Op) != 0) {
1666       Changed = true;
1667       DidPruneOps = true;
1668       unsigned OrigOpNumber = 0;
1669       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1670         OrigOpNumber++;
1671       assert((OrigOpNumber != Ops.size()) &&
1672              "expected to find TokenFactor Operand");
1673       // Re-mark worklist from OrigOpNumber to OpNumber
1674       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1675         if (Worklist[i].second == OrigOpNumber) {
1676           Worklist[i].second = OpNumber;
1677         }
1678       }
1679       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1680       OpWorkCount[OrigOpNumber] = 0;
1681       NumLeftToConsider--;
1682     }
1683     // Add if it's a new chain
1684     if (SeenChains.insert(Op).second) {
1685       OpWorkCount[OpNumber]++;
1686       Worklist.push_back(std::make_pair(Op, OpNumber));
1687     }
1688   };
1689
1690   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1691     // We need at least be consider at least 2 Ops to prune.
1692     if (NumLeftToConsider <= 1)
1693       break;
1694     auto CurNode = Worklist[i].first;
1695     auto CurOpNumber = Worklist[i].second;
1696     assert((OpWorkCount[CurOpNumber] > 0) &&
1697            "Node should not appear in worklist");
1698     switch (CurNode->getOpcode()) {
1699     case ISD::EntryToken:
1700       // Hitting EntryToken is the only way for the search to terminate without
1701       // hitting
1702       // another operand's search. Prevent us from marking this operand
1703       // considered.
1704       NumLeftToConsider++;
1705       break;
1706     case ISD::TokenFactor:
1707       for (const SDValue &Op : CurNode->op_values())
1708         AddToWorklist(i, Op.getNode(), CurOpNumber);
1709       break;
1710     case ISD::CopyFromReg:
1711     case ISD::CopyToReg:
1712       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1713       break;
1714     default:
1715       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1716         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1717       break;
1718     }
1719     OpWorkCount[CurOpNumber]--;
1720     if (OpWorkCount[CurOpNumber] == 0)
1721       NumLeftToConsider--;
1722   }
1723
1724   SDValue Result;
1725
1726   // If we've changed things around then replace token factor.
1727   if (Changed) {
1728     if (Ops.empty()) {
1729       // The entry token is the only possible outcome.
1730       Result = DAG.getEntryNode();
1731     } else {
1732       if (DidPruneOps) {
1733         SmallVector<SDValue, 8> PrunedOps;
1734         //
1735         for (const SDValue &Op : Ops) {
1736           if (SeenChains.count(Op.getNode()) == 0)
1737             PrunedOps.push_back(Op);
1738         }
1739         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1740       } else {
1741         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1742       }
1743     }
1744
1745     // Add users to worklist, since we may introduce a lot of new
1746     // chained token factors while removing memory deps.
1747     return CombineTo(N, Result, true /*add to worklist*/);
1748   }
1749
1750   return Result;
1751 }
1752
1753 /// MERGE_VALUES can always be eliminated.
1754 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1755   WorklistRemover DeadNodes(*this);
1756   // Replacing results may cause a different MERGE_VALUES to suddenly
1757   // be CSE'd with N, and carry its uses with it. Iterate until no
1758   // uses remain, to ensure that the node can be safely deleted.
1759   // First add the users of this node to the work list so that they
1760   // can be tried again once they have new operands.
1761   AddUsersToWorklist(N);
1762   do {
1763     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1764       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1765   } while (!N->use_empty());
1766   deleteAndRecombine(N);
1767   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1768 }
1769
1770 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1771 /// ConstantSDNode pointer else nullptr.
1772 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1773   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1774   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1775 }
1776
1777 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1778   auto BinOpcode = BO->getOpcode();
1779   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1780           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1781           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1782           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1783           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1784           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1785           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1786           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1787           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1788          "Unexpected binary operator");
1789
1790   // Bail out if any constants are opaque because we can't constant fold those.
1791   SDValue C1 = BO->getOperand(1);
1792   if (!isConstantOrConstantVector(C1, true) &&
1793       !isConstantFPBuildVectorOrConstantFP(C1))
1794     return SDValue();
1795
1796   // Don't do this unless the old select is going away. We want to eliminate the
1797   // binary operator, not replace a binop with a select.
1798   // TODO: Handle ISD::SELECT_CC.
1799   SDValue Sel = BO->getOperand(0);
1800   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1801     return SDValue();
1802
1803   SDValue CT = Sel.getOperand(1);
1804   if (!isConstantOrConstantVector(CT, true) &&
1805       !isConstantFPBuildVectorOrConstantFP(CT))
1806     return SDValue();
1807
1808   SDValue CF = Sel.getOperand(2);
1809   if (!isConstantOrConstantVector(CF, true) &&
1810       !isConstantFPBuildVectorOrConstantFP(CF))
1811     return SDValue();
1812
1813   // We have a select-of-constants followed by a binary operator with a
1814   // constant. Eliminate the binop by pulling the constant math into the select.
1815   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1816   EVT VT = Sel.getValueType();
1817   SDLoc DL(Sel);
1818   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1819   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1820           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1821          "Failed to constant fold a binop with constant operands");
1822
1823   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1824   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1825           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1826          "Failed to constant fold a binop with constant operands");
1827
1828   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1829 }
1830
1831 SDValue DAGCombiner::visitADD(SDNode *N) {
1832   SDValue N0 = N->getOperand(0);
1833   SDValue N1 = N->getOperand(1);
1834   EVT VT = N0.getValueType();
1835   SDLoc DL(N);
1836
1837   // fold vector ops
1838   if (VT.isVector()) {
1839     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1840       return FoldedVOp;
1841
1842     // fold (add x, 0) -> x, vector edition
1843     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1844       return N0;
1845     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1846       return N1;
1847   }
1848
1849   // fold (add x, undef) -> undef
1850   if (N0.isUndef())
1851     return N0;
1852
1853   if (N1.isUndef())
1854     return N1;
1855
1856   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1857     // canonicalize constant to RHS
1858     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1859       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1860     // fold (add c1, c2) -> c1+c2
1861     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1862                                       N1.getNode());
1863   }
1864
1865   // fold (add x, 0) -> x
1866   if (isNullConstant(N1))
1867     return N0;
1868
1869   // fold ((c1-A)+c2) -> (c1+c2)-A
1870   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1871     if (N0.getOpcode() == ISD::SUB)
1872       if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1873         return DAG.getNode(ISD::SUB, DL, VT,
1874                            DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1875                            N0.getOperand(1));
1876       }
1877   }
1878
1879   if (SDValue NewSel = foldBinOpIntoSelect(N))
1880     return NewSel;
1881
1882   // reassociate add
1883   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1884     return RADD;
1885
1886   // fold ((0-A) + B) -> B-A
1887   if (N0.getOpcode() == ISD::SUB &&
1888       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1889     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1890
1891   // fold (A + (0-B)) -> A-B
1892   if (N1.getOpcode() == ISD::SUB &&
1893       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1894     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1895
1896   // fold (A+(B-A)) -> B
1897   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1898     return N1.getOperand(0);
1899
1900   // fold ((B-A)+A) -> B
1901   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1902     return N0.getOperand(0);
1903
1904   // fold (A+(B-(A+C))) to (B-C)
1905   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1906       N0 == N1.getOperand(1).getOperand(0))
1907     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1908                        N1.getOperand(1).getOperand(1));
1909
1910   // fold (A+(B-(C+A))) to (B-C)
1911   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1912       N0 == N1.getOperand(1).getOperand(1))
1913     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1914                        N1.getOperand(1).getOperand(0));
1915
1916   // fold (A+((B-A)+or-C)) to (B+or-C)
1917   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1918       N1.getOperand(0).getOpcode() == ISD::SUB &&
1919       N0 == N1.getOperand(0).getOperand(1))
1920     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1921                        N1.getOperand(1));
1922
1923   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1924   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1925     SDValue N00 = N0.getOperand(0);
1926     SDValue N01 = N0.getOperand(1);
1927     SDValue N10 = N1.getOperand(0);
1928     SDValue N11 = N1.getOperand(1);
1929
1930     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1931       return DAG.getNode(ISD::SUB, DL, VT,
1932                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1933                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1934   }
1935
1936   if (SimplifyDemandedBits(SDValue(N, 0)))
1937     return SDValue(N, 0);
1938
1939   // fold (a+b) -> (a|b) iff a and b share no bits.
1940   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1941       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1942     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1943
1944   if (SDValue Combined = visitADDLike(N0, N1, N))
1945     return Combined;
1946
1947   if (SDValue Combined = visitADDLike(N1, N0, N))
1948     return Combined;
1949
1950   return SDValue();
1951 }
1952
1953 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
1954   EVT VT = N0.getValueType();
1955   SDLoc DL(LocReference);
1956
1957   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1958   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1959       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1960     return DAG.getNode(ISD::SUB, DL, VT, N0,
1961                        DAG.getNode(ISD::SHL, DL, VT,
1962                                    N1.getOperand(0).getOperand(1),
1963                                    N1.getOperand(1)));
1964
1965   if (N1.getOpcode() == ISD::AND) {
1966     SDValue AndOp0 = N1.getOperand(0);
1967     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1968     unsigned DestBits = VT.getScalarSizeInBits();
1969
1970     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1971     // and similar xforms where the inner op is either ~0 or 0.
1972     if (NumSignBits == DestBits &&
1973         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1974       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
1975   }
1976
1977   // add (sext i1), X -> sub X, (zext i1)
1978   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1979       N0.getOperand(0).getValueType() == MVT::i1 &&
1980       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1981     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1982     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1983   }
1984
1985   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1986   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1987     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1988     if (TN->getVT() == MVT::i1) {
1989       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1990                                  DAG.getConstant(1, DL, VT));
1991       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1992     }
1993   }
1994
1995   return SDValue();
1996 }
1997
1998 SDValue DAGCombiner::visitADDC(SDNode *N) {
1999   SDValue N0 = N->getOperand(0);
2000   SDValue N1 = N->getOperand(1);
2001   EVT VT = N0.getValueType();
2002   SDLoc DL(N);
2003
2004   // If the flag result is dead, turn this into an ADD.
2005   if (!N->hasAnyUseOfValue(1))
2006     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2007                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2008
2009   // canonicalize constant to RHS.
2010   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2011   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2012   if (N0C && !N1C)
2013     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2014
2015   // fold (addc x, 0) -> x + no carry out
2016   if (isNullConstant(N1))
2017     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2018                                         DL, MVT::Glue));
2019
2020   // If it cannot overflow, transform into an add.
2021   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2022     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2023                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2024
2025   return SDValue();
2026 }
2027
2028 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2029   SDValue N0 = N->getOperand(0);
2030   SDValue N1 = N->getOperand(1);
2031   EVT VT = N0.getValueType();
2032   if (VT.isVector())
2033     return SDValue();
2034
2035   EVT CarryVT = N->getValueType(1);
2036   SDLoc DL(N);
2037
2038   // If the flag result is dead, turn this into an ADD.
2039   if (!N->hasAnyUseOfValue(1))
2040     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2041                      DAG.getUNDEF(CarryVT));
2042
2043   // canonicalize constant to RHS.
2044   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2045   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2046   if (N0C && !N1C)
2047     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2048
2049   // fold (uaddo x, 0) -> x + no carry out
2050   if (isNullConstant(N1))
2051     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2052
2053   // If it cannot overflow, transform into an add.
2054   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2055     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2056                      DAG.getConstant(0, DL, CarryVT));
2057
2058   return SDValue();
2059 }
2060
2061 SDValue DAGCombiner::visitADDE(SDNode *N) {
2062   SDValue N0 = N->getOperand(0);
2063   SDValue N1 = N->getOperand(1);
2064   SDValue CarryIn = N->getOperand(2);
2065
2066   // canonicalize constant to RHS
2067   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2068   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2069   if (N0C && !N1C)
2070     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2071                        N1, N0, CarryIn);
2072
2073   // fold (adde x, y, false) -> (addc x, y)
2074   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2075     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2076
2077   return SDValue();
2078 }
2079
2080 // Since it may not be valid to emit a fold to zero for vector initializers
2081 // check if we can before folding.
2082 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2083                              SelectionDAG &DAG, bool LegalOperations,
2084                              bool LegalTypes) {
2085   if (!VT.isVector())
2086     return DAG.getConstant(0, DL, VT);
2087   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2088     return DAG.getConstant(0, DL, VT);
2089   return SDValue();
2090 }
2091
2092 SDValue DAGCombiner::visitSUB(SDNode *N) {
2093   SDValue N0 = N->getOperand(0);
2094   SDValue N1 = N->getOperand(1);
2095   EVT VT = N0.getValueType();
2096   SDLoc DL(N);
2097
2098   // fold vector ops
2099   if (VT.isVector()) {
2100     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2101       return FoldedVOp;
2102
2103     // fold (sub x, 0) -> x, vector edition
2104     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2105       return N0;
2106   }
2107
2108   // fold (sub x, x) -> 0
2109   // FIXME: Refactor this and xor and other similar operations together.
2110   if (N0 == N1)
2111     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2112   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2113       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2114     // fold (sub c1, c2) -> c1-c2
2115     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2116                                       N1.getNode());
2117   }
2118
2119   if (SDValue NewSel = foldBinOpIntoSelect(N))
2120     return NewSel;
2121
2122   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2123
2124   // fold (sub x, c) -> (add x, -c)
2125   if (N1C) {
2126     return DAG.getNode(ISD::ADD, DL, VT, N0,
2127                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2128   }
2129
2130   if (isNullConstantOrNullSplatConstant(N0)) {
2131     unsigned BitWidth = VT.getScalarSizeInBits();
2132     // Right-shifting everything out but the sign bit followed by negation is
2133     // the same as flipping arithmetic/logical shift type without the negation:
2134     // -(X >>u 31) -> (X >>s 31)
2135     // -(X >>s 31) -> (X >>u 31)
2136     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2137       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2138       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2139         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2140         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2141           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2142       }
2143     }
2144
2145     // 0 - X --> 0 if the sub is NUW.
2146     if (N->getFlags()->hasNoUnsignedWrap())
2147       return N0;
2148
2149     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2150       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2151       // N1 must be 0 because negating the minimum signed value is undefined.
2152       if (N->getFlags()->hasNoSignedWrap())
2153         return N0;
2154
2155       // 0 - X --> X if X is 0 or the minimum signed value.
2156       return N1;
2157     }
2158   }
2159
2160   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2161   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2162     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2163
2164   // fold A-(A-B) -> B
2165   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2166     return N1.getOperand(1);
2167
2168   // fold (A+B)-A -> B
2169   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2170     return N0.getOperand(1);
2171
2172   // fold (A+B)-B -> A
2173   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2174     return N0.getOperand(0);
2175
2176   // fold C2-(A+C1) -> (C2-C1)-A
2177   if (N1.getOpcode() == ISD::ADD) {
2178     SDValue N11 = N1.getOperand(1);
2179     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2180         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2181       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2182       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2183     }
2184   }
2185
2186   // fold ((A+(B+or-C))-B) -> A+or-C
2187   if (N0.getOpcode() == ISD::ADD &&
2188       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2189        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2190       N0.getOperand(1).getOperand(0) == N1)
2191     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2192                        N0.getOperand(1).getOperand(1));
2193
2194   // fold ((A+(C+B))-B) -> A+C
2195   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2196       N0.getOperand(1).getOperand(1) == N1)
2197     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2198                        N0.getOperand(1).getOperand(0));
2199
2200   // fold ((A-(B-C))-C) -> A-B
2201   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2202       N0.getOperand(1).getOperand(1) == N1)
2203     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2204                        N0.getOperand(1).getOperand(0));
2205
2206   // If either operand of a sub is undef, the result is undef
2207   if (N0.isUndef())
2208     return N0;
2209   if (N1.isUndef())
2210     return N1;
2211
2212   // If the relocation model supports it, consider symbol offsets.
2213   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2214     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2215       // fold (sub Sym, c) -> Sym-c
2216       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2217         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2218                                     GA->getOffset() -
2219                                         (uint64_t)N1C->getSExtValue());
2220       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2221       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2222         if (GA->getGlobal() == GB->getGlobal())
2223           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2224                                  DL, VT);
2225     }
2226
2227   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2228   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2229     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2230     if (TN->getVT() == MVT::i1) {
2231       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2232                                  DAG.getConstant(1, DL, VT));
2233       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2234     }
2235   }
2236
2237   return SDValue();
2238 }
2239
2240 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2241   SDValue N0 = N->getOperand(0);
2242   SDValue N1 = N->getOperand(1);
2243   EVT VT = N0.getValueType();
2244   SDLoc DL(N);
2245
2246   // If the flag result is dead, turn this into an SUB.
2247   if (!N->hasAnyUseOfValue(1))
2248     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2249                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2250
2251   // fold (subc x, x) -> 0 + no borrow
2252   if (N0 == N1)
2253     return CombineTo(N, DAG.getConstant(0, DL, VT),
2254                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2255
2256   // fold (subc x, 0) -> x + no borrow
2257   if (isNullConstant(N1))
2258     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2259
2260   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2261   if (isAllOnesConstant(N0))
2262     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2263                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2264
2265   return SDValue();
2266 }
2267
2268 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2269   SDValue N0 = N->getOperand(0);
2270   SDValue N1 = N->getOperand(1);
2271   EVT VT = N0.getValueType();
2272   if (VT.isVector())
2273     return SDValue();
2274
2275   EVT CarryVT = N->getValueType(1);
2276   SDLoc DL(N);
2277
2278   // If the flag result is dead, turn this into an SUB.
2279   if (!N->hasAnyUseOfValue(1))
2280     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2281                      DAG.getUNDEF(CarryVT));
2282
2283   // fold (usubo x, x) -> 0 + no borrow
2284   if (N0 == N1)
2285     return CombineTo(N, DAG.getConstant(0, DL, VT),
2286                      DAG.getConstant(0, DL, CarryVT));
2287
2288   // fold (usubo x, 0) -> x + no borrow
2289   if (isNullConstant(N1))
2290     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2291
2292   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2293   if (isAllOnesConstant(N0))
2294     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2295                      DAG.getConstant(0, DL, CarryVT));
2296
2297   return SDValue();
2298 }
2299
2300 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2301   SDValue N0 = N->getOperand(0);
2302   SDValue N1 = N->getOperand(1);
2303   SDValue CarryIn = N->getOperand(2);
2304
2305   // fold (sube x, y, false) -> (subc x, y)
2306   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2307     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2308
2309   return SDValue();
2310 }
2311
2312 SDValue DAGCombiner::visitMUL(SDNode *N) {
2313   SDValue N0 = N->getOperand(0);
2314   SDValue N1 = N->getOperand(1);
2315   EVT VT = N0.getValueType();
2316
2317   // fold (mul x, undef) -> 0
2318   if (N0.isUndef() || N1.isUndef())
2319     return DAG.getConstant(0, SDLoc(N), VT);
2320
2321   bool N0IsConst = false;
2322   bool N1IsConst = false;
2323   bool N1IsOpaqueConst = false;
2324   bool N0IsOpaqueConst = false;
2325   APInt ConstValue0, ConstValue1;
2326   // fold vector ops
2327   if (VT.isVector()) {
2328     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2329       return FoldedVOp;
2330
2331     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2332     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2333   } else {
2334     N0IsConst = isa<ConstantSDNode>(N0);
2335     if (N0IsConst) {
2336       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2337       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2338     }
2339     N1IsConst = isa<ConstantSDNode>(N1);
2340     if (N1IsConst) {
2341       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2342       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2343     }
2344   }
2345
2346   // fold (mul c1, c2) -> c1*c2
2347   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2348     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2349                                       N0.getNode(), N1.getNode());
2350
2351   // canonicalize constant to RHS (vector doesn't have to splat)
2352   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2353      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2354     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2355   // fold (mul x, 0) -> 0
2356   if (N1IsConst && ConstValue1 == 0)
2357     return N1;
2358   // We require a splat of the entire scalar bit width for non-contiguous
2359   // bit patterns.
2360   bool IsFullSplat =
2361     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2362   // fold (mul x, 1) -> x
2363   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2364     return N0;
2365
2366   if (SDValue NewSel = foldBinOpIntoSelect(N))
2367     return NewSel;
2368
2369   // fold (mul x, -1) -> 0-x
2370   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2371     SDLoc DL(N);
2372     return DAG.getNode(ISD::SUB, DL, VT,
2373                        DAG.getConstant(0, DL, VT), N0);
2374   }
2375   // fold (mul x, (1 << c)) -> x << c
2376   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2377       IsFullSplat) {
2378     SDLoc DL(N);
2379     return DAG.getNode(ISD::SHL, DL, VT, N0,
2380                        DAG.getConstant(ConstValue1.logBase2(), DL,
2381                                        getShiftAmountTy(N0.getValueType())));
2382   }
2383   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2384   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2385       IsFullSplat) {
2386     unsigned Log2Val = (-ConstValue1).logBase2();
2387     SDLoc DL(N);
2388     // FIXME: If the input is something that is easily negated (e.g. a
2389     // single-use add), we should put the negate there.
2390     return DAG.getNode(ISD::SUB, DL, VT,
2391                        DAG.getConstant(0, DL, VT),
2392                        DAG.getNode(ISD::SHL, DL, VT, N0,
2393                             DAG.getConstant(Log2Val, DL,
2394                                       getShiftAmountTy(N0.getValueType()))));
2395   }
2396
2397   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2398   if (N0.getOpcode() == ISD::SHL &&
2399       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2400       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2401     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2402     if (isConstantOrConstantVector(C3))
2403       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2404   }
2405
2406   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2407   // use.
2408   {
2409     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2410
2411     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2412     if (N0.getOpcode() == ISD::SHL &&
2413         isConstantOrConstantVector(N0.getOperand(1)) &&
2414         N0.getNode()->hasOneUse()) {
2415       Sh = N0; Y = N1;
2416     } else if (N1.getOpcode() == ISD::SHL &&
2417                isConstantOrConstantVector(N1.getOperand(1)) &&
2418                N1.getNode()->hasOneUse()) {
2419       Sh = N1; Y = N0;
2420     }
2421
2422     if (Sh.getNode()) {
2423       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2424       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2425     }
2426   }
2427
2428   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2429   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2430       N0.getOpcode() == ISD::ADD &&
2431       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2432       isMulAddWithConstProfitable(N, N0, N1))
2433       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2434                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2435                                      N0.getOperand(0), N1),
2436                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2437                                      N0.getOperand(1), N1));
2438
2439   // reassociate mul
2440   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2441     return RMUL;
2442
2443   return SDValue();
2444 }
2445
2446 /// Return true if divmod libcall is available.
2447 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2448                                      const TargetLowering &TLI) {
2449   RTLIB::Libcall LC;
2450   EVT NodeType = Node->getValueType(0);
2451   if (!NodeType.isSimple())
2452     return false;
2453   switch (NodeType.getSimpleVT().SimpleTy) {
2454   default: return false; // No libcall for vector types.
2455   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2456   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2457   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2458   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2459   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2460   }
2461
2462   return TLI.getLibcallName(LC) != nullptr;
2463 }
2464
2465 /// Issue divrem if both quotient and remainder are needed.
2466 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2467   if (Node->use_empty())
2468     return SDValue(); // This is a dead node, leave it alone.
2469
2470   unsigned Opcode = Node->getOpcode();
2471   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2472   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2473
2474   // DivMod lib calls can still work on non-legal types if using lib-calls.
2475   EVT VT = Node->getValueType(0);
2476   if (VT.isVector() || !VT.isInteger())
2477     return SDValue();
2478
2479   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2480     return SDValue();
2481
2482   // If DIVREM is going to get expanded into a libcall,
2483   // but there is no libcall available, then don't combine.
2484   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2485       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2486     return SDValue();
2487
2488   // If div is legal, it's better to do the normal expansion
2489   unsigned OtherOpcode = 0;
2490   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2491     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2492     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2493       return SDValue();
2494   } else {
2495     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2496     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2497       return SDValue();
2498   }
2499
2500   SDValue Op0 = Node->getOperand(0);
2501   SDValue Op1 = Node->getOperand(1);
2502   SDValue combined;
2503   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2504          UE = Op0.getNode()->use_end(); UI != UE;) {
2505     SDNode *User = *UI++;
2506     if (User == Node || User->use_empty())
2507       continue;
2508     // Convert the other matching node(s), too;
2509     // otherwise, the DIVREM may get target-legalized into something
2510     // target-specific that we won't be able to recognize.
2511     unsigned UserOpc = User->getOpcode();
2512     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2513         User->getOperand(0) == Op0 &&
2514         User->getOperand(1) == Op1) {
2515       if (!combined) {
2516         if (UserOpc == OtherOpcode) {
2517           SDVTList VTs = DAG.getVTList(VT, VT);
2518           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2519         } else if (UserOpc == DivRemOpc) {
2520           combined = SDValue(User, 0);
2521         } else {
2522           assert(UserOpc == Opcode);
2523           continue;
2524         }
2525       }
2526       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2527         CombineTo(User, combined);
2528       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2529         CombineTo(User, combined.getValue(1));
2530     }
2531   }
2532   return combined;
2533 }
2534
2535 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2536   SDValue N0 = N->getOperand(0);
2537   SDValue N1 = N->getOperand(1);
2538   EVT VT = N->getValueType(0);
2539   SDLoc DL(N);
2540
2541   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2542     return DAG.getUNDEF(VT);
2543
2544   // undef / X -> 0
2545   // undef % X -> 0
2546   if (N0.isUndef())
2547     return DAG.getConstant(0, DL, VT);
2548
2549   return SDValue();
2550 }
2551
2552 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2553   SDValue N0 = N->getOperand(0);
2554   SDValue N1 = N->getOperand(1);
2555   EVT VT = N->getValueType(0);
2556
2557   // fold vector ops
2558   if (VT.isVector())
2559     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2560       return FoldedVOp;
2561
2562   SDLoc DL(N);
2563
2564   // fold (sdiv c1, c2) -> c1/c2
2565   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2566   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2567   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2568     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2569   // fold (sdiv X, 1) -> X
2570   if (N1C && N1C->isOne())
2571     return N0;
2572   // fold (sdiv X, -1) -> 0-X
2573   if (N1C && N1C->isAllOnesValue())
2574     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2575
2576   if (SDValue V = simplifyDivRem(N, DAG))
2577     return V;
2578
2579   if (SDValue NewSel = foldBinOpIntoSelect(N))
2580     return NewSel;
2581
2582   // If we know the sign bits of both operands are zero, strength reduce to a
2583   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2584   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2585     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2586
2587   // fold (sdiv X, pow2) -> simple ops after legalize
2588   // FIXME: We check for the exact bit here because the generic lowering gives
2589   // better results in that case. The target-specific lowering should learn how
2590   // to handle exact sdivs efficiently.
2591   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2592       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2593       (N1C->getAPIntValue().isPowerOf2() ||
2594        (-N1C->getAPIntValue()).isPowerOf2())) {
2595     // Target-specific implementation of sdiv x, pow2.
2596     if (SDValue Res = BuildSDIVPow2(N))
2597       return Res;
2598
2599     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2600
2601     // Splat the sign bit into the register
2602     SDValue SGN =
2603         DAG.getNode(ISD::SRA, DL, VT, N0,
2604                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2605                                     getShiftAmountTy(N0.getValueType())));
2606     AddToWorklist(SGN.getNode());
2607
2608     // Add (N0 < 0) ? abs2 - 1 : 0;
2609     SDValue SRL =
2610         DAG.getNode(ISD::SRL, DL, VT, SGN,
2611                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2612                                     getShiftAmountTy(SGN.getValueType())));
2613     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2614     AddToWorklist(SRL.getNode());
2615     AddToWorklist(ADD.getNode());    // Divide by pow2
2616     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2617                   DAG.getConstant(lg2, DL,
2618                                   getShiftAmountTy(ADD.getValueType())));
2619
2620     // If we're dividing by a positive value, we're done.  Otherwise, we must
2621     // negate the result.
2622     if (N1C->getAPIntValue().isNonNegative())
2623       return SRA;
2624
2625     AddToWorklist(SRA.getNode());
2626     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2627   }
2628
2629   // If integer divide is expensive and we satisfy the requirements, emit an
2630   // alternate sequence.  Targets may check function attributes for size/speed
2631   // trade-offs.
2632   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2633   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2634     if (SDValue Op = BuildSDIV(N))
2635       return Op;
2636
2637   // sdiv, srem -> sdivrem
2638   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2639   // true.  Otherwise, we break the simplification logic in visitREM().
2640   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2641     if (SDValue DivRem = useDivRem(N))
2642         return DivRem;
2643
2644   return SDValue();
2645 }
2646
2647 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2648   SDValue N0 = N->getOperand(0);
2649   SDValue N1 = N->getOperand(1);
2650   EVT VT = N->getValueType(0);
2651
2652   // fold vector ops
2653   if (VT.isVector())
2654     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2655       return FoldedVOp;
2656
2657   SDLoc DL(N);
2658
2659   // fold (udiv c1, c2) -> c1/c2
2660   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2661   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2662   if (N0C && N1C)
2663     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2664                                                     N0C, N1C))
2665       return Folded;
2666
2667   if (SDValue V = simplifyDivRem(N, DAG))
2668     return V;
2669
2670   if (SDValue NewSel = foldBinOpIntoSelect(N))
2671     return NewSel;
2672
2673   // fold (udiv x, (1 << c)) -> x >>u c
2674   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2675       DAG.isKnownToBeAPowerOfTwo(N1)) {
2676     SDValue LogBase2 = BuildLogBase2(N1, DL);
2677     AddToWorklist(LogBase2.getNode());
2678
2679     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2680     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2681     AddToWorklist(Trunc.getNode());
2682     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2683   }
2684
2685   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2686   if (N1.getOpcode() == ISD::SHL) {
2687     SDValue N10 = N1.getOperand(0);
2688     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2689         DAG.isKnownToBeAPowerOfTwo(N10)) {
2690       SDValue LogBase2 = BuildLogBase2(N10, DL);
2691       AddToWorklist(LogBase2.getNode());
2692
2693       EVT ADDVT = N1.getOperand(1).getValueType();
2694       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2695       AddToWorklist(Trunc.getNode());
2696       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2697       AddToWorklist(Add.getNode());
2698       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2699     }
2700   }
2701
2702   // fold (udiv x, c) -> alternate
2703   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2704   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2705     if (SDValue Op = BuildUDIV(N))
2706       return Op;
2707
2708   // sdiv, srem -> sdivrem
2709   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2710   // true.  Otherwise, we break the simplification logic in visitREM().
2711   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2712     if (SDValue DivRem = useDivRem(N))
2713         return DivRem;
2714
2715   return SDValue();
2716 }
2717
2718 // handles ISD::SREM and ISD::UREM
2719 SDValue DAGCombiner::visitREM(SDNode *N) {
2720   unsigned Opcode = N->getOpcode();
2721   SDValue N0 = N->getOperand(0);
2722   SDValue N1 = N->getOperand(1);
2723   EVT VT = N->getValueType(0);
2724   bool isSigned = (Opcode == ISD::SREM);
2725   SDLoc DL(N);
2726
2727   // fold (rem c1, c2) -> c1%c2
2728   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2729   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2730   if (N0C && N1C)
2731     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2732       return Folded;
2733
2734   if (SDValue V = simplifyDivRem(N, DAG))
2735     return V;
2736
2737   if (SDValue NewSel = foldBinOpIntoSelect(N))
2738     return NewSel;
2739
2740   if (isSigned) {
2741     // If we know the sign bits of both operands are zero, strength reduce to a
2742     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2743     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2744       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2745   } else {
2746     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2747     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2748       // fold (urem x, pow2) -> (and x, pow2-1)
2749       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2750       AddToWorklist(Add.getNode());
2751       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2752     }
2753     if (N1.getOpcode() == ISD::SHL &&
2754         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2755       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2756       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2757       AddToWorklist(Add.getNode());
2758       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2759     }
2760   }
2761
2762   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2763
2764   // If X/C can be simplified by the division-by-constant logic, lower
2765   // X%C to the equivalent of X-X/C*C.
2766   // To avoid mangling nodes, this simplification requires that the combine()
2767   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2768   // against this by skipping the simplification if isIntDivCheap().  When
2769   // div is not cheap, combine will not return a DIVREM.  Regardless,
2770   // checking cheapness here makes sense since the simplification results in
2771   // fatter code.
2772   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2773     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2774     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2775     AddToWorklist(Div.getNode());
2776     SDValue OptimizedDiv = combine(Div.getNode());
2777     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2778       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2779              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2780       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2781       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2782       AddToWorklist(Mul.getNode());
2783       return Sub;
2784     }
2785   }
2786
2787   // sdiv, srem -> sdivrem
2788   if (SDValue DivRem = useDivRem(N))
2789     return DivRem.getValue(1);
2790
2791   return SDValue();
2792 }
2793
2794 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2795   SDValue N0 = N->getOperand(0);
2796   SDValue N1 = N->getOperand(1);
2797   EVT VT = N->getValueType(0);
2798   SDLoc DL(N);
2799
2800   // fold (mulhs x, 0) -> 0
2801   if (isNullConstant(N1))
2802     return N1;
2803   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2804   if (isOneConstant(N1)) {
2805     SDLoc DL(N);
2806     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2807                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2808                                        getShiftAmountTy(N0.getValueType())));
2809   }
2810   // fold (mulhs x, undef) -> 0
2811   if (N0.isUndef() || N1.isUndef())
2812     return DAG.getConstant(0, SDLoc(N), VT);
2813
2814   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2815   // plus a shift.
2816   if (VT.isSimple() && !VT.isVector()) {
2817     MVT Simple = VT.getSimpleVT();
2818     unsigned SimpleSize = Simple.getSizeInBits();
2819     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2820     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2821       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2822       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2823       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2824       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2825             DAG.getConstant(SimpleSize, DL,
2826                             getShiftAmountTy(N1.getValueType())));
2827       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2828     }
2829   }
2830
2831   return SDValue();
2832 }
2833
2834 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2835   SDValue N0 = N->getOperand(0);
2836   SDValue N1 = N->getOperand(1);
2837   EVT VT = N->getValueType(0);
2838   SDLoc DL(N);
2839
2840   // fold (mulhu x, 0) -> 0
2841   if (isNullConstant(N1))
2842     return N1;
2843   // fold (mulhu x, 1) -> 0
2844   if (isOneConstant(N1))
2845     return DAG.getConstant(0, DL, N0.getValueType());
2846   // fold (mulhu x, undef) -> 0
2847   if (N0.isUndef() || N1.isUndef())
2848     return DAG.getConstant(0, DL, VT);
2849
2850   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2851   // plus a shift.
2852   if (VT.isSimple() && !VT.isVector()) {
2853     MVT Simple = VT.getSimpleVT();
2854     unsigned SimpleSize = Simple.getSizeInBits();
2855     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2856     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2857       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2858       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2859       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2860       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2861             DAG.getConstant(SimpleSize, DL,
2862                             getShiftAmountTy(N1.getValueType())));
2863       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2864     }
2865   }
2866
2867   return SDValue();
2868 }
2869
2870 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2871 /// give the opcodes for the two computations that are being performed. Return
2872 /// true if a simplification was made.
2873 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2874                                                 unsigned HiOp) {
2875   // If the high half is not needed, just compute the low half.
2876   bool HiExists = N->hasAnyUseOfValue(1);
2877   if (!HiExists &&
2878       (!LegalOperations ||
2879        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2880     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2881     return CombineTo(N, Res, Res);
2882   }
2883
2884   // If the low half is not needed, just compute the high half.
2885   bool LoExists = N->hasAnyUseOfValue(0);
2886   if (!LoExists &&
2887       (!LegalOperations ||
2888        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2889     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2890     return CombineTo(N, Res, Res);
2891   }
2892
2893   // If both halves are used, return as it is.
2894   if (LoExists && HiExists)
2895     return SDValue();
2896
2897   // If the two computed results can be simplified separately, separate them.
2898   if (LoExists) {
2899     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2900     AddToWorklist(Lo.getNode());
2901     SDValue LoOpt = combine(Lo.getNode());
2902     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2903         (!LegalOperations ||
2904          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2905       return CombineTo(N, LoOpt, LoOpt);
2906   }
2907
2908   if (HiExists) {
2909     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2910     AddToWorklist(Hi.getNode());
2911     SDValue HiOpt = combine(Hi.getNode());
2912     if (HiOpt.getNode() && HiOpt != Hi &&
2913         (!LegalOperations ||
2914          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2915       return CombineTo(N, HiOpt, HiOpt);
2916   }
2917
2918   return SDValue();
2919 }
2920
2921 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2922   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2923     return Res;
2924
2925   EVT VT = N->getValueType(0);
2926   SDLoc DL(N);
2927
2928   // If the type is twice as wide is legal, transform the mulhu to a wider
2929   // multiply plus a shift.
2930   if (VT.isSimple() && !VT.isVector()) {
2931     MVT Simple = VT.getSimpleVT();
2932     unsigned SimpleSize = Simple.getSizeInBits();
2933     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2934     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2935       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2936       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2937       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2938       // Compute the high part as N1.
2939       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2940             DAG.getConstant(SimpleSize, DL,
2941                             getShiftAmountTy(Lo.getValueType())));
2942       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2943       // Compute the low part as N0.
2944       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2945       return CombineTo(N, Lo, Hi);
2946     }
2947   }
2948
2949   return SDValue();
2950 }
2951
2952 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2953   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2954     return Res;
2955
2956   EVT VT = N->getValueType(0);
2957   SDLoc DL(N);
2958
2959   // If the type is twice as wide is legal, transform the mulhu to a wider
2960   // multiply plus a shift.
2961   if (VT.isSimple() && !VT.isVector()) {
2962     MVT Simple = VT.getSimpleVT();
2963     unsigned SimpleSize = Simple.getSizeInBits();
2964     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2965     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2966       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2967       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2968       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2969       // Compute the high part as N1.
2970       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2971             DAG.getConstant(SimpleSize, DL,
2972                             getShiftAmountTy(Lo.getValueType())));
2973       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2974       // Compute the low part as N0.
2975       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2976       return CombineTo(N, Lo, Hi);
2977     }
2978   }
2979
2980   return SDValue();
2981 }
2982
2983 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2984   // (smulo x, 2) -> (saddo x, x)
2985   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2986     if (C2->getAPIntValue() == 2)
2987       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2988                          N->getOperand(0), N->getOperand(0));
2989
2990   return SDValue();
2991 }
2992
2993 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2994   // (umulo x, 2) -> (uaddo x, x)
2995   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2996     if (C2->getAPIntValue() == 2)
2997       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2998                          N->getOperand(0), N->getOperand(0));
2999
3000   return SDValue();
3001 }
3002
3003 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3004   SDValue N0 = N->getOperand(0);
3005   SDValue N1 = N->getOperand(1);
3006   EVT VT = N0.getValueType();
3007
3008   // fold vector ops
3009   if (VT.isVector())
3010     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3011       return FoldedVOp;
3012
3013   // fold (add c1, c2) -> c1+c2
3014   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3015   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3016   if (N0C && N1C)
3017     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3018
3019   // canonicalize constant to RHS
3020   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3021      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3022     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3023
3024   return SDValue();
3025 }
3026
3027 /// If this is a binary operator with two operands of the same opcode, try to
3028 /// simplify it.
3029 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3030   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3031   EVT VT = N0.getValueType();
3032   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3033
3034   // Bail early if none of these transforms apply.
3035   if (N0.getNumOperands() == 0) return SDValue();
3036
3037   // For each of OP in AND/OR/XOR:
3038   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3039   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3040   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3041   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3042   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3043   //
3044   // do not sink logical op inside of a vector extend, since it may combine
3045   // into a vsetcc.
3046   EVT Op0VT = N0.getOperand(0).getValueType();
3047   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3048        N0.getOpcode() == ISD::SIGN_EXTEND ||
3049        N0.getOpcode() == ISD::BSWAP ||
3050        // Avoid infinite looping with PromoteIntBinOp.
3051        (N0.getOpcode() == ISD::ANY_EXTEND &&
3052         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3053        (N0.getOpcode() == ISD::TRUNCATE &&
3054         (!TLI.isZExtFree(VT, Op0VT) ||
3055          !TLI.isTruncateFree(Op0VT, VT)) &&
3056         TLI.isTypeLegal(Op0VT))) &&
3057       !VT.isVector() &&
3058       Op0VT == N1.getOperand(0).getValueType() &&
3059       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3060     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3061                                  N0.getOperand(0).getValueType(),
3062                                  N0.getOperand(0), N1.getOperand(0));
3063     AddToWorklist(ORNode.getNode());
3064     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3065   }
3066
3067   // For each of OP in SHL/SRL/SRA/AND...
3068   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3069   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3070   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3071   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3072        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3073       N0.getOperand(1) == N1.getOperand(1)) {
3074     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3075                                  N0.getOperand(0).getValueType(),
3076                                  N0.getOperand(0), N1.getOperand(0));
3077     AddToWorklist(ORNode.getNode());
3078     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3079                        ORNode, N0.getOperand(1));
3080   }
3081
3082   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3083   // Only perform this optimization up until type legalization, before
3084   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3085   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3086   // we don't want to undo this promotion.
3087   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3088   // on scalars.
3089   if ((N0.getOpcode() == ISD::BITCAST ||
3090        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3091        Level <= AfterLegalizeTypes) {
3092     SDValue In0 = N0.getOperand(0);
3093     SDValue In1 = N1.getOperand(0);
3094     EVT In0Ty = In0.getValueType();
3095     EVT In1Ty = In1.getValueType();
3096     SDLoc DL(N);
3097     // If both incoming values are integers, and the original types are the
3098     // same.
3099     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3100       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3101       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3102       AddToWorklist(Op.getNode());
3103       return BC;
3104     }
3105   }
3106
3107   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3108   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3109   // If both shuffles use the same mask, and both shuffle within a single
3110   // vector, then it is worthwhile to move the swizzle after the operation.
3111   // The type-legalizer generates this pattern when loading illegal
3112   // vector types from memory. In many cases this allows additional shuffle
3113   // optimizations.
3114   // There are other cases where moving the shuffle after the xor/and/or
3115   // is profitable even if shuffles don't perform a swizzle.
3116   // If both shuffles use the same mask, and both shuffles have the same first
3117   // or second operand, then it might still be profitable to move the shuffle
3118   // after the xor/and/or operation.
3119   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3120     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3121     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3122
3123     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3124            "Inputs to shuffles are not the same type");
3125
3126     // Check that both shuffles use the same mask. The masks are known to be of
3127     // the same length because the result vector type is the same.
3128     // Check also that shuffles have only one use to avoid introducing extra
3129     // instructions.
3130     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3131         SVN0->getMask().equals(SVN1->getMask())) {
3132       SDValue ShOp = N0->getOperand(1);
3133
3134       // Don't try to fold this node if it requires introducing a
3135       // build vector of all zeros that might be illegal at this stage.
3136       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3137         if (!LegalTypes)
3138           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3139         else
3140           ShOp = SDValue();
3141       }
3142
3143       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3144       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3145       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3146       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3147         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3148                                       N0->getOperand(0), N1->getOperand(0));
3149         AddToWorklist(NewNode.getNode());
3150         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3151                                     SVN0->getMask());
3152       }
3153
3154       // Don't try to fold this node if it requires introducing a
3155       // build vector of all zeros that might be illegal at this stage.
3156       ShOp = N0->getOperand(0);
3157       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3158         if (!LegalTypes)
3159           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3160         else
3161           ShOp = SDValue();
3162       }
3163
3164       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3165       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3166       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3167       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3168         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3169                                       N0->getOperand(1), N1->getOperand(1));
3170         AddToWorklist(NewNode.getNode());
3171         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3172                                     SVN0->getMask());
3173       }
3174     }
3175   }
3176
3177   return SDValue();
3178 }
3179
3180 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3181 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3182                                        const SDLoc &DL) {
3183   SDValue LL, LR, RL, RR, N0CC, N1CC;
3184   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3185       !isSetCCEquivalent(N1, RL, RR, N1CC))
3186     return SDValue();
3187
3188   assert(N0.getValueType() == N1.getValueType() &&
3189          "Unexpected operand types for bitwise logic op");
3190   assert(LL.getValueType() == LR.getValueType() &&
3191          RL.getValueType() == RR.getValueType() &&
3192          "Unexpected operand types for setcc");
3193
3194   // If we're here post-legalization or the logic op type is not i1, the logic
3195   // op type must match a setcc result type. Also, all folds require new
3196   // operations on the left and right operands, so those types must match.
3197   EVT VT = N0.getValueType();
3198   EVT OpVT = LL.getValueType();
3199   if (LegalOperations || VT != MVT::i1)
3200     if (VT != getSetCCResultType(OpVT))
3201       return SDValue();
3202   if (OpVT != RL.getValueType())
3203     return SDValue();
3204
3205   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3206   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3207   bool IsInteger = OpVT.isInteger();
3208   if (LR == RR && CC0 == CC1 && IsInteger) {
3209     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3210     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3211
3212     // All bits clear?
3213     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3214     // All sign bits clear?
3215     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3216     // Any bits set?
3217     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3218     // Any sign bits set?
3219     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3220
3221     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3222     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3223     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3224     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3225     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3226       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3227       AddToWorklist(Or.getNode());
3228       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3229     }
3230
3231     // All bits set?
3232     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3233     // All sign bits set?
3234     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3235     // Any bits clear?
3236     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3237     // Any sign bits clear?
3238     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3239
3240     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3241     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3242     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3243     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3244     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3245       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3246       AddToWorklist(And.getNode());
3247       return DAG.getSetCC(DL, VT, And, LR, CC1);
3248     }
3249   }
3250
3251   // TODO: What is the 'or' equivalent of this fold?
3252   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3253   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3254       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3255        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3256     SDValue One = DAG.getConstant(1, DL, OpVT);
3257     SDValue Two = DAG.getConstant(2, DL, OpVT);
3258     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3259     AddToWorklist(Add.getNode());
3260     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3261   }
3262
3263   // Try more general transforms if the predicates match and the only user of
3264   // the compares is the 'and' or 'or'.
3265   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3266       N0.hasOneUse() && N1.hasOneUse()) {
3267     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3268     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3269     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3270       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3271       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3272       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3273       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3274       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3275     }
3276   }
3277
3278   // Canonicalize equivalent operands to LL == RL.
3279   if (LL == RR && LR == RL) {
3280     CC1 = ISD::getSetCCSwappedOperands(CC1);
3281     std::swap(RL, RR);
3282   }
3283
3284   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3285   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3286   if (LL == RL && LR == RR) {
3287     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3288                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3289     if (NewCC != ISD::SETCC_INVALID &&
3290         (!LegalOperations ||
3291          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3292           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3293       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3294   }
3295
3296   return SDValue();
3297 }
3298
3299 /// This contains all DAGCombine rules which reduce two values combined by
3300 /// an And operation to a single value. This makes them reusable in the context
3301 /// of visitSELECT(). Rules involving constants are not included as
3302 /// visitSELECT() already handles those cases.
3303 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3304   EVT VT = N1.getValueType();
3305   SDLoc DL(N);
3306
3307   // fold (and x, undef) -> 0
3308   if (N0.isUndef() || N1.isUndef())
3309     return DAG.getConstant(0, DL, VT);
3310
3311   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3312     return V;
3313
3314   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3315       VT.getSizeInBits() <= 64) {
3316     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3317       APInt ADDC = ADDI->getAPIntValue();
3318       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3319         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3320         // immediate for an add, but it is legal if its top c2 bits are set,
3321         // transform the ADD so the immediate doesn't need to be materialized
3322         // in a register.
3323         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3324           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3325                                              SRLI->getZExtValue());
3326           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3327             ADDC |= Mask;
3328             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3329               SDLoc DL0(N0);
3330               SDValue NewAdd =
3331                 DAG.getNode(ISD::ADD, DL0, VT,
3332                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3333               CombineTo(N0.getNode(), NewAdd);
3334               // Return N so it doesn't get rechecked!
3335               return SDValue(N, 0);
3336             }
3337           }
3338         }
3339       }
3340     }
3341   }
3342
3343   // Reduce bit extract of low half of an integer to the narrower type.
3344   // (and (srl i64:x, K), KMask) ->
3345   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3346   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3347     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3348       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3349         unsigned Size = VT.getSizeInBits();
3350         const APInt &AndMask = CAnd->getAPIntValue();
3351         unsigned ShiftBits = CShift->getZExtValue();
3352
3353         // Bail out, this node will probably disappear anyway.
3354         if (ShiftBits == 0)
3355           return SDValue();
3356
3357         unsigned MaskBits = AndMask.countTrailingOnes();
3358         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3359
3360         if (AndMask.isMask() &&
3361             // Required bits must not span the two halves of the integer and
3362             // must fit in the half size type.
3363             (ShiftBits + MaskBits <= Size / 2) &&
3364             TLI.isNarrowingProfitable(VT, HalfVT) &&
3365             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3366             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3367             TLI.isTruncateFree(VT, HalfVT) &&
3368             TLI.isZExtFree(HalfVT, VT)) {
3369           // The isNarrowingProfitable is to avoid regressions on PPC and
3370           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3371           // on downstream users of this. Those patterns could probably be
3372           // extended to handle extensions mixed in.
3373
3374           SDValue SL(N0);
3375           assert(MaskBits <= Size);
3376
3377           // Extracting the highest bit of the low half.
3378           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3379           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3380                                       N0.getOperand(0));
3381
3382           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3383           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3384           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3385           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3386           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3387         }
3388       }
3389     }
3390   }
3391
3392   return SDValue();
3393 }
3394
3395 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3396                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3397                                    bool &NarrowLoad) {
3398   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3399
3400   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3401     return false;
3402
3403   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3404   LoadedVT = LoadN->getMemoryVT();
3405
3406   if (ExtVT == LoadedVT &&
3407       (!LegalOperations ||
3408        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3409     // ZEXTLOAD will match without needing to change the size of the value being
3410     // loaded.
3411     NarrowLoad = false;
3412     return true;
3413   }
3414
3415   // Do not change the width of a volatile load.
3416   if (LoadN->isVolatile())
3417     return false;
3418
3419   // Do not generate loads of non-round integer types since these can
3420   // be expensive (and would be wrong if the type is not byte sized).
3421   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3422     return false;
3423
3424   if (LegalOperations &&
3425       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3426     return false;
3427
3428   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3429     return false;
3430
3431   NarrowLoad = true;
3432   return true;
3433 }
3434
3435 SDValue DAGCombiner::visitAND(SDNode *N) {
3436   SDValue N0 = N->getOperand(0);
3437   SDValue N1 = N->getOperand(1);
3438   EVT VT = N1.getValueType();
3439
3440   // x & x --> x
3441   if (N0 == N1)
3442     return N0;
3443
3444   // fold vector ops
3445   if (VT.isVector()) {
3446     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3447       return FoldedVOp;
3448
3449     // fold (and x, 0) -> 0, vector edition
3450     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3451       // do not return N0, because undef node may exist in N0
3452       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3453                              SDLoc(N), N0.getValueType());
3454     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3455       // do not return N1, because undef node may exist in N1
3456       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3457                              SDLoc(N), N1.getValueType());
3458
3459     // fold (and x, -1) -> x, vector edition
3460     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3461       return N1;
3462     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3463       return N0;
3464   }
3465
3466   // fold (and c1, c2) -> c1&c2
3467   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3468   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3469   if (N0C && N1C && !N1C->isOpaque())
3470     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3471   // canonicalize constant to RHS
3472   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3473      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3474     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3475   // fold (and x, -1) -> x
3476   if (isAllOnesConstant(N1))
3477     return N0;
3478   // if (and x, c) is known to be zero, return 0
3479   unsigned BitWidth = VT.getScalarSizeInBits();
3480   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3481                                    APInt::getAllOnesValue(BitWidth)))
3482     return DAG.getConstant(0, SDLoc(N), VT);
3483
3484   if (SDValue NewSel = foldBinOpIntoSelect(N))
3485     return NewSel;
3486
3487   // reassociate and
3488   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3489     return RAND;
3490   // fold (and (or x, C), D) -> D if (C & D) == D
3491   if (N1C && N0.getOpcode() == ISD::OR)
3492     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3493       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3494         return N1;
3495   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3496   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3497     SDValue N0Op0 = N0.getOperand(0);
3498     APInt Mask = ~N1C->getAPIntValue();
3499     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3500     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3501       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3502                                  N0.getValueType(), N0Op0);
3503
3504       // Replace uses of the AND with uses of the Zero extend node.
3505       CombineTo(N, Zext);
3506
3507       // We actually want to replace all uses of the any_extend with the
3508       // zero_extend, to avoid duplicating things.  This will later cause this
3509       // AND to be folded.
3510       CombineTo(N0.getNode(), Zext);
3511       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3512     }
3513   }
3514   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3515   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3516   // already be zero by virtue of the width of the base type of the load.
3517   //
3518   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3519   // more cases.
3520   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3521        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3522        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3523        N0.getOperand(0).getResNo() == 0) ||
3524       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3525     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3526                                          N0 : N0.getOperand(0) );
3527
3528     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3529     // This can be a pure constant or a vector splat, in which case we treat the
3530     // vector as a scalar and use the splat value.
3531     APInt Constant = APInt::getNullValue(1);
3532     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3533       Constant = C->getAPIntValue();
3534     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3535       APInt SplatValue, SplatUndef;
3536       unsigned SplatBitSize;
3537       bool HasAnyUndefs;
3538       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3539                                              SplatBitSize, HasAnyUndefs);
3540       if (IsSplat) {
3541         // Undef bits can contribute to a possible optimisation if set, so
3542         // set them.
3543         SplatValue |= SplatUndef;
3544
3545         // The splat value may be something like "0x00FFFFFF", which means 0 for
3546         // the first vector value and FF for the rest, repeating. We need a mask
3547         // that will apply equally to all members of the vector, so AND all the
3548         // lanes of the constant together.
3549         EVT VT = Vector->getValueType(0);
3550         unsigned BitWidth = VT.getScalarSizeInBits();
3551
3552         // If the splat value has been compressed to a bitlength lower
3553         // than the size of the vector lane, we need to re-expand it to
3554         // the lane size.
3555         if (BitWidth > SplatBitSize)
3556           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3557                SplatBitSize < BitWidth;
3558                SplatBitSize = SplatBitSize * 2)
3559             SplatValue |= SplatValue.shl(SplatBitSize);
3560
3561         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3562         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3563         if (SplatBitSize % BitWidth == 0) {
3564           Constant = APInt::getAllOnesValue(BitWidth);
3565           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3566             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3567         }
3568       }
3569     }
3570
3571     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3572     // actually legal and isn't going to get expanded, else this is a false
3573     // optimisation.
3574     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3575                                                     Load->getValueType(0),
3576                                                     Load->getMemoryVT());
3577
3578     // Resize the constant to the same size as the original memory access before
3579     // extension. If it is still the AllOnesValue then this AND is completely
3580     // unneeded.
3581     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3582
3583     bool B;
3584     switch (Load->getExtensionType()) {
3585     default: B = false; break;
3586     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3587     case ISD::ZEXTLOAD:
3588     case ISD::NON_EXTLOAD: B = true; break;
3589     }
3590
3591     if (B && Constant.isAllOnesValue()) {
3592       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3593       // preserve semantics once we get rid of the AND.
3594       SDValue NewLoad(Load, 0);
3595
3596       // Fold the AND away. NewLoad may get replaced immediately.
3597       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3598
3599       if (Load->getExtensionType() == ISD::EXTLOAD) {
3600         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3601                               Load->getValueType(0), SDLoc(Load),
3602                               Load->getChain(), Load->getBasePtr(),
3603                               Load->getOffset(), Load->getMemoryVT(),
3604                               Load->getMemOperand());
3605         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3606         if (Load->getNumValues() == 3) {
3607           // PRE/POST_INC loads have 3 values.
3608           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3609                            NewLoad.getValue(2) };
3610           CombineTo(Load, To, 3, true);
3611         } else {
3612           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3613         }
3614       }
3615
3616       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3617     }
3618   }
3619
3620   // fold (and (load x), 255) -> (zextload x, i8)
3621   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3622   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3623   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3624                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3625                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3626     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3627     LoadSDNode *LN0 = HasAnyExt
3628       ? cast<LoadSDNode>(N0.getOperand(0))
3629       : cast<LoadSDNode>(N0);
3630     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3631         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3632       auto NarrowLoad = false;
3633       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3634       EVT ExtVT, LoadedVT;
3635       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3636                            NarrowLoad)) {
3637         if (!NarrowLoad) {
3638           SDValue NewLoad =
3639             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3640                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3641                            LN0->getMemOperand());
3642           AddToWorklist(N);
3643           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3644           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3645         } else {
3646           EVT PtrType = LN0->getOperand(1).getValueType();
3647
3648           unsigned Alignment = LN0->getAlignment();
3649           SDValue NewPtr = LN0->getBasePtr();
3650
3651           // For big endian targets, we need to add an offset to the pointer
3652           // to load the correct bytes.  For little endian systems, we merely
3653           // need to read fewer bytes from the same pointer.
3654           if (DAG.getDataLayout().isBigEndian()) {
3655             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3656             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3657             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3658             SDLoc DL(LN0);
3659             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3660                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3661             Alignment = MinAlign(Alignment, PtrOff);
3662           }
3663
3664           AddToWorklist(NewPtr.getNode());
3665
3666           SDValue Load = DAG.getExtLoad(
3667               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3668               LN0->getPointerInfo(), ExtVT, Alignment,
3669               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3670           AddToWorklist(N);
3671           CombineTo(LN0, Load, Load.getValue(1));
3672           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3673         }
3674       }
3675     }
3676   }
3677
3678   if (SDValue Combined = visitANDLike(N0, N1, N))
3679     return Combined;
3680
3681   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3682   if (N0.getOpcode() == N1.getOpcode())
3683     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3684       return Tmp;
3685
3686   // Masking the negated extension of a boolean is just the zero-extended
3687   // boolean:
3688   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3689   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3690   //
3691   // Note: the SimplifyDemandedBits fold below can make an information-losing
3692   // transform, and then we have no way to find this better fold.
3693   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3694     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3695     SDValue SubRHS = N0.getOperand(1);
3696     if (SubLHS && SubLHS->isNullValue()) {
3697       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3698           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3699         return SubRHS;
3700       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3701           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3702         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3703     }
3704   }
3705
3706   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3707   // fold (and (sra)) -> (and (srl)) when possible.
3708   if (SimplifyDemandedBits(SDValue(N, 0)))
3709     return SDValue(N, 0);
3710
3711   // fold (zext_inreg (extload x)) -> (zextload x)
3712   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3713     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3714     EVT MemVT = LN0->getMemoryVT();
3715     // If we zero all the possible extended bits, then we can turn this into
3716     // a zextload if we are running before legalize or the operation is legal.
3717     unsigned BitWidth = N1.getScalarValueSizeInBits();
3718     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3719                            BitWidth - MemVT.getScalarSizeInBits())) &&
3720         ((!LegalOperations && !LN0->isVolatile()) ||
3721          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3722       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3723                                        LN0->getChain(), LN0->getBasePtr(),
3724                                        MemVT, LN0->getMemOperand());
3725       AddToWorklist(N);
3726       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3727       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3728     }
3729   }
3730   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3731   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3732       N0.hasOneUse()) {
3733     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3734     EVT MemVT = LN0->getMemoryVT();
3735     // If we zero all the possible extended bits, then we can turn this into
3736     // a zextload if we are running before legalize or the operation is legal.
3737     unsigned BitWidth = N1.getScalarValueSizeInBits();
3738     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3739                            BitWidth - MemVT.getScalarSizeInBits())) &&
3740         ((!LegalOperations && !LN0->isVolatile()) ||
3741          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3742       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3743                                        LN0->getChain(), LN0->getBasePtr(),
3744                                        MemVT, LN0->getMemOperand());
3745       AddToWorklist(N);
3746       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3747       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3748     }
3749   }
3750   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3751   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3752     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3753                                            N0.getOperand(1), false))
3754       return BSwap;
3755   }
3756
3757   return SDValue();
3758 }
3759
3760 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3761 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3762                                         bool DemandHighBits) {
3763   if (!LegalOperations)
3764     return SDValue();
3765
3766   EVT VT = N->getValueType(0);
3767   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3768     return SDValue();
3769   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3770     return SDValue();
3771
3772   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3773   bool LookPassAnd0 = false;
3774   bool LookPassAnd1 = false;
3775   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3776       std::swap(N0, N1);
3777   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3778       std::swap(N0, N1);
3779   if (N0.getOpcode() == ISD::AND) {
3780     if (!N0.getNode()->hasOneUse())
3781       return SDValue();
3782     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3783     if (!N01C || N01C->getZExtValue() != 0xFF00)
3784       return SDValue();
3785     N0 = N0.getOperand(0);
3786     LookPassAnd0 = true;
3787   }
3788
3789   if (N1.getOpcode() == ISD::AND) {
3790     if (!N1.getNode()->hasOneUse())
3791       return SDValue();
3792     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3793     if (!N11C || N11C->getZExtValue() != 0xFF)
3794       return SDValue();
3795     N1 = N1.getOperand(0);
3796     LookPassAnd1 = true;
3797   }
3798
3799   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3800     std::swap(N0, N1);
3801   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3802     return SDValue();
3803   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3804     return SDValue();
3805
3806   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3807   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3808   if (!N01C || !N11C)
3809     return SDValue();
3810   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3811     return SDValue();
3812
3813   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3814   SDValue N00 = N0->getOperand(0);
3815   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3816     if (!N00.getNode()->hasOneUse())
3817       return SDValue();
3818     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3819     if (!N001C || N001C->getZExtValue() != 0xFF)
3820       return SDValue();
3821     N00 = N00.getOperand(0);
3822     LookPassAnd0 = true;
3823   }
3824
3825   SDValue N10 = N1->getOperand(0);
3826   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3827     if (!N10.getNode()->hasOneUse())
3828       return SDValue();
3829     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3830     if (!N101C || N101C->getZExtValue() != 0xFF00)
3831       return SDValue();
3832     N10 = N10.getOperand(0);
3833     LookPassAnd1 = true;
3834   }
3835
3836   if (N00 != N10)
3837     return SDValue();
3838
3839   // Make sure everything beyond the low halfword gets set to zero since the SRL
3840   // 16 will clear the top bits.
3841   unsigned OpSizeInBits = VT.getSizeInBits();
3842   if (DemandHighBits && OpSizeInBits > 16) {
3843     // If the left-shift isn't masked out then the only way this is a bswap is
3844     // if all bits beyond the low 8 are 0. In that case the entire pattern
3845     // reduces to a left shift anyway: leave it for other parts of the combiner.
3846     if (!LookPassAnd0)
3847       return SDValue();
3848
3849     // However, if the right shift isn't masked out then it might be because
3850     // it's not needed. See if we can spot that too.
3851     if (!LookPassAnd1 &&
3852         !DAG.MaskedValueIsZero(
3853             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3854       return SDValue();
3855   }
3856
3857   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3858   if (OpSizeInBits > 16) {
3859     SDLoc DL(N);
3860     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3861                       DAG.getConstant(OpSizeInBits - 16, DL,
3862                                       getShiftAmountTy(VT)));
3863   }
3864   return Res;
3865 }
3866
3867 /// Return true if the specified node is an element that makes up a 32-bit
3868 /// packed halfword byteswap.
3869 /// ((x & 0x000000ff) << 8) |
3870 /// ((x & 0x0000ff00) >> 8) |
3871 /// ((x & 0x00ff0000) << 8) |
3872 /// ((x & 0xff000000) >> 8)
3873 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3874   if (!N.getNode()->hasOneUse())
3875     return false;
3876
3877   unsigned Opc = N.getOpcode();
3878   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3879     return false;
3880
3881   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3882   if (!N1C)
3883     return false;
3884
3885   unsigned Num;
3886   switch (N1C->getZExtValue()) {
3887   default:
3888     return false;
3889   case 0xFF:       Num = 0; break;
3890   case 0xFF00:     Num = 1; break;
3891   case 0xFF0000:   Num = 2; break;
3892   case 0xFF000000: Num = 3; break;
3893   }
3894
3895   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3896   SDValue N0 = N.getOperand(0);
3897   if (Opc == ISD::AND) {
3898     if (Num == 0 || Num == 2) {
3899       // (x >> 8) & 0xff
3900       // (x >> 8) & 0xff0000
3901       if (N0.getOpcode() != ISD::SRL)
3902         return false;
3903       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3904       if (!C || C->getZExtValue() != 8)
3905         return false;
3906     } else {
3907       // (x << 8) & 0xff00
3908       // (x << 8) & 0xff000000
3909       if (N0.getOpcode() != ISD::SHL)
3910         return false;
3911       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3912       if (!C || C->getZExtValue() != 8)
3913         return false;
3914     }
3915   } else if (Opc == ISD::SHL) {
3916     // (x & 0xff) << 8
3917     // (x & 0xff0000) << 8
3918     if (Num != 0 && Num != 2)
3919       return false;
3920     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3921     if (!C || C->getZExtValue() != 8)
3922       return false;
3923   } else { // Opc == ISD::SRL
3924     // (x & 0xff00) >> 8
3925     // (x & 0xff000000) >> 8
3926     if (Num != 1 && Num != 3)
3927       return false;
3928     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3929     if (!C || C->getZExtValue() != 8)
3930       return false;
3931   }
3932
3933   if (Parts[Num])
3934     return false;
3935
3936   Parts[Num] = N0.getOperand(0).getNode();
3937   return true;
3938 }
3939
3940 /// Match a 32-bit packed halfword bswap. That is
3941 /// ((x & 0x000000ff) << 8) |
3942 /// ((x & 0x0000ff00) >> 8) |
3943 /// ((x & 0x00ff0000) << 8) |
3944 /// ((x & 0xff000000) >> 8)
3945 /// => (rotl (bswap x), 16)
3946 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3947   if (!LegalOperations)
3948     return SDValue();
3949
3950   EVT VT = N->getValueType(0);
3951   if (VT != MVT::i32)
3952     return SDValue();
3953   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3954     return SDValue();
3955
3956   // Look for either
3957   // (or (or (and), (and)), (or (and), (and)))
3958   // (or (or (or (and), (and)), (and)), (and))
3959   if (N0.getOpcode() != ISD::OR)
3960     return SDValue();
3961   SDValue N00 = N0.getOperand(0);
3962   SDValue N01 = N0.getOperand(1);
3963   SDNode *Parts[4] = {};
3964
3965   if (N1.getOpcode() == ISD::OR &&
3966       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3967     // (or (or (and), (and)), (or (and), (and)))
3968     SDValue N000 = N00.getOperand(0);
3969     if (!isBSwapHWordElement(N000, Parts))
3970       return SDValue();
3971
3972     SDValue N001 = N00.getOperand(1);
3973     if (!isBSwapHWordElement(N001, Parts))
3974       return SDValue();
3975     SDValue N010 = N01.getOperand(0);
3976     if (!isBSwapHWordElement(N010, Parts))
3977       return SDValue();
3978     SDValue N011 = N01.getOperand(1);
3979     if (!isBSwapHWordElement(N011, Parts))
3980       return SDValue();
3981   } else {
3982     // (or (or (or (and), (and)), (and)), (and))
3983     if (!isBSwapHWordElement(N1, Parts))
3984       return SDValue();
3985     if (!isBSwapHWordElement(N01, Parts))
3986       return SDValue();
3987     if (N00.getOpcode() != ISD::OR)
3988       return SDValue();
3989     SDValue N000 = N00.getOperand(0);
3990     if (!isBSwapHWordElement(N000, Parts))
3991       return SDValue();
3992     SDValue N001 = N00.getOperand(1);
3993     if (!isBSwapHWordElement(N001, Parts))
3994       return SDValue();
3995   }
3996
3997   // Make sure the parts are all coming from the same node.
3998   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3999     return SDValue();
4000
4001   SDLoc DL(N);
4002   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4003                               SDValue(Parts[0], 0));
4004
4005   // Result of the bswap should be rotated by 16. If it's not legal, then
4006   // do  (x << 16) | (x >> 16).
4007   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4008   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4009     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4010   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4011     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4012   return DAG.getNode(ISD::OR, DL, VT,
4013                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4014                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4015 }
4016
4017 /// This contains all DAGCombine rules which reduce two values combined by
4018 /// an Or operation to a single value \see visitANDLike().
4019 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4020   EVT VT = N1.getValueType();
4021   SDLoc DL(N);
4022
4023   // fold (or x, undef) -> -1
4024   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4025     return DAG.getAllOnesConstant(DL, VT);
4026
4027   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4028     return V;
4029
4030   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4031   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4032       // Don't increase # computations.
4033       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4034     // We can only do this xform if we know that bits from X that are set in C2
4035     // but not in C1 are already zero.  Likewise for Y.
4036     if (const ConstantSDNode *N0O1C =
4037         getAsNonOpaqueConstant(N0.getOperand(1))) {
4038       if (const ConstantSDNode *N1O1C =
4039           getAsNonOpaqueConstant(N1.getOperand(1))) {
4040         // We can only do this xform if we know that bits from X that are set in
4041         // C2 but not in C1 are already zero.  Likewise for Y.
4042         const APInt &LHSMask = N0O1C->getAPIntValue();
4043         const APInt &RHSMask = N1O1C->getAPIntValue();
4044
4045         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4046             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4047           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4048                                   N0.getOperand(0), N1.getOperand(0));
4049           return DAG.getNode(ISD::AND, DL, VT, X,
4050                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4051         }
4052       }
4053     }
4054   }
4055
4056   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4057   if (N0.getOpcode() == ISD::AND &&
4058       N1.getOpcode() == ISD::AND &&
4059       N0.getOperand(0) == N1.getOperand(0) &&
4060       // Don't increase # computations.
4061       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4062     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4063                             N0.getOperand(1), N1.getOperand(1));
4064     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4065   }
4066
4067   return SDValue();
4068 }
4069
4070 SDValue DAGCombiner::visitOR(SDNode *N) {
4071   SDValue N0 = N->getOperand(0);
4072   SDValue N1 = N->getOperand(1);
4073   EVT VT = N1.getValueType();
4074
4075   // x | x --> x
4076   if (N0 == N1)
4077     return N0;
4078
4079   // fold vector ops
4080   if (VT.isVector()) {
4081     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4082       return FoldedVOp;
4083
4084     // fold (or x, 0) -> x, vector edition
4085     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4086       return N1;
4087     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4088       return N0;
4089
4090     // fold (or x, -1) -> -1, vector edition
4091     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4092       // do not return N0, because undef node may exist in N0
4093       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4094     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4095       // do not return N1, because undef node may exist in N1
4096       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4097
4098     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4099     // Do this only if the resulting shuffle is legal.
4100     if (isa<ShuffleVectorSDNode>(N0) &&
4101         isa<ShuffleVectorSDNode>(N1) &&
4102         // Avoid folding a node with illegal type.
4103         TLI.isTypeLegal(VT)) {
4104       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4105       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4106       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4107       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4108       // Ensure both shuffles have a zero input.
4109       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4110         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4111         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4112         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4113         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4114         bool CanFold = true;
4115         int NumElts = VT.getVectorNumElements();
4116         SmallVector<int, 4> Mask(NumElts);
4117
4118         for (int i = 0; i != NumElts; ++i) {
4119           int M0 = SV0->getMaskElt(i);
4120           int M1 = SV1->getMaskElt(i);
4121
4122           // Determine if either index is pointing to a zero vector.
4123           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4124           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4125
4126           // If one element is zero and the otherside is undef, keep undef.
4127           // This also handles the case that both are undef.
4128           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4129             Mask[i] = -1;
4130             continue;
4131           }
4132
4133           // Make sure only one of the elements is zero.
4134           if (M0Zero == M1Zero) {
4135             CanFold = false;
4136             break;
4137           }
4138
4139           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4140
4141           // We have a zero and non-zero element. If the non-zero came from
4142           // SV0 make the index a LHS index. If it came from SV1, make it
4143           // a RHS index. We need to mod by NumElts because we don't care
4144           // which operand it came from in the original shuffles.
4145           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4146         }
4147
4148         if (CanFold) {
4149           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4150           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4151
4152           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4153           if (!LegalMask) {
4154             std::swap(NewLHS, NewRHS);
4155             ShuffleVectorSDNode::commuteMask(Mask);
4156             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4157           }
4158
4159           if (LegalMask)
4160             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4161         }
4162       }
4163     }
4164   }
4165
4166   // fold (or c1, c2) -> c1|c2
4167   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4168   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4169   if (N0C && N1C && !N1C->isOpaque())
4170     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4171   // canonicalize constant to RHS
4172   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4173      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4174     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4175   // fold (or x, 0) -> x
4176   if (isNullConstant(N1))
4177     return N0;
4178   // fold (or x, -1) -> -1
4179   if (isAllOnesConstant(N1))
4180     return N1;
4181
4182   if (SDValue NewSel = foldBinOpIntoSelect(N))
4183     return NewSel;
4184
4185   // fold (or x, c) -> c iff (x & ~c) == 0
4186   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4187     return N1;
4188
4189   if (SDValue Combined = visitORLike(N0, N1, N))
4190     return Combined;
4191
4192   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4193   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4194     return BSwap;
4195   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4196     return BSwap;
4197
4198   // reassociate or
4199   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4200     return ROR;
4201   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4202   // iff (c1 & c2) != 0.
4203   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4204              isa<ConstantSDNode>(N0.getOperand(1))) {
4205     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
4206     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
4207       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
4208                                                    N1C, C1))
4209         return DAG.getNode(
4210             ISD::AND, SDLoc(N), VT,
4211             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4212       return SDValue();
4213     }
4214   }
4215   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4216   if (N0.getOpcode() == N1.getOpcode())
4217     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4218       return Tmp;
4219
4220   // See if this is some rotate idiom.
4221   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4222     return SDValue(Rot, 0);
4223
4224   if (SDValue Load = MatchLoadCombine(N))
4225     return Load;
4226
4227   // Simplify the operands using demanded-bits information.
4228   if (SimplifyDemandedBits(SDValue(N, 0)))
4229     return SDValue(N, 0);
4230
4231   return SDValue();
4232 }
4233
4234 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4235 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4236   if (Op.getOpcode() == ISD::AND) {
4237     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4238       Mask = Op.getOperand(1);
4239       Op = Op.getOperand(0);
4240     } else {
4241       return false;
4242     }
4243   }
4244
4245   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4246     Shift = Op;
4247     return true;
4248   }
4249
4250   return false;
4251 }
4252
4253 // Return true if we can prove that, whenever Neg and Pos are both in the
4254 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4255 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4256 //
4257 //     (or (shift1 X, Neg), (shift2 X, Pos))
4258 //
4259 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4260 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4261 // to consider shift amounts with defined behavior.
4262 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4263   // If EltSize is a power of 2 then:
4264   //
4265   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4266   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4267   //
4268   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4269   // for the stronger condition:
4270   //
4271   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4272   //
4273   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4274   // we can just replace Neg with Neg' for the rest of the function.
4275   //
4276   // In other cases we check for the even stronger condition:
4277   //
4278   //     Neg == EltSize - Pos                                    [B]
4279   //
4280   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4281   // behavior if Pos == 0 (and consequently Neg == EltSize).
4282   //
4283   // We could actually use [A] whenever EltSize is a power of 2, but the
4284   // only extra cases that it would match are those uninteresting ones
4285   // where Neg and Pos are never in range at the same time.  E.g. for
4286   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4287   // as well as (sub 32, Pos), but:
4288   //
4289   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4290   //
4291   // always invokes undefined behavior for 32-bit X.
4292   //
4293   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4294   unsigned MaskLoBits = 0;
4295   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4296     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4297       if (NegC->getAPIntValue() == EltSize - 1) {
4298         Neg = Neg.getOperand(0);
4299         MaskLoBits = Log2_64(EltSize);
4300       }
4301     }
4302   }
4303
4304   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4305   if (Neg.getOpcode() != ISD::SUB)
4306     return false;
4307   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4308   if (!NegC)
4309     return false;
4310   SDValue NegOp1 = Neg.getOperand(1);
4311
4312   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4313   // Pos'.  The truncation is redundant for the purpose of the equality.
4314   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4315     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4316       if (PosC->getAPIntValue() == EltSize - 1)
4317         Pos = Pos.getOperand(0);
4318
4319   // The condition we need is now:
4320   //
4321   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4322   //
4323   // If NegOp1 == Pos then we need:
4324   //
4325   //              EltSize & Mask == NegC & Mask
4326   //
4327   // (because "x & Mask" is a truncation and distributes through subtraction).
4328   APInt Width;
4329   if (Pos == NegOp1)
4330     Width = NegC->getAPIntValue();
4331
4332   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4333   // Then the condition we want to prove becomes:
4334   //
4335   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4336   //
4337   // which, again because "x & Mask" is a truncation, becomes:
4338   //
4339   //                NegC & Mask == (EltSize - PosC) & Mask
4340   //             EltSize & Mask == (NegC + PosC) & Mask
4341   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4342     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4343       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4344     else
4345       return false;
4346   } else
4347     return false;
4348
4349   // Now we just need to check that EltSize & Mask == Width & Mask.
4350   if (MaskLoBits)
4351     // EltSize & Mask is 0 since Mask is EltSize - 1.
4352     return Width.getLoBits(MaskLoBits) == 0;
4353   return Width == EltSize;
4354 }
4355
4356 // A subroutine of MatchRotate used once we have found an OR of two opposite
4357 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4358 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4359 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4360 // Neg with outer conversions stripped away.
4361 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4362                                        SDValue Neg, SDValue InnerPos,
4363                                        SDValue InnerNeg, unsigned PosOpcode,
4364                                        unsigned NegOpcode, const SDLoc &DL) {
4365   // fold (or (shl x, (*ext y)),
4366   //          (srl x, (*ext (sub 32, y)))) ->
4367   //   (rotl x, y) or (rotr x, (sub 32, y))
4368   //
4369   // fold (or (shl x, (*ext (sub 32, y))),
4370   //          (srl x, (*ext y))) ->
4371   //   (rotr x, y) or (rotl x, (sub 32, y))
4372   EVT VT = Shifted.getValueType();
4373   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4374     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4375     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4376                        HasPos ? Pos : Neg).getNode();
4377   }
4378
4379   return nullptr;
4380 }
4381
4382 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4383 // idioms for rotate, and if the target supports rotation instructions, generate
4384 // a rot[lr].
4385 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4386   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4387   EVT VT = LHS.getValueType();
4388   if (!TLI.isTypeLegal(VT)) return nullptr;
4389
4390   // The target must have at least one rotate flavor.
4391   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4392   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4393   if (!HasROTL && !HasROTR) return nullptr;
4394
4395   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4396   SDValue LHSShift;   // The shift.
4397   SDValue LHSMask;    // AND value if any.
4398   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4399     return nullptr; // Not part of a rotate.
4400
4401   SDValue RHSShift;   // The shift.
4402   SDValue RHSMask;    // AND value if any.
4403   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4404     return nullptr; // Not part of a rotate.
4405
4406   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4407     return nullptr;   // Not shifting the same value.
4408
4409   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4410     return nullptr;   // Shifts must disagree.
4411
4412   // Canonicalize shl to left side in a shl/srl pair.
4413   if (RHSShift.getOpcode() == ISD::SHL) {
4414     std::swap(LHS, RHS);
4415     std::swap(LHSShift, RHSShift);
4416     std::swap(LHSMask, RHSMask);
4417   }
4418
4419   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4420   SDValue LHSShiftArg = LHSShift.getOperand(0);
4421   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4422   SDValue RHSShiftArg = RHSShift.getOperand(0);
4423   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4424
4425   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4426   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4427   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4428     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4429     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4430     if ((LShVal + RShVal) != EltSizeInBits)
4431       return nullptr;
4432
4433     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4434                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4435
4436     // If there is an AND of either shifted operand, apply it to the result.
4437     if (LHSMask.getNode() || RHSMask.getNode()) {
4438       SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4439
4440       if (LHSMask.getNode()) {
4441         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4442         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4443                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4444                                        DAG.getConstant(RHSBits, DL, VT)));
4445       }
4446       if (RHSMask.getNode()) {
4447         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4448         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4449                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4450                                        DAG.getConstant(LHSBits, DL, VT)));
4451       }
4452
4453       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4454     }
4455
4456     return Rot.getNode();
4457   }
4458
4459   // If there is a mask here, and we have a variable shift, we can't be sure
4460   // that we're masking out the right stuff.
4461   if (LHSMask.getNode() || RHSMask.getNode())
4462     return nullptr;
4463
4464   // If the shift amount is sign/zext/any-extended just peel it off.
4465   SDValue LExtOp0 = LHSShiftAmt;
4466   SDValue RExtOp0 = RHSShiftAmt;
4467   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4468        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4469        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4470        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4471       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4472        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4473        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4474        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4475     LExtOp0 = LHSShiftAmt.getOperand(0);
4476     RExtOp0 = RHSShiftAmt.getOperand(0);
4477   }
4478
4479   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4480                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4481   if (TryL)
4482     return TryL;
4483
4484   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4485                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4486   if (TryR)
4487     return TryR;
4488
4489   return nullptr;
4490 }
4491
4492 namespace {
4493 /// Helper struct to parse and store a memory address as base + index + offset.
4494 /// We ignore sign extensions when it is safe to do so.
4495 /// The following two expressions are not equivalent. To differentiate we need
4496 /// to store whether there was a sign extension involved in the index
4497 /// computation.
4498 ///  (load (i64 add (i64 copyfromreg %c)
4499 ///                 (i64 signextend (add (i8 load %index)
4500 ///                                      (i8 1))))
4501 /// vs
4502 ///
4503 /// (load (i64 add (i64 copyfromreg %c)
4504 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
4505 ///                                         (i32 1)))))
4506 struct BaseIndexOffset {
4507   SDValue Base;
4508   SDValue Index;
4509   int64_t Offset;
4510   bool IsIndexSignExt;
4511
4512   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4513
4514   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4515                   bool IsIndexSignExt) :
4516     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4517
4518   bool equalBaseIndex(const BaseIndexOffset &Other) {
4519     return Other.Base == Base && Other.Index == Index &&
4520       Other.IsIndexSignExt == IsIndexSignExt;
4521   }
4522
4523   /// Parses tree in Ptr for base, index, offset addresses.
4524   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4525                                int64_t PartialOffset = 0) {
4526     bool IsIndexSignExt = false;
4527
4528     // Split up a folded GlobalAddress+Offset into its component parts.
4529     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4530       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4531         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4532                                                     SDLoc(GA),
4533                                                     GA->getValueType(0),
4534                                                     /*Offset=*/PartialOffset,
4535                                                     /*isTargetGA=*/false,
4536                                                     GA->getTargetFlags()),
4537                                SDValue(),
4538                                GA->getOffset(),
4539                                IsIndexSignExt);
4540       }
4541
4542     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4543     // instruction, then it could be just the BASE or everything else we don't
4544     // know how to handle. Just use Ptr as BASE and give up.
4545     if (Ptr->getOpcode() != ISD::ADD)
4546       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4547
4548     // We know that we have at least an ADD instruction. Try to pattern match
4549     // the simple case of BASE + OFFSET.
4550     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4551       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4552       return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4553     }
4554
4555     // Inside a loop the current BASE pointer is calculated using an ADD and a
4556     // MUL instruction. In this case Ptr is the actual BASE pointer.
4557     // (i64 add (i64 %array_ptr)
4558     //          (i64 mul (i64 %induction_var)
4559     //                   (i64 %element_size)))
4560     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4561       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4562
4563     // Look at Base + Index + Offset cases.
4564     SDValue Base = Ptr->getOperand(0);
4565     SDValue IndexOffset = Ptr->getOperand(1);
4566
4567     // Skip signextends.
4568     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4569       IndexOffset = IndexOffset->getOperand(0);
4570       IsIndexSignExt = true;
4571     }
4572
4573     // Either the case of Base + Index (no offset) or something else.
4574     if (IndexOffset->getOpcode() != ISD::ADD)
4575       return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4576
4577     // Now we have the case of Base + Index + offset.
4578     SDValue Index = IndexOffset->getOperand(0);
4579     SDValue Offset = IndexOffset->getOperand(1);
4580
4581     if (!isa<ConstantSDNode>(Offset))
4582       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4583
4584     // Ignore signextends.
4585     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4586       Index = Index->getOperand(0);
4587       IsIndexSignExt = true;
4588     } else IsIndexSignExt = false;
4589
4590     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4591     return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4592   }
4593 };
4594 } // namespace
4595
4596 namespace {
4597 /// Represents known origin of an individual byte in load combine pattern. The
4598 /// value of the byte is either constant zero or comes from memory.
4599 struct ByteProvider {
4600   // For constant zero providers Load is set to nullptr. For memory providers
4601   // Load represents the node which loads the byte from memory.
4602   // ByteOffset is the offset of the byte in the value produced by the load.
4603   LoadSDNode *Load;
4604   unsigned ByteOffset;
4605
4606   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4607
4608   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4609     return ByteProvider(Load, ByteOffset);
4610   }
4611   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4612
4613   bool isConstantZero() const { return !Load; }
4614   bool isMemory() const { return Load; }
4615
4616   bool operator==(const ByteProvider &Other) const {
4617     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4618   }
4619
4620 private:
4621   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4622       : Load(Load), ByteOffset(ByteOffset) {}
4623 };
4624
4625 /// Recursively traverses the expression calculating the origin of the requested
4626 /// byte of the given value. Returns None if the provider can't be calculated.
4627 ///
4628 /// For all the values except the root of the expression verifies that the value
4629 /// has exactly one use and if it's not true return None. This way if the origin
4630 /// of the byte is returned it's guaranteed that the values which contribute to
4631 /// the byte are not used outside of this expression.
4632 ///
4633 /// Because the parts of the expression are not allowed to have more than one
4634 /// use this function iterates over trees, not DAGs. So it never visits the same
4635 /// node more than once.
4636 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4637                                                    unsigned Depth,
4638                                                    bool Root = false) {
4639   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4640   if (Depth == 10)
4641     return None;
4642
4643   if (!Root && !Op.hasOneUse())
4644     return None;
4645
4646   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4647   unsigned BitWidth = Op.getValueSizeInBits();
4648   if (BitWidth % 8 != 0)
4649     return None;
4650   unsigned ByteWidth = BitWidth / 8;
4651   assert(Index < ByteWidth && "invalid index requested");
4652   (void) ByteWidth;
4653
4654   switch (Op.getOpcode()) {
4655   case ISD::OR: {
4656     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4657     if (!LHS)
4658       return None;
4659     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4660     if (!RHS)
4661       return None;
4662
4663     if (LHS->isConstantZero())
4664       return RHS;
4665     if (RHS->isConstantZero())
4666       return LHS;
4667     return None;
4668   }
4669   case ISD::SHL: {
4670     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4671     if (!ShiftOp)
4672       return None;
4673
4674     uint64_t BitShift = ShiftOp->getZExtValue();
4675     if (BitShift % 8 != 0)
4676       return None;
4677     uint64_t ByteShift = BitShift / 8;
4678
4679     return Index < ByteShift
4680                ? ByteProvider::getConstantZero()
4681                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4682                                        Depth + 1);
4683   }
4684   case ISD::ANY_EXTEND:
4685   case ISD::SIGN_EXTEND:
4686   case ISD::ZERO_EXTEND: {
4687     SDValue NarrowOp = Op->getOperand(0);
4688     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4689     if (NarrowBitWidth % 8 != 0)
4690       return None;
4691     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4692
4693     if (Index >= NarrowByteWidth)
4694       return Op.getOpcode() == ISD::ZERO_EXTEND
4695                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4696                  : None;
4697     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4698   }
4699   case ISD::BSWAP:
4700     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4701                                  Depth + 1);
4702   case ISD::LOAD: {
4703     auto L = cast<LoadSDNode>(Op.getNode());
4704     if (L->isVolatile() || L->isIndexed())
4705       return None;
4706
4707     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4708     if (NarrowBitWidth % 8 != 0)
4709       return None;
4710     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4711
4712     if (Index >= NarrowByteWidth)
4713       return L->getExtensionType() == ISD::ZEXTLOAD
4714                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4715                  : None;
4716     return ByteProvider::getMemory(L, Index);
4717   }
4718   }
4719
4720   return None;
4721 }
4722 } // namespace
4723
4724 /// Match a pattern where a wide type scalar value is loaded by several narrow
4725 /// loads and combined by shifts and ors. Fold it into a single load or a load
4726 /// and a BSWAP if the targets supports it.
4727 ///
4728 /// Assuming little endian target:
4729 ///  i8 *a = ...
4730 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4731 /// =>
4732 ///  i32 val = *((i32)a)
4733 ///
4734 ///  i8 *a = ...
4735 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4736 /// =>
4737 ///  i32 val = BSWAP(*((i32)a))
4738 ///
4739 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4740 /// interact well with the worklist mechanism. When a part of the pattern is
4741 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4742 /// but the root node of the pattern which triggers the load combine is not
4743 /// necessarily a direct user of the changed node. For example, once the address
4744 /// of t28 load is reassociated load combine won't be triggered:
4745 ///             t25: i32 = add t4, Constant:i32<2>
4746 ///           t26: i64 = sign_extend t25
4747 ///        t27: i64 = add t2, t26
4748 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4749 ///     t29: i32 = zero_extend t28
4750 ///   t32: i32 = shl t29, Constant:i8<8>
4751 /// t33: i32 = or t23, t32
4752 /// As a possible fix visitLoad can check if the load can be a part of a load
4753 /// combine pattern and add corresponding OR roots to the worklist.
4754 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4755   assert(N->getOpcode() == ISD::OR &&
4756          "Can only match load combining against OR nodes");
4757
4758   // Handles simple types only
4759   EVT VT = N->getValueType(0);
4760   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4761     return SDValue();
4762   unsigned ByteWidth = VT.getSizeInBits() / 8;
4763
4764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4765   // Before legalize we can introduce too wide illegal loads which will be later
4766   // split into legal sized loads. This enables us to combine i64 load by i8
4767   // patterns to a couple of i32 loads on 32 bit targets.
4768   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4769     return SDValue();
4770
4771   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4772     unsigned BW, unsigned i) { return i; };
4773   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4774     unsigned BW, unsigned i) { return BW - i - 1; };
4775
4776   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4777   auto MemoryByteOffset = [&] (ByteProvider P) {
4778     assert(P.isMemory() && "Must be a memory byte provider");
4779     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4780     assert(LoadBitWidth % 8 == 0 &&
4781            "can only analyze providers for individual bytes not bit");
4782     unsigned LoadByteWidth = LoadBitWidth / 8;
4783     return IsBigEndianTarget
4784             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4785             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4786   };
4787
4788   Optional<BaseIndexOffset> Base;
4789   SDValue Chain;
4790
4791   SmallSet<LoadSDNode *, 8> Loads;
4792   Optional<ByteProvider> FirstByteProvider;
4793   int64_t FirstOffset = INT64_MAX;
4794
4795   // Check if all the bytes of the OR we are looking at are loaded from the same
4796   // base address. Collect bytes offsets from Base address in ByteOffsets.
4797   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4798   for (unsigned i = 0; i < ByteWidth; i++) {
4799     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4800     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4801       return SDValue();
4802
4803     LoadSDNode *L = P->Load;
4804     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4805            "Must be enforced by calculateByteProvider");
4806     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4807
4808     // All loads must share the same chain
4809     SDValue LChain = L->getChain();
4810     if (!Chain)
4811       Chain = LChain;
4812     else if (Chain != LChain)
4813       return SDValue();
4814
4815     // Loads must share the same base address
4816     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4817     if (!Base)
4818       Base = Ptr;
4819     else if (!Base->equalBaseIndex(Ptr))
4820       return SDValue();
4821
4822     // Calculate the offset of the current byte from the base address
4823     int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
4824     ByteOffsets[i] = ByteOffsetFromBase;
4825
4826     // Remember the first byte load
4827     if (ByteOffsetFromBase < FirstOffset) {
4828       FirstByteProvider = P;
4829       FirstOffset = ByteOffsetFromBase;
4830     }
4831
4832     Loads.insert(L);
4833   }
4834   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4835          "memory, so there must be at least one load which produces the value");
4836   assert(Base && "Base address of the accessed memory location must be set");
4837   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4838
4839   // Check if the bytes of the OR we are looking at match with either big or
4840   // little endian value load
4841   bool BigEndian = true, LittleEndian = true;
4842   for (unsigned i = 0; i < ByteWidth; i++) {
4843     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4844     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4845     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4846     if (!BigEndian && !LittleEndian)
4847       return SDValue();
4848   }
4849   assert((BigEndian != LittleEndian) && "should be either or");
4850   assert(FirstByteProvider && "must be set");
4851
4852   // Ensure that the first byte is loaded from zero offset of the first load.
4853   // So the combined value can be loaded from the first load address.
4854   if (MemoryByteOffset(*FirstByteProvider) != 0)
4855     return SDValue();
4856   LoadSDNode *FirstLoad = FirstByteProvider->Load;
4857
4858   // The node we are looking at matches with the pattern, check if we can
4859   // replace it with a single load and bswap if needed.
4860
4861   // If the load needs byte swap check if the target supports it
4862   bool NeedsBswap = IsBigEndianTarget != BigEndian;
4863
4864   // Before legalize we can introduce illegal bswaps which will be later
4865   // converted to an explicit bswap sequence. This way we end up with a single
4866   // load and byte shuffling instead of several loads and byte shuffling.
4867   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4868     return SDValue();
4869
4870   // Check that a load of the wide type is both allowed and fast on the target
4871   bool Fast = false;
4872   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4873                                         VT, FirstLoad->getAddressSpace(),
4874                                         FirstLoad->getAlignment(), &Fast);
4875   if (!Allowed || !Fast)
4876     return SDValue();
4877
4878   SDValue NewLoad =
4879       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4880                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4881
4882   // Transfer chain users from old loads to the new load.
4883   for (LoadSDNode *L : Loads)
4884     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4885
4886   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4887 }
4888
4889 SDValue DAGCombiner::visitXOR(SDNode *N) {
4890   SDValue N0 = N->getOperand(0);
4891   SDValue N1 = N->getOperand(1);
4892   EVT VT = N0.getValueType();
4893
4894   // fold vector ops
4895   if (VT.isVector()) {
4896     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4897       return FoldedVOp;
4898
4899     // fold (xor x, 0) -> x, vector edition
4900     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4901       return N1;
4902     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4903       return N0;
4904   }
4905
4906   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4907   if (N0.isUndef() && N1.isUndef())
4908     return DAG.getConstant(0, SDLoc(N), VT);
4909   // fold (xor x, undef) -> undef
4910   if (N0.isUndef())
4911     return N0;
4912   if (N1.isUndef())
4913     return N1;
4914   // fold (xor c1, c2) -> c1^c2
4915   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4916   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4917   if (N0C && N1C)
4918     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4919   // canonicalize constant to RHS
4920   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4921      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4922     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4923   // fold (xor x, 0) -> x
4924   if (isNullConstant(N1))
4925     return N0;
4926
4927   if (SDValue NewSel = foldBinOpIntoSelect(N))
4928     return NewSel;
4929
4930   // reassociate xor
4931   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4932     return RXOR;
4933
4934   // fold !(x cc y) -> (x !cc y)
4935   SDValue LHS, RHS, CC;
4936   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4937     bool isInt = LHS.getValueType().isInteger();
4938     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4939                                                isInt);
4940
4941     if (!LegalOperations ||
4942         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4943       switch (N0.getOpcode()) {
4944       default:
4945         llvm_unreachable("Unhandled SetCC Equivalent!");
4946       case ISD::SETCC:
4947         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
4948       case ISD::SELECT_CC:
4949         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
4950                                N0.getOperand(3), NotCC);
4951       }
4952     }
4953   }
4954
4955   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4956   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4957       N0.getNode()->hasOneUse() &&
4958       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4959     SDValue V = N0.getOperand(0);
4960     SDLoc DL(N0);
4961     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4962                     DAG.getConstant(1, DL, V.getValueType()));
4963     AddToWorklist(V.getNode());
4964     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4965   }
4966
4967   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4968   if (isOneConstant(N1) && VT == MVT::i1 &&
4969       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4970     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4971     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4972       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4973       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4974       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4975       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4976       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4977     }
4978   }
4979   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4980   if (isAllOnesConstant(N1) &&
4981       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4982     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4983     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4984       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4985       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4986       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4987       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4988       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4989     }
4990   }
4991   // fold (xor (and x, y), y) -> (and (not x), y)
4992   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4993       N0->getOperand(1) == N1) {
4994     SDValue X = N0->getOperand(0);
4995     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4996     AddToWorklist(NotX.getNode());
4997     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4998   }
4999   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5000   if (N1C && N0.getOpcode() == ISD::XOR) {
5001     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5002       SDLoc DL(N);
5003       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5004                          DAG.getConstant(N1C->getAPIntValue() ^
5005                                          N00C->getAPIntValue(), DL, VT));
5006     }
5007     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5008       SDLoc DL(N);
5009       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5010                          DAG.getConstant(N1C->getAPIntValue() ^
5011                                          N01C->getAPIntValue(), DL, VT));
5012     }
5013   }
5014
5015   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5016   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5017   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5018       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5019       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5020     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5021       if (C->getAPIntValue() == (OpSizeInBits - 1))
5022         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5023   }
5024
5025   // fold (xor x, x) -> 0
5026   if (N0 == N1)
5027     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5028
5029   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5030   // Here is a concrete example of this equivalence:
5031   // i16   x ==  14
5032   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5033   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5034   //
5035   // =>
5036   //
5037   // i16     ~1      == 0b1111111111111110
5038   // i16 rol(~1, 14) == 0b1011111111111111
5039   //
5040   // Some additional tips to help conceptualize this transform:
5041   // - Try to see the operation as placing a single zero in a value of all ones.
5042   // - There exists no value for x which would allow the result to contain zero.
5043   // - Values of x larger than the bitwidth are undefined and do not require a
5044   //   consistent result.
5045   // - Pushing the zero left requires shifting one bits in from the right.
5046   // A rotate left of ~1 is a nice way of achieving the desired result.
5047   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5048       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5049     SDLoc DL(N);
5050     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5051                        N0.getOperand(1));
5052   }
5053
5054   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5055   if (N0.getOpcode() == N1.getOpcode())
5056     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5057       return Tmp;
5058
5059   // Simplify the expression using non-local knowledge.
5060   if (SimplifyDemandedBits(SDValue(N, 0)))
5061     return SDValue(N, 0);
5062
5063   return SDValue();
5064 }
5065
5066 /// Handle transforms common to the three shifts, when the shift amount is a
5067 /// constant.
5068 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5069   SDNode *LHS = N->getOperand(0).getNode();
5070   if (!LHS->hasOneUse()) return SDValue();
5071
5072   // We want to pull some binops through shifts, so that we have (and (shift))
5073   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5074   // thing happens with address calculations, so it's important to canonicalize
5075   // it.
5076   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5077
5078   switch (LHS->getOpcode()) {
5079   default: return SDValue();
5080   case ISD::OR:
5081   case ISD::XOR:
5082     HighBitSet = false; // We can only transform sra if the high bit is clear.
5083     break;
5084   case ISD::AND:
5085     HighBitSet = true;  // We can only transform sra if the high bit is set.
5086     break;
5087   case ISD::ADD:
5088     if (N->getOpcode() != ISD::SHL)
5089       return SDValue(); // only shl(add) not sr[al](add).
5090     HighBitSet = false; // We can only transform sra if the high bit is clear.
5091     break;
5092   }
5093
5094   // We require the RHS of the binop to be a constant and not opaque as well.
5095   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5096   if (!BinOpCst) return SDValue();
5097
5098   // FIXME: disable this unless the input to the binop is a shift by a constant
5099   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5100   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5101   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5102                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5103                  BinOpLHSVal->getOpcode() == ISD::SRL;
5104   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5105                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5106
5107   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5108       !isCopyOrSelect)
5109     return SDValue();
5110
5111   if (isCopyOrSelect && N->hasOneUse())
5112     return SDValue();
5113
5114   EVT VT = N->getValueType(0);
5115
5116   // If this is a signed shift right, and the high bit is modified by the
5117   // logical operation, do not perform the transformation. The highBitSet
5118   // boolean indicates the value of the high bit of the constant which would
5119   // cause it to be modified for this operation.
5120   if (N->getOpcode() == ISD::SRA) {
5121     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5122     if (BinOpRHSSignSet != HighBitSet)
5123       return SDValue();
5124   }
5125
5126   if (!TLI.isDesirableToCommuteWithShift(LHS))
5127     return SDValue();
5128
5129   // Fold the constants, shifting the binop RHS by the shift amount.
5130   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5131                                N->getValueType(0),
5132                                LHS->getOperand(1), N->getOperand(1));
5133   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5134
5135   // Create the new shift.
5136   SDValue NewShift = DAG.getNode(N->getOpcode(),
5137                                  SDLoc(LHS->getOperand(0)),
5138                                  VT, LHS->getOperand(0), N->getOperand(1));
5139
5140   // Create the new binop.
5141   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5142 }
5143
5144 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5145   assert(N->getOpcode() == ISD::TRUNCATE);
5146   assert(N->getOperand(0).getOpcode() == ISD::AND);
5147
5148   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5149   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5150     SDValue N01 = N->getOperand(0).getOperand(1);
5151     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5152       SDLoc DL(N);
5153       EVT TruncVT = N->getValueType(0);
5154       SDValue N00 = N->getOperand(0).getOperand(0);
5155       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5156       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5157       AddToWorklist(Trunc00.getNode());
5158       AddToWorklist(Trunc01.getNode());
5159       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5160     }
5161   }
5162
5163   return SDValue();
5164 }
5165
5166 SDValue DAGCombiner::visitRotate(SDNode *N) {
5167   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5168   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5169       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5170     if (SDValue NewOp1 =
5171             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5172       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5173                          N->getOperand(0), NewOp1);
5174   }
5175   return SDValue();
5176 }
5177
5178 SDValue DAGCombiner::visitSHL(SDNode *N) {
5179   SDValue N0 = N->getOperand(0);
5180   SDValue N1 = N->getOperand(1);
5181   EVT VT = N0.getValueType();
5182   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5183
5184   // fold vector ops
5185   if (VT.isVector()) {
5186     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5187       return FoldedVOp;
5188
5189     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5190     // If setcc produces all-one true value then:
5191     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5192     if (N1CV && N1CV->isConstant()) {
5193       if (N0.getOpcode() == ISD::AND) {
5194         SDValue N00 = N0->getOperand(0);
5195         SDValue N01 = N0->getOperand(1);
5196         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5197
5198         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5199             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5200                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5201           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5202                                                      N01CV, N1CV))
5203             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5204         }
5205       }
5206     }
5207   }
5208
5209   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5210
5211   // fold (shl c1, c2) -> c1<<c2
5212   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5213   if (N0C && N1C && !N1C->isOpaque())
5214     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5215   // fold (shl 0, x) -> 0
5216   if (isNullConstant(N0))
5217     return N0;
5218   // fold (shl x, c >= size(x)) -> undef
5219   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5220     return DAG.getUNDEF(VT);
5221   // fold (shl x, 0) -> x
5222   if (N1C && N1C->isNullValue())
5223     return N0;
5224   // fold (shl undef, x) -> 0
5225   if (N0.isUndef())
5226     return DAG.getConstant(0, SDLoc(N), VT);
5227
5228   if (SDValue NewSel = foldBinOpIntoSelect(N))
5229     return NewSel;
5230
5231   // if (shl x, c) is known to be zero, return 0
5232   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5233                             APInt::getAllOnesValue(OpSizeInBits)))
5234     return DAG.getConstant(0, SDLoc(N), VT);
5235   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5236   if (N1.getOpcode() == ISD::TRUNCATE &&
5237       N1.getOperand(0).getOpcode() == ISD::AND) {
5238     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5239       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5240   }
5241
5242   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5243     return SDValue(N, 0);
5244
5245   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5246   if (N1C && N0.getOpcode() == ISD::SHL) {
5247     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5248       SDLoc DL(N);
5249       APInt c1 = N0C1->getAPIntValue();
5250       APInt c2 = N1C->getAPIntValue();
5251       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5252
5253       APInt Sum = c1 + c2;
5254       if (Sum.uge(OpSizeInBits))
5255         return DAG.getConstant(0, DL, VT);
5256
5257       return DAG.getNode(
5258           ISD::SHL, DL, VT, N0.getOperand(0),
5259           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5260     }
5261   }
5262
5263   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5264   // For this to be valid, the second form must not preserve any of the bits
5265   // that are shifted out by the inner shift in the first form.  This means
5266   // the outer shift size must be >= the number of bits added by the ext.
5267   // As a corollary, we don't care what kind of ext it is.
5268   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5269               N0.getOpcode() == ISD::ANY_EXTEND ||
5270               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5271       N0.getOperand(0).getOpcode() == ISD::SHL) {
5272     SDValue N0Op0 = N0.getOperand(0);
5273     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5274       APInt c1 = N0Op0C1->getAPIntValue();
5275       APInt c2 = N1C->getAPIntValue();
5276       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5277
5278       EVT InnerShiftVT = N0Op0.getValueType();
5279       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5280       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5281         SDLoc DL(N0);
5282         APInt Sum = c1 + c2;
5283         if (Sum.uge(OpSizeInBits))
5284           return DAG.getConstant(0, DL, VT);
5285
5286         return DAG.getNode(
5287             ISD::SHL, DL, VT,
5288             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5289             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5290       }
5291     }
5292   }
5293
5294   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5295   // Only fold this if the inner zext has no other uses to avoid increasing
5296   // the total number of instructions.
5297   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5298       N0.getOperand(0).getOpcode() == ISD::SRL) {
5299     SDValue N0Op0 = N0.getOperand(0);
5300     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5301       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5302         uint64_t c1 = N0Op0C1->getZExtValue();
5303         uint64_t c2 = N1C->getZExtValue();
5304         if (c1 == c2) {
5305           SDValue NewOp0 = N0.getOperand(0);
5306           EVT CountVT = NewOp0.getOperand(1).getValueType();
5307           SDLoc DL(N);
5308           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5309                                        NewOp0,
5310                                        DAG.getConstant(c2, DL, CountVT));
5311           AddToWorklist(NewSHL.getNode());
5312           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5313         }
5314       }
5315     }
5316   }
5317
5318   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5319   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5320   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5321       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
5322     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5323       uint64_t C1 = N0C1->getZExtValue();
5324       uint64_t C2 = N1C->getZExtValue();
5325       SDLoc DL(N);
5326       if (C1 <= C2)
5327         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5328                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5329       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5330                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5331     }
5332   }
5333
5334   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5335   //                               (and (srl x, (sub c1, c2), MASK)
5336   // Only fold this if the inner shift has no other uses -- if it does, folding
5337   // this will increase the total number of instructions.
5338   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5339     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5340       uint64_t c1 = N0C1->getZExtValue();
5341       if (c1 < OpSizeInBits) {
5342         uint64_t c2 = N1C->getZExtValue();
5343         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5344         SDValue Shift;
5345         if (c2 > c1) {
5346           Mask = Mask.shl(c2 - c1);
5347           SDLoc DL(N);
5348           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5349                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5350         } else {
5351           Mask.lshrInPlace(c1 - c2);
5352           SDLoc DL(N);
5353           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5354                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5355         }
5356         SDLoc DL(N0);
5357         return DAG.getNode(ISD::AND, DL, VT, Shift,
5358                            DAG.getConstant(Mask, DL, VT));
5359       }
5360     }
5361   }
5362
5363   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5364   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5365       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5366     SDLoc DL(N);
5367     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5368     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5369     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5370   }
5371
5372   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5373   // Variant of version done on multiply, except mul by a power of 2 is turned
5374   // into a shift.
5375   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5376       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5377       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5378     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5379     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5380     AddToWorklist(Shl0.getNode());
5381     AddToWorklist(Shl1.getNode());
5382     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5383   }
5384
5385   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5386   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5387       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5388       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5389     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5390     if (isConstantOrConstantVector(Shl))
5391       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5392   }
5393
5394   if (N1C && !N1C->isOpaque())
5395     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5396       return NewSHL;
5397
5398   return SDValue();
5399 }
5400
5401 SDValue DAGCombiner::visitSRA(SDNode *N) {
5402   SDValue N0 = N->getOperand(0);
5403   SDValue N1 = N->getOperand(1);
5404   EVT VT = N0.getValueType();
5405   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5406
5407   // Arithmetic shifting an all-sign-bit value is a no-op.
5408   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5409     return N0;
5410
5411   // fold vector ops
5412   if (VT.isVector())
5413     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5414       return FoldedVOp;
5415
5416   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5417
5418   // fold (sra c1, c2) -> (sra c1, c2)
5419   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5420   if (N0C && N1C && !N1C->isOpaque())
5421     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5422   // fold (sra 0, x) -> 0
5423   if (isNullConstant(N0))
5424     return N0;
5425   // fold (sra -1, x) -> -1
5426   if (isAllOnesConstant(N0))
5427     return N0;
5428   // fold (sra x, c >= size(x)) -> undef
5429   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5430     return DAG.getUNDEF(VT);
5431   // fold (sra x, 0) -> x
5432   if (N1C && N1C->isNullValue())
5433     return N0;
5434
5435   if (SDValue NewSel = foldBinOpIntoSelect(N))
5436     return NewSel;
5437
5438   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5439   // sext_inreg.
5440   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5441     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5442     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5443     if (VT.isVector())
5444       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5445                                ExtVT, VT.getVectorNumElements());
5446     if ((!LegalOperations ||
5447          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5448       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5449                          N0.getOperand(0), DAG.getValueType(ExtVT));
5450   }
5451
5452   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5453   if (N1C && N0.getOpcode() == ISD::SRA) {
5454     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5455       SDLoc DL(N);
5456       APInt c1 = N0C1->getAPIntValue();
5457       APInt c2 = N1C->getAPIntValue();
5458       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5459
5460       APInt Sum = c1 + c2;
5461       if (Sum.uge(OpSizeInBits))
5462         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5463
5464       return DAG.getNode(
5465           ISD::SRA, DL, VT, N0.getOperand(0),
5466           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5467     }
5468   }
5469
5470   // fold (sra (shl X, m), (sub result_size, n))
5471   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5472   // result_size - n != m.
5473   // If truncate is free for the target sext(shl) is likely to result in better
5474   // code.
5475   if (N0.getOpcode() == ISD::SHL && N1C) {
5476     // Get the two constanst of the shifts, CN0 = m, CN = n.
5477     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5478     if (N01C) {
5479       LLVMContext &Ctx = *DAG.getContext();
5480       // Determine what the truncate's result bitsize and type would be.
5481       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5482
5483       if (VT.isVector())
5484         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5485
5486       // Determine the residual right-shift amount.
5487       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5488
5489       // If the shift is not a no-op (in which case this should be just a sign
5490       // extend already), the truncated to type is legal, sign_extend is legal
5491       // on that type, and the truncate to that type is both legal and free,
5492       // perform the transform.
5493       if ((ShiftAmt > 0) &&
5494           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5495           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5496           TLI.isTruncateFree(VT, TruncVT)) {
5497
5498         SDLoc DL(N);
5499         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5500             getShiftAmountTy(N0.getOperand(0).getValueType()));
5501         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5502                                     N0.getOperand(0), Amt);
5503         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5504                                     Shift);
5505         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5506                            N->getValueType(0), Trunc);
5507       }
5508     }
5509   }
5510
5511   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5512   if (N1.getOpcode() == ISD::TRUNCATE &&
5513       N1.getOperand(0).getOpcode() == ISD::AND) {
5514     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5515       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5516   }
5517
5518   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5519   //      if c1 is equal to the number of bits the trunc removes
5520   if (N0.getOpcode() == ISD::TRUNCATE &&
5521       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5522        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5523       N0.getOperand(0).hasOneUse() &&
5524       N0.getOperand(0).getOperand(1).hasOneUse() &&
5525       N1C) {
5526     SDValue N0Op0 = N0.getOperand(0);
5527     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5528       unsigned LargeShiftVal = LargeShift->getZExtValue();
5529       EVT LargeVT = N0Op0.getValueType();
5530
5531       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5532         SDLoc DL(N);
5533         SDValue Amt =
5534           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5535                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5536         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5537                                   N0Op0.getOperand(0), Amt);
5538         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5539       }
5540     }
5541   }
5542
5543   // Simplify, based on bits shifted out of the LHS.
5544   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5545     return SDValue(N, 0);
5546
5547
5548   // If the sign bit is known to be zero, switch this to a SRL.
5549   if (DAG.SignBitIsZero(N0))
5550     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5551
5552   if (N1C && !N1C->isOpaque())
5553     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5554       return NewSRA;
5555
5556   return SDValue();
5557 }
5558
5559 SDValue DAGCombiner::visitSRL(SDNode *N) {
5560   SDValue N0 = N->getOperand(0);
5561   SDValue N1 = N->getOperand(1);
5562   EVT VT = N0.getValueType();
5563   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5564
5565   // fold vector ops
5566   if (VT.isVector())
5567     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5568       return FoldedVOp;
5569
5570   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5571
5572   // fold (srl c1, c2) -> c1 >>u c2
5573   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5574   if (N0C && N1C && !N1C->isOpaque())
5575     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5576   // fold (srl 0, x) -> 0
5577   if (isNullConstant(N0))
5578     return N0;
5579   // fold (srl x, c >= size(x)) -> undef
5580   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5581     return DAG.getUNDEF(VT);
5582   // fold (srl x, 0) -> x
5583   if (N1C && N1C->isNullValue())
5584     return N0;
5585
5586   if (SDValue NewSel = foldBinOpIntoSelect(N))
5587     return NewSel;
5588
5589   // if (srl x, c) is known to be zero, return 0
5590   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5591                                    APInt::getAllOnesValue(OpSizeInBits)))
5592     return DAG.getConstant(0, SDLoc(N), VT);
5593
5594   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5595   if (N1C && N0.getOpcode() == ISD::SRL) {
5596     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5597       SDLoc DL(N);
5598       APInt c1 = N0C1->getAPIntValue();
5599       APInt c2 = N1C->getAPIntValue();
5600       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5601
5602       APInt Sum = c1 + c2;
5603       if (Sum.uge(OpSizeInBits))
5604         return DAG.getConstant(0, DL, VT);
5605
5606       return DAG.getNode(
5607           ISD::SRL, DL, VT, N0.getOperand(0),
5608           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5609     }
5610   }
5611
5612   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5613   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5614       N0.getOperand(0).getOpcode() == ISD::SRL &&
5615       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
5616     uint64_t c1 =
5617       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
5618     uint64_t c2 = N1C->getZExtValue();
5619     EVT InnerShiftVT = N0.getOperand(0).getValueType();
5620     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
5621     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5622     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5623     if (c1 + OpSizeInBits == InnerShiftSize) {
5624       SDLoc DL(N0);
5625       if (c1 + c2 >= InnerShiftSize)
5626         return DAG.getConstant(0, DL, VT);
5627       return DAG.getNode(ISD::TRUNCATE, DL, VT,
5628                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5629                                      N0.getOperand(0)->getOperand(0),
5630                                      DAG.getConstant(c1 + c2, DL,
5631                                                      ShiftCountVT)));
5632     }
5633   }
5634
5635   // fold (srl (shl x, c), c) -> (and x, cst2)
5636   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5637       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5638     SDLoc DL(N);
5639     SDValue Mask =
5640         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5641     AddToWorklist(Mask.getNode());
5642     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5643   }
5644
5645   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5646   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5647     // Shifting in all undef bits?
5648     EVT SmallVT = N0.getOperand(0).getValueType();
5649     unsigned BitSize = SmallVT.getScalarSizeInBits();
5650     if (N1C->getZExtValue() >= BitSize)
5651       return DAG.getUNDEF(VT);
5652
5653     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5654       uint64_t ShiftAmt = N1C->getZExtValue();
5655       SDLoc DL0(N0);
5656       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5657                                        N0.getOperand(0),
5658                           DAG.getConstant(ShiftAmt, DL0,
5659                                           getShiftAmountTy(SmallVT)));
5660       AddToWorklist(SmallShift.getNode());
5661       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5662       SDLoc DL(N);
5663       return DAG.getNode(ISD::AND, DL, VT,
5664                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5665                          DAG.getConstant(Mask, DL, VT));
5666     }
5667   }
5668
5669   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5670   // bit, which is unmodified by sra.
5671   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5672     if (N0.getOpcode() == ISD::SRA)
5673       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5674   }
5675
5676   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5677   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5678       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5679     APInt KnownZero, KnownOne;
5680     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5681
5682     // If any of the input bits are KnownOne, then the input couldn't be all
5683     // zeros, thus the result of the srl will always be zero.
5684     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5685
5686     // If all of the bits input the to ctlz node are known to be zero, then
5687     // the result of the ctlz is "32" and the result of the shift is one.
5688     APInt UnknownBits = ~KnownZero;
5689     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5690
5691     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5692     if ((UnknownBits & (UnknownBits - 1)) == 0) {
5693       // Okay, we know that only that the single bit specified by UnknownBits
5694       // could be set on input to the CTLZ node. If this bit is set, the SRL
5695       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5696       // to an SRL/XOR pair, which is likely to simplify more.
5697       unsigned ShAmt = UnknownBits.countTrailingZeros();
5698       SDValue Op = N0.getOperand(0);
5699
5700       if (ShAmt) {
5701         SDLoc DL(N0);
5702         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5703                   DAG.getConstant(ShAmt, DL,
5704                                   getShiftAmountTy(Op.getValueType())));
5705         AddToWorklist(Op.getNode());
5706       }
5707
5708       SDLoc DL(N);
5709       return DAG.getNode(ISD::XOR, DL, VT,
5710                          Op, DAG.getConstant(1, DL, VT));
5711     }
5712   }
5713
5714   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5715   if (N1.getOpcode() == ISD::TRUNCATE &&
5716       N1.getOperand(0).getOpcode() == ISD::AND) {
5717     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5718       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5719   }
5720
5721   // fold operands of srl based on knowledge that the low bits are not
5722   // demanded.
5723   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5724     return SDValue(N, 0);
5725
5726   if (N1C && !N1C->isOpaque())
5727     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5728       return NewSRL;
5729
5730   // Attempt to convert a srl of a load into a narrower zero-extending load.
5731   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5732     return NarrowLoad;
5733
5734   // Here is a common situation. We want to optimize:
5735   //
5736   //   %a = ...
5737   //   %b = and i32 %a, 2
5738   //   %c = srl i32 %b, 1
5739   //   brcond i32 %c ...
5740   //
5741   // into
5742   //
5743   //   %a = ...
5744   //   %b = and %a, 2
5745   //   %c = setcc eq %b, 0
5746   //   brcond %c ...
5747   //
5748   // However when after the source operand of SRL is optimized into AND, the SRL
5749   // itself may not be optimized further. Look for it and add the BRCOND into
5750   // the worklist.
5751   if (N->hasOneUse()) {
5752     SDNode *Use = *N->use_begin();
5753     if (Use->getOpcode() == ISD::BRCOND)
5754       AddToWorklist(Use);
5755     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5756       // Also look pass the truncate.
5757       Use = *Use->use_begin();
5758       if (Use->getOpcode() == ISD::BRCOND)
5759         AddToWorklist(Use);
5760     }
5761   }
5762
5763   return SDValue();
5764 }
5765
5766 SDValue DAGCombiner::visitABS(SDNode *N) {
5767   SDValue N0 = N->getOperand(0);
5768   EVT VT = N->getValueType(0);
5769
5770   // fold (abs c1) -> c2
5771   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5772     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5773   // fold (abs (abs x)) -> (abs x)
5774   if (N0.getOpcode() == ISD::ABS)
5775     return N0;
5776   // fold (abs x) -> x iff not-negative
5777   if (DAG.SignBitIsZero(N0))
5778     return N0;
5779   return SDValue();
5780 }
5781
5782 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5783   SDValue N0 = N->getOperand(0);
5784   EVT VT = N->getValueType(0);
5785
5786   // fold (bswap c1) -> c2
5787   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5788     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5789   // fold (bswap (bswap x)) -> x
5790   if (N0.getOpcode() == ISD::BSWAP)
5791     return N0->getOperand(0);
5792   return SDValue();
5793 }
5794
5795 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5796   SDValue N0 = N->getOperand(0);
5797   EVT VT = N->getValueType(0);
5798
5799   // fold (bitreverse c1) -> c2
5800   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5801     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5802   // fold (bitreverse (bitreverse x)) -> x
5803   if (N0.getOpcode() == ISD::BITREVERSE)
5804     return N0.getOperand(0);
5805   return SDValue();
5806 }
5807
5808 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5809   SDValue N0 = N->getOperand(0);
5810   EVT VT = N->getValueType(0);
5811
5812   // fold (ctlz c1) -> c2
5813   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5814     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5815   return SDValue();
5816 }
5817
5818 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5819   SDValue N0 = N->getOperand(0);
5820   EVT VT = N->getValueType(0);
5821
5822   // fold (ctlz_zero_undef c1) -> c2
5823   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5824     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5825   return SDValue();
5826 }
5827
5828 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5829   SDValue N0 = N->getOperand(0);
5830   EVT VT = N->getValueType(0);
5831
5832   // fold (cttz c1) -> c2
5833   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5834     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5835   return SDValue();
5836 }
5837
5838 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5839   SDValue N0 = N->getOperand(0);
5840   EVT VT = N->getValueType(0);
5841
5842   // fold (cttz_zero_undef c1) -> c2
5843   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5844     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5845   return SDValue();
5846 }
5847
5848 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5849   SDValue N0 = N->getOperand(0);
5850   EVT VT = N->getValueType(0);
5851
5852   // fold (ctpop c1) -> c2
5853   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5854     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5855   return SDValue();
5856 }
5857
5858
5859 /// \brief Generate Min/Max node
5860 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5861                                    SDValue RHS, SDValue True, SDValue False,
5862                                    ISD::CondCode CC, const TargetLowering &TLI,
5863                                    SelectionDAG &DAG) {
5864   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5865     return SDValue();
5866
5867   switch (CC) {
5868   case ISD::SETOLT:
5869   case ISD::SETOLE:
5870   case ISD::SETLT:
5871   case ISD::SETLE:
5872   case ISD::SETULT:
5873   case ISD::SETULE: {
5874     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5875     if (TLI.isOperationLegal(Opcode, VT))
5876       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5877     return SDValue();
5878   }
5879   case ISD::SETOGT:
5880   case ISD::SETOGE:
5881   case ISD::SETGT:
5882   case ISD::SETGE:
5883   case ISD::SETUGT:
5884   case ISD::SETUGE: {
5885     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5886     if (TLI.isOperationLegal(Opcode, VT))
5887       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5888     return SDValue();
5889   }
5890   default:
5891     return SDValue();
5892   }
5893 }
5894
5895 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5896   SDValue Cond = N->getOperand(0);
5897   SDValue N1 = N->getOperand(1);
5898   SDValue N2 = N->getOperand(2);
5899   EVT VT = N->getValueType(0);
5900   EVT CondVT = Cond.getValueType();
5901   SDLoc DL(N);
5902
5903   if (!VT.isInteger())
5904     return SDValue();
5905
5906   auto *C1 = dyn_cast<ConstantSDNode>(N1);
5907   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5908   if (!C1 || !C2)
5909     return SDValue();
5910
5911   // Only do this before legalization to avoid conflicting with target-specific
5912   // transforms in the other direction (create a select from a zext/sext). There
5913   // is also a target-independent combine here in DAGCombiner in the other
5914   // direction for (select Cond, -1, 0) when the condition is not i1.
5915   if (CondVT == MVT::i1 && !LegalOperations) {
5916     if (C1->isNullValue() && C2->isOne()) {
5917       // select Cond, 0, 1 --> zext (!Cond)
5918       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
5919       if (VT != MVT::i1)
5920         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
5921       return NotCond;
5922     }
5923     if (C1->isNullValue() && C2->isAllOnesValue()) {
5924       // select Cond, 0, -1 --> sext (!Cond)
5925       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
5926       if (VT != MVT::i1)
5927         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
5928       return NotCond;
5929     }
5930     if (C1->isOne() && C2->isNullValue()) {
5931       // select Cond, 1, 0 --> zext (Cond)
5932       if (VT != MVT::i1)
5933         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
5934       return Cond;
5935     }
5936     if (C1->isAllOnesValue() && C2->isNullValue()) {
5937       // select Cond, -1, 0 --> sext (Cond)
5938       if (VT != MVT::i1)
5939         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
5940       return Cond;
5941     }
5942
5943     // For any constants that differ by 1, we can transform the select into an
5944     // extend and add. Use a target hook because some targets may prefer to
5945     // transform in the other direction.
5946     if (TLI.convertSelectOfConstantsToMath()) {
5947       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
5948         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
5949         if (VT != MVT::i1)
5950           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
5951         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
5952       }
5953       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
5954         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
5955         if (VT != MVT::i1)
5956           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
5957         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
5958       }
5959     }
5960
5961     return SDValue();
5962   }
5963
5964   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5965   // We can't do this reliably if integer based booleans have different contents
5966   // to floating point based booleans. This is because we can't tell whether we
5967   // have an integer-based boolean or a floating-point-based boolean unless we
5968   // can find the SETCC that produced it and inspect its operands. This is
5969   // fairly easy if C is the SETCC node, but it can potentially be
5970   // undiscoverable (or not reasonably discoverable). For example, it could be
5971   // in another basic block or it could require searching a complicated
5972   // expression.
5973   if (CondVT.isInteger() &&
5974       TLI.getBooleanContents(false, true) ==
5975           TargetLowering::ZeroOrOneBooleanContent &&
5976       TLI.getBooleanContents(false, false) ==
5977           TargetLowering::ZeroOrOneBooleanContent &&
5978       C1->isNullValue() && C2->isOne()) {
5979     SDValue NotCond =
5980         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
5981     if (VT.bitsEq(CondVT))
5982       return NotCond;
5983     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5984   }
5985
5986   return SDValue();
5987 }
5988
5989 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5990   SDValue N0 = N->getOperand(0);
5991   SDValue N1 = N->getOperand(1);
5992   SDValue N2 = N->getOperand(2);
5993   EVT VT = N->getValueType(0);
5994   EVT VT0 = N0.getValueType();
5995
5996   // fold (select C, X, X) -> X
5997   if (N1 == N2)
5998     return N1;
5999   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6000     // fold (select true, X, Y) -> X
6001     // fold (select false, X, Y) -> Y
6002     return !N0C->isNullValue() ? N1 : N2;
6003   }
6004   // fold (select X, X, Y) -> (or X, Y)
6005   // fold (select X, 1, Y) -> (or C, Y)
6006   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6007     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6008
6009   if (SDValue V = foldSelectOfConstants(N))
6010     return V;
6011
6012   // fold (select C, 0, X) -> (and (not C), X)
6013   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6014     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6015     AddToWorklist(NOTNode.getNode());
6016     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6017   }
6018   // fold (select C, X, 1) -> (or (not C), X)
6019   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6020     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6021     AddToWorklist(NOTNode.getNode());
6022     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6023   }
6024   // fold (select X, Y, X) -> (and X, Y)
6025   // fold (select X, Y, 0) -> (and X, Y)
6026   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6027     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6028
6029   // If we can fold this based on the true/false value, do so.
6030   if (SimplifySelectOps(N, N1, N2))
6031     return SDValue(N, 0);  // Don't revisit N.
6032
6033   if (VT0 == MVT::i1) {
6034     // The code in this block deals with the following 2 equivalences:
6035     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6036     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6037     // The target can specify its preferred form with the
6038     // shouldNormalizeToSelectSequence() callback. However we always transform
6039     // to the right anyway if we find the inner select exists in the DAG anyway
6040     // and we always transform to the left side if we know that we can further
6041     // optimize the combination of the conditions.
6042     bool normalizeToSequence
6043       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6044     // select (and Cond0, Cond1), X, Y
6045     //   -> select Cond0, (select Cond1, X, Y), Y
6046     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6047       SDValue Cond0 = N0->getOperand(0);
6048       SDValue Cond1 = N0->getOperand(1);
6049       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6050                                         N1.getValueType(), Cond1, N1, N2);
6051       if (normalizeToSequence || !InnerSelect.use_empty())
6052         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6053                            InnerSelect, N2);
6054     }
6055     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6056     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6057       SDValue Cond0 = N0->getOperand(0);
6058       SDValue Cond1 = N0->getOperand(1);
6059       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6060                                         N1.getValueType(), Cond1, N1, N2);
6061       if (normalizeToSequence || !InnerSelect.use_empty())
6062         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6063                            InnerSelect);
6064     }
6065
6066     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6067     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6068       SDValue N1_0 = N1->getOperand(0);
6069       SDValue N1_1 = N1->getOperand(1);
6070       SDValue N1_2 = N1->getOperand(2);
6071       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6072         // Create the actual and node if we can generate good code for it.
6073         if (!normalizeToSequence) {
6074           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6075                                     N0, N1_0);
6076           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6077                              N1_1, N2);
6078         }
6079         // Otherwise see if we can optimize the "and" to a better pattern.
6080         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6081           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6082                              N1_1, N2);
6083       }
6084     }
6085     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6086     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6087       SDValue N2_0 = N2->getOperand(0);
6088       SDValue N2_1 = N2->getOperand(1);
6089       SDValue N2_2 = N2->getOperand(2);
6090       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6091         // Create the actual or node if we can generate good code for it.
6092         if (!normalizeToSequence) {
6093           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6094                                    N0, N2_0);
6095           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6096                              N1, N2_2);
6097         }
6098         // Otherwise see if we can optimize to a better pattern.
6099         if (SDValue Combined = visitORLike(N0, N2_0, N))
6100           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6101                              N1, N2_2);
6102       }
6103     }
6104   }
6105
6106   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6107   if (VT0 == MVT::i1) {
6108     if (N0->getOpcode() == ISD::XOR) {
6109       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6110         SDValue Cond0 = N0->getOperand(0);
6111         if (C->isOne())
6112           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6113                              Cond0, N2, N1);
6114       }
6115     }
6116   }
6117
6118   // fold selects based on a setcc into other things, such as min/max/abs
6119   if (N0.getOpcode() == ISD::SETCC) {
6120     // select x, y (fcmp lt x, y) -> fminnum x, y
6121     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6122     //
6123     // This is OK if we don't care about what happens if either operand is a
6124     // NaN.
6125     //
6126
6127     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6128     // no signed zeros as well as no nans.
6129     const TargetOptions &Options = DAG.getTarget().Options;
6130     if (Options.UnsafeFPMath &&
6131         VT.isFloatingPoint() && N0.hasOneUse() &&
6132         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6133       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6134
6135       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6136                                                 N0.getOperand(1), N1, N2, CC,
6137                                                 TLI, DAG))
6138         return FMinMax;
6139     }
6140
6141     if ((!LegalOperations &&
6142          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6143         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6144       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6145                          N0.getOperand(0), N0.getOperand(1),
6146                          N1, N2, N0.getOperand(2));
6147     return SimplifySelect(SDLoc(N), N0, N1, N2);
6148   }
6149
6150   return SDValue();
6151 }
6152
6153 static
6154 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6155   SDLoc DL(N);
6156   EVT LoVT, HiVT;
6157   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6158
6159   // Split the inputs.
6160   SDValue Lo, Hi, LL, LH, RL, RH;
6161   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6162   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6163
6164   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6165   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6166
6167   return std::make_pair(Lo, Hi);
6168 }
6169
6170 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6171 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6172 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6173   SDLoc DL(N);
6174   SDValue Cond = N->getOperand(0);
6175   SDValue LHS = N->getOperand(1);
6176   SDValue RHS = N->getOperand(2);
6177   EVT VT = N->getValueType(0);
6178   int NumElems = VT.getVectorNumElements();
6179   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6180          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6181          Cond.getOpcode() == ISD::BUILD_VECTOR);
6182
6183   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6184   // binary ones here.
6185   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6186     return SDValue();
6187
6188   // We're sure we have an even number of elements due to the
6189   // concat_vectors we have as arguments to vselect.
6190   // Skip BV elements until we find one that's not an UNDEF
6191   // After we find an UNDEF element, keep looping until we get to half the
6192   // length of the BV and see if all the non-undef nodes are the same.
6193   ConstantSDNode *BottomHalf = nullptr;
6194   for (int i = 0; i < NumElems / 2; ++i) {
6195     if (Cond->getOperand(i)->isUndef())
6196       continue;
6197
6198     if (BottomHalf == nullptr)
6199       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6200     else if (Cond->getOperand(i).getNode() != BottomHalf)
6201       return SDValue();
6202   }
6203
6204   // Do the same for the second half of the BuildVector
6205   ConstantSDNode *TopHalf = nullptr;
6206   for (int i = NumElems / 2; i < NumElems; ++i) {
6207     if (Cond->getOperand(i)->isUndef())
6208       continue;
6209
6210     if (TopHalf == nullptr)
6211       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6212     else if (Cond->getOperand(i).getNode() != TopHalf)
6213       return SDValue();
6214   }
6215
6216   assert(TopHalf && BottomHalf &&
6217          "One half of the selector was all UNDEFs and the other was all the "
6218          "same value. This should have been addressed before this function.");
6219   return DAG.getNode(
6220       ISD::CONCAT_VECTORS, DL, VT,
6221       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6222       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6223 }
6224
6225 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6226
6227   if (Level >= AfterLegalizeTypes)
6228     return SDValue();
6229
6230   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6231   SDValue Mask = MSC->getMask();
6232   SDValue Data  = MSC->getValue();
6233   SDLoc DL(N);
6234
6235   // If the MSCATTER data type requires splitting and the mask is provided by a
6236   // SETCC, then split both nodes and its operands before legalization. This
6237   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6238   // and enables future optimizations (e.g. min/max pattern matching on X86).
6239   if (Mask.getOpcode() != ISD::SETCC)
6240     return SDValue();
6241
6242   // Check if any splitting is required.
6243   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6244       TargetLowering::TypeSplitVector)
6245     return SDValue();
6246   SDValue MaskLo, MaskHi, Lo, Hi;
6247   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6248
6249   EVT LoVT, HiVT;
6250   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6251
6252   SDValue Chain = MSC->getChain();
6253
6254   EVT MemoryVT = MSC->getMemoryVT();
6255   unsigned Alignment = MSC->getOriginalAlignment();
6256
6257   EVT LoMemVT, HiMemVT;
6258   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6259
6260   SDValue DataLo, DataHi;
6261   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6262
6263   SDValue BasePtr = MSC->getBasePtr();
6264   SDValue IndexLo, IndexHi;
6265   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6266
6267   MachineMemOperand *MMO = DAG.getMachineFunction().
6268     getMachineMemOperand(MSC->getPointerInfo(),
6269                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6270                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6271
6272   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6273   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6274                             DL, OpsLo, MMO);
6275
6276   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6277   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6278                             DL, OpsHi, MMO);
6279
6280   AddToWorklist(Lo.getNode());
6281   AddToWorklist(Hi.getNode());
6282
6283   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6284 }
6285
6286 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6287
6288   if (Level >= AfterLegalizeTypes)
6289     return SDValue();
6290
6291   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6292   SDValue Mask = MST->getMask();
6293   SDValue Data  = MST->getValue();
6294   EVT VT = Data.getValueType();
6295   SDLoc DL(N);
6296
6297   // If the MSTORE data type requires splitting and the mask is provided by a
6298   // SETCC, then split both nodes and its operands before legalization. This
6299   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6300   // and enables future optimizations (e.g. min/max pattern matching on X86).
6301   if (Mask.getOpcode() == ISD::SETCC) {
6302
6303     // Check if any splitting is required.
6304     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6305         TargetLowering::TypeSplitVector)
6306       return SDValue();
6307
6308     SDValue MaskLo, MaskHi, Lo, Hi;
6309     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6310
6311     SDValue Chain = MST->getChain();
6312     SDValue Ptr   = MST->getBasePtr();
6313
6314     EVT MemoryVT = MST->getMemoryVT();
6315     unsigned Alignment = MST->getOriginalAlignment();
6316
6317     // if Alignment is equal to the vector size,
6318     // take the half of it for the second part
6319     unsigned SecondHalfAlignment =
6320       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6321
6322     EVT LoMemVT, HiMemVT;
6323     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6324
6325     SDValue DataLo, DataHi;
6326     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6327
6328     MachineMemOperand *MMO = DAG.getMachineFunction().
6329       getMachineMemOperand(MST->getPointerInfo(),
6330                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6331                            Alignment, MST->getAAInfo(), MST->getRanges());
6332
6333     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6334                             MST->isTruncatingStore(),
6335                             MST->isCompressingStore());
6336
6337     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6338                                      MST->isCompressingStore());
6339
6340     MMO = DAG.getMachineFunction().
6341       getMachineMemOperand(MST->getPointerInfo(),
6342                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6343                            SecondHalfAlignment, MST->getAAInfo(),
6344                            MST->getRanges());
6345
6346     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6347                             MST->isTruncatingStore(),
6348                             MST->isCompressingStore());
6349
6350     AddToWorklist(Lo.getNode());
6351     AddToWorklist(Hi.getNode());
6352
6353     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6354   }
6355   return SDValue();
6356 }
6357
6358 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6359
6360   if (Level >= AfterLegalizeTypes)
6361     return SDValue();
6362
6363   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6364   SDValue Mask = MGT->getMask();
6365   SDLoc DL(N);
6366
6367   // If the MGATHER result requires splitting and the mask is provided by a
6368   // SETCC, then split both nodes and its operands before legalization. This
6369   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6370   // and enables future optimizations (e.g. min/max pattern matching on X86).
6371
6372   if (Mask.getOpcode() != ISD::SETCC)
6373     return SDValue();
6374
6375   EVT VT = N->getValueType(0);
6376
6377   // Check if any splitting is required.
6378   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6379       TargetLowering::TypeSplitVector)
6380     return SDValue();
6381
6382   SDValue MaskLo, MaskHi, Lo, Hi;
6383   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6384
6385   SDValue Src0 = MGT->getValue();
6386   SDValue Src0Lo, Src0Hi;
6387   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6388
6389   EVT LoVT, HiVT;
6390   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6391
6392   SDValue Chain = MGT->getChain();
6393   EVT MemoryVT = MGT->getMemoryVT();
6394   unsigned Alignment = MGT->getOriginalAlignment();
6395
6396   EVT LoMemVT, HiMemVT;
6397   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6398
6399   SDValue BasePtr = MGT->getBasePtr();
6400   SDValue Index = MGT->getIndex();
6401   SDValue IndexLo, IndexHi;
6402   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6403
6404   MachineMemOperand *MMO = DAG.getMachineFunction().
6405     getMachineMemOperand(MGT->getPointerInfo(),
6406                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6407                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6408
6409   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6410   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6411                             MMO);
6412
6413   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6414   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6415                             MMO);
6416
6417   AddToWorklist(Lo.getNode());
6418   AddToWorklist(Hi.getNode());
6419
6420   // Build a factor node to remember that this load is independent of the
6421   // other one.
6422   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6423                       Hi.getValue(1));
6424
6425   // Legalized the chain result - switch anything that used the old chain to
6426   // use the new one.
6427   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6428
6429   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6430
6431   SDValue RetOps[] = { GatherRes, Chain };
6432   return DAG.getMergeValues(RetOps, DL);
6433 }
6434
6435 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6436
6437   if (Level >= AfterLegalizeTypes)
6438     return SDValue();
6439
6440   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6441   SDValue Mask = MLD->getMask();
6442   SDLoc DL(N);
6443
6444   // If the MLOAD result requires splitting and the mask is provided by a
6445   // SETCC, then split both nodes and its operands before legalization. This
6446   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6447   // and enables future optimizations (e.g. min/max pattern matching on X86).
6448
6449   if (Mask.getOpcode() == ISD::SETCC) {
6450     EVT VT = N->getValueType(0);
6451
6452     // Check if any splitting is required.
6453     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6454         TargetLowering::TypeSplitVector)
6455       return SDValue();
6456
6457     SDValue MaskLo, MaskHi, Lo, Hi;
6458     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6459
6460     SDValue Src0 = MLD->getSrc0();
6461     SDValue Src0Lo, Src0Hi;
6462     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6463
6464     EVT LoVT, HiVT;
6465     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6466
6467     SDValue Chain = MLD->getChain();
6468     SDValue Ptr   = MLD->getBasePtr();
6469     EVT MemoryVT = MLD->getMemoryVT();
6470     unsigned Alignment = MLD->getOriginalAlignment();
6471
6472     // if Alignment is equal to the vector size,
6473     // take the half of it for the second part
6474     unsigned SecondHalfAlignment =
6475       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6476          Alignment/2 : Alignment;
6477
6478     EVT LoMemVT, HiMemVT;
6479     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6480
6481     MachineMemOperand *MMO = DAG.getMachineFunction().
6482     getMachineMemOperand(MLD->getPointerInfo(),
6483                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6484                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6485
6486     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6487                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6488
6489     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6490                                      MLD->isExpandingLoad());
6491
6492     MMO = DAG.getMachineFunction().
6493     getMachineMemOperand(MLD->getPointerInfo(),
6494                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6495                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6496
6497     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6498                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6499
6500     AddToWorklist(Lo.getNode());
6501     AddToWorklist(Hi.getNode());
6502
6503     // Build a factor node to remember that this load is independent of the
6504     // other one.
6505     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6506                         Hi.getValue(1));
6507
6508     // Legalized the chain result - switch anything that used the old chain to
6509     // use the new one.
6510     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6511
6512     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6513
6514     SDValue RetOps[] = { LoadRes, Chain };
6515     return DAG.getMergeValues(RetOps, DL);
6516   }
6517   return SDValue();
6518 }
6519
6520 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6521   SDValue N0 = N->getOperand(0);
6522   SDValue N1 = N->getOperand(1);
6523   SDValue N2 = N->getOperand(2);
6524   SDLoc DL(N);
6525
6526   // fold (vselect C, X, X) -> X
6527   if (N1 == N2)
6528     return N1;
6529
6530   // Canonicalize integer abs.
6531   // vselect (setg[te] X,  0),  X, -X ->
6532   // vselect (setgt    X, -1),  X, -X ->
6533   // vselect (setl[te] X,  0), -X,  X ->
6534   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6535   if (N0.getOpcode() == ISD::SETCC) {
6536     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6537     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6538     bool isAbs = false;
6539     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6540
6541     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6542          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6543         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6544       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6545     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6546              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6547       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6548
6549     if (isAbs) {
6550       EVT VT = LHS.getValueType();
6551       SDValue Shift = DAG.getNode(
6552           ISD::SRA, DL, VT, LHS,
6553           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6554       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6555       AddToWorklist(Shift.getNode());
6556       AddToWorklist(Add.getNode());
6557       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6558     }
6559   }
6560
6561   if (SimplifySelectOps(N, N1, N2))
6562     return SDValue(N, 0);  // Don't revisit N.
6563
6564   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6565   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6566     return N1;
6567   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6568   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6569     return N2;
6570
6571   // The ConvertSelectToConcatVector function is assuming both the above
6572   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6573   // and addressed.
6574   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6575       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6576       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6577     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6578       return CV;
6579   }
6580
6581   return SDValue();
6582 }
6583
6584 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6585   SDValue N0 = N->getOperand(0);
6586   SDValue N1 = N->getOperand(1);
6587   SDValue N2 = N->getOperand(2);
6588   SDValue N3 = N->getOperand(3);
6589   SDValue N4 = N->getOperand(4);
6590   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6591
6592   // fold select_cc lhs, rhs, x, x, cc -> x
6593   if (N2 == N3)
6594     return N2;
6595
6596   // Determine if the condition we're dealing with is constant
6597   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6598                                   CC, SDLoc(N), false)) {
6599     AddToWorklist(SCC.getNode());
6600
6601     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6602       if (!SCCC->isNullValue())
6603         return N2;    // cond always true -> true val
6604       else
6605         return N3;    // cond always false -> false val
6606     } else if (SCC->isUndef()) {
6607       // When the condition is UNDEF, just return the first operand. This is
6608       // coherent the DAG creation, no setcc node is created in this case
6609       return N2;
6610     } else if (SCC.getOpcode() == ISD::SETCC) {
6611       // Fold to a simpler select_cc
6612       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6613                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6614                          SCC.getOperand(2));
6615     }
6616   }
6617
6618   // If we can fold this based on the true/false value, do so.
6619   if (SimplifySelectOps(N, N2, N3))
6620     return SDValue(N, 0);  // Don't revisit N.
6621
6622   // fold select_cc into other things, such as min/max/abs
6623   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6624 }
6625
6626 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6627   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6628                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6629                        SDLoc(N));
6630 }
6631
6632 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6633   SDValue LHS = N->getOperand(0);
6634   SDValue RHS = N->getOperand(1);
6635   SDValue Carry = N->getOperand(2);
6636   SDValue Cond = N->getOperand(3);
6637
6638   // If Carry is false, fold to a regular SETCC.
6639   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6640     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6641
6642   return SDValue();
6643 }
6644
6645 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6646 /// a build_vector of constants.
6647 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6648 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6649 /// Vector extends are not folded if operations are legal; this is to
6650 /// avoid introducing illegal build_vector dag nodes.
6651 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6652                                          SelectionDAG &DAG, bool LegalTypes,
6653                                          bool LegalOperations) {
6654   unsigned Opcode = N->getOpcode();
6655   SDValue N0 = N->getOperand(0);
6656   EVT VT = N->getValueType(0);
6657
6658   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6659          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6660          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6661          && "Expected EXTEND dag node in input!");
6662
6663   // fold (sext c1) -> c1
6664   // fold (zext c1) -> c1
6665   // fold (aext c1) -> c1
6666   if (isa<ConstantSDNode>(N0))
6667     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6668
6669   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6670   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6671   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6672   EVT SVT = VT.getScalarType();
6673   if (!(VT.isVector() &&
6674       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6675       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6676     return nullptr;
6677
6678   // We can fold this node into a build_vector.
6679   unsigned VTBits = SVT.getSizeInBits();
6680   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6681   SmallVector<SDValue, 8> Elts;
6682   unsigned NumElts = VT.getVectorNumElements();
6683   SDLoc DL(N);
6684
6685   for (unsigned i=0; i != NumElts; ++i) {
6686     SDValue Op = N0->getOperand(i);
6687     if (Op->isUndef()) {
6688       Elts.push_back(DAG.getUNDEF(SVT));
6689       continue;
6690     }
6691
6692     SDLoc DL(Op);
6693     // Get the constant value and if needed trunc it to the size of the type.
6694     // Nodes like build_vector might have constants wider than the scalar type.
6695     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6696     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6697       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6698     else
6699       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6700   }
6701
6702   return DAG.getBuildVector(VT, DL, Elts).getNode();
6703 }
6704
6705 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6706 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6707 // transformation. Returns true if extension are possible and the above
6708 // mentioned transformation is profitable.
6709 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6710                                     unsigned ExtOpc,
6711                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6712                                     const TargetLowering &TLI) {
6713   bool HasCopyToRegUses = false;
6714   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6715   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6716                             UE = N0.getNode()->use_end();
6717        UI != UE; ++UI) {
6718     SDNode *User = *UI;
6719     if (User == N)
6720       continue;
6721     if (UI.getUse().getResNo() != N0.getResNo())
6722       continue;
6723     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6724     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6725       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6726       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6727         // Sign bits will be lost after a zext.
6728         return false;
6729       bool Add = false;
6730       for (unsigned i = 0; i != 2; ++i) {
6731         SDValue UseOp = User->getOperand(i);
6732         if (UseOp == N0)
6733           continue;
6734         if (!isa<ConstantSDNode>(UseOp))
6735           return false;
6736         Add = true;
6737       }
6738       if (Add)
6739         ExtendNodes.push_back(User);
6740       continue;
6741     }
6742     // If truncates aren't free and there are users we can't
6743     // extend, it isn't worthwhile.
6744     if (!isTruncFree)
6745       return false;
6746     // Remember if this value is live-out.
6747     if (User->getOpcode() == ISD::CopyToReg)
6748       HasCopyToRegUses = true;
6749   }
6750
6751   if (HasCopyToRegUses) {
6752     bool BothLiveOut = false;
6753     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6754          UI != UE; ++UI) {
6755       SDUse &Use = UI.getUse();
6756       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6757         BothLiveOut = true;
6758         break;
6759       }
6760     }
6761     if (BothLiveOut)
6762       // Both unextended and extended values are live out. There had better be
6763       // a good reason for the transformation.
6764       return ExtendNodes.size();
6765   }
6766   return true;
6767 }
6768
6769 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6770                                   SDValue Trunc, SDValue ExtLoad,
6771                                   const SDLoc &DL, ISD::NodeType ExtType) {
6772   // Extend SetCC uses if necessary.
6773   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6774     SDNode *SetCC = SetCCs[i];
6775     SmallVector<SDValue, 4> Ops;
6776
6777     for (unsigned j = 0; j != 2; ++j) {
6778       SDValue SOp = SetCC->getOperand(j);
6779       if (SOp == Trunc)
6780         Ops.push_back(ExtLoad);
6781       else
6782         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6783     }
6784
6785     Ops.push_back(SetCC->getOperand(2));
6786     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6787   }
6788 }
6789
6790 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6791 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6792   SDValue N0 = N->getOperand(0);
6793   EVT DstVT = N->getValueType(0);
6794   EVT SrcVT = N0.getValueType();
6795
6796   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6797           N->getOpcode() == ISD::ZERO_EXTEND) &&
6798          "Unexpected node type (not an extend)!");
6799
6800   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6801   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6802   //   (v8i32 (sext (v8i16 (load x))))
6803   // into:
6804   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6805   //                          (v4i32 (sextload (x + 16)))))
6806   // Where uses of the original load, i.e.:
6807   //   (v8i16 (load x))
6808   // are replaced with:
6809   //   (v8i16 (truncate
6810   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6811   //                            (v4i32 (sextload (x + 16)))))))
6812   //
6813   // This combine is only applicable to illegal, but splittable, vectors.
6814   // All legal types, and illegal non-vector types, are handled elsewhere.
6815   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6816   //
6817   if (N0->getOpcode() != ISD::LOAD)
6818     return SDValue();
6819
6820   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6821
6822   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6823       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6824       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6825     return SDValue();
6826
6827   SmallVector<SDNode *, 4> SetCCs;
6828   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6829     return SDValue();
6830
6831   ISD::LoadExtType ExtType =
6832       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6833
6834   // Try to split the vector types to get down to legal types.
6835   EVT SplitSrcVT = SrcVT;
6836   EVT SplitDstVT = DstVT;
6837   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6838          SplitSrcVT.getVectorNumElements() > 1) {
6839     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6840     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6841   }
6842
6843   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6844     return SDValue();
6845
6846   SDLoc DL(N);
6847   const unsigned NumSplits =
6848       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6849   const unsigned Stride = SplitSrcVT.getStoreSize();
6850   SmallVector<SDValue, 4> Loads;
6851   SmallVector<SDValue, 4> Chains;
6852
6853   SDValue BasePtr = LN0->getBasePtr();
6854   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6855     const unsigned Offset = Idx * Stride;
6856     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6857
6858     SDValue SplitLoad = DAG.getExtLoad(
6859         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6860         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6861         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6862
6863     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6864                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6865
6866     Loads.push_back(SplitLoad.getValue(0));
6867     Chains.push_back(SplitLoad.getValue(1));
6868   }
6869
6870   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6871   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6872
6873   // Simplify TF.
6874   AddToWorklist(NewChain.getNode());
6875
6876   CombineTo(N, NewValue);
6877
6878   // Replace uses of the original load (before extension)
6879   // with a truncate of the concatenated sextloaded vectors.
6880   SDValue Trunc =
6881       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6882   CombineTo(N0.getNode(), Trunc, NewChain);
6883   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6884                   (ISD::NodeType)N->getOpcode());
6885   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6886 }
6887
6888 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6889   SDValue N0 = N->getOperand(0);
6890   EVT VT = N->getValueType(0);
6891   SDLoc DL(N);
6892
6893   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6894                                               LegalOperations))
6895     return SDValue(Res, 0);
6896
6897   // fold (sext (sext x)) -> (sext x)
6898   // fold (sext (aext x)) -> (sext x)
6899   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6900     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
6901
6902   if (N0.getOpcode() == ISD::TRUNCATE) {
6903     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6904     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6905     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6906       SDNode *oye = N0.getOperand(0).getNode();
6907       if (NarrowLoad.getNode() != N0.getNode()) {
6908         CombineTo(N0.getNode(), NarrowLoad);
6909         // CombineTo deleted the truncate, if needed, but not what's under it.
6910         AddToWorklist(oye);
6911       }
6912       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6913     }
6914
6915     // See if the value being truncated is already sign extended.  If so, just
6916     // eliminate the trunc/sext pair.
6917     SDValue Op = N0.getOperand(0);
6918     unsigned OpBits   = Op.getScalarValueSizeInBits();
6919     unsigned MidBits  = N0.getScalarValueSizeInBits();
6920     unsigned DestBits = VT.getScalarSizeInBits();
6921     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6922
6923     if (OpBits == DestBits) {
6924       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6925       // bits, it is already ready.
6926       if (NumSignBits > DestBits-MidBits)
6927         return Op;
6928     } else if (OpBits < DestBits) {
6929       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6930       // bits, just sext from i32.
6931       if (NumSignBits > OpBits-MidBits)
6932         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
6933     } else {
6934       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6935       // bits, just truncate to i32.
6936       if (NumSignBits > OpBits-MidBits)
6937         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
6938     }
6939
6940     // fold (sext (truncate x)) -> (sextinreg x).
6941     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6942                                                  N0.getValueType())) {
6943       if (OpBits < DestBits)
6944         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6945       else if (OpBits > DestBits)
6946         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6947       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
6948                          DAG.getValueType(N0.getValueType()));
6949     }
6950   }
6951
6952   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6953   // Only generate vector extloads when 1) they're legal, and 2) they are
6954   // deemed desirable by the target.
6955   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6956       ((!LegalOperations && !VT.isVector() &&
6957         !cast<LoadSDNode>(N0)->isVolatile()) ||
6958        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6959     bool DoXform = true;
6960     SmallVector<SDNode*, 4> SetCCs;
6961     if (!N0.hasOneUse())
6962       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6963     if (VT.isVector())
6964       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6965     if (DoXform) {
6966       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6967       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
6968                                        LN0->getBasePtr(), N0.getValueType(),
6969                                        LN0->getMemOperand());
6970       CombineTo(N, ExtLoad);
6971       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6972                                   N0.getValueType(), ExtLoad);
6973       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6974       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
6975       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6976     }
6977   }
6978
6979   // fold (sext (load x)) to multiple smaller sextloads.
6980   // Only on illegal but splittable vectors.
6981   if (SDValue ExtLoad = CombineExtLoad(N))
6982     return ExtLoad;
6983
6984   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6985   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6986   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6987       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6988     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6989     EVT MemVT = LN0->getMemoryVT();
6990     if ((!LegalOperations && !LN0->isVolatile()) ||
6991         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6992       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
6993                                        LN0->getBasePtr(), MemVT,
6994                                        LN0->getMemOperand());
6995       CombineTo(N, ExtLoad);
6996       CombineTo(N0.getNode(),
6997                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6998                             N0.getValueType(), ExtLoad),
6999                 ExtLoad.getValue(1));
7000       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7001     }
7002   }
7003
7004   // fold (sext (and/or/xor (load x), cst)) ->
7005   //      (and/or/xor (sextload x), (sext cst))
7006   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7007        N0.getOpcode() == ISD::XOR) &&
7008       isa<LoadSDNode>(N0.getOperand(0)) &&
7009       N0.getOperand(1).getOpcode() == ISD::Constant &&
7010       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7011       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7012     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7013     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7014       bool DoXform = true;
7015       SmallVector<SDNode*, 4> SetCCs;
7016       if (!N0.hasOneUse())
7017         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7018                                           SetCCs, TLI);
7019       if (DoXform) {
7020         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7021                                          LN0->getChain(), LN0->getBasePtr(),
7022                                          LN0->getMemoryVT(),
7023                                          LN0->getMemOperand());
7024         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7025         Mask = Mask.sext(VT.getSizeInBits());
7026         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7027                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7028         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7029                                     SDLoc(N0.getOperand(0)),
7030                                     N0.getOperand(0).getValueType(), ExtLoad);
7031         CombineTo(N, And);
7032         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7033         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7034         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7035       }
7036     }
7037   }
7038
7039   if (N0.getOpcode() == ISD::SETCC) {
7040     SDValue N00 = N0.getOperand(0);
7041     SDValue N01 = N0.getOperand(1);
7042     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7043     EVT N00VT = N0.getOperand(0).getValueType();
7044
7045     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7046     // Only do this before legalize for now.
7047     if (VT.isVector() && !LegalOperations &&
7048         TLI.getBooleanContents(N00VT) ==
7049             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7050       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7051       // of the same size as the compared operands. Only optimize sext(setcc())
7052       // if this is the case.
7053       EVT SVT = getSetCCResultType(N00VT);
7054
7055       // We know that the # elements of the results is the same as the
7056       // # elements of the compare (and the # elements of the compare result
7057       // for that matter).  Check to see that they are the same size.  If so,
7058       // we know that the element size of the sext'd result matches the
7059       // element size of the compare operands.
7060       if (VT.getSizeInBits() == SVT.getSizeInBits())
7061         return DAG.getSetCC(DL, VT, N00, N01, CC);
7062
7063       // If the desired elements are smaller or larger than the source
7064       // elements, we can use a matching integer vector type and then
7065       // truncate/sign extend.
7066       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7067       if (SVT == MatchingVecType) {
7068         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7069         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7070       }
7071     }
7072
7073     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7074     // Here, T can be 1 or -1, depending on the type of the setcc and
7075     // getBooleanContents().
7076     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7077
7078     // To determine the "true" side of the select, we need to know the high bit
7079     // of the value returned by the setcc if it evaluates to true.
7080     // If the type of the setcc is i1, then the true case of the select is just
7081     // sext(i1 1), that is, -1.
7082     // If the type of the setcc is larger (say, i8) then the value of the high
7083     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7084     // of the appropriate width.
7085     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7086                                            : TLI.getConstTrueVal(DAG, VT, DL);
7087     SDValue Zero = DAG.getConstant(0, DL, VT);
7088     if (SDValue SCC =
7089             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7090       return SCC;
7091
7092     if (!VT.isVector()) {
7093       EVT SetCCVT = getSetCCResultType(N00VT);
7094       // Don't do this transform for i1 because there's a select transform
7095       // that would reverse it.
7096       // TODO: We should not do this transform at all without a target hook
7097       // because a sext is likely cheaper than a select?
7098       if (SetCCVT.getScalarSizeInBits() != 1 &&
7099           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7100         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7101         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7102       }
7103     }
7104   }
7105
7106   // fold (sext x) -> (zext x) if the sign bit is known zero.
7107   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7108       DAG.SignBitIsZero(N0))
7109     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7110
7111   return SDValue();
7112 }
7113
7114 // isTruncateOf - If N is a truncate of some other value, return true, record
7115 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
7116 // This function computes KnownZero to avoid a duplicated call to
7117 // computeKnownBits in the caller.
7118 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7119                          APInt &KnownZero) {
7120   APInt KnownOne;
7121   if (N->getOpcode() == ISD::TRUNCATE) {
7122     Op = N->getOperand(0);
7123     DAG.computeKnownBits(Op, KnownZero, KnownOne);
7124     return true;
7125   }
7126
7127   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7128       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7129     return false;
7130
7131   SDValue Op0 = N->getOperand(0);
7132   SDValue Op1 = N->getOperand(1);
7133   assert(Op0.getValueType() == Op1.getValueType());
7134
7135   if (isNullConstant(Op0))
7136     Op = Op1;
7137   else if (isNullConstant(Op1))
7138     Op = Op0;
7139   else
7140     return false;
7141
7142   DAG.computeKnownBits(Op, KnownZero, KnownOne);
7143
7144   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
7145     return false;
7146
7147   return true;
7148 }
7149
7150 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7151   SDValue N0 = N->getOperand(0);
7152   EVT VT = N->getValueType(0);
7153
7154   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7155                                               LegalOperations))
7156     return SDValue(Res, 0);
7157
7158   // fold (zext (zext x)) -> (zext x)
7159   // fold (zext (aext x)) -> (zext x)
7160   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7161     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7162                        N0.getOperand(0));
7163
7164   // fold (zext (truncate x)) -> (zext x) or
7165   //      (zext (truncate x)) -> (truncate x)
7166   // This is valid when the truncated bits of x are already zero.
7167   // FIXME: We should extend this to work for vectors too.
7168   SDValue Op;
7169   APInt KnownZero;
7170   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
7171     APInt TruncatedBits =
7172       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7173       APInt(Op.getValueSizeInBits(), 0) :
7174       APInt::getBitsSet(Op.getValueSizeInBits(),
7175                         N0.getValueSizeInBits(),
7176                         std::min(Op.getValueSizeInBits(),
7177                                  VT.getSizeInBits()));
7178     if (TruncatedBits == (KnownZero & TruncatedBits)) {
7179       if (VT.bitsGT(Op.getValueType()))
7180         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
7181       if (VT.bitsLT(Op.getValueType()))
7182         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7183
7184       return Op;
7185     }
7186   }
7187
7188   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7189   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7190   if (N0.getOpcode() == ISD::TRUNCATE) {
7191     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7192       SDNode *oye = N0.getOperand(0).getNode();
7193       if (NarrowLoad.getNode() != N0.getNode()) {
7194         CombineTo(N0.getNode(), NarrowLoad);
7195         // CombineTo deleted the truncate, if needed, but not what's under it.
7196         AddToWorklist(oye);
7197       }
7198       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7199     }
7200   }
7201
7202   // fold (zext (truncate x)) -> (and x, mask)
7203   if (N0.getOpcode() == ISD::TRUNCATE) {
7204     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7205     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7206     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7207       SDNode *oye = N0.getOperand(0).getNode();
7208       if (NarrowLoad.getNode() != N0.getNode()) {
7209         CombineTo(N0.getNode(), NarrowLoad);
7210         // CombineTo deleted the truncate, if needed, but not what's under it.
7211         AddToWorklist(oye);
7212       }
7213       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7214     }
7215
7216     EVT SrcVT = N0.getOperand(0).getValueType();
7217     EVT MinVT = N0.getValueType();
7218
7219     // Try to mask before the extension to avoid having to generate a larger mask,
7220     // possibly over several sub-vectors.
7221     if (SrcVT.bitsLT(VT)) {
7222       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7223                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7224         SDValue Op = N0.getOperand(0);
7225         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7226         AddToWorklist(Op.getNode());
7227         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7228       }
7229     }
7230
7231     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7232       SDValue Op = N0.getOperand(0);
7233       if (SrcVT.bitsLT(VT)) {
7234         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
7235         AddToWorklist(Op.getNode());
7236       } else if (SrcVT.bitsGT(VT)) {
7237         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7238         AddToWorklist(Op.getNode());
7239       }
7240       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7241     }
7242   }
7243
7244   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7245   // if either of the casts is not free.
7246   if (N0.getOpcode() == ISD::AND &&
7247       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7248       N0.getOperand(1).getOpcode() == ISD::Constant &&
7249       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7250                            N0.getValueType()) ||
7251        !TLI.isZExtFree(N0.getValueType(), VT))) {
7252     SDValue X = N0.getOperand(0).getOperand(0);
7253     if (X.getValueType().bitsLT(VT)) {
7254       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
7255     } else if (X.getValueType().bitsGT(VT)) {
7256       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7257     }
7258     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7259     Mask = Mask.zext(VT.getSizeInBits());
7260     SDLoc DL(N);
7261     return DAG.getNode(ISD::AND, DL, VT,
7262                        X, DAG.getConstant(Mask, DL, VT));
7263   }
7264
7265   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7266   // Only generate vector extloads when 1) they're legal, and 2) they are
7267   // deemed desirable by the target.
7268   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7269       ((!LegalOperations && !VT.isVector() &&
7270         !cast<LoadSDNode>(N0)->isVolatile()) ||
7271        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7272     bool DoXform = true;
7273     SmallVector<SDNode*, 4> SetCCs;
7274     if (!N0.hasOneUse())
7275       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7276     if (VT.isVector())
7277       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7278     if (DoXform) {
7279       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7280       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7281                                        LN0->getChain(),
7282                                        LN0->getBasePtr(), N0.getValueType(),
7283                                        LN0->getMemOperand());
7284
7285       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7286                                   N0.getValueType(), ExtLoad);
7287       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7288
7289       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7290                       ISD::ZERO_EXTEND);
7291       CombineTo(N, ExtLoad);
7292       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7293     }
7294   }
7295
7296   // fold (zext (load x)) to multiple smaller zextloads.
7297   // Only on illegal but splittable vectors.
7298   if (SDValue ExtLoad = CombineExtLoad(N))
7299     return ExtLoad;
7300
7301   // fold (zext (and/or/xor (load x), cst)) ->
7302   //      (and/or/xor (zextload x), (zext cst))
7303   // Unless (and (load x) cst) will match as a zextload already and has
7304   // additional users.
7305   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7306        N0.getOpcode() == ISD::XOR) &&
7307       isa<LoadSDNode>(N0.getOperand(0)) &&
7308       N0.getOperand(1).getOpcode() == ISD::Constant &&
7309       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7310       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7311     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7312     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7313       bool DoXform = true;
7314       SmallVector<SDNode*, 4> SetCCs;
7315       if (!N0.hasOneUse()) {
7316         if (N0.getOpcode() == ISD::AND) {
7317           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7318           auto NarrowLoad = false;
7319           EVT LoadResultTy = AndC->getValueType(0);
7320           EVT ExtVT, LoadedVT;
7321           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7322                                NarrowLoad))
7323             DoXform = false;
7324         }
7325         if (DoXform)
7326           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7327                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7328       }
7329       if (DoXform) {
7330         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7331                                          LN0->getChain(), LN0->getBasePtr(),
7332                                          LN0->getMemoryVT(),
7333                                          LN0->getMemOperand());
7334         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7335         Mask = Mask.zext(VT.getSizeInBits());
7336         SDLoc DL(N);
7337         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7338                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7339         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7340                                     SDLoc(N0.getOperand(0)),
7341                                     N0.getOperand(0).getValueType(), ExtLoad);
7342         CombineTo(N, And);
7343         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7344         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
7345                         ISD::ZERO_EXTEND);
7346         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7347       }
7348     }
7349   }
7350
7351   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7352   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7353   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7354       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7355     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7356     EVT MemVT = LN0->getMemoryVT();
7357     if ((!LegalOperations && !LN0->isVolatile()) ||
7358         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7359       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7360                                        LN0->getChain(),
7361                                        LN0->getBasePtr(), MemVT,
7362                                        LN0->getMemOperand());
7363       CombineTo(N, ExtLoad);
7364       CombineTo(N0.getNode(),
7365                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7366                             ExtLoad),
7367                 ExtLoad.getValue(1));
7368       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7369     }
7370   }
7371
7372   if (N0.getOpcode() == ISD::SETCC) {
7373     // Only do this before legalize for now.
7374     if (!LegalOperations && VT.isVector() &&
7375         N0.getValueType().getVectorElementType() == MVT::i1) {
7376       EVT N00VT = N0.getOperand(0).getValueType();
7377       if (getSetCCResultType(N00VT) == N0.getValueType())
7378         return SDValue();
7379
7380       // We know that the # elements of the results is the same as the #
7381       // elements of the compare (and the # elements of the compare result for
7382       // that matter). Check to see that they are the same size. If so, we know
7383       // that the element size of the sext'd result matches the element size of
7384       // the compare operands.
7385       SDLoc DL(N);
7386       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7387       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7388         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7389         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7390                                      N0.getOperand(1), N0.getOperand(2));
7391         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7392       }
7393
7394       // If the desired elements are smaller or larger than the source
7395       // elements we can use a matching integer vector type and then
7396       // truncate/sign extend.
7397       EVT MatchingElementType = EVT::getIntegerVT(
7398           *DAG.getContext(), N00VT.getScalarSizeInBits());
7399       EVT MatchingVectorType = EVT::getVectorVT(
7400           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7401       SDValue VsetCC =
7402           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7403                       N0.getOperand(1), N0.getOperand(2));
7404       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7405                          VecOnes);
7406     }
7407
7408     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7409     SDLoc DL(N);
7410     if (SDValue SCC = SimplifySelectCC(
7411             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7412             DAG.getConstant(0, DL, VT),
7413             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7414       return SCC;
7415   }
7416
7417   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7418   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7419       isa<ConstantSDNode>(N0.getOperand(1)) &&
7420       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7421       N0.hasOneUse()) {
7422     SDValue ShAmt = N0.getOperand(1);
7423     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7424     if (N0.getOpcode() == ISD::SHL) {
7425       SDValue InnerZExt = N0.getOperand(0);
7426       // If the original shl may be shifting out bits, do not perform this
7427       // transformation.
7428       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7429         InnerZExt.getOperand(0).getValueSizeInBits();
7430       if (ShAmtVal > KnownZeroBits)
7431         return SDValue();
7432     }
7433
7434     SDLoc DL(N);
7435
7436     // Ensure that the shift amount is wide enough for the shifted value.
7437     if (VT.getSizeInBits() >= 256)
7438       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7439
7440     return DAG.getNode(N0.getOpcode(), DL, VT,
7441                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7442                        ShAmt);
7443   }
7444
7445   return SDValue();
7446 }
7447
7448 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7449   SDValue N0 = N->getOperand(0);
7450   EVT VT = N->getValueType(0);
7451
7452   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7453                                               LegalOperations))
7454     return SDValue(Res, 0);
7455
7456   // fold (aext (aext x)) -> (aext x)
7457   // fold (aext (zext x)) -> (zext x)
7458   // fold (aext (sext x)) -> (sext x)
7459   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7460       N0.getOpcode() == ISD::ZERO_EXTEND ||
7461       N0.getOpcode() == ISD::SIGN_EXTEND)
7462     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7463
7464   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7465   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7466   if (N0.getOpcode() == ISD::TRUNCATE) {
7467     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7468       SDNode *oye = N0.getOperand(0).getNode();
7469       if (NarrowLoad.getNode() != N0.getNode()) {
7470         CombineTo(N0.getNode(), NarrowLoad);
7471         // CombineTo deleted the truncate, if needed, but not what's under it.
7472         AddToWorklist(oye);
7473       }
7474       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7475     }
7476   }
7477
7478   // fold (aext (truncate x))
7479   if (N0.getOpcode() == ISD::TRUNCATE) {
7480     SDValue TruncOp = N0.getOperand(0);
7481     if (TruncOp.getValueType() == VT)
7482       return TruncOp; // x iff x size == zext size.
7483     if (TruncOp.getValueType().bitsGT(VT))
7484       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
7485     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
7486   }
7487
7488   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7489   // if the trunc is not free.
7490   if (N0.getOpcode() == ISD::AND &&
7491       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7492       N0.getOperand(1).getOpcode() == ISD::Constant &&
7493       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7494                           N0.getValueType())) {
7495     SDLoc DL(N);
7496     SDValue X = N0.getOperand(0).getOperand(0);
7497     if (X.getValueType().bitsLT(VT)) {
7498       X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
7499     } else if (X.getValueType().bitsGT(VT)) {
7500       X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
7501     }
7502     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7503     Mask = Mask.zext(VT.getSizeInBits());
7504     return DAG.getNode(ISD::AND, DL, VT,
7505                        X, DAG.getConstant(Mask, DL, VT));
7506   }
7507
7508   // fold (aext (load x)) -> (aext (truncate (extload x)))
7509   // None of the supported targets knows how to perform load and any_ext
7510   // on vectors in one instruction.  We only perform this transformation on
7511   // scalars.
7512   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7513       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7514       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7515     bool DoXform = true;
7516     SmallVector<SDNode*, 4> SetCCs;
7517     if (!N0.hasOneUse())
7518       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7519     if (DoXform) {
7520       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7521       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7522                                        LN0->getChain(),
7523                                        LN0->getBasePtr(), N0.getValueType(),
7524                                        LN0->getMemOperand());
7525       CombineTo(N, ExtLoad);
7526       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7527                                   N0.getValueType(), ExtLoad);
7528       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7529       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7530                       ISD::ANY_EXTEND);
7531       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7532     }
7533   }
7534
7535   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7536   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7537   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7538   if (N0.getOpcode() == ISD::LOAD &&
7539       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7540       N0.hasOneUse()) {
7541     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7542     ISD::LoadExtType ExtType = LN0->getExtensionType();
7543     EVT MemVT = LN0->getMemoryVT();
7544     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7545       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7546                                        VT, LN0->getChain(), LN0->getBasePtr(),
7547                                        MemVT, LN0->getMemOperand());
7548       CombineTo(N, ExtLoad);
7549       CombineTo(N0.getNode(),
7550                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7551                             N0.getValueType(), ExtLoad),
7552                 ExtLoad.getValue(1));
7553       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7554     }
7555   }
7556
7557   if (N0.getOpcode() == ISD::SETCC) {
7558     // For vectors:
7559     // aext(setcc) -> vsetcc
7560     // aext(setcc) -> truncate(vsetcc)
7561     // aext(setcc) -> aext(vsetcc)
7562     // Only do this before legalize for now.
7563     if (VT.isVector() && !LegalOperations) {
7564       EVT N0VT = N0.getOperand(0).getValueType();
7565         // We know that the # elements of the results is the same as the
7566         // # elements of the compare (and the # elements of the compare result
7567         // for that matter).  Check to see that they are the same size.  If so,
7568         // we know that the element size of the sext'd result matches the
7569         // element size of the compare operands.
7570       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7571         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7572                              N0.getOperand(1),
7573                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7574       // If the desired elements are smaller or larger than the source
7575       // elements we can use a matching integer vector type and then
7576       // truncate/any extend
7577       else {
7578         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7579         SDValue VsetCC =
7580           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7581                         N0.getOperand(1),
7582                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7583         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7584       }
7585     }
7586
7587     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7588     SDLoc DL(N);
7589     if (SDValue SCC = SimplifySelectCC(
7590             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7591             DAG.getConstant(0, DL, VT),
7592             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7593       return SCC;
7594   }
7595
7596   return SDValue();
7597 }
7598
7599 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7600   SDValue N0 = N->getOperand(0);
7601   SDValue N1 = N->getOperand(1);
7602   EVT EVT = cast<VTSDNode>(N1)->getVT();
7603
7604   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7605   if (N0.getOpcode() == ISD::AssertZext &&
7606       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7607     return N0;
7608
7609   return SDValue();
7610 }
7611
7612 /// See if the specified operand can be simplified with the knowledge that only
7613 /// the bits specified by Mask are used.  If so, return the simpler operand,
7614 /// otherwise return a null SDValue.
7615 ///
7616 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7617 /// simplify nodes with multiple uses more aggressively.)
7618 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7619   switch (V.getOpcode()) {
7620   default: break;
7621   case ISD::Constant: {
7622     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7623     assert(CV && "Const value should be ConstSDNode.");
7624     const APInt &CVal = CV->getAPIntValue();
7625     APInt NewVal = CVal & Mask;
7626     if (NewVal != CVal)
7627       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7628     break;
7629   }
7630   case ISD::OR:
7631   case ISD::XOR:
7632     // If the LHS or RHS don't contribute bits to the or, drop them.
7633     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7634       return V.getOperand(1);
7635     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7636       return V.getOperand(0);
7637     break;
7638   case ISD::SRL:
7639     // Only look at single-use SRLs.
7640     if (!V.getNode()->hasOneUse())
7641       break;
7642     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7643       // See if we can recursively simplify the LHS.
7644       unsigned Amt = RHSC->getZExtValue();
7645
7646       // Watch out for shift count overflow though.
7647       if (Amt >= Mask.getBitWidth()) break;
7648       APInt NewMask = Mask << Amt;
7649       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7650         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7651                            SimplifyLHS, V.getOperand(1));
7652     }
7653     break;
7654   case ISD::AND: {
7655     // X & -1 -> X (ignoring bits which aren't demanded).
7656     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7657     if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7658       return V.getOperand(0);
7659     break;
7660   }
7661   }
7662   return SDValue();
7663 }
7664
7665 /// If the result of a wider load is shifted to right of N  bits and then
7666 /// truncated to a narrower type and where N is a multiple of number of bits of
7667 /// the narrower type, transform it to a narrower load from address + N / num of
7668 /// bits of new type. If the result is to be extended, also fold the extension
7669 /// to form a extending load.
7670 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7671   unsigned Opc = N->getOpcode();
7672
7673   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7674   SDValue N0 = N->getOperand(0);
7675   EVT VT = N->getValueType(0);
7676   EVT ExtVT = VT;
7677
7678   // This transformation isn't valid for vector loads.
7679   if (VT.isVector())
7680     return SDValue();
7681
7682   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7683   // extended to VT.
7684   if (Opc == ISD::SIGN_EXTEND_INREG) {
7685     ExtType = ISD::SEXTLOAD;
7686     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7687   } else if (Opc == ISD::SRL) {
7688     // Another special-case: SRL is basically zero-extending a narrower value.
7689     ExtType = ISD::ZEXTLOAD;
7690     N0 = SDValue(N, 0);
7691     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7692     if (!N01) return SDValue();
7693     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7694                               VT.getSizeInBits() - N01->getZExtValue());
7695   }
7696   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7697     return SDValue();
7698
7699   unsigned EVTBits = ExtVT.getSizeInBits();
7700
7701   // Do not generate loads of non-round integer types since these can
7702   // be expensive (and would be wrong if the type is not byte sized).
7703   if (!ExtVT.isRound())
7704     return SDValue();
7705
7706   unsigned ShAmt = 0;
7707   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7708     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7709       ShAmt = N01->getZExtValue();
7710       // Is the shift amount a multiple of size of VT?
7711       if ((ShAmt & (EVTBits-1)) == 0) {
7712         N0 = N0.getOperand(0);
7713         // Is the load width a multiple of size of VT?
7714         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7715           return SDValue();
7716       }
7717
7718       // At this point, we must have a load or else we can't do the transform.
7719       if (!isa<LoadSDNode>(N0)) return SDValue();
7720
7721       // Because a SRL must be assumed to *need* to zero-extend the high bits
7722       // (as opposed to anyext the high bits), we can't combine the zextload
7723       // lowering of SRL and an sextload.
7724       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7725         return SDValue();
7726
7727       // If the shift amount is larger than the input type then we're not
7728       // accessing any of the loaded bytes.  If the load was a zextload/extload
7729       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7730       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7731         return SDValue();
7732     }
7733   }
7734
7735   // If the load is shifted left (and the result isn't shifted back right),
7736   // we can fold the truncate through the shift.
7737   unsigned ShLeftAmt = 0;
7738   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7739       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7740     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7741       ShLeftAmt = N01->getZExtValue();
7742       N0 = N0.getOperand(0);
7743     }
7744   }
7745
7746   // If we haven't found a load, we can't narrow it.  Don't transform one with
7747   // multiple uses, this would require adding a new load.
7748   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7749     return SDValue();
7750
7751   // Don't change the width of a volatile load.
7752   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7753   if (LN0->isVolatile())
7754     return SDValue();
7755
7756   // Verify that we are actually reducing a load width here.
7757   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7758     return SDValue();
7759
7760   // For the transform to be legal, the load must produce only two values
7761   // (the value loaded and the chain).  Don't transform a pre-increment
7762   // load, for example, which produces an extra value.  Otherwise the
7763   // transformation is not equivalent, and the downstream logic to replace
7764   // uses gets things wrong.
7765   if (LN0->getNumValues() > 2)
7766     return SDValue();
7767
7768   // If the load that we're shrinking is an extload and we're not just
7769   // discarding the extension we can't simply shrink the load. Bail.
7770   // TODO: It would be possible to merge the extensions in some cases.
7771   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7772       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7773     return SDValue();
7774
7775   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7776     return SDValue();
7777
7778   EVT PtrType = N0.getOperand(1).getValueType();
7779
7780   if (PtrType == MVT::Untyped || PtrType.isExtended())
7781     // It's not possible to generate a constant of extended or untyped type.
7782     return SDValue();
7783
7784   // For big endian targets, we need to adjust the offset to the pointer to
7785   // load the correct bytes.
7786   if (DAG.getDataLayout().isBigEndian()) {
7787     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7788     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7789     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7790   }
7791
7792   uint64_t PtrOff = ShAmt / 8;
7793   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7794   SDLoc DL(LN0);
7795   // The original load itself didn't wrap, so an offset within it doesn't.
7796   SDNodeFlags Flags;
7797   Flags.setNoUnsignedWrap(true);
7798   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7799                                PtrType, LN0->getBasePtr(),
7800                                DAG.getConstant(PtrOff, DL, PtrType),
7801                                &Flags);
7802   AddToWorklist(NewPtr.getNode());
7803
7804   SDValue Load;
7805   if (ExtType == ISD::NON_EXTLOAD)
7806     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7807                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7808                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7809   else
7810     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7811                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7812                           NewAlign, LN0->getMemOperand()->getFlags(),
7813                           LN0->getAAInfo());
7814
7815   // Replace the old load's chain with the new load's chain.
7816   WorklistRemover DeadNodes(*this);
7817   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7818
7819   // Shift the result left, if we've swallowed a left shift.
7820   SDValue Result = Load;
7821   if (ShLeftAmt != 0) {
7822     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7823     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7824       ShImmTy = VT;
7825     // If the shift amount is as large as the result size (but, presumably,
7826     // no larger than the source) then the useful bits of the result are
7827     // zero; we can't simply return the shortened shift, because the result
7828     // of that operation is undefined.
7829     SDLoc DL(N0);
7830     if (ShLeftAmt >= VT.getSizeInBits())
7831       Result = DAG.getConstant(0, DL, VT);
7832     else
7833       Result = DAG.getNode(ISD::SHL, DL, VT,
7834                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7835   }
7836
7837   // Return the new loaded value.
7838   return Result;
7839 }
7840
7841 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7842   SDValue N0 = N->getOperand(0);
7843   SDValue N1 = N->getOperand(1);
7844   EVT VT = N->getValueType(0);
7845   EVT EVT = cast<VTSDNode>(N1)->getVT();
7846   unsigned VTBits = VT.getScalarSizeInBits();
7847   unsigned EVTBits = EVT.getScalarSizeInBits();
7848
7849   if (N0.isUndef())
7850     return DAG.getUNDEF(VT);
7851
7852   // fold (sext_in_reg c1) -> c1
7853   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7854     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7855
7856   // If the input is already sign extended, just drop the extension.
7857   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7858     return N0;
7859
7860   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7861   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7862       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7863     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7864                        N0.getOperand(0), N1);
7865
7866   // fold (sext_in_reg (sext x)) -> (sext x)
7867   // fold (sext_in_reg (aext x)) -> (sext x)
7868   // if x is small enough.
7869   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7870     SDValue N00 = N0.getOperand(0);
7871     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7872         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7873       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7874   }
7875
7876   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
7877   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
7878        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
7879        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
7880       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
7881     if (!LegalOperations ||
7882         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
7883       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
7884   }
7885
7886   // fold (sext_in_reg (zext x)) -> (sext x)
7887   // iff we are extending the source sign bit.
7888   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
7889     SDValue N00 = N0.getOperand(0);
7890     if (N00.getScalarValueSizeInBits() == EVTBits &&
7891         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7892       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7893   }
7894
7895   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7896   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
7897     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7898
7899   // fold operands of sext_in_reg based on knowledge that the top bits are not
7900   // demanded.
7901   if (SimplifyDemandedBits(SDValue(N, 0)))
7902     return SDValue(N, 0);
7903
7904   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7905   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7906   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7907     return NarrowLoad;
7908
7909   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7910   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7911   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7912   if (N0.getOpcode() == ISD::SRL) {
7913     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7914       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7915         // We can turn this into an SRA iff the input to the SRL is already sign
7916         // extended enough.
7917         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7918         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7919           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7920                              N0.getOperand(0), N0.getOperand(1));
7921       }
7922   }
7923
7924   // fold (sext_inreg (extload x)) -> (sextload x)
7925   if (ISD::isEXTLoad(N0.getNode()) &&
7926       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7927       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7928       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7929        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7930     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7931     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7932                                      LN0->getChain(),
7933                                      LN0->getBasePtr(), EVT,
7934                                      LN0->getMemOperand());
7935     CombineTo(N, ExtLoad);
7936     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7937     AddToWorklist(ExtLoad.getNode());
7938     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7939   }
7940   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7941   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7942       N0.hasOneUse() &&
7943       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7944       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7945        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7946     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7947     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7948                                      LN0->getChain(),
7949                                      LN0->getBasePtr(), EVT,
7950                                      LN0->getMemOperand());
7951     CombineTo(N, ExtLoad);
7952     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7953     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7954   }
7955
7956   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7957   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7958     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7959                                            N0.getOperand(1), false))
7960       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7961                          BSwap, N1);
7962   }
7963
7964   return SDValue();
7965 }
7966
7967 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7968   SDValue N0 = N->getOperand(0);
7969   EVT VT = N->getValueType(0);
7970
7971   if (N0.isUndef())
7972     return DAG.getUNDEF(VT);
7973
7974   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7975                                               LegalOperations))
7976     return SDValue(Res, 0);
7977
7978   return SDValue();
7979 }
7980
7981 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7982   SDValue N0 = N->getOperand(0);
7983   EVT VT = N->getValueType(0);
7984
7985   if (N0.isUndef())
7986     return DAG.getUNDEF(VT);
7987
7988   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7989                                               LegalOperations))
7990     return SDValue(Res, 0);
7991
7992   return SDValue();
7993 }
7994
7995 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7996   SDValue N0 = N->getOperand(0);
7997   EVT VT = N->getValueType(0);
7998   bool isLE = DAG.getDataLayout().isLittleEndian();
7999
8000   // noop truncate
8001   if (N0.getValueType() == N->getValueType(0))
8002     return N0;
8003   // fold (truncate c1) -> c1
8004   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8005     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8006   // fold (truncate (truncate x)) -> (truncate x)
8007   if (N0.getOpcode() == ISD::TRUNCATE)
8008     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8009   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8010   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8011       N0.getOpcode() == ISD::SIGN_EXTEND ||
8012       N0.getOpcode() == ISD::ANY_EXTEND) {
8013     // if the source is smaller than the dest, we still need an extend.
8014     if (N0.getOperand(0).getValueType().bitsLT(VT))
8015       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8016     // if the source is larger than the dest, than we just need the truncate.
8017     if (N0.getOperand(0).getValueType().bitsGT(VT))
8018       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8019     // if the source and dest are the same type, we can drop both the extend
8020     // and the truncate.
8021     return N0.getOperand(0);
8022   }
8023
8024   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8025   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8026     return SDValue();
8027
8028   // Fold extract-and-trunc into a narrow extract. For example:
8029   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8030   //   i32 y = TRUNCATE(i64 x)
8031   //        -- becomes --
8032   //   v16i8 b = BITCAST (v2i64 val)
8033   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8034   //
8035   // Note: We only run this optimization after type legalization (which often
8036   // creates this pattern) and before operation legalization after which
8037   // we need to be more careful about the vector instructions that we generate.
8038   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8039       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8040
8041     EVT VecTy = N0.getOperand(0).getValueType();
8042     EVT ExTy = N0.getValueType();
8043     EVT TrTy = N->getValueType(0);
8044
8045     unsigned NumElem = VecTy.getVectorNumElements();
8046     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8047
8048     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8049     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8050
8051     SDValue EltNo = N0->getOperand(1);
8052     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8053       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8054       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8055       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8056
8057       SDLoc DL(N);
8058       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8059                          DAG.getBitcast(NVT, N0.getOperand(0)),
8060                          DAG.getConstant(Index, DL, IndexTy));
8061     }
8062   }
8063
8064   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8065   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8066     EVT SrcVT = N0.getValueType();
8067     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8068         TLI.isTruncateFree(SrcVT, VT)) {
8069       SDLoc SL(N0);
8070       SDValue Cond = N0.getOperand(0);
8071       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8072       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8073       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8074     }
8075   }
8076
8077   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8078   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8079       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8080       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8081     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
8082       uint64_t Amt = CAmt->getZExtValue();
8083       unsigned Size = VT.getScalarSizeInBits();
8084
8085       if (Amt < Size) {
8086         SDLoc SL(N);
8087         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8088
8089         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8090         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
8091                            DAG.getConstant(Amt, SL, AmtVT));
8092       }
8093     }
8094   }
8095
8096   // Fold a series of buildvector, bitcast, and truncate if possible.
8097   // For example fold
8098   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8099   //   (2xi32 (buildvector x, y)).
8100   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8101       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8102       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8103       N0.getOperand(0).hasOneUse()) {
8104
8105     SDValue BuildVect = N0.getOperand(0);
8106     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8107     EVT TruncVecEltTy = VT.getVectorElementType();
8108
8109     // Check that the element types match.
8110     if (BuildVectEltTy == TruncVecEltTy) {
8111       // Now we only need to compute the offset of the truncated elements.
8112       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8113       unsigned TruncVecNumElts = VT.getVectorNumElements();
8114       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8115
8116       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8117              "Invalid number of elements");
8118
8119       SmallVector<SDValue, 8> Opnds;
8120       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8121         Opnds.push_back(BuildVect.getOperand(i));
8122
8123       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8124     }
8125   }
8126
8127   // See if we can simplify the input to this truncate through knowledge that
8128   // only the low bits are being used.
8129   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8130   // Currently we only perform this optimization on scalars because vectors
8131   // may have different active low bits.
8132   if (!VT.isVector()) {
8133     if (SDValue Shorter =
8134             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8135                                                      VT.getSizeInBits())))
8136       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8137   }
8138
8139   // fold (truncate (load x)) -> (smaller load x)
8140   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8141   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8142     if (SDValue Reduced = ReduceLoadWidth(N))
8143       return Reduced;
8144
8145     // Handle the case where the load remains an extending load even
8146     // after truncation.
8147     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8148       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8149       if (!LN0->isVolatile() &&
8150           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8151         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8152                                          VT, LN0->getChain(), LN0->getBasePtr(),
8153                                          LN0->getMemoryVT(),
8154                                          LN0->getMemOperand());
8155         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8156         return NewLoad;
8157       }
8158     }
8159   }
8160
8161   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8162   // where ... are all 'undef'.
8163   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8164     SmallVector<EVT, 8> VTs;
8165     SDValue V;
8166     unsigned Idx = 0;
8167     unsigned NumDefs = 0;
8168
8169     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8170       SDValue X = N0.getOperand(i);
8171       if (!X.isUndef()) {
8172         V = X;
8173         Idx = i;
8174         NumDefs++;
8175       }
8176       // Stop if more than one members are non-undef.
8177       if (NumDefs > 1)
8178         break;
8179       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8180                                      VT.getVectorElementType(),
8181                                      X.getValueType().getVectorNumElements()));
8182     }
8183
8184     if (NumDefs == 0)
8185       return DAG.getUNDEF(VT);
8186
8187     if (NumDefs == 1) {
8188       assert(V.getNode() && "The single defined operand is empty!");
8189       SmallVector<SDValue, 8> Opnds;
8190       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8191         if (i != Idx) {
8192           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8193           continue;
8194         }
8195         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8196         AddToWorklist(NV.getNode());
8197         Opnds.push_back(NV);
8198       }
8199       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8200     }
8201   }
8202
8203   // Fold truncate of a bitcast of a vector to an extract of the low vector
8204   // element.
8205   //
8206   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8207   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8208     SDValue VecSrc = N0.getOperand(0);
8209     EVT SrcVT = VecSrc.getValueType();
8210     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8211         (!LegalOperations ||
8212          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8213       SDLoc SL(N);
8214
8215       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8216       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8217                          VecSrc, DAG.getConstant(0, SL, IdxVT));
8218     }
8219   }
8220
8221   // Simplify the operands using demanded-bits information.
8222   if (!VT.isVector() &&
8223       SimplifyDemandedBits(SDValue(N, 0)))
8224     return SDValue(N, 0);
8225
8226   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8227   // When the adde's carry is not used.
8228   if (N0.getOpcode() == ISD::ADDE && N0.hasOneUse() &&
8229       !N0.getNode()->hasAnyUseOfValue(1) &&
8230       (!LegalOperations || TLI.isOperationLegal(ISD::ADDE, VT))) {
8231     SDLoc SL(N);
8232     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8233     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8234     return DAG.getNode(ISD::ADDE, SL, DAG.getVTList(VT, MVT::Glue),
8235                        X, Y, N0.getOperand(2));
8236   }
8237
8238   return SDValue();
8239 }
8240
8241 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8242   SDValue Elt = N->getOperand(i);
8243   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8244     return Elt.getNode();
8245   return Elt.getOperand(Elt.getResNo()).getNode();
8246 }
8247
8248 /// build_pair (load, load) -> load
8249 /// if load locations are consecutive.
8250 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8251   assert(N->getOpcode() == ISD::BUILD_PAIR);
8252
8253   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8254   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8255   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8256       LD1->getAddressSpace() != LD2->getAddressSpace())
8257     return SDValue();
8258   EVT LD1VT = LD1->getValueType(0);
8259   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8260   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8261       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8262     unsigned Align = LD1->getAlignment();
8263     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8264         VT.getTypeForEVT(*DAG.getContext()));
8265
8266     if (NewAlign <= Align &&
8267         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8268       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8269                          LD1->getPointerInfo(), Align);
8270   }
8271
8272   return SDValue();
8273 }
8274
8275 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8276   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8277   // and Lo parts; on big-endian machines it doesn't.
8278   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8279 }
8280
8281 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8282                                     const TargetLowering &TLI) {
8283   // If this is not a bitcast to an FP type or if the target doesn't have
8284   // IEEE754-compliant FP logic, we're done.
8285   EVT VT = N->getValueType(0);
8286   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8287     return SDValue();
8288
8289   // TODO: Use splat values for the constant-checking below and remove this
8290   // restriction.
8291   SDValue N0 = N->getOperand(0);
8292   EVT SourceVT = N0.getValueType();
8293   if (SourceVT.isVector())
8294     return SDValue();
8295
8296   unsigned FPOpcode;
8297   APInt SignMask;
8298   switch (N0.getOpcode()) {
8299   case ISD::AND:
8300     FPOpcode = ISD::FABS;
8301     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8302     break;
8303   case ISD::XOR:
8304     FPOpcode = ISD::FNEG;
8305     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8306     break;
8307   // TODO: ISD::OR --> ISD::FNABS?
8308   default:
8309     return SDValue();
8310   }
8311
8312   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8313   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8314   SDValue LogicOp0 = N0.getOperand(0);
8315   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8316   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8317       LogicOp0.getOpcode() == ISD::BITCAST &&
8318       LogicOp0->getOperand(0).getValueType() == VT)
8319     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8320
8321   return SDValue();
8322 }
8323
8324 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8325   SDValue N0 = N->getOperand(0);
8326   EVT VT = N->getValueType(0);
8327
8328   if (N0.isUndef())
8329     return DAG.getUNDEF(VT);
8330
8331   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8332   // Only do this before legalize, since afterward the target may be depending
8333   // on the bitconvert.
8334   // First check to see if this is all constant.
8335   if (!LegalTypes &&
8336       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8337       VT.isVector()) {
8338     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8339
8340     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8341     assert(!DestEltVT.isVector() &&
8342            "Element type of vector ValueType must not be vector!");
8343     if (isSimple)
8344       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8345   }
8346
8347   // If the input is a constant, let getNode fold it.
8348   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8349     // If we can't allow illegal operations, we need to check that this is just
8350     // a fp -> int or int -> conversion and that the resulting operation will
8351     // be legal.
8352     if (!LegalOperations ||
8353         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8354          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8355         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8356          TLI.isOperationLegal(ISD::Constant, VT)))
8357       return DAG.getBitcast(VT, N0);
8358   }
8359
8360   // (conv (conv x, t1), t2) -> (conv x, t2)
8361   if (N0.getOpcode() == ISD::BITCAST)
8362     return DAG.getBitcast(VT, N0.getOperand(0));
8363
8364   // fold (conv (load x)) -> (load (conv*)x)
8365   // If the resultant load doesn't need a higher alignment than the original!
8366   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8367       // Do not change the width of a volatile load.
8368       !cast<LoadSDNode>(N0)->isVolatile() &&
8369       // Do not remove the cast if the types differ in endian layout.
8370       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8371           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8372       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8373       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8374     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8375     unsigned OrigAlign = LN0->getAlignment();
8376
8377     bool Fast = false;
8378     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8379                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8380         Fast) {
8381       SDValue Load =
8382           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8383                       LN0->getPointerInfo(), OrigAlign,
8384                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8385       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8386       return Load;
8387     }
8388   }
8389
8390   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8391     return V;
8392
8393   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8394   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8395   //
8396   // For ppc_fp128:
8397   // fold (bitcast (fneg x)) ->
8398   //     flipbit = signbit
8399   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8400   //
8401   // fold (bitcast (fabs x)) ->
8402   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8403   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8404   // This often reduces constant pool loads.
8405   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8406        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8407       N0.getNode()->hasOneUse() && VT.isInteger() &&
8408       !VT.isVector() && !N0.getValueType().isVector()) {
8409     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8410     AddToWorklist(NewConv.getNode());
8411
8412     SDLoc DL(N);
8413     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8414       assert(VT.getSizeInBits() == 128);
8415       SDValue SignBit = DAG.getConstant(
8416           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8417       SDValue FlipBit;
8418       if (N0.getOpcode() == ISD::FNEG) {
8419         FlipBit = SignBit;
8420         AddToWorklist(FlipBit.getNode());
8421       } else {
8422         assert(N0.getOpcode() == ISD::FABS);
8423         SDValue Hi =
8424             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8425                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8426                                               SDLoc(NewConv)));
8427         AddToWorklist(Hi.getNode());
8428         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8429         AddToWorklist(FlipBit.getNode());
8430       }
8431       SDValue FlipBits =
8432           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8433       AddToWorklist(FlipBits.getNode());
8434       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8435     }
8436     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8437     if (N0.getOpcode() == ISD::FNEG)
8438       return DAG.getNode(ISD::XOR, DL, VT,
8439                          NewConv, DAG.getConstant(SignBit, DL, VT));
8440     assert(N0.getOpcode() == ISD::FABS);
8441     return DAG.getNode(ISD::AND, DL, VT,
8442                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8443   }
8444
8445   // fold (bitconvert (fcopysign cst, x)) ->
8446   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8447   // Note that we don't handle (copysign x, cst) because this can always be
8448   // folded to an fneg or fabs.
8449   //
8450   // For ppc_fp128:
8451   // fold (bitcast (fcopysign cst, x)) ->
8452   //     flipbit = (and (extract_element
8453   //                     (xor (bitcast cst), (bitcast x)), 0),
8454   //                    signbit)
8455   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8456   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8457       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8458       VT.isInteger() && !VT.isVector()) {
8459     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8460     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8461     if (isTypeLegal(IntXVT)) {
8462       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8463       AddToWorklist(X.getNode());
8464
8465       // If X has a different width than the result/lhs, sext it or truncate it.
8466       unsigned VTWidth = VT.getSizeInBits();
8467       if (OrigXWidth < VTWidth) {
8468         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8469         AddToWorklist(X.getNode());
8470       } else if (OrigXWidth > VTWidth) {
8471         // To get the sign bit in the right place, we have to shift it right
8472         // before truncating.
8473         SDLoc DL(X);
8474         X = DAG.getNode(ISD::SRL, DL,
8475                         X.getValueType(), X,
8476                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8477                                         X.getValueType()));
8478         AddToWorklist(X.getNode());
8479         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8480         AddToWorklist(X.getNode());
8481       }
8482
8483       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8484         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8485         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8486         AddToWorklist(Cst.getNode());
8487         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8488         AddToWorklist(X.getNode());
8489         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8490         AddToWorklist(XorResult.getNode());
8491         SDValue XorResult64 = DAG.getNode(
8492             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8493             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8494                                   SDLoc(XorResult)));
8495         AddToWorklist(XorResult64.getNode());
8496         SDValue FlipBit =
8497             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8498                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8499         AddToWorklist(FlipBit.getNode());
8500         SDValue FlipBits =
8501             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8502         AddToWorklist(FlipBits.getNode());
8503         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8504       }
8505       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8506       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8507                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8508       AddToWorklist(X.getNode());
8509
8510       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8511       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8512                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8513       AddToWorklist(Cst.getNode());
8514
8515       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8516     }
8517   }
8518
8519   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8520   if (N0.getOpcode() == ISD::BUILD_PAIR)
8521     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8522       return CombineLD;
8523
8524   // Remove double bitcasts from shuffles - this is often a legacy of
8525   // XformToShuffleWithZero being used to combine bitmaskings (of
8526   // float vectors bitcast to integer vectors) into shuffles.
8527   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8528   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8529       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8530       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8531       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8532     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8533
8534     // If operands are a bitcast, peek through if it casts the original VT.
8535     // If operands are a constant, just bitcast back to original VT.
8536     auto PeekThroughBitcast = [&](SDValue Op) {
8537       if (Op.getOpcode() == ISD::BITCAST &&
8538           Op.getOperand(0).getValueType() == VT)
8539         return SDValue(Op.getOperand(0));
8540       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8541           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8542         return DAG.getBitcast(VT, Op);
8543       return SDValue();
8544     };
8545
8546     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8547     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8548     if (!(SV0 && SV1))
8549       return SDValue();
8550
8551     int MaskScale =
8552         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8553     SmallVector<int, 8> NewMask;
8554     for (int M : SVN->getMask())
8555       for (int i = 0; i != MaskScale; ++i)
8556         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8557
8558     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8559     if (!LegalMask) {
8560       std::swap(SV0, SV1);
8561       ShuffleVectorSDNode::commuteMask(NewMask);
8562       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8563     }
8564
8565     if (LegalMask)
8566       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8567   }
8568
8569   return SDValue();
8570 }
8571
8572 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8573   EVT VT = N->getValueType(0);
8574   return CombineConsecutiveLoads(N, VT);
8575 }
8576
8577 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8578 /// operands. DstEltVT indicates the destination element value type.
8579 SDValue DAGCombiner::
8580 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8581   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8582
8583   // If this is already the right type, we're done.
8584   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8585
8586   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8587   unsigned DstBitSize = DstEltVT.getSizeInBits();
8588
8589   // If this is a conversion of N elements of one type to N elements of another
8590   // type, convert each element.  This handles FP<->INT cases.
8591   if (SrcBitSize == DstBitSize) {
8592     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8593                               BV->getValueType(0).getVectorNumElements());
8594
8595     // Due to the FP element handling below calling this routine recursively,
8596     // we can end up with a scalar-to-vector node here.
8597     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8598       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8599                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8600
8601     SmallVector<SDValue, 8> Ops;
8602     for (SDValue Op : BV->op_values()) {
8603       // If the vector element type is not legal, the BUILD_VECTOR operands
8604       // are promoted and implicitly truncated.  Make that explicit here.
8605       if (Op.getValueType() != SrcEltVT)
8606         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8607       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8608       AddToWorklist(Ops.back().getNode());
8609     }
8610     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8611   }
8612
8613   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8614   // handle annoying details of growing/shrinking FP values, we convert them to
8615   // int first.
8616   if (SrcEltVT.isFloatingPoint()) {
8617     // Convert the input float vector to a int vector where the elements are the
8618     // same sizes.
8619     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8620     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8621     SrcEltVT = IntVT;
8622   }
8623
8624   // Now we know the input is an integer vector.  If the output is a FP type,
8625   // convert to integer first, then to FP of the right size.
8626   if (DstEltVT.isFloatingPoint()) {
8627     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8628     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8629
8630     // Next, convert to FP elements of the same size.
8631     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8632   }
8633
8634   SDLoc DL(BV);
8635
8636   // Okay, we know the src/dst types are both integers of differing types.
8637   // Handling growing first.
8638   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8639   if (SrcBitSize < DstBitSize) {
8640     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8641
8642     SmallVector<SDValue, 8> Ops;
8643     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8644          i += NumInputsPerOutput) {
8645       bool isLE = DAG.getDataLayout().isLittleEndian();
8646       APInt NewBits = APInt(DstBitSize, 0);
8647       bool EltIsUndef = true;
8648       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8649         // Shift the previously computed bits over.
8650         NewBits <<= SrcBitSize;
8651         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8652         if (Op.isUndef()) continue;
8653         EltIsUndef = false;
8654
8655         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8656                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8657       }
8658
8659       if (EltIsUndef)
8660         Ops.push_back(DAG.getUNDEF(DstEltVT));
8661       else
8662         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8663     }
8664
8665     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8666     return DAG.getBuildVector(VT, DL, Ops);
8667   }
8668
8669   // Finally, this must be the case where we are shrinking elements: each input
8670   // turns into multiple outputs.
8671   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8672   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8673                             NumOutputsPerInput*BV->getNumOperands());
8674   SmallVector<SDValue, 8> Ops;
8675
8676   for (const SDValue &Op : BV->op_values()) {
8677     if (Op.isUndef()) {
8678       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8679       continue;
8680     }
8681
8682     APInt OpVal = cast<ConstantSDNode>(Op)->
8683                   getAPIntValue().zextOrTrunc(SrcBitSize);
8684
8685     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8686       APInt ThisVal = OpVal.trunc(DstBitSize);
8687       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8688       OpVal.lshrInPlace(DstBitSize);
8689     }
8690
8691     // For big endian targets, swap the order of the pieces of each element.
8692     if (DAG.getDataLayout().isBigEndian())
8693       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8694   }
8695
8696   return DAG.getBuildVector(VT, DL, Ops);
8697 }
8698
8699 static bool isContractable(SDNode *N) {
8700   SDNodeFlags F = cast<BinaryWithFlagsSDNode>(N)->Flags;
8701   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8702 }
8703
8704 /// Try to perform FMA combining on a given FADD node.
8705 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8706   SDValue N0 = N->getOperand(0);
8707   SDValue N1 = N->getOperand(1);
8708   EVT VT = N->getValueType(0);
8709   SDLoc SL(N);
8710
8711   const TargetOptions &Options = DAG.getTarget().Options;
8712
8713   // Floating-point multiply-add with intermediate rounding.
8714   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8715
8716   // Floating-point multiply-add without intermediate rounding.
8717   bool HasFMA =
8718       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8719       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8720
8721   // No valid opcode, do not combine.
8722   if (!HasFMAD && !HasFMA)
8723     return SDValue();
8724
8725   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8726                               Options.UnsafeFPMath || HasFMAD);
8727   // If the addition is not contractable, do not combine.
8728   if (!AllowFusionGlobally && !isContractable(N))
8729     return SDValue();
8730
8731   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8732   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8733     return SDValue();
8734
8735   // Always prefer FMAD to FMA for precision.
8736   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8737   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8738   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8739
8740   // Is the node an FMUL and contractable either due to global flags or
8741   // SDNodeFlags.
8742   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8743     if (N.getOpcode() != ISD::FMUL)
8744       return false;
8745     return AllowFusionGlobally || isContractable(N.getNode());
8746   };
8747   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8748   // prefer to fold the multiply with fewer uses.
8749   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8750     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8751       std::swap(N0, N1);
8752   }
8753
8754   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8755   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8756     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8757                        N0.getOperand(0), N0.getOperand(1), N1);
8758   }
8759
8760   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8761   // Note: Commutes FADD operands.
8762   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8763     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8764                        N1.getOperand(0), N1.getOperand(1), N0);
8765   }
8766
8767   // Look through FP_EXTEND nodes to do more combining.
8768   if (LookThroughFPExt) {
8769     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8770     if (N0.getOpcode() == ISD::FP_EXTEND) {
8771       SDValue N00 = N0.getOperand(0);
8772       if (isContractableFMUL(N00))
8773         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8774                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8775                                        N00.getOperand(0)),
8776                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8777                                        N00.getOperand(1)), N1);
8778     }
8779
8780     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8781     // Note: Commutes FADD operands.
8782     if (N1.getOpcode() == ISD::FP_EXTEND) {
8783       SDValue N10 = N1.getOperand(0);
8784       if (isContractableFMUL(N10))
8785         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8786                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8787                                        N10.getOperand(0)),
8788                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8789                                        N10.getOperand(1)), N0);
8790     }
8791   }
8792
8793   // More folding opportunities when target permits.
8794   if (Aggressive) {
8795     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8796     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8797     // are currently only supported on binary nodes.
8798     if (Options.UnsafeFPMath &&
8799         N0.getOpcode() == PreferredFusedOpcode &&
8800         N0.getOperand(2).getOpcode() == ISD::FMUL &&
8801         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8802       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8803                          N0.getOperand(0), N0.getOperand(1),
8804                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8805                                      N0.getOperand(2).getOperand(0),
8806                                      N0.getOperand(2).getOperand(1),
8807                                      N1));
8808     }
8809
8810     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8811     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8812     // are currently only supported on binary nodes.
8813     if (Options.UnsafeFPMath &&
8814         N1->getOpcode() == PreferredFusedOpcode &&
8815         N1.getOperand(2).getOpcode() == ISD::FMUL &&
8816         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
8817       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8818                          N1.getOperand(0), N1.getOperand(1),
8819                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8820                                      N1.getOperand(2).getOperand(0),
8821                                      N1.getOperand(2).getOperand(1),
8822                                      N0));
8823     }
8824
8825     if (LookThroughFPExt) {
8826       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8827       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8828       auto FoldFAddFMAFPExtFMul = [&] (
8829           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8830         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8831                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8832                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8833                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8834                                        Z));
8835       };
8836       if (N0.getOpcode() == PreferredFusedOpcode) {
8837         SDValue N02 = N0.getOperand(2);
8838         if (N02.getOpcode() == ISD::FP_EXTEND) {
8839           SDValue N020 = N02.getOperand(0);
8840           if (isContractableFMUL(N020))
8841             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8842                                         N020.getOperand(0), N020.getOperand(1),
8843                                         N1);
8844         }
8845       }
8846
8847       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8848       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8849       // FIXME: This turns two single-precision and one double-precision
8850       // operation into two double-precision operations, which might not be
8851       // interesting for all targets, especially GPUs.
8852       auto FoldFAddFPExtFMAFMul = [&] (
8853           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8854         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8855                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8856                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8857                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8858                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8859                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8860                                        Z));
8861       };
8862       if (N0.getOpcode() == ISD::FP_EXTEND) {
8863         SDValue N00 = N0.getOperand(0);
8864         if (N00.getOpcode() == PreferredFusedOpcode) {
8865           SDValue N002 = N00.getOperand(2);
8866           if (isContractableFMUL(N002))
8867             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8868                                         N002.getOperand(0), N002.getOperand(1),
8869                                         N1);
8870         }
8871       }
8872
8873       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8874       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8875       if (N1.getOpcode() == PreferredFusedOpcode) {
8876         SDValue N12 = N1.getOperand(2);
8877         if (N12.getOpcode() == ISD::FP_EXTEND) {
8878           SDValue N120 = N12.getOperand(0);
8879           if (isContractableFMUL(N120))
8880             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8881                                         N120.getOperand(0), N120.getOperand(1),
8882                                         N0);
8883         }
8884       }
8885
8886       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8887       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8888       // FIXME: This turns two single-precision and one double-precision
8889       // operation into two double-precision operations, which might not be
8890       // interesting for all targets, especially GPUs.
8891       if (N1.getOpcode() == ISD::FP_EXTEND) {
8892         SDValue N10 = N1.getOperand(0);
8893         if (N10.getOpcode() == PreferredFusedOpcode) {
8894           SDValue N102 = N10.getOperand(2);
8895           if (isContractableFMUL(N102))
8896             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8897                                         N102.getOperand(0), N102.getOperand(1),
8898                                         N0);
8899         }
8900       }
8901     }
8902   }
8903
8904   return SDValue();
8905 }
8906
8907 /// Try to perform FMA combining on a given FSUB node.
8908 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8909   SDValue N0 = N->getOperand(0);
8910   SDValue N1 = N->getOperand(1);
8911   EVT VT = N->getValueType(0);
8912   SDLoc SL(N);
8913
8914   const TargetOptions &Options = DAG.getTarget().Options;
8915   // Floating-point multiply-add with intermediate rounding.
8916   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8917
8918   // Floating-point multiply-add without intermediate rounding.
8919   bool HasFMA =
8920       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8921       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8922
8923   // No valid opcode, do not combine.
8924   if (!HasFMAD && !HasFMA)
8925     return SDValue();
8926
8927   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8928                               Options.UnsafeFPMath || HasFMAD);
8929   // If the subtraction is not contractable, do not combine.
8930   if (!AllowFusionGlobally && !isContractable(N))
8931     return SDValue();
8932
8933   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8934   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8935     return SDValue();
8936
8937   // Always prefer FMAD to FMA for precision.
8938   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8939   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8940   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8941
8942   // Is the node an FMUL and contractable either due to global flags or
8943   // SDNodeFlags.
8944   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8945     if (N.getOpcode() != ISD::FMUL)
8946       return false;
8947     return AllowFusionGlobally || isContractable(N.getNode());
8948   };
8949
8950   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8951   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8952     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8953                        N0.getOperand(0), N0.getOperand(1),
8954                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8955   }
8956
8957   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8958   // Note: Commutes FSUB operands.
8959   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
8960     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8961                        DAG.getNode(ISD::FNEG, SL, VT,
8962                                    N1.getOperand(0)),
8963                        N1.getOperand(1), N0);
8964
8965   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8966   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
8967       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8968     SDValue N00 = N0.getOperand(0).getOperand(0);
8969     SDValue N01 = N0.getOperand(0).getOperand(1);
8970     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8971                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8972                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8973   }
8974
8975   // Look through FP_EXTEND nodes to do more combining.
8976   if (LookThroughFPExt) {
8977     // fold (fsub (fpext (fmul x, y)), z)
8978     //   -> (fma (fpext x), (fpext y), (fneg z))
8979     if (N0.getOpcode() == ISD::FP_EXTEND) {
8980       SDValue N00 = N0.getOperand(0);
8981       if (isContractableFMUL(N00))
8982         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8983                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8984                                        N00.getOperand(0)),
8985                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8986                                        N00.getOperand(1)),
8987                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8988     }
8989
8990     // fold (fsub x, (fpext (fmul y, z)))
8991     //   -> (fma (fneg (fpext y)), (fpext z), x)
8992     // Note: Commutes FSUB operands.
8993     if (N1.getOpcode() == ISD::FP_EXTEND) {
8994       SDValue N10 = N1.getOperand(0);
8995       if (isContractableFMUL(N10))
8996         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8997                            DAG.getNode(ISD::FNEG, SL, VT,
8998                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8999                                                    N10.getOperand(0))),
9000                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9001                                        N10.getOperand(1)),
9002                            N0);
9003     }
9004
9005     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9006     //   -> (fneg (fma (fpext x), (fpext y), z))
9007     // Note: This could be removed with appropriate canonicalization of the
9008     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9009     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9010     // from implementing the canonicalization in visitFSUB.
9011     if (N0.getOpcode() == ISD::FP_EXTEND) {
9012       SDValue N00 = N0.getOperand(0);
9013       if (N00.getOpcode() == ISD::FNEG) {
9014         SDValue N000 = N00.getOperand(0);
9015         if (isContractableFMUL(N000)) {
9016           return DAG.getNode(ISD::FNEG, SL, VT,
9017                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9018                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9019                                                      N000.getOperand(0)),
9020                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9021                                                      N000.getOperand(1)),
9022                                          N1));
9023         }
9024       }
9025     }
9026
9027     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9028     //   -> (fneg (fma (fpext x)), (fpext y), z)
9029     // Note: This could be removed with appropriate canonicalization of the
9030     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9031     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9032     // from implementing the canonicalization in visitFSUB.
9033     if (N0.getOpcode() == ISD::FNEG) {
9034       SDValue N00 = N0.getOperand(0);
9035       if (N00.getOpcode() == ISD::FP_EXTEND) {
9036         SDValue N000 = N00.getOperand(0);
9037         if (isContractableFMUL(N000)) {
9038           return DAG.getNode(ISD::FNEG, SL, VT,
9039                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9040                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9041                                                      N000.getOperand(0)),
9042                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9043                                                      N000.getOperand(1)),
9044                                          N1));
9045         }
9046       }
9047     }
9048
9049   }
9050
9051   // More folding opportunities when target permits.
9052   if (Aggressive) {
9053     // fold (fsub (fma x, y, (fmul u, v)), z)
9054     //   -> (fma x, y (fma u, v, (fneg z)))
9055     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9056     // are currently only supported on binary nodes.
9057     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9058         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9059         N0.getOperand(2)->hasOneUse()) {
9060       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9061                          N0.getOperand(0), N0.getOperand(1),
9062                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9063                                      N0.getOperand(2).getOperand(0),
9064                                      N0.getOperand(2).getOperand(1),
9065                                      DAG.getNode(ISD::FNEG, SL, VT,
9066                                                  N1)));
9067     }
9068
9069     // fold (fsub x, (fma y, z, (fmul u, v)))
9070     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9071     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9072     // are currently only supported on binary nodes.
9073     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9074         isContractableFMUL(N1.getOperand(2))) {
9075       SDValue N20 = N1.getOperand(2).getOperand(0);
9076       SDValue N21 = N1.getOperand(2).getOperand(1);
9077       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9078                          DAG.getNode(ISD::FNEG, SL, VT,
9079                                      N1.getOperand(0)),
9080                          N1.getOperand(1),
9081                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9082                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9083
9084                                      N21, N0));
9085     }
9086
9087     if (LookThroughFPExt) {
9088       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9089       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9090       if (N0.getOpcode() == PreferredFusedOpcode) {
9091         SDValue N02 = N0.getOperand(2);
9092         if (N02.getOpcode() == ISD::FP_EXTEND) {
9093           SDValue N020 = N02.getOperand(0);
9094           if (isContractableFMUL(N020))
9095             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9096                                N0.getOperand(0), N0.getOperand(1),
9097                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9098                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9099                                                        N020.getOperand(0)),
9100                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9101                                                        N020.getOperand(1)),
9102                                            DAG.getNode(ISD::FNEG, SL, VT,
9103                                                        N1)));
9104         }
9105       }
9106
9107       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9108       //   -> (fma (fpext x), (fpext y),
9109       //           (fma (fpext u), (fpext v), (fneg z)))
9110       // FIXME: This turns two single-precision and one double-precision
9111       // operation into two double-precision operations, which might not be
9112       // interesting for all targets, especially GPUs.
9113       if (N0.getOpcode() == ISD::FP_EXTEND) {
9114         SDValue N00 = N0.getOperand(0);
9115         if (N00.getOpcode() == PreferredFusedOpcode) {
9116           SDValue N002 = N00.getOperand(2);
9117           if (isContractableFMUL(N002))
9118             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9119                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9120                                            N00.getOperand(0)),
9121                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9122                                            N00.getOperand(1)),
9123                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9124                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9125                                                        N002.getOperand(0)),
9126                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9127                                                        N002.getOperand(1)),
9128                                            DAG.getNode(ISD::FNEG, SL, VT,
9129                                                        N1)));
9130         }
9131       }
9132
9133       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9134       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9135       if (N1.getOpcode() == PreferredFusedOpcode &&
9136         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9137         SDValue N120 = N1.getOperand(2).getOperand(0);
9138         if (isContractableFMUL(N120)) {
9139           SDValue N1200 = N120.getOperand(0);
9140           SDValue N1201 = N120.getOperand(1);
9141           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9142                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9143                              N1.getOperand(1),
9144                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9145                                          DAG.getNode(ISD::FNEG, SL, VT,
9146                                              DAG.getNode(ISD::FP_EXTEND, SL,
9147                                                          VT, N1200)),
9148                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9149                                                      N1201),
9150                                          N0));
9151         }
9152       }
9153
9154       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9155       //   -> (fma (fneg (fpext y)), (fpext z),
9156       //           (fma (fneg (fpext u)), (fpext v), x))
9157       // FIXME: This turns two single-precision and one double-precision
9158       // operation into two double-precision operations, which might not be
9159       // interesting for all targets, especially GPUs.
9160       if (N1.getOpcode() == ISD::FP_EXTEND &&
9161         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9162         SDValue N100 = N1.getOperand(0).getOperand(0);
9163         SDValue N101 = N1.getOperand(0).getOperand(1);
9164         SDValue N102 = N1.getOperand(0).getOperand(2);
9165         if (isContractableFMUL(N102)) {
9166           SDValue N1020 = N102.getOperand(0);
9167           SDValue N1021 = N102.getOperand(1);
9168           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9169                              DAG.getNode(ISD::FNEG, SL, VT,
9170                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9171                                                      N100)),
9172                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9173                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9174                                          DAG.getNode(ISD::FNEG, SL, VT,
9175                                              DAG.getNode(ISD::FP_EXTEND, SL,
9176                                                          VT, N1020)),
9177                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9178                                                      N1021),
9179                                          N0));
9180         }
9181       }
9182     }
9183   }
9184
9185   return SDValue();
9186 }
9187
9188 /// Try to perform FMA combining on a given FMUL node based on the distributive
9189 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9190 /// subtraction instead of addition).
9191 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9192   SDValue N0 = N->getOperand(0);
9193   SDValue N1 = N->getOperand(1);
9194   EVT VT = N->getValueType(0);
9195   SDLoc SL(N);
9196
9197   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9198
9199   const TargetOptions &Options = DAG.getTarget().Options;
9200
9201   // The transforms below are incorrect when x == 0 and y == inf, because the
9202   // intermediate multiplication produces a nan.
9203   if (!Options.NoInfsFPMath)
9204     return SDValue();
9205
9206   // Floating-point multiply-add without intermediate rounding.
9207   bool HasFMA =
9208       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9209       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9210       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9211
9212   // Floating-point multiply-add with intermediate rounding. This can result
9213   // in a less precise result due to the changed rounding order.
9214   bool HasFMAD = Options.UnsafeFPMath &&
9215                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9216
9217   // No valid opcode, do not combine.
9218   if (!HasFMAD && !HasFMA)
9219     return SDValue();
9220
9221   // Always prefer FMAD to FMA for precision.
9222   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9223   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9224
9225   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9226   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9227   auto FuseFADD = [&](SDValue X, SDValue Y) {
9228     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9229       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9230       if (XC1 && XC1->isExactlyValue(+1.0))
9231         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9232       if (XC1 && XC1->isExactlyValue(-1.0))
9233         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9234                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9235     }
9236     return SDValue();
9237   };
9238
9239   if (SDValue FMA = FuseFADD(N0, N1))
9240     return FMA;
9241   if (SDValue FMA = FuseFADD(N1, N0))
9242     return FMA;
9243
9244   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9245   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9246   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9247   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9248   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9249     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9250       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9251       if (XC0 && XC0->isExactlyValue(+1.0))
9252         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9253                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9254                            Y);
9255       if (XC0 && XC0->isExactlyValue(-1.0))
9256         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9257                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9258                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9259
9260       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9261       if (XC1 && XC1->isExactlyValue(+1.0))
9262         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9263                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9264       if (XC1 && XC1->isExactlyValue(-1.0))
9265         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9266     }
9267     return SDValue();
9268   };
9269
9270   if (SDValue FMA = FuseFSUB(N0, N1))
9271     return FMA;
9272   if (SDValue FMA = FuseFSUB(N1, N0))
9273     return FMA;
9274
9275   return SDValue();
9276 }
9277
9278 SDValue DAGCombiner::visitFADD(SDNode *N) {
9279   SDValue N0 = N->getOperand(0);
9280   SDValue N1 = N->getOperand(1);
9281   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9282   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9283   EVT VT = N->getValueType(0);
9284   SDLoc DL(N);
9285   const TargetOptions &Options = DAG.getTarget().Options;
9286   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9287
9288   // fold vector ops
9289   if (VT.isVector())
9290     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9291       return FoldedVOp;
9292
9293   // fold (fadd c1, c2) -> c1 + c2
9294   if (N0CFP && N1CFP)
9295     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9296
9297   // canonicalize constant to RHS
9298   if (N0CFP && !N1CFP)
9299     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9300
9301   if (SDValue NewSel = foldBinOpIntoSelect(N))
9302     return NewSel;
9303
9304   // fold (fadd A, (fneg B)) -> (fsub A, B)
9305   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9306       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9307     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9308                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9309
9310   // fold (fadd (fneg A), B) -> (fsub B, A)
9311   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9312       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9313     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9314                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9315
9316   // FIXME: Auto-upgrade the target/function-level option.
9317   if (Options.NoSignedZerosFPMath || N->getFlags()->hasNoSignedZeros()) {
9318     // fold (fadd A, 0) -> A
9319     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9320       if (N1C->isZero())
9321         return N0;
9322   }
9323
9324   // If 'unsafe math' is enabled, fold lots of things.
9325   if (Options.UnsafeFPMath) {
9326     // No FP constant should be created after legalization as Instruction
9327     // Selection pass has a hard time dealing with FP constants.
9328     bool AllowNewConst = (Level < AfterLegalizeDAG);
9329
9330     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9331     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9332         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9333       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9334                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9335                                      Flags),
9336                          Flags);
9337
9338     // If allowed, fold (fadd (fneg x), x) -> 0.0
9339     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9340       return DAG.getConstantFP(0.0, DL, VT);
9341
9342     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9343     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9344       return DAG.getConstantFP(0.0, DL, VT);
9345
9346     // We can fold chains of FADD's of the same value into multiplications.
9347     // This transform is not safe in general because we are reducing the number
9348     // of rounding steps.
9349     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9350       if (N0.getOpcode() == ISD::FMUL) {
9351         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9352         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9353
9354         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9355         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9356           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9357                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9358           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9359         }
9360
9361         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9362         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9363             N1.getOperand(0) == N1.getOperand(1) &&
9364             N0.getOperand(0) == N1.getOperand(0)) {
9365           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9366                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9367           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9368         }
9369       }
9370
9371       if (N1.getOpcode() == ISD::FMUL) {
9372         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9373         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9374
9375         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9376         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9377           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9378                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9379           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9380         }
9381
9382         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9383         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9384             N0.getOperand(0) == N0.getOperand(1) &&
9385             N1.getOperand(0) == N0.getOperand(0)) {
9386           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9387                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9388           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9389         }
9390       }
9391
9392       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9393         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9394         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9395         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9396             (N0.getOperand(0) == N1)) {
9397           return DAG.getNode(ISD::FMUL, DL, VT,
9398                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9399         }
9400       }
9401
9402       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9403         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9404         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9405         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9406             N1.getOperand(0) == N0) {
9407           return DAG.getNode(ISD::FMUL, DL, VT,
9408                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9409         }
9410       }
9411
9412       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9413       if (AllowNewConst &&
9414           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9415           N0.getOperand(0) == N0.getOperand(1) &&
9416           N1.getOperand(0) == N1.getOperand(1) &&
9417           N0.getOperand(0) == N1.getOperand(0)) {
9418         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9419                            DAG.getConstantFP(4.0, DL, VT), Flags);
9420       }
9421     }
9422   } // enable-unsafe-fp-math
9423
9424   // FADD -> FMA combines:
9425   if (SDValue Fused = visitFADDForFMACombine(N)) {
9426     AddToWorklist(Fused.getNode());
9427     return Fused;
9428   }
9429   return SDValue();
9430 }
9431
9432 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9433   SDValue N0 = N->getOperand(0);
9434   SDValue N1 = N->getOperand(1);
9435   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9436   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9437   EVT VT = N->getValueType(0);
9438   SDLoc DL(N);
9439   const TargetOptions &Options = DAG.getTarget().Options;
9440   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9441
9442   // fold vector ops
9443   if (VT.isVector())
9444     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9445       return FoldedVOp;
9446
9447   // fold (fsub c1, c2) -> c1-c2
9448   if (N0CFP && N1CFP)
9449     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9450
9451   if (SDValue NewSel = foldBinOpIntoSelect(N))
9452     return NewSel;
9453
9454   // fold (fsub A, (fneg B)) -> (fadd A, B)
9455   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9456     return DAG.getNode(ISD::FADD, DL, VT, N0,
9457                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9458
9459   // FIXME: Auto-upgrade the target/function-level option.
9460   if (Options.NoSignedZerosFPMath  || N->getFlags()->hasNoSignedZeros()) {
9461     // (fsub 0, B) -> -B
9462     if (N0CFP && N0CFP->isZero()) {
9463       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9464         return GetNegatedExpression(N1, DAG, LegalOperations);
9465       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9466         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9467     }
9468   }
9469
9470   // If 'unsafe math' is enabled, fold lots of things.
9471   if (Options.UnsafeFPMath) {
9472     // (fsub A, 0) -> A
9473     if (N1CFP && N1CFP->isZero())
9474       return N0;
9475
9476     // (fsub x, x) -> 0.0
9477     if (N0 == N1)
9478       return DAG.getConstantFP(0.0f, DL, VT);
9479
9480     // (fsub x, (fadd x, y)) -> (fneg y)
9481     // (fsub x, (fadd y, x)) -> (fneg y)
9482     if (N1.getOpcode() == ISD::FADD) {
9483       SDValue N10 = N1->getOperand(0);
9484       SDValue N11 = N1->getOperand(1);
9485
9486       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9487         return GetNegatedExpression(N11, DAG, LegalOperations);
9488
9489       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9490         return GetNegatedExpression(N10, DAG, LegalOperations);
9491     }
9492   }
9493
9494   // FSUB -> FMA combines:
9495   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9496     AddToWorklist(Fused.getNode());
9497     return Fused;
9498   }
9499
9500   return SDValue();
9501 }
9502
9503 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9504   SDValue N0 = N->getOperand(0);
9505   SDValue N1 = N->getOperand(1);
9506   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9507   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9508   EVT VT = N->getValueType(0);
9509   SDLoc DL(N);
9510   const TargetOptions &Options = DAG.getTarget().Options;
9511   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9512
9513   // fold vector ops
9514   if (VT.isVector()) {
9515     // This just handles C1 * C2 for vectors. Other vector folds are below.
9516     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9517       return FoldedVOp;
9518   }
9519
9520   // fold (fmul c1, c2) -> c1*c2
9521   if (N0CFP && N1CFP)
9522     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9523
9524   // canonicalize constant to RHS
9525   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9526      !isConstantFPBuildVectorOrConstantFP(N1))
9527     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9528
9529   // fold (fmul A, 1.0) -> A
9530   if (N1CFP && N1CFP->isExactlyValue(1.0))
9531     return N0;
9532
9533   if (SDValue NewSel = foldBinOpIntoSelect(N))
9534     return NewSel;
9535
9536   if (Options.UnsafeFPMath) {
9537     // fold (fmul A, 0) -> 0
9538     if (N1CFP && N1CFP->isZero())
9539       return N1;
9540
9541     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9542     if (N0.getOpcode() == ISD::FMUL) {
9543       // Fold scalars or any vector constants (not just splats).
9544       // This fold is done in general by InstCombine, but extra fmul insts
9545       // may have been generated during lowering.
9546       SDValue N00 = N0.getOperand(0);
9547       SDValue N01 = N0.getOperand(1);
9548       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9549       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9550       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9551
9552       // Check 1: Make sure that the first operand of the inner multiply is NOT
9553       // a constant. Otherwise, we may induce infinite looping.
9554       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9555         // Check 2: Make sure that the second operand of the inner multiply and
9556         // the second operand of the outer multiply are constants.
9557         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9558             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9559           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9560           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9561         }
9562       }
9563     }
9564
9565     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9566     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9567     // during an early run of DAGCombiner can prevent folding with fmuls
9568     // inserted during lowering.
9569     if (N0.getOpcode() == ISD::FADD &&
9570         (N0.getOperand(0) == N0.getOperand(1)) &&
9571         N0.hasOneUse()) {
9572       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9573       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9574       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9575     }
9576   }
9577
9578   // fold (fmul X, 2.0) -> (fadd X, X)
9579   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9580     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9581
9582   // fold (fmul X, -1.0) -> (fneg X)
9583   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9584     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9585       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9586
9587   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9588   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9589     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9590       // Both can be negated for free, check to see if at least one is cheaper
9591       // negated.
9592       if (LHSNeg == 2 || RHSNeg == 2)
9593         return DAG.getNode(ISD::FMUL, DL, VT,
9594                            GetNegatedExpression(N0, DAG, LegalOperations),
9595                            GetNegatedExpression(N1, DAG, LegalOperations),
9596                            Flags);
9597     }
9598   }
9599
9600   // FMUL -> FMA combines:
9601   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9602     AddToWorklist(Fused.getNode());
9603     return Fused;
9604   }
9605
9606   return SDValue();
9607 }
9608
9609 SDValue DAGCombiner::visitFMA(SDNode *N) {
9610   SDValue N0 = N->getOperand(0);
9611   SDValue N1 = N->getOperand(1);
9612   SDValue N2 = N->getOperand(2);
9613   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9614   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9615   EVT VT = N->getValueType(0);
9616   SDLoc DL(N);
9617   const TargetOptions &Options = DAG.getTarget().Options;
9618
9619   // Constant fold FMA.
9620   if (isa<ConstantFPSDNode>(N0) &&
9621       isa<ConstantFPSDNode>(N1) &&
9622       isa<ConstantFPSDNode>(N2)) {
9623     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9624   }
9625
9626   if (Options.UnsafeFPMath) {
9627     if (N0CFP && N0CFP->isZero())
9628       return N2;
9629     if (N1CFP && N1CFP->isZero())
9630       return N2;
9631   }
9632   // TODO: The FMA node should have flags that propagate to these nodes.
9633   if (N0CFP && N0CFP->isExactlyValue(1.0))
9634     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9635   if (N1CFP && N1CFP->isExactlyValue(1.0))
9636     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9637
9638   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9639   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9640      !isConstantFPBuildVectorOrConstantFP(N1))
9641     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9642
9643   // TODO: FMA nodes should have flags that propagate to the created nodes.
9644   // For now, create a Flags object for use with all unsafe math transforms.
9645   SDNodeFlags Flags;
9646   Flags.setUnsafeAlgebra(true);
9647
9648   if (Options.UnsafeFPMath) {
9649     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9650     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9651         isConstantFPBuildVectorOrConstantFP(N1) &&
9652         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9653       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9654                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9655                                      &Flags), &Flags);
9656     }
9657
9658     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9659     if (N0.getOpcode() == ISD::FMUL &&
9660         isConstantFPBuildVectorOrConstantFP(N1) &&
9661         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9662       return DAG.getNode(ISD::FMA, DL, VT,
9663                          N0.getOperand(0),
9664                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9665                                      &Flags),
9666                          N2);
9667     }
9668   }
9669
9670   // (fma x, 1, y) -> (fadd x, y)
9671   // (fma x, -1, y) -> (fadd (fneg x), y)
9672   if (N1CFP) {
9673     if (N1CFP->isExactlyValue(1.0))
9674       // TODO: The FMA node should have flags that propagate to this node.
9675       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9676
9677     if (N1CFP->isExactlyValue(-1.0) &&
9678         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9679       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9680       AddToWorklist(RHSNeg.getNode());
9681       // TODO: The FMA node should have flags that propagate to this node.
9682       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9683     }
9684   }
9685
9686   if (Options.UnsafeFPMath) {
9687     // (fma x, c, x) -> (fmul x, (c+1))
9688     if (N1CFP && N0 == N2) {
9689       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9690                          DAG.getNode(ISD::FADD, DL, VT, N1,
9691                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
9692                          &Flags);
9693     }
9694
9695     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9696     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9697       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9698                          DAG.getNode(ISD::FADD, DL, VT, N1,
9699                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
9700                          &Flags);
9701     }
9702   }
9703
9704   return SDValue();
9705 }
9706
9707 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9708 // reciprocal.
9709 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9710 // Notice that this is not always beneficial. One reason is different targets
9711 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9712 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9713 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9714 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9715   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9716   const SDNodeFlags *Flags = N->getFlags();
9717   if (!UnsafeMath && !Flags->hasAllowReciprocal())
9718     return SDValue();
9719
9720   // Skip if current node is a reciprocal.
9721   SDValue N0 = N->getOperand(0);
9722   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9723   if (N0CFP && N0CFP->isExactlyValue(1.0))
9724     return SDValue();
9725
9726   // Exit early if the target does not want this transform or if there can't
9727   // possibly be enough uses of the divisor to make the transform worthwhile.
9728   SDValue N1 = N->getOperand(1);
9729   unsigned MinUses = TLI.combineRepeatedFPDivisors();
9730   if (!MinUses || N1->use_size() < MinUses)
9731     return SDValue();
9732
9733   // Find all FDIV users of the same divisor.
9734   // Use a set because duplicates may be present in the user list.
9735   SetVector<SDNode *> Users;
9736   for (auto *U : N1->uses()) {
9737     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9738       // This division is eligible for optimization only if global unsafe math
9739       // is enabled or if this division allows reciprocal formation.
9740       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
9741         Users.insert(U);
9742     }
9743   }
9744
9745   // Now that we have the actual number of divisor uses, make sure it meets
9746   // the minimum threshold specified by the target.
9747   if (Users.size() < MinUses)
9748     return SDValue();
9749
9750   EVT VT = N->getValueType(0);
9751   SDLoc DL(N);
9752   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9753   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9754
9755   // Dividend / Divisor -> Dividend * Reciprocal
9756   for (auto *U : Users) {
9757     SDValue Dividend = U->getOperand(0);
9758     if (Dividend != FPOne) {
9759       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9760                                     Reciprocal, Flags);
9761       CombineTo(U, NewNode);
9762     } else if (U != Reciprocal.getNode()) {
9763       // In the absence of fast-math-flags, this user node is always the
9764       // same node as Reciprocal, but with FMF they may be different nodes.
9765       CombineTo(U, Reciprocal);
9766     }
9767   }
9768   return SDValue(N, 0);  // N was replaced.
9769 }
9770
9771 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9772   SDValue N0 = N->getOperand(0);
9773   SDValue N1 = N->getOperand(1);
9774   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9775   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9776   EVT VT = N->getValueType(0);
9777   SDLoc DL(N);
9778   const TargetOptions &Options = DAG.getTarget().Options;
9779   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9780
9781   // fold vector ops
9782   if (VT.isVector())
9783     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9784       return FoldedVOp;
9785
9786   // fold (fdiv c1, c2) -> c1/c2
9787   if (N0CFP && N1CFP)
9788     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9789
9790   if (SDValue NewSel = foldBinOpIntoSelect(N))
9791     return NewSel;
9792
9793   if (Options.UnsafeFPMath) {
9794     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9795     if (N1CFP) {
9796       // Compute the reciprocal 1.0 / c2.
9797       const APFloat &N1APF = N1CFP->getValueAPF();
9798       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
9799       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
9800       // Only do the transform if the reciprocal is a legal fp immediate that
9801       // isn't too nasty (eg NaN, denormal, ...).
9802       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
9803           (!LegalOperations ||
9804            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
9805            // backend)... we should handle this gracefully after Legalize.
9806            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
9807            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
9808            TLI.isFPImmLegal(Recip, VT)))
9809         return DAG.getNode(ISD::FMUL, DL, VT, N0,
9810                            DAG.getConstantFP(Recip, DL, VT), Flags);
9811     }
9812
9813     // If this FDIV is part of a reciprocal square root, it may be folded
9814     // into a target-specific square root estimate instruction.
9815     if (N1.getOpcode() == ISD::FSQRT) {
9816       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
9817         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9818       }
9819     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
9820                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9821       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9822                                           Flags)) {
9823         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
9824         AddToWorklist(RV.getNode());
9825         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9826       }
9827     } else if (N1.getOpcode() == ISD::FP_ROUND &&
9828                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9829       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9830                                           Flags)) {
9831         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9832         AddToWorklist(RV.getNode());
9833         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9834       }
9835     } else if (N1.getOpcode() == ISD::FMUL) {
9836       // Look through an FMUL. Even though this won't remove the FDIV directly,
9837       // it's still worthwhile to get rid of the FSQRT if possible.
9838       SDValue SqrtOp;
9839       SDValue OtherOp;
9840       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9841         SqrtOp = N1.getOperand(0);
9842         OtherOp = N1.getOperand(1);
9843       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9844         SqrtOp = N1.getOperand(1);
9845         OtherOp = N1.getOperand(0);
9846       }
9847       if (SqrtOp.getNode()) {
9848         // We found a FSQRT, so try to make this fold:
9849         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9850         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9851           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9852           AddToWorklist(RV.getNode());
9853           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9854         }
9855       }
9856     }
9857
9858     // Fold into a reciprocal estimate and multiply instead of a real divide.
9859     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9860       AddToWorklist(RV.getNode());
9861       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9862     }
9863   }
9864
9865   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9866   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9867     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9868       // Both can be negated for free, check to see if at least one is cheaper
9869       // negated.
9870       if (LHSNeg == 2 || RHSNeg == 2)
9871         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9872                            GetNegatedExpression(N0, DAG, LegalOperations),
9873                            GetNegatedExpression(N1, DAG, LegalOperations),
9874                            Flags);
9875     }
9876   }
9877
9878   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9879     return CombineRepeatedDivisors;
9880
9881   return SDValue();
9882 }
9883
9884 SDValue DAGCombiner::visitFREM(SDNode *N) {
9885   SDValue N0 = N->getOperand(0);
9886   SDValue N1 = N->getOperand(1);
9887   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9888   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9889   EVT VT = N->getValueType(0);
9890
9891   // fold (frem c1, c2) -> fmod(c1,c2)
9892   if (N0CFP && N1CFP)
9893     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9894                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9895
9896   if (SDValue NewSel = foldBinOpIntoSelect(N))
9897     return NewSel;
9898
9899   return SDValue();
9900 }
9901
9902 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9903   if (!DAG.getTarget().Options.UnsafeFPMath)
9904     return SDValue();
9905
9906   SDValue N0 = N->getOperand(0);
9907   if (TLI.isFsqrtCheap(N0, DAG))
9908     return SDValue();
9909
9910   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9911   // For now, create a Flags object for use with all unsafe math transforms.
9912   SDNodeFlags Flags;
9913   Flags.setUnsafeAlgebra(true);
9914   return buildSqrtEstimate(N0, &Flags);
9915 }
9916
9917 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9918 /// copysign(x, fp_round(y)) -> copysign(x, y)
9919 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9920   SDValue N1 = N->getOperand(1);
9921   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9922        N1.getOpcode() == ISD::FP_ROUND)) {
9923     // Do not optimize out type conversion of f128 type yet.
9924     // For some targets like x86_64, configuration is changed to keep one f128
9925     // value in one SSE register, but instruction selection cannot handle
9926     // FCOPYSIGN on SSE registers yet.
9927     EVT N1VT = N1->getValueType(0);
9928     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9929     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9930   }
9931   return false;
9932 }
9933
9934 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9935   SDValue N0 = N->getOperand(0);
9936   SDValue N1 = N->getOperand(1);
9937   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9938   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9939   EVT VT = N->getValueType(0);
9940
9941   if (N0CFP && N1CFP) // Constant fold
9942     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9943
9944   if (N1CFP) {
9945     const APFloat &V = N1CFP->getValueAPF();
9946     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9947     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9948     if (!V.isNegative()) {
9949       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9950         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9951     } else {
9952       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9953         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9954                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9955     }
9956   }
9957
9958   // copysign(fabs(x), y) -> copysign(x, y)
9959   // copysign(fneg(x), y) -> copysign(x, y)
9960   // copysign(copysign(x,z), y) -> copysign(x, y)
9961   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9962       N0.getOpcode() == ISD::FCOPYSIGN)
9963     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9964
9965   // copysign(x, abs(y)) -> abs(x)
9966   if (N1.getOpcode() == ISD::FABS)
9967     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9968
9969   // copysign(x, copysign(y,z)) -> copysign(x, z)
9970   if (N1.getOpcode() == ISD::FCOPYSIGN)
9971     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9972
9973   // copysign(x, fp_extend(y)) -> copysign(x, y)
9974   // copysign(x, fp_round(y)) -> copysign(x, y)
9975   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9976     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9977
9978   return SDValue();
9979 }
9980
9981 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9982   SDValue N0 = N->getOperand(0);
9983   EVT VT = N->getValueType(0);
9984   EVT OpVT = N0.getValueType();
9985
9986   // fold (sint_to_fp c1) -> c1fp
9987   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9988       // ...but only if the target supports immediate floating-point values
9989       (!LegalOperations ||
9990        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9991     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9992
9993   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9994   // but UINT_TO_FP is legal on this target, try to convert.
9995   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9996       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9997     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9998     if (DAG.SignBitIsZero(N0))
9999       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10000   }
10001
10002   // The next optimizations are desirable only if SELECT_CC can be lowered.
10003   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10004     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10005     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10006         !VT.isVector() &&
10007         (!LegalOperations ||
10008          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10009       SDLoc DL(N);
10010       SDValue Ops[] =
10011         { N0.getOperand(0), N0.getOperand(1),
10012           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10013           N0.getOperand(2) };
10014       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10015     }
10016
10017     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10018     //      (select_cc x, y, 1.0, 0.0,, cc)
10019     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10020         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10021         (!LegalOperations ||
10022          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10023       SDLoc DL(N);
10024       SDValue Ops[] =
10025         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10026           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10027           N0.getOperand(0).getOperand(2) };
10028       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10029     }
10030   }
10031
10032   return SDValue();
10033 }
10034
10035 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10036   SDValue N0 = N->getOperand(0);
10037   EVT VT = N->getValueType(0);
10038   EVT OpVT = N0.getValueType();
10039
10040   // fold (uint_to_fp c1) -> c1fp
10041   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10042       // ...but only if the target supports immediate floating-point values
10043       (!LegalOperations ||
10044        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10045     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10046
10047   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10048   // but SINT_TO_FP is legal on this target, try to convert.
10049   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10050       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10051     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10052     if (DAG.SignBitIsZero(N0))
10053       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10054   }
10055
10056   // The next optimizations are desirable only if SELECT_CC can be lowered.
10057   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10058     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10059
10060     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10061         (!LegalOperations ||
10062          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10063       SDLoc DL(N);
10064       SDValue Ops[] =
10065         { N0.getOperand(0), N0.getOperand(1),
10066           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10067           N0.getOperand(2) };
10068       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10069     }
10070   }
10071
10072   return SDValue();
10073 }
10074
10075 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10076 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10077   SDValue N0 = N->getOperand(0);
10078   EVT VT = N->getValueType(0);
10079
10080   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10081     return SDValue();
10082
10083   SDValue Src = N0.getOperand(0);
10084   EVT SrcVT = Src.getValueType();
10085   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10086   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10087
10088   // We can safely assume the conversion won't overflow the output range,
10089   // because (for example) (uint8_t)18293.f is undefined behavior.
10090
10091   // Since we can assume the conversion won't overflow, our decision as to
10092   // whether the input will fit in the float should depend on the minimum
10093   // of the input range and output range.
10094
10095   // This means this is also safe for a signed input and unsigned output, since
10096   // a negative input would lead to undefined behavior.
10097   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10098   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10099   unsigned ActualSize = std::min(InputSize, OutputSize);
10100   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10101
10102   // We can only fold away the float conversion if the input range can be
10103   // represented exactly in the float range.
10104   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10105     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10106       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10107                                                        : ISD::ZERO_EXTEND;
10108       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10109     }
10110     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10111       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10112     return DAG.getBitcast(VT, Src);
10113   }
10114   return SDValue();
10115 }
10116
10117 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10118   SDValue N0 = N->getOperand(0);
10119   EVT VT = N->getValueType(0);
10120
10121   // fold (fp_to_sint c1fp) -> c1
10122   if (isConstantFPBuildVectorOrConstantFP(N0))
10123     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10124
10125   return FoldIntToFPToInt(N, DAG);
10126 }
10127
10128 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10129   SDValue N0 = N->getOperand(0);
10130   EVT VT = N->getValueType(0);
10131
10132   // fold (fp_to_uint c1fp) -> c1
10133   if (isConstantFPBuildVectorOrConstantFP(N0))
10134     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10135
10136   return FoldIntToFPToInt(N, DAG);
10137 }
10138
10139 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10140   SDValue N0 = N->getOperand(0);
10141   SDValue N1 = N->getOperand(1);
10142   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10143   EVT VT = N->getValueType(0);
10144
10145   // fold (fp_round c1fp) -> c1fp
10146   if (N0CFP)
10147     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10148
10149   // fold (fp_round (fp_extend x)) -> x
10150   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10151     return N0.getOperand(0);
10152
10153   // fold (fp_round (fp_round x)) -> (fp_round x)
10154   if (N0.getOpcode() == ISD::FP_ROUND) {
10155     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10156     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10157
10158     // Skip this folding if it results in an fp_round from f80 to f16.
10159     //
10160     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10161     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10162     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10163     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10164     // x86.
10165     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10166       return SDValue();
10167
10168     // If the first fp_round isn't a value preserving truncation, it might
10169     // introduce a tie in the second fp_round, that wouldn't occur in the
10170     // single-step fp_round we want to fold to.
10171     // In other words, double rounding isn't the same as rounding.
10172     // Also, this is a value preserving truncation iff both fp_round's are.
10173     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10174       SDLoc DL(N);
10175       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10176                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10177     }
10178   }
10179
10180   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10181   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10182     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10183                               N0.getOperand(0), N1);
10184     AddToWorklist(Tmp.getNode());
10185     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10186                        Tmp, N0.getOperand(1));
10187   }
10188
10189   return SDValue();
10190 }
10191
10192 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10193   SDValue N0 = N->getOperand(0);
10194   EVT VT = N->getValueType(0);
10195   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10196   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10197
10198   // fold (fp_round_inreg c1fp) -> c1fp
10199   if (N0CFP && isTypeLegal(EVT)) {
10200     SDLoc DL(N);
10201     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10202     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10203   }
10204
10205   return SDValue();
10206 }
10207
10208 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10209   SDValue N0 = N->getOperand(0);
10210   EVT VT = N->getValueType(0);
10211
10212   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10213   if (N->hasOneUse() &&
10214       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10215     return SDValue();
10216
10217   // fold (fp_extend c1fp) -> c1fp
10218   if (isConstantFPBuildVectorOrConstantFP(N0))
10219     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10220
10221   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10222   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10223       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10224     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10225
10226   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10227   // value of X.
10228   if (N0.getOpcode() == ISD::FP_ROUND
10229       && N0.getConstantOperandVal(1) == 1) {
10230     SDValue In = N0.getOperand(0);
10231     if (In.getValueType() == VT) return In;
10232     if (VT.bitsLT(In.getValueType()))
10233       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10234                          In, N0.getOperand(1));
10235     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10236   }
10237
10238   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10239   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10240        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10241     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10242     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10243                                      LN0->getChain(),
10244                                      LN0->getBasePtr(), N0.getValueType(),
10245                                      LN0->getMemOperand());
10246     CombineTo(N, ExtLoad);
10247     CombineTo(N0.getNode(),
10248               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10249                           N0.getValueType(), ExtLoad,
10250                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10251               ExtLoad.getValue(1));
10252     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10253   }
10254
10255   return SDValue();
10256 }
10257
10258 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10259   SDValue N0 = N->getOperand(0);
10260   EVT VT = N->getValueType(0);
10261
10262   // fold (fceil c1) -> fceil(c1)
10263   if (isConstantFPBuildVectorOrConstantFP(N0))
10264     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10265
10266   return SDValue();
10267 }
10268
10269 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10270   SDValue N0 = N->getOperand(0);
10271   EVT VT = N->getValueType(0);
10272
10273   // fold (ftrunc c1) -> ftrunc(c1)
10274   if (isConstantFPBuildVectorOrConstantFP(N0))
10275     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10276
10277   return SDValue();
10278 }
10279
10280 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10281   SDValue N0 = N->getOperand(0);
10282   EVT VT = N->getValueType(0);
10283
10284   // fold (ffloor c1) -> ffloor(c1)
10285   if (isConstantFPBuildVectorOrConstantFP(N0))
10286     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10287
10288   return SDValue();
10289 }
10290
10291 // FIXME: FNEG and FABS have a lot in common; refactor.
10292 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10293   SDValue N0 = N->getOperand(0);
10294   EVT VT = N->getValueType(0);
10295
10296   // Constant fold FNEG.
10297   if (isConstantFPBuildVectorOrConstantFP(N0))
10298     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10299
10300   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10301                          &DAG.getTarget().Options))
10302     return GetNegatedExpression(N0, DAG, LegalOperations);
10303
10304   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10305   // constant pool values.
10306   if (!TLI.isFNegFree(VT) &&
10307       N0.getOpcode() == ISD::BITCAST &&
10308       N0.getNode()->hasOneUse()) {
10309     SDValue Int = N0.getOperand(0);
10310     EVT IntVT = Int.getValueType();
10311     if (IntVT.isInteger() && !IntVT.isVector()) {
10312       APInt SignMask;
10313       if (N0.getValueType().isVector()) {
10314         // For a vector, get a mask such as 0x80... per scalar element
10315         // and splat it.
10316         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10317         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10318       } else {
10319         // For a scalar, just generate 0x80...
10320         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10321       }
10322       SDLoc DL0(N0);
10323       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10324                         DAG.getConstant(SignMask, DL0, IntVT));
10325       AddToWorklist(Int.getNode());
10326       return DAG.getBitcast(VT, Int);
10327     }
10328   }
10329
10330   // (fneg (fmul c, x)) -> (fmul -c, x)
10331   if (N0.getOpcode() == ISD::FMUL &&
10332       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10333     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10334     if (CFP1) {
10335       APFloat CVal = CFP1->getValueAPF();
10336       CVal.changeSign();
10337       if (Level >= AfterLegalizeDAG &&
10338           (TLI.isFPImmLegal(CVal, VT) ||
10339            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10340         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10341                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10342                                        N0.getOperand(1)),
10343                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
10344     }
10345   }
10346
10347   return SDValue();
10348 }
10349
10350 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10351   SDValue N0 = N->getOperand(0);
10352   SDValue N1 = N->getOperand(1);
10353   EVT VT = N->getValueType(0);
10354   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10355   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10356
10357   if (N0CFP && N1CFP) {
10358     const APFloat &C0 = N0CFP->getValueAPF();
10359     const APFloat &C1 = N1CFP->getValueAPF();
10360     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10361   }
10362
10363   // Canonicalize to constant on RHS.
10364   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10365      !isConstantFPBuildVectorOrConstantFP(N1))
10366     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10367
10368   return SDValue();
10369 }
10370
10371 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10372   SDValue N0 = N->getOperand(0);
10373   SDValue N1 = N->getOperand(1);
10374   EVT VT = N->getValueType(0);
10375   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10376   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10377
10378   if (N0CFP && N1CFP) {
10379     const APFloat &C0 = N0CFP->getValueAPF();
10380     const APFloat &C1 = N1CFP->getValueAPF();
10381     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10382   }
10383
10384   // Canonicalize to constant on RHS.
10385   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10386      !isConstantFPBuildVectorOrConstantFP(N1))
10387     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10388
10389   return SDValue();
10390 }
10391
10392 SDValue DAGCombiner::visitFABS(SDNode *N) {
10393   SDValue N0 = N->getOperand(0);
10394   EVT VT = N->getValueType(0);
10395
10396   // fold (fabs c1) -> fabs(c1)
10397   if (isConstantFPBuildVectorOrConstantFP(N0))
10398     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10399
10400   // fold (fabs (fabs x)) -> (fabs x)
10401   if (N0.getOpcode() == ISD::FABS)
10402     return N->getOperand(0);
10403
10404   // fold (fabs (fneg x)) -> (fabs x)
10405   // fold (fabs (fcopysign x, y)) -> (fabs x)
10406   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10407     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10408
10409   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10410   // constant pool values.
10411   if (!TLI.isFAbsFree(VT) &&
10412       N0.getOpcode() == ISD::BITCAST &&
10413       N0.getNode()->hasOneUse()) {
10414     SDValue Int = N0.getOperand(0);
10415     EVT IntVT = Int.getValueType();
10416     if (IntVT.isInteger() && !IntVT.isVector()) {
10417       APInt SignMask;
10418       if (N0.getValueType().isVector()) {
10419         // For a vector, get a mask such as 0x7f... per scalar element
10420         // and splat it.
10421         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10422         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10423       } else {
10424         // For a scalar, just generate 0x7f...
10425         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10426       }
10427       SDLoc DL(N0);
10428       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10429                         DAG.getConstant(SignMask, DL, IntVT));
10430       AddToWorklist(Int.getNode());
10431       return DAG.getBitcast(N->getValueType(0), Int);
10432     }
10433   }
10434
10435   return SDValue();
10436 }
10437
10438 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10439   SDValue Chain = N->getOperand(0);
10440   SDValue N1 = N->getOperand(1);
10441   SDValue N2 = N->getOperand(2);
10442
10443   // If N is a constant we could fold this into a fallthrough or unconditional
10444   // branch. However that doesn't happen very often in normal code, because
10445   // Instcombine/SimplifyCFG should have handled the available opportunities.
10446   // If we did this folding here, it would be necessary to update the
10447   // MachineBasicBlock CFG, which is awkward.
10448
10449   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10450   // on the target.
10451   if (N1.getOpcode() == ISD::SETCC &&
10452       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10453                                    N1.getOperand(0).getValueType())) {
10454     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10455                        Chain, N1.getOperand(2),
10456                        N1.getOperand(0), N1.getOperand(1), N2);
10457   }
10458
10459   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10460       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10461        (N1.getOperand(0).hasOneUse() &&
10462         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10463     SDNode *Trunc = nullptr;
10464     if (N1.getOpcode() == ISD::TRUNCATE) {
10465       // Look pass the truncate.
10466       Trunc = N1.getNode();
10467       N1 = N1.getOperand(0);
10468     }
10469
10470     // Match this pattern so that we can generate simpler code:
10471     //
10472     //   %a = ...
10473     //   %b = and i32 %a, 2
10474     //   %c = srl i32 %b, 1
10475     //   brcond i32 %c ...
10476     //
10477     // into
10478     //
10479     //   %a = ...
10480     //   %b = and i32 %a, 2
10481     //   %c = setcc eq %b, 0
10482     //   brcond %c ...
10483     //
10484     // This applies only when the AND constant value has one bit set and the
10485     // SRL constant is equal to the log2 of the AND constant. The back-end is
10486     // smart enough to convert the result into a TEST/JMP sequence.
10487     SDValue Op0 = N1.getOperand(0);
10488     SDValue Op1 = N1.getOperand(1);
10489
10490     if (Op0.getOpcode() == ISD::AND &&
10491         Op1.getOpcode() == ISD::Constant) {
10492       SDValue AndOp1 = Op0.getOperand(1);
10493
10494       if (AndOp1.getOpcode() == ISD::Constant) {
10495         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10496
10497         if (AndConst.isPowerOf2() &&
10498             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10499           SDLoc DL(N);
10500           SDValue SetCC =
10501             DAG.getSetCC(DL,
10502                          getSetCCResultType(Op0.getValueType()),
10503                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10504                          ISD::SETNE);
10505
10506           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10507                                           MVT::Other, Chain, SetCC, N2);
10508           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10509           // will convert it back to (X & C1) >> C2.
10510           CombineTo(N, NewBRCond, false);
10511           // Truncate is dead.
10512           if (Trunc)
10513             deleteAndRecombine(Trunc);
10514           // Replace the uses of SRL with SETCC
10515           WorklistRemover DeadNodes(*this);
10516           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10517           deleteAndRecombine(N1.getNode());
10518           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10519         }
10520       }
10521     }
10522
10523     if (Trunc)
10524       // Restore N1 if the above transformation doesn't match.
10525       N1 = N->getOperand(1);
10526   }
10527
10528   // Transform br(xor(x, y)) -> br(x != y)
10529   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10530   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10531     SDNode *TheXor = N1.getNode();
10532     SDValue Op0 = TheXor->getOperand(0);
10533     SDValue Op1 = TheXor->getOperand(1);
10534     if (Op0.getOpcode() == Op1.getOpcode()) {
10535       // Avoid missing important xor optimizations.
10536       if (SDValue Tmp = visitXOR(TheXor)) {
10537         if (Tmp.getNode() != TheXor) {
10538           DEBUG(dbgs() << "\nReplacing.8 ";
10539                 TheXor->dump(&DAG);
10540                 dbgs() << "\nWith: ";
10541                 Tmp.getNode()->dump(&DAG);
10542                 dbgs() << '\n');
10543           WorklistRemover DeadNodes(*this);
10544           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10545           deleteAndRecombine(TheXor);
10546           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10547                              MVT::Other, Chain, Tmp, N2);
10548         }
10549
10550         // visitXOR has changed XOR's operands or replaced the XOR completely,
10551         // bail out.
10552         return SDValue(N, 0);
10553       }
10554     }
10555
10556     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10557       bool Equal = false;
10558       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10559           Op0.getOpcode() == ISD::XOR) {
10560         TheXor = Op0.getNode();
10561         Equal = true;
10562       }
10563
10564       EVT SetCCVT = N1.getValueType();
10565       if (LegalTypes)
10566         SetCCVT = getSetCCResultType(SetCCVT);
10567       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10568                                    SetCCVT,
10569                                    Op0, Op1,
10570                                    Equal ? ISD::SETEQ : ISD::SETNE);
10571       // Replace the uses of XOR with SETCC
10572       WorklistRemover DeadNodes(*this);
10573       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10574       deleteAndRecombine(N1.getNode());
10575       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10576                          MVT::Other, Chain, SetCC, N2);
10577     }
10578   }
10579
10580   return SDValue();
10581 }
10582
10583 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10584 //
10585 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10586   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10587   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10588
10589   // If N is a constant we could fold this into a fallthrough or unconditional
10590   // branch. However that doesn't happen very often in normal code, because
10591   // Instcombine/SimplifyCFG should have handled the available opportunities.
10592   // If we did this folding here, it would be necessary to update the
10593   // MachineBasicBlock CFG, which is awkward.
10594
10595   // Use SimplifySetCC to simplify SETCC's.
10596   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10597                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10598                                false);
10599   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10600
10601   // fold to a simpler setcc
10602   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10603     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10604                        N->getOperand(0), Simp.getOperand(2),
10605                        Simp.getOperand(0), Simp.getOperand(1),
10606                        N->getOperand(4));
10607
10608   return SDValue();
10609 }
10610
10611 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10612 /// and that N may be folded in the load / store addressing mode.
10613 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10614                                     SelectionDAG &DAG,
10615                                     const TargetLowering &TLI) {
10616   EVT VT;
10617   unsigned AS;
10618
10619   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10620     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10621       return false;
10622     VT = LD->getMemoryVT();
10623     AS = LD->getAddressSpace();
10624   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10625     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10626       return false;
10627     VT = ST->getMemoryVT();
10628     AS = ST->getAddressSpace();
10629   } else
10630     return false;
10631
10632   TargetLowering::AddrMode AM;
10633   if (N->getOpcode() == ISD::ADD) {
10634     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10635     if (Offset)
10636       // [reg +/- imm]
10637       AM.BaseOffs = Offset->getSExtValue();
10638     else
10639       // [reg +/- reg]
10640       AM.Scale = 1;
10641   } else if (N->getOpcode() == ISD::SUB) {
10642     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10643     if (Offset)
10644       // [reg +/- imm]
10645       AM.BaseOffs = -Offset->getSExtValue();
10646     else
10647       // [reg +/- reg]
10648       AM.Scale = 1;
10649   } else
10650     return false;
10651
10652   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10653                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10654 }
10655
10656 /// Try turning a load/store into a pre-indexed load/store when the base
10657 /// pointer is an add or subtract and it has other uses besides the load/store.
10658 /// After the transformation, the new indexed load/store has effectively folded
10659 /// the add/subtract in and all of its other uses are redirected to the
10660 /// new load/store.
10661 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10662   if (Level < AfterLegalizeDAG)
10663     return false;
10664
10665   bool isLoad = true;
10666   SDValue Ptr;
10667   EVT VT;
10668   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10669     if (LD->isIndexed())
10670       return false;
10671     VT = LD->getMemoryVT();
10672     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10673         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10674       return false;
10675     Ptr = LD->getBasePtr();
10676   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10677     if (ST->isIndexed())
10678       return false;
10679     VT = ST->getMemoryVT();
10680     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10681         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10682       return false;
10683     Ptr = ST->getBasePtr();
10684     isLoad = false;
10685   } else {
10686     return false;
10687   }
10688
10689   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10690   // out.  There is no reason to make this a preinc/predec.
10691   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10692       Ptr.getNode()->hasOneUse())
10693     return false;
10694
10695   // Ask the target to do addressing mode selection.
10696   SDValue BasePtr;
10697   SDValue Offset;
10698   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10699   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10700     return false;
10701
10702   // Backends without true r+i pre-indexed forms may need to pass a
10703   // constant base with a variable offset so that constant coercion
10704   // will work with the patterns in canonical form.
10705   bool Swapped = false;
10706   if (isa<ConstantSDNode>(BasePtr)) {
10707     std::swap(BasePtr, Offset);
10708     Swapped = true;
10709   }
10710
10711   // Don't create a indexed load / store with zero offset.
10712   if (isNullConstant(Offset))
10713     return false;
10714
10715   // Try turning it into a pre-indexed load / store except when:
10716   // 1) The new base ptr is a frame index.
10717   // 2) If N is a store and the new base ptr is either the same as or is a
10718   //    predecessor of the value being stored.
10719   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10720   //    that would create a cycle.
10721   // 4) All uses are load / store ops that use it as old base ptr.
10722
10723   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
10724   // (plus the implicit offset) to a register to preinc anyway.
10725   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10726     return false;
10727
10728   // Check #2.
10729   if (!isLoad) {
10730     SDValue Val = cast<StoreSDNode>(N)->getValue();
10731     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10732       return false;
10733   }
10734
10735   // Caches for hasPredecessorHelper.
10736   SmallPtrSet<const SDNode *, 32> Visited;
10737   SmallVector<const SDNode *, 16> Worklist;
10738   Worklist.push_back(N);
10739
10740   // If the offset is a constant, there may be other adds of constants that
10741   // can be folded with this one. We should do this to avoid having to keep
10742   // a copy of the original base pointer.
10743   SmallVector<SDNode *, 16> OtherUses;
10744   if (isa<ConstantSDNode>(Offset))
10745     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10746                               UE = BasePtr.getNode()->use_end();
10747          UI != UE; ++UI) {
10748       SDUse &Use = UI.getUse();
10749       // Skip the use that is Ptr and uses of other results from BasePtr's
10750       // node (important for nodes that return multiple results).
10751       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10752         continue;
10753
10754       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10755         continue;
10756
10757       if (Use.getUser()->getOpcode() != ISD::ADD &&
10758           Use.getUser()->getOpcode() != ISD::SUB) {
10759         OtherUses.clear();
10760         break;
10761       }
10762
10763       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10764       if (!isa<ConstantSDNode>(Op1)) {
10765         OtherUses.clear();
10766         break;
10767       }
10768
10769       // FIXME: In some cases, we can be smarter about this.
10770       if (Op1.getValueType() != Offset.getValueType()) {
10771         OtherUses.clear();
10772         break;
10773       }
10774
10775       OtherUses.push_back(Use.getUser());
10776     }
10777
10778   if (Swapped)
10779     std::swap(BasePtr, Offset);
10780
10781   // Now check for #3 and #4.
10782   bool RealUse = false;
10783
10784   for (SDNode *Use : Ptr.getNode()->uses()) {
10785     if (Use == N)
10786       continue;
10787     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10788       return false;
10789
10790     // If Ptr may be folded in addressing mode of other use, then it's
10791     // not profitable to do this transformation.
10792     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
10793       RealUse = true;
10794   }
10795
10796   if (!RealUse)
10797     return false;
10798
10799   SDValue Result;
10800   if (isLoad)
10801     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10802                                 BasePtr, Offset, AM);
10803   else
10804     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10805                                  BasePtr, Offset, AM);
10806   ++PreIndexedNodes;
10807   ++NodesCombined;
10808   DEBUG(dbgs() << "\nReplacing.4 ";
10809         N->dump(&DAG);
10810         dbgs() << "\nWith: ";
10811         Result.getNode()->dump(&DAG);
10812         dbgs() << '\n');
10813   WorklistRemover DeadNodes(*this);
10814   if (isLoad) {
10815     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10816     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10817   } else {
10818     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10819   }
10820
10821   // Finally, since the node is now dead, remove it from the graph.
10822   deleteAndRecombine(N);
10823
10824   if (Swapped)
10825     std::swap(BasePtr, Offset);
10826
10827   // Replace other uses of BasePtr that can be updated to use Ptr
10828   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10829     unsigned OffsetIdx = 1;
10830     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10831       OffsetIdx = 0;
10832     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10833            BasePtr.getNode() && "Expected BasePtr operand");
10834
10835     // We need to replace ptr0 in the following expression:
10836     //   x0 * offset0 + y0 * ptr0 = t0
10837     // knowing that
10838     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10839     //
10840     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10841     // indexed load/store and the expresion that needs to be re-written.
10842     //
10843     // Therefore, we have:
10844     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10845
10846     ConstantSDNode *CN =
10847       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10848     int X0, X1, Y0, Y1;
10849     const APInt &Offset0 = CN->getAPIntValue();
10850     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10851
10852     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10853     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10854     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10855     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10856
10857     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10858
10859     APInt CNV = Offset0;
10860     if (X0 < 0) CNV = -CNV;
10861     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10862     else CNV = CNV - Offset1;
10863
10864     SDLoc DL(OtherUses[i]);
10865
10866     // We can now generate the new expression.
10867     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10868     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10869
10870     SDValue NewUse = DAG.getNode(Opcode,
10871                                  DL,
10872                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10873     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10874     deleteAndRecombine(OtherUses[i]);
10875   }
10876
10877   // Replace the uses of Ptr with uses of the updated base value.
10878   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10879   deleteAndRecombine(Ptr.getNode());
10880
10881   return true;
10882 }
10883
10884 /// Try to combine a load/store with a add/sub of the base pointer node into a
10885 /// post-indexed load/store. The transformation folded the add/subtract into the
10886 /// new indexed load/store effectively and all of its uses are redirected to the
10887 /// new load/store.
10888 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10889   if (Level < AfterLegalizeDAG)
10890     return false;
10891
10892   bool isLoad = true;
10893   SDValue Ptr;
10894   EVT VT;
10895   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10896     if (LD->isIndexed())
10897       return false;
10898     VT = LD->getMemoryVT();
10899     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10900         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10901       return false;
10902     Ptr = LD->getBasePtr();
10903   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10904     if (ST->isIndexed())
10905       return false;
10906     VT = ST->getMemoryVT();
10907     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10908         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10909       return false;
10910     Ptr = ST->getBasePtr();
10911     isLoad = false;
10912   } else {
10913     return false;
10914   }
10915
10916   if (Ptr.getNode()->hasOneUse())
10917     return false;
10918
10919   for (SDNode *Op : Ptr.getNode()->uses()) {
10920     if (Op == N ||
10921         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10922       continue;
10923
10924     SDValue BasePtr;
10925     SDValue Offset;
10926     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10927     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10928       // Don't create a indexed load / store with zero offset.
10929       if (isNullConstant(Offset))
10930         continue;
10931
10932       // Try turning it into a post-indexed load / store except when
10933       // 1) All uses are load / store ops that use it as base ptr (and
10934       //    it may be folded as addressing mmode).
10935       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10936       //    nor a successor of N. Otherwise, if Op is folded that would
10937       //    create a cycle.
10938
10939       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10940         continue;
10941
10942       // Check for #1.
10943       bool TryNext = false;
10944       for (SDNode *Use : BasePtr.getNode()->uses()) {
10945         if (Use == Ptr.getNode())
10946           continue;
10947
10948         // If all the uses are load / store addresses, then don't do the
10949         // transformation.
10950         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10951           bool RealUse = false;
10952           for (SDNode *UseUse : Use->uses()) {
10953             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10954               RealUse = true;
10955           }
10956
10957           if (!RealUse) {
10958             TryNext = true;
10959             break;
10960           }
10961         }
10962       }
10963
10964       if (TryNext)
10965         continue;
10966
10967       // Check for #2
10968       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10969         SDValue Result = isLoad
10970           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10971                                BasePtr, Offset, AM)
10972           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10973                                 BasePtr, Offset, AM);
10974         ++PostIndexedNodes;
10975         ++NodesCombined;
10976         DEBUG(dbgs() << "\nReplacing.5 ";
10977               N->dump(&DAG);
10978               dbgs() << "\nWith: ";
10979               Result.getNode()->dump(&DAG);
10980               dbgs() << '\n');
10981         WorklistRemover DeadNodes(*this);
10982         if (isLoad) {
10983           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10984           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10985         } else {
10986           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10987         }
10988
10989         // Finally, since the node is now dead, remove it from the graph.
10990         deleteAndRecombine(N);
10991
10992         // Replace the uses of Use with uses of the updated base value.
10993         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10994                                       Result.getValue(isLoad ? 1 : 0));
10995         deleteAndRecombine(Op);
10996         return true;
10997       }
10998     }
10999   }
11000
11001   return false;
11002 }
11003
11004 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11005 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11006   ISD::MemIndexedMode AM = LD->getAddressingMode();
11007   assert(AM != ISD::UNINDEXED);
11008   SDValue BP = LD->getOperand(1);
11009   SDValue Inc = LD->getOperand(2);
11010
11011   // Some backends use TargetConstants for load offsets, but don't expect
11012   // TargetConstants in general ADD nodes. We can convert these constants into
11013   // regular Constants (if the constant is not opaque).
11014   assert((Inc.getOpcode() != ISD::TargetConstant ||
11015           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11016          "Cannot split out indexing using opaque target constants");
11017   if (Inc.getOpcode() == ISD::TargetConstant) {
11018     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11019     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11020                           ConstInc->getValueType(0));
11021   }
11022
11023   unsigned Opc =
11024       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11025   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11026 }
11027
11028 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11029   LoadSDNode *LD  = cast<LoadSDNode>(N);
11030   SDValue Chain = LD->getChain();
11031   SDValue Ptr   = LD->getBasePtr();
11032
11033   // If load is not volatile and there are no uses of the loaded value (and
11034   // the updated indexed value in case of indexed loads), change uses of the
11035   // chain value into uses of the chain input (i.e. delete the dead load).
11036   if (!LD->isVolatile()) {
11037     if (N->getValueType(1) == MVT::Other) {
11038       // Unindexed loads.
11039       if (!N->hasAnyUseOfValue(0)) {
11040         // It's not safe to use the two value CombineTo variant here. e.g.
11041         // v1, chain2 = load chain1, loc
11042         // v2, chain3 = load chain2, loc
11043         // v3         = add v2, c
11044         // Now we replace use of chain2 with chain1.  This makes the second load
11045         // isomorphic to the one we are deleting, and thus makes this load live.
11046         DEBUG(dbgs() << "\nReplacing.6 ";
11047               N->dump(&DAG);
11048               dbgs() << "\nWith chain: ";
11049               Chain.getNode()->dump(&DAG);
11050               dbgs() << "\n");
11051         WorklistRemover DeadNodes(*this);
11052         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11053         AddUsersToWorklist(Chain.getNode());
11054         if (N->use_empty())
11055           deleteAndRecombine(N);
11056
11057         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11058       }
11059     } else {
11060       // Indexed loads.
11061       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11062
11063       // If this load has an opaque TargetConstant offset, then we cannot split
11064       // the indexing into an add/sub directly (that TargetConstant may not be
11065       // valid for a different type of node, and we cannot convert an opaque
11066       // target constant into a regular constant).
11067       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11068                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11069
11070       if (!N->hasAnyUseOfValue(0) &&
11071           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11072         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11073         SDValue Index;
11074         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11075           Index = SplitIndexingFromLoad(LD);
11076           // Try to fold the base pointer arithmetic into subsequent loads and
11077           // stores.
11078           AddUsersToWorklist(N);
11079         } else
11080           Index = DAG.getUNDEF(N->getValueType(1));
11081         DEBUG(dbgs() << "\nReplacing.7 ";
11082               N->dump(&DAG);
11083               dbgs() << "\nWith: ";
11084               Undef.getNode()->dump(&DAG);
11085               dbgs() << " and 2 other values\n");
11086         WorklistRemover DeadNodes(*this);
11087         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11088         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11089         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11090         deleteAndRecombine(N);
11091         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11092       }
11093     }
11094   }
11095
11096   // If this load is directly stored, replace the load value with the stored
11097   // value.
11098   // TODO: Handle store large -> read small portion.
11099   // TODO: Handle TRUNCSTORE/LOADEXT
11100   if (OptLevel != CodeGenOpt::None &&
11101       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11102     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11103       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11104       if (PrevST->getBasePtr() == Ptr &&
11105           PrevST->getValue().getValueType() == N->getValueType(0))
11106         return CombineTo(N, PrevST->getOperand(1), Chain);
11107     }
11108   }
11109
11110   // Try to infer better alignment information than the load already has.
11111   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11112     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11113       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11114         SDValue NewLoad = DAG.getExtLoad(
11115             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11116             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11117             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11118         if (NewLoad.getNode() != N)
11119           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11120       }
11121     }
11122   }
11123
11124   if (LD->isUnindexed()) {
11125     // Walk up chain skipping non-aliasing memory nodes.
11126     SDValue BetterChain = FindBetterChain(N, Chain);
11127
11128     // If there is a better chain.
11129     if (Chain != BetterChain) {
11130       SDValue ReplLoad;
11131
11132       // Replace the chain to void dependency.
11133       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11134         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11135                                BetterChain, Ptr, LD->getMemOperand());
11136       } else {
11137         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11138                                   LD->getValueType(0),
11139                                   BetterChain, Ptr, LD->getMemoryVT(),
11140                                   LD->getMemOperand());
11141       }
11142
11143       // Create token factor to keep old chain connected.
11144       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11145                                   MVT::Other, Chain, ReplLoad.getValue(1));
11146
11147       // Make sure the new and old chains are cleaned up.
11148       AddToWorklist(Token.getNode());
11149
11150       // Replace uses with load result and token factor. Don't add users
11151       // to work list.
11152       return CombineTo(N, ReplLoad.getValue(0), Token, false);
11153     }
11154   }
11155
11156   // Try transforming N to an indexed load.
11157   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11158     return SDValue(N, 0);
11159
11160   // Try to slice up N to more direct loads if the slices are mapped to
11161   // different register banks or pairing can take place.
11162   if (SliceUpLoad(N))
11163     return SDValue(N, 0);
11164
11165   return SDValue();
11166 }
11167
11168 namespace {
11169 /// \brief Helper structure used to slice a load in smaller loads.
11170 /// Basically a slice is obtained from the following sequence:
11171 /// Origin = load Ty1, Base
11172 /// Shift = srl Ty1 Origin, CstTy Amount
11173 /// Inst = trunc Shift to Ty2
11174 ///
11175 /// Then, it will be rewriten into:
11176 /// Slice = load SliceTy, Base + SliceOffset
11177 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11178 ///
11179 /// SliceTy is deduced from the number of bits that are actually used to
11180 /// build Inst.
11181 struct LoadedSlice {
11182   /// \brief Helper structure used to compute the cost of a slice.
11183   struct Cost {
11184     /// Are we optimizing for code size.
11185     bool ForCodeSize;
11186     /// Various cost.
11187     unsigned Loads;
11188     unsigned Truncates;
11189     unsigned CrossRegisterBanksCopies;
11190     unsigned ZExts;
11191     unsigned Shift;
11192
11193     Cost(bool ForCodeSize = false)
11194         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11195           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11196
11197     /// \brief Get the cost of one isolated slice.
11198     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11199         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11200           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11201       EVT TruncType = LS.Inst->getValueType(0);
11202       EVT LoadedType = LS.getLoadedType();
11203       if (TruncType != LoadedType &&
11204           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11205         ZExts = 1;
11206     }
11207
11208     /// \brief Account for slicing gain in the current cost.
11209     /// Slicing provide a few gains like removing a shift or a
11210     /// truncate. This method allows to grow the cost of the original
11211     /// load with the gain from this slice.
11212     void addSliceGain(const LoadedSlice &LS) {
11213       // Each slice saves a truncate.
11214       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11215       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11216                               LS.Inst->getValueType(0)))
11217         ++Truncates;
11218       // If there is a shift amount, this slice gets rid of it.
11219       if (LS.Shift)
11220         ++Shift;
11221       // If this slice can merge a cross register bank copy, account for it.
11222       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11223         ++CrossRegisterBanksCopies;
11224     }
11225
11226     Cost &operator+=(const Cost &RHS) {
11227       Loads += RHS.Loads;
11228       Truncates += RHS.Truncates;
11229       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11230       ZExts += RHS.ZExts;
11231       Shift += RHS.Shift;
11232       return *this;
11233     }
11234
11235     bool operator==(const Cost &RHS) const {
11236       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11237              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11238              ZExts == RHS.ZExts && Shift == RHS.Shift;
11239     }
11240
11241     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11242
11243     bool operator<(const Cost &RHS) const {
11244       // Assume cross register banks copies are as expensive as loads.
11245       // FIXME: Do we want some more target hooks?
11246       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11247       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11248       // Unless we are optimizing for code size, consider the
11249       // expensive operation first.
11250       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11251         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11252       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11253              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11254     }
11255
11256     bool operator>(const Cost &RHS) const { return RHS < *this; }
11257
11258     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11259
11260     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11261   };
11262   // The last instruction that represent the slice. This should be a
11263   // truncate instruction.
11264   SDNode *Inst;
11265   // The original load instruction.
11266   LoadSDNode *Origin;
11267   // The right shift amount in bits from the original load.
11268   unsigned Shift;
11269   // The DAG from which Origin came from.
11270   // This is used to get some contextual information about legal types, etc.
11271   SelectionDAG *DAG;
11272
11273   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11274               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11275       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11276
11277   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11278   /// \return Result is \p BitWidth and has used bits set to 1 and
11279   ///         not used bits set to 0.
11280   APInt getUsedBits() const {
11281     // Reproduce the trunc(lshr) sequence:
11282     // - Start from the truncated value.
11283     // - Zero extend to the desired bit width.
11284     // - Shift left.
11285     assert(Origin && "No original load to compare against.");
11286     unsigned BitWidth = Origin->getValueSizeInBits(0);
11287     assert(Inst && "This slice is not bound to an instruction");
11288     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11289            "Extracted slice is bigger than the whole type!");
11290     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11291     UsedBits.setAllBits();
11292     UsedBits = UsedBits.zext(BitWidth);
11293     UsedBits <<= Shift;
11294     return UsedBits;
11295   }
11296
11297   /// \brief Get the size of the slice to be loaded in bytes.
11298   unsigned getLoadedSize() const {
11299     unsigned SliceSize = getUsedBits().countPopulation();
11300     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11301     return SliceSize / 8;
11302   }
11303
11304   /// \brief Get the type that will be loaded for this slice.
11305   /// Note: This may not be the final type for the slice.
11306   EVT getLoadedType() const {
11307     assert(DAG && "Missing context");
11308     LLVMContext &Ctxt = *DAG->getContext();
11309     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11310   }
11311
11312   /// \brief Get the alignment of the load used for this slice.
11313   unsigned getAlignment() const {
11314     unsigned Alignment = Origin->getAlignment();
11315     unsigned Offset = getOffsetFromBase();
11316     if (Offset != 0)
11317       Alignment = MinAlign(Alignment, Alignment + Offset);
11318     return Alignment;
11319   }
11320
11321   /// \brief Check if this slice can be rewritten with legal operations.
11322   bool isLegal() const {
11323     // An invalid slice is not legal.
11324     if (!Origin || !Inst || !DAG)
11325       return false;
11326
11327     // Offsets are for indexed load only, we do not handle that.
11328     if (!Origin->getOffset().isUndef())
11329       return false;
11330
11331     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11332
11333     // Check that the type is legal.
11334     EVT SliceType = getLoadedType();
11335     if (!TLI.isTypeLegal(SliceType))
11336       return false;
11337
11338     // Check that the load is legal for this type.
11339     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11340       return false;
11341
11342     // Check that the offset can be computed.
11343     // 1. Check its type.
11344     EVT PtrType = Origin->getBasePtr().getValueType();
11345     if (PtrType == MVT::Untyped || PtrType.isExtended())
11346       return false;
11347
11348     // 2. Check that it fits in the immediate.
11349     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11350       return false;
11351
11352     // 3. Check that the computation is legal.
11353     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11354       return false;
11355
11356     // Check that the zext is legal if it needs one.
11357     EVT TruncateType = Inst->getValueType(0);
11358     if (TruncateType != SliceType &&
11359         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11360       return false;
11361
11362     return true;
11363   }
11364
11365   /// \brief Get the offset in bytes of this slice in the original chunk of
11366   /// bits.
11367   /// \pre DAG != nullptr.
11368   uint64_t getOffsetFromBase() const {
11369     assert(DAG && "Missing context.");
11370     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11371     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11372     uint64_t Offset = Shift / 8;
11373     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11374     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11375            "The size of the original loaded type is not a multiple of a"
11376            " byte.");
11377     // If Offset is bigger than TySizeInBytes, it means we are loading all
11378     // zeros. This should have been optimized before in the process.
11379     assert(TySizeInBytes > Offset &&
11380            "Invalid shift amount for given loaded size");
11381     if (IsBigEndian)
11382       Offset = TySizeInBytes - Offset - getLoadedSize();
11383     return Offset;
11384   }
11385
11386   /// \brief Generate the sequence of instructions to load the slice
11387   /// represented by this object and redirect the uses of this slice to
11388   /// this new sequence of instructions.
11389   /// \pre this->Inst && this->Origin are valid Instructions and this
11390   /// object passed the legal check: LoadedSlice::isLegal returned true.
11391   /// \return The last instruction of the sequence used to load the slice.
11392   SDValue loadSlice() const {
11393     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11394     const SDValue &OldBaseAddr = Origin->getBasePtr();
11395     SDValue BaseAddr = OldBaseAddr;
11396     // Get the offset in that chunk of bytes w.r.t. the endianness.
11397     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11398     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11399     if (Offset) {
11400       // BaseAddr = BaseAddr + Offset.
11401       EVT ArithType = BaseAddr.getValueType();
11402       SDLoc DL(Origin);
11403       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11404                               DAG->getConstant(Offset, DL, ArithType));
11405     }
11406
11407     // Create the type of the loaded slice according to its size.
11408     EVT SliceType = getLoadedType();
11409
11410     // Create the load for the slice.
11411     SDValue LastInst =
11412         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11413                      Origin->getPointerInfo().getWithOffset(Offset),
11414                      getAlignment(), Origin->getMemOperand()->getFlags());
11415     // If the final type is not the same as the loaded type, this means that
11416     // we have to pad with zero. Create a zero extend for that.
11417     EVT FinalType = Inst->getValueType(0);
11418     if (SliceType != FinalType)
11419       LastInst =
11420           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11421     return LastInst;
11422   }
11423
11424   /// \brief Check if this slice can be merged with an expensive cross register
11425   /// bank copy. E.g.,
11426   /// i = load i32
11427   /// f = bitcast i32 i to float
11428   bool canMergeExpensiveCrossRegisterBankCopy() const {
11429     if (!Inst || !Inst->hasOneUse())
11430       return false;
11431     SDNode *Use = *Inst->use_begin();
11432     if (Use->getOpcode() != ISD::BITCAST)
11433       return false;
11434     assert(DAG && "Missing context");
11435     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11436     EVT ResVT = Use->getValueType(0);
11437     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11438     const TargetRegisterClass *ArgRC =
11439         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11440     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11441       return false;
11442
11443     // At this point, we know that we perform a cross-register-bank copy.
11444     // Check if it is expensive.
11445     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11446     // Assume bitcasts are cheap, unless both register classes do not
11447     // explicitly share a common sub class.
11448     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11449       return false;
11450
11451     // Check if it will be merged with the load.
11452     // 1. Check the alignment constraint.
11453     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11454         ResVT.getTypeForEVT(*DAG->getContext()));
11455
11456     if (RequiredAlignment > getAlignment())
11457       return false;
11458
11459     // 2. Check that the load is a legal operation for that type.
11460     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11461       return false;
11462
11463     // 3. Check that we do not have a zext in the way.
11464     if (Inst->getValueType(0) != getLoadedType())
11465       return false;
11466
11467     return true;
11468   }
11469 };
11470 }
11471
11472 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11473 /// \p UsedBits looks like 0..0 1..1 0..0.
11474 static bool areUsedBitsDense(const APInt &UsedBits) {
11475   // If all the bits are one, this is dense!
11476   if (UsedBits.isAllOnesValue())
11477     return true;
11478
11479   // Get rid of the unused bits on the right.
11480   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11481   // Get rid of the unused bits on the left.
11482   if (NarrowedUsedBits.countLeadingZeros())
11483     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11484   // Check that the chunk of bits is completely used.
11485   return NarrowedUsedBits.isAllOnesValue();
11486 }
11487
11488 /// \brief Check whether or not \p First and \p Second are next to each other
11489 /// in memory. This means that there is no hole between the bits loaded
11490 /// by \p First and the bits loaded by \p Second.
11491 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11492                                      const LoadedSlice &Second) {
11493   assert(First.Origin == Second.Origin && First.Origin &&
11494          "Unable to match different memory origins.");
11495   APInt UsedBits = First.getUsedBits();
11496   assert((UsedBits & Second.getUsedBits()) == 0 &&
11497          "Slices are not supposed to overlap.");
11498   UsedBits |= Second.getUsedBits();
11499   return areUsedBitsDense(UsedBits);
11500 }
11501
11502 /// \brief Adjust the \p GlobalLSCost according to the target
11503 /// paring capabilities and the layout of the slices.
11504 /// \pre \p GlobalLSCost should account for at least as many loads as
11505 /// there is in the slices in \p LoadedSlices.
11506 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11507                                  LoadedSlice::Cost &GlobalLSCost) {
11508   unsigned NumberOfSlices = LoadedSlices.size();
11509   // If there is less than 2 elements, no pairing is possible.
11510   if (NumberOfSlices < 2)
11511     return;
11512
11513   // Sort the slices so that elements that are likely to be next to each
11514   // other in memory are next to each other in the list.
11515   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11516             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11517     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11518     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11519   });
11520   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11521   // First (resp. Second) is the first (resp. Second) potentially candidate
11522   // to be placed in a paired load.
11523   const LoadedSlice *First = nullptr;
11524   const LoadedSlice *Second = nullptr;
11525   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11526                 // Set the beginning of the pair.
11527                                                            First = Second) {
11528
11529     Second = &LoadedSlices[CurrSlice];
11530
11531     // If First is NULL, it means we start a new pair.
11532     // Get to the next slice.
11533     if (!First)
11534       continue;
11535
11536     EVT LoadedType = First->getLoadedType();
11537
11538     // If the types of the slices are different, we cannot pair them.
11539     if (LoadedType != Second->getLoadedType())
11540       continue;
11541
11542     // Check if the target supplies paired loads for this type.
11543     unsigned RequiredAlignment = 0;
11544     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11545       // move to the next pair, this type is hopeless.
11546       Second = nullptr;
11547       continue;
11548     }
11549     // Check if we meet the alignment requirement.
11550     if (RequiredAlignment > First->getAlignment())
11551       continue;
11552
11553     // Check that both loads are next to each other in memory.
11554     if (!areSlicesNextToEachOther(*First, *Second))
11555       continue;
11556
11557     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11558     --GlobalLSCost.Loads;
11559     // Move to the next pair.
11560     Second = nullptr;
11561   }
11562 }
11563
11564 /// \brief Check the profitability of all involved LoadedSlice.
11565 /// Currently, it is considered profitable if there is exactly two
11566 /// involved slices (1) which are (2) next to each other in memory, and
11567 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11568 ///
11569 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11570 /// the elements themselves.
11571 ///
11572 /// FIXME: When the cost model will be mature enough, we can relax
11573 /// constraints (1) and (2).
11574 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11575                                 const APInt &UsedBits, bool ForCodeSize) {
11576   unsigned NumberOfSlices = LoadedSlices.size();
11577   if (StressLoadSlicing)
11578     return NumberOfSlices > 1;
11579
11580   // Check (1).
11581   if (NumberOfSlices != 2)
11582     return false;
11583
11584   // Check (2).
11585   if (!areUsedBitsDense(UsedBits))
11586     return false;
11587
11588   // Check (3).
11589   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11590   // The original code has one big load.
11591   OrigCost.Loads = 1;
11592   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11593     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11594     // Accumulate the cost of all the slices.
11595     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11596     GlobalSlicingCost += SliceCost;
11597
11598     // Account as cost in the original configuration the gain obtained
11599     // with the current slices.
11600     OrigCost.addSliceGain(LS);
11601   }
11602
11603   // If the target supports paired load, adjust the cost accordingly.
11604   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11605   return OrigCost > GlobalSlicingCost;
11606 }
11607
11608 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11609 /// operations, split it in the various pieces being extracted.
11610 ///
11611 /// This sort of thing is introduced by SROA.
11612 /// This slicing takes care not to insert overlapping loads.
11613 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11614 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11615   if (Level < AfterLegalizeDAG)
11616     return false;
11617
11618   LoadSDNode *LD = cast<LoadSDNode>(N);
11619   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11620       !LD->getValueType(0).isInteger())
11621     return false;
11622
11623   // Keep track of already used bits to detect overlapping values.
11624   // In that case, we will just abort the transformation.
11625   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11626
11627   SmallVector<LoadedSlice, 4> LoadedSlices;
11628
11629   // Check if this load is used as several smaller chunks of bits.
11630   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11631   // of computation for each trunc.
11632   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11633        UI != UIEnd; ++UI) {
11634     // Skip the uses of the chain.
11635     if (UI.getUse().getResNo() != 0)
11636       continue;
11637
11638     SDNode *User = *UI;
11639     unsigned Shift = 0;
11640
11641     // Check if this is a trunc(lshr).
11642     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11643         isa<ConstantSDNode>(User->getOperand(1))) {
11644       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
11645       User = *User->use_begin();
11646     }
11647
11648     // At this point, User is a Truncate, iff we encountered, trunc or
11649     // trunc(lshr).
11650     if (User->getOpcode() != ISD::TRUNCATE)
11651       return false;
11652
11653     // The width of the type must be a power of 2 and greater than 8-bits.
11654     // Otherwise the load cannot be represented in LLVM IR.
11655     // Moreover, if we shifted with a non-8-bits multiple, the slice
11656     // will be across several bytes. We do not support that.
11657     unsigned Width = User->getValueSizeInBits(0);
11658     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11659       return 0;
11660
11661     // Build the slice for this chain of computations.
11662     LoadedSlice LS(User, LD, Shift, &DAG);
11663     APInt CurrentUsedBits = LS.getUsedBits();
11664
11665     // Check if this slice overlaps with another.
11666     if ((CurrentUsedBits & UsedBits) != 0)
11667       return false;
11668     // Update the bits used globally.
11669     UsedBits |= CurrentUsedBits;
11670
11671     // Check if the new slice would be legal.
11672     if (!LS.isLegal())
11673       return false;
11674
11675     // Record the slice.
11676     LoadedSlices.push_back(LS);
11677   }
11678
11679   // Abort slicing if it does not seem to be profitable.
11680   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11681     return false;
11682
11683   ++SlicedLoads;
11684
11685   // Rewrite each chain to use an independent load.
11686   // By construction, each chain can be represented by a unique load.
11687
11688   // Prepare the argument for the new token factor for all the slices.
11689   SmallVector<SDValue, 8> ArgChains;
11690   for (SmallVectorImpl<LoadedSlice>::const_iterator
11691            LSIt = LoadedSlices.begin(),
11692            LSItEnd = LoadedSlices.end();
11693        LSIt != LSItEnd; ++LSIt) {
11694     SDValue SliceInst = LSIt->loadSlice();
11695     CombineTo(LSIt->Inst, SliceInst, true);
11696     if (SliceInst.getOpcode() != ISD::LOAD)
11697       SliceInst = SliceInst.getOperand(0);
11698     assert(SliceInst->getOpcode() == ISD::LOAD &&
11699            "It takes more than a zext to get to the loaded slice!!");
11700     ArgChains.push_back(SliceInst.getValue(1));
11701   }
11702
11703   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11704                               ArgChains);
11705   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11706   AddToWorklist(Chain.getNode());
11707   return true;
11708 }
11709
11710 /// Check to see if V is (and load (ptr), imm), where the load is having
11711 /// specific bytes cleared out.  If so, return the byte size being masked out
11712 /// and the shift amount.
11713 static std::pair<unsigned, unsigned>
11714 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11715   std::pair<unsigned, unsigned> Result(0, 0);
11716
11717   // Check for the structure we're looking for.
11718   if (V->getOpcode() != ISD::AND ||
11719       !isa<ConstantSDNode>(V->getOperand(1)) ||
11720       !ISD::isNormalLoad(V->getOperand(0).getNode()))
11721     return Result;
11722
11723   // Check the chain and pointer.
11724   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11725   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
11726
11727   // The store should be chained directly to the load or be an operand of a
11728   // tokenfactor.
11729   if (LD == Chain.getNode())
11730     ; // ok.
11731   else if (Chain->getOpcode() != ISD::TokenFactor)
11732     return Result; // Fail.
11733   else {
11734     bool isOk = false;
11735     for (const SDValue &ChainOp : Chain->op_values())
11736       if (ChainOp.getNode() == LD) {
11737         isOk = true;
11738         break;
11739       }
11740     if (!isOk) return Result;
11741   }
11742
11743   // This only handles simple types.
11744   if (V.getValueType() != MVT::i16 &&
11745       V.getValueType() != MVT::i32 &&
11746       V.getValueType() != MVT::i64)
11747     return Result;
11748
11749   // Check the constant mask.  Invert it so that the bits being masked out are
11750   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
11751   // follow the sign bit for uniformity.
11752   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11753   unsigned NotMaskLZ = countLeadingZeros(NotMask);
11754   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
11755   unsigned NotMaskTZ = countTrailingZeros(NotMask);
11756   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
11757   if (NotMaskLZ == 64) return Result;  // All zero mask.
11758
11759   // See if we have a continuous run of bits.  If so, we have 0*1+0*
11760   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11761     return Result;
11762
11763   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11764   if (V.getValueType() != MVT::i64 && NotMaskLZ)
11765     NotMaskLZ -= 64-V.getValueSizeInBits();
11766
11767   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11768   switch (MaskedBytes) {
11769   case 1:
11770   case 2:
11771   case 4: break;
11772   default: return Result; // All one mask, or 5-byte mask.
11773   }
11774
11775   // Verify that the first bit starts at a multiple of mask so that the access
11776   // is aligned the same as the access width.
11777   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11778
11779   Result.first = MaskedBytes;
11780   Result.second = NotMaskTZ/8;
11781   return Result;
11782 }
11783
11784
11785 /// Check to see if IVal is something that provides a value as specified by
11786 /// MaskInfo. If so, replace the specified store with a narrower store of
11787 /// truncated IVal.
11788 static SDNode *
11789 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11790                                 SDValue IVal, StoreSDNode *St,
11791                                 DAGCombiner *DC) {
11792   unsigned NumBytes = MaskInfo.first;
11793   unsigned ByteShift = MaskInfo.second;
11794   SelectionDAG &DAG = DC->getDAG();
11795
11796   // Check to see if IVal is all zeros in the part being masked in by the 'or'
11797   // that uses this.  If not, this is not a replacement.
11798   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
11799                                   ByteShift*8, (ByteShift+NumBytes)*8);
11800   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
11801
11802   // Check that it is legal on the target to do this.  It is legal if the new
11803   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
11804   // legalization.
11805   MVT VT = MVT::getIntegerVT(NumBytes*8);
11806   if (!DC->isTypeLegal(VT))
11807     return nullptr;
11808
11809   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
11810   // shifted by ByteShift and truncated down to NumBytes.
11811   if (ByteShift) {
11812     SDLoc DL(IVal);
11813     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
11814                        DAG.getConstant(ByteShift*8, DL,
11815                                     DC->getShiftAmountTy(IVal.getValueType())));
11816   }
11817
11818   // Figure out the offset for the store and the alignment of the access.
11819   unsigned StOffset;
11820   unsigned NewAlign = St->getAlignment();
11821
11822   if (DAG.getDataLayout().isLittleEndian())
11823     StOffset = ByteShift;
11824   else
11825     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11826
11827   SDValue Ptr = St->getBasePtr();
11828   if (StOffset) {
11829     SDLoc DL(IVal);
11830     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11831                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11832     NewAlign = MinAlign(NewAlign, StOffset);
11833   }
11834
11835   // Truncate down to the new size.
11836   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11837
11838   ++OpsNarrowed;
11839   return DAG
11840       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11841                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11842       .getNode();
11843 }
11844
11845
11846 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11847 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11848 /// narrowing the load and store if it would end up being a win for performance
11849 /// or code size.
11850 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11851   StoreSDNode *ST  = cast<StoreSDNode>(N);
11852   if (ST->isVolatile())
11853     return SDValue();
11854
11855   SDValue Chain = ST->getChain();
11856   SDValue Value = ST->getValue();
11857   SDValue Ptr   = ST->getBasePtr();
11858   EVT VT = Value.getValueType();
11859
11860   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11861     return SDValue();
11862
11863   unsigned Opc = Value.getOpcode();
11864
11865   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11866   // is a byte mask indicating a consecutive number of bytes, check to see if
11867   // Y is known to provide just those bytes.  If so, we try to replace the
11868   // load + replace + store sequence with a single (narrower) store, which makes
11869   // the load dead.
11870   if (Opc == ISD::OR) {
11871     std::pair<unsigned, unsigned> MaskedLoad;
11872     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11873     if (MaskedLoad.first)
11874       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11875                                                   Value.getOperand(1), ST,this))
11876         return SDValue(NewST, 0);
11877
11878     // Or is commutative, so try swapping X and Y.
11879     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11880     if (MaskedLoad.first)
11881       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11882                                                   Value.getOperand(0), ST,this))
11883         return SDValue(NewST, 0);
11884   }
11885
11886   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11887       Value.getOperand(1).getOpcode() != ISD::Constant)
11888     return SDValue();
11889
11890   SDValue N0 = Value.getOperand(0);
11891   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11892       Chain == SDValue(N0.getNode(), 1)) {
11893     LoadSDNode *LD = cast<LoadSDNode>(N0);
11894     if (LD->getBasePtr() != Ptr ||
11895         LD->getPointerInfo().getAddrSpace() !=
11896         ST->getPointerInfo().getAddrSpace())
11897       return SDValue();
11898
11899     // Find the type to narrow it the load / op / store to.
11900     SDValue N1 = Value.getOperand(1);
11901     unsigned BitWidth = N1.getValueSizeInBits();
11902     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11903     if (Opc == ISD::AND)
11904       Imm ^= APInt::getAllOnesValue(BitWidth);
11905     if (Imm == 0 || Imm.isAllOnesValue())
11906       return SDValue();
11907     unsigned ShAmt = Imm.countTrailingZeros();
11908     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11909     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11910     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11911     // The narrowing should be profitable, the load/store operation should be
11912     // legal (or custom) and the store size should be equal to the NewVT width.
11913     while (NewBW < BitWidth &&
11914            (NewVT.getStoreSizeInBits() != NewBW ||
11915             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11916             !TLI.isNarrowingProfitable(VT, NewVT))) {
11917       NewBW = NextPowerOf2(NewBW);
11918       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11919     }
11920     if (NewBW >= BitWidth)
11921       return SDValue();
11922
11923     // If the lsb changed does not start at the type bitwidth boundary,
11924     // start at the previous one.
11925     if (ShAmt % NewBW)
11926       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11927     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11928                                    std::min(BitWidth, ShAmt + NewBW));
11929     if ((Imm & Mask) == Imm) {
11930       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11931       if (Opc == ISD::AND)
11932         NewImm ^= APInt::getAllOnesValue(NewBW);
11933       uint64_t PtrOff = ShAmt / 8;
11934       // For big endian targets, we need to adjust the offset to the pointer to
11935       // load the correct bytes.
11936       if (DAG.getDataLayout().isBigEndian())
11937         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11938
11939       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11940       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11941       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11942         return SDValue();
11943
11944       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11945                                    Ptr.getValueType(), Ptr,
11946                                    DAG.getConstant(PtrOff, SDLoc(LD),
11947                                                    Ptr.getValueType()));
11948       SDValue NewLD =
11949           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11950                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11951                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11952       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11953                                    DAG.getConstant(NewImm, SDLoc(Value),
11954                                                    NewVT));
11955       SDValue NewST =
11956           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11957                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11958
11959       AddToWorklist(NewPtr.getNode());
11960       AddToWorklist(NewLD.getNode());
11961       AddToWorklist(NewVal.getNode());
11962       WorklistRemover DeadNodes(*this);
11963       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11964       ++OpsNarrowed;
11965       return NewST;
11966     }
11967   }
11968
11969   return SDValue();
11970 }
11971
11972 /// For a given floating point load / store pair, if the load value isn't used
11973 /// by any other operations, then consider transforming the pair to integer
11974 /// load / store operations if the target deems the transformation profitable.
11975 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11976   StoreSDNode *ST  = cast<StoreSDNode>(N);
11977   SDValue Chain = ST->getChain();
11978   SDValue Value = ST->getValue();
11979   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11980       Value.hasOneUse() &&
11981       Chain == SDValue(Value.getNode(), 1)) {
11982     LoadSDNode *LD = cast<LoadSDNode>(Value);
11983     EVT VT = LD->getMemoryVT();
11984     if (!VT.isFloatingPoint() ||
11985         VT != ST->getMemoryVT() ||
11986         LD->isNonTemporal() ||
11987         ST->isNonTemporal() ||
11988         LD->getPointerInfo().getAddrSpace() != 0 ||
11989         ST->getPointerInfo().getAddrSpace() != 0)
11990       return SDValue();
11991
11992     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11993     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11994         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11995         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11996         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11997       return SDValue();
11998
11999     unsigned LDAlign = LD->getAlignment();
12000     unsigned STAlign = ST->getAlignment();
12001     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12002     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12003     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12004       return SDValue();
12005
12006     SDValue NewLD =
12007         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12008                     LD->getPointerInfo(), LDAlign);
12009
12010     SDValue NewST =
12011         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12012                      ST->getPointerInfo(), STAlign);
12013
12014     AddToWorklist(NewLD.getNode());
12015     AddToWorklist(NewST.getNode());
12016     WorklistRemover DeadNodes(*this);
12017     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12018     ++LdStFP2Int;
12019     return NewST;
12020   }
12021
12022   return SDValue();
12023 }
12024
12025 // This is a helper function for visitMUL to check the profitability
12026 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12027 // MulNode is the original multiply, AddNode is (add x, c1),
12028 // and ConstNode is c2.
12029 //
12030 // If the (add x, c1) has multiple uses, we could increase
12031 // the number of adds if we make this transformation.
12032 // It would only be worth doing this if we can remove a
12033 // multiply in the process. Check for that here.
12034 // To illustrate:
12035 //     (A + c1) * c3
12036 //     (A + c2) * c3
12037 // We're checking for cases where we have common "c3 * A" expressions.
12038 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12039                                               SDValue &AddNode,
12040                                               SDValue &ConstNode) {
12041   APInt Val;
12042
12043   // If the add only has one use, this would be OK to do.
12044   if (AddNode.getNode()->hasOneUse())
12045     return true;
12046
12047   // Walk all the users of the constant with which we're multiplying.
12048   for (SDNode *Use : ConstNode->uses()) {
12049
12050     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12051       continue;
12052
12053     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12054       SDNode *OtherOp;
12055       SDNode *MulVar = AddNode.getOperand(0).getNode();
12056
12057       // OtherOp is what we're multiplying against the constant.
12058       if (Use->getOperand(0) == ConstNode)
12059         OtherOp = Use->getOperand(1).getNode();
12060       else
12061         OtherOp = Use->getOperand(0).getNode();
12062
12063       // Check to see if multiply is with the same operand of our "add".
12064       //
12065       //     ConstNode  = CONST
12066       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12067       //     ...
12068       //     AddNode  = (A + c1)  <-- MulVar is A.
12069       //         = AddNode * ConstNode   <-- current visiting instruction.
12070       //
12071       // If we make this transformation, we will have a common
12072       // multiply (ConstNode * A) that we can save.
12073       if (OtherOp == MulVar)
12074         return true;
12075
12076       // Now check to see if a future expansion will give us a common
12077       // multiply.
12078       //
12079       //     ConstNode  = CONST
12080       //     AddNode    = (A + c1)
12081       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12082       //     ...
12083       //     OtherOp = (A + c2)
12084       //     Use     = OtherOp * ConstNode <-- visiting Use.
12085       //
12086       // If we make this transformation, we will have a common
12087       // multiply (CONST * A) after we also do the same transformation
12088       // to the "t2" instruction.
12089       if (OtherOp->getOpcode() == ISD::ADD &&
12090           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12091           OtherOp->getOperand(0).getNode() == MulVar)
12092         return true;
12093     }
12094   }
12095
12096   // Didn't find a case where this would be profitable.
12097   return false;
12098 }
12099
12100 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12101                                          unsigned NumStores) {
12102   SmallVector<SDValue, 8> Chains;
12103   SmallPtrSet<const SDNode *, 8> Visited;
12104   SDLoc StoreDL(StoreNodes[0].MemNode);
12105
12106   for (unsigned i = 0; i < NumStores; ++i) {
12107     Visited.insert(StoreNodes[i].MemNode);
12108   }
12109
12110   // don't include nodes that are children
12111   for (unsigned i = 0; i < NumStores; ++i) {
12112     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12113       Chains.push_back(StoreNodes[i].MemNode->getChain());
12114   }
12115
12116   assert(Chains.size() > 0 && "Chain should have generated a chain");
12117   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12118 }
12119
12120 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12121                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
12122                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
12123   // Make sure we have something to merge.
12124   if (NumStores < 2)
12125     return false;
12126
12127   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12128
12129   // The latest Node in the DAG.
12130   SDLoc DL(StoreNodes[0].MemNode);
12131
12132   SDValue StoredVal;
12133   if (UseVector) {
12134     bool IsVec = MemVT.isVector();
12135     unsigned Elts = NumStores;
12136     if (IsVec) {
12137       // When merging vector stores, get the total number of elements.
12138       Elts *= MemVT.getVectorNumElements();
12139     }
12140     // Get the type for the merged vector store.
12141     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12142     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12143
12144     if (IsConstantSrc) {
12145       SmallVector<SDValue, 8> BuildVector;
12146       for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12147         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12148         SDValue Val = St->getValue();
12149         if (MemVT.getScalarType().isInteger())
12150           if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12151             Val = DAG.getConstant(
12152                 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12153                 SDLoc(CFP), MemVT);
12154         BuildVector.push_back(Val);
12155       }
12156       StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12157     } else {
12158       SmallVector<SDValue, 8> Ops;
12159       for (unsigned i = 0; i < NumStores; ++i) {
12160         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12161         SDValue Val = St->getValue();
12162         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12163         if (Val.getValueType() != MemVT)
12164           return false;
12165         Ops.push_back(Val);
12166       }
12167
12168       // Build the extracted vector elements back into a vector.
12169       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12170                               DL, Ty, Ops);    }
12171   } else {
12172     // We should always use a vector store when merging extracted vector
12173     // elements, so this path implies a store of constants.
12174     assert(IsConstantSrc && "Merged vector elements should use vector store");
12175
12176     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12177     APInt StoreInt(SizeInBits, 0);
12178
12179     // Construct a single integer constant which is made of the smaller
12180     // constant inputs.
12181     bool IsLE = DAG.getDataLayout().isLittleEndian();
12182     for (unsigned i = 0; i < NumStores; ++i) {
12183       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12184       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12185
12186       SDValue Val = St->getValue();
12187       StoreInt <<= ElementSizeBytes * 8;
12188       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12189         StoreInt |= C->getAPIntValue().zext(SizeInBits);
12190       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12191         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
12192       } else {
12193         llvm_unreachable("Invalid constant element type");
12194       }
12195     }
12196
12197     // Create the new Load and Store operations.
12198     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12199     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12200   }
12201
12202   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12203   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12204   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
12205                                   FirstInChain->getBasePtr(),
12206                                   FirstInChain->getPointerInfo(),
12207                                   FirstInChain->getAlignment());
12208
12209   // Replace all merged stores with the new store.
12210   for (unsigned i = 0; i < NumStores; ++i)
12211     CombineTo(StoreNodes[i].MemNode, NewStore);
12212
12213   AddToWorklist(NewChain.getNode());
12214   return true;
12215 }
12216
12217 void DAGCombiner::getStoreMergeCandidates(
12218     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12219   // This holds the base pointer, index, and the offset in bytes from the base
12220   // pointer.
12221   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12222   EVT MemVT = St->getMemoryVT();
12223
12224   // We must have a base and an offset.
12225   if (!BasePtr.Base.getNode())
12226     return;
12227
12228   // Do not handle stores to undef base pointers.
12229   if (BasePtr.Base.isUndef())
12230     return;
12231
12232   bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12233   bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12234                        isa<ConstantFPSDNode>(St->getValue());
12235   bool IsExtractVecSrc =
12236       (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12237        St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12238   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool {
12239     if (Other->isVolatile() || Other->isIndexed())
12240       return false;
12241     // We can merge constant floats to equivalent integers
12242     if (Other->getMemoryVT() != MemVT)
12243       if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12244             isa<ConstantFPSDNode>(Other->getValue())))
12245         return false;
12246     if (IsLoadSrc)
12247       if (!isa<LoadSDNode>(Other->getValue()))
12248         return false;
12249     if (IsConstantSrc)
12250       if (!(isa<ConstantSDNode>(Other->getValue()) ||
12251             isa<ConstantFPSDNode>(Other->getValue())))
12252         return false;
12253     if (IsExtractVecSrc)
12254       if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12255             Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12256         return false;
12257     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12258     return (Ptr.equalBaseIndex(BasePtr));
12259   };
12260   // We looking for a root node which is an ancestor to all mergable
12261   // stores. We search up through a load, to our root and then down
12262   // through all children. For instance we will find Store{1,2,3} if
12263   // St is Store1, Store2. or Store3 where the root is not a load
12264   // which always true for nonvolatile ops. TODO: Expand
12265   // the search to find all valid candidates through multiple layers of loads.
12266   //
12267   // Root
12268   // |-------|-------|
12269   // Load    Load    Store3
12270   // |       |
12271   // Store1   Store2
12272   //
12273   // FIXME: We should be able to climb and
12274   // descend TokenFactors to find candidates as well.
12275
12276   SDNode *RootNode = (St->getChain()).getNode();
12277
12278   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12279     RootNode = Ldn->getChain().getNode();
12280     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12281       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12282         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12283           if (I2.getOperandNo() == 0)
12284             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12285               BaseIndexOffset Ptr;
12286               if (CandidateMatch(OtherST, Ptr))
12287                 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12288             }
12289   } else
12290     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12291       if (I.getOperandNo() == 0)
12292         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12293           BaseIndexOffset Ptr;
12294           if (CandidateMatch(OtherST, Ptr))
12295             StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12296         }
12297 }
12298
12299 // We need to check that merging these stores does not cause a loop
12300 // in the DAG. Any store candidate may depend on another candidate
12301 // indirectly through its operand (we already consider dependencies
12302 // through the chain). Check in parallel by searching up from
12303 // non-chain operands of candidates.
12304 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12305     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12306   SmallPtrSet<const SDNode *, 16> Visited;
12307   SmallVector<const SDNode *, 8> Worklist;
12308   // search ops of store candidates
12309   for (unsigned i = 0; i < NumStores; ++i) {
12310     SDNode *n = StoreNodes[i].MemNode;
12311     // Potential loops may happen only through non-chain operands
12312     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12313       Worklist.push_back(n->getOperand(j).getNode());
12314   }
12315   // search through DAG. We can stop early if we find a storenode
12316   for (unsigned i = 0; i < NumStores; ++i) {
12317     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12318       return false;
12319   }
12320   return true;
12321 }
12322
12323 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12324   if (OptLevel == CodeGenOpt::None)
12325     return false;
12326
12327   EVT MemVT = St->getMemoryVT();
12328   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12329
12330   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12331     return false;
12332
12333   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12334       Attribute::NoImplicitFloat);
12335
12336   // This function cannot currently deal with non-byte-sized memory sizes.
12337   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12338     return false;
12339
12340   if (!MemVT.isSimple())
12341     return false;
12342
12343   // Perform an early exit check. Do not bother looking at stored values that
12344   // are not constants, loads, or extracted vector elements.
12345   SDValue StoredVal = St->getValue();
12346   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12347   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12348                        isa<ConstantFPSDNode>(StoredVal);
12349   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12350                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12351
12352   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12353     return false;
12354
12355   // Don't merge vectors into wider vectors if the source data comes from loads.
12356   // TODO: This restriction can be lifted by using logic similar to the
12357   // ExtractVecSrc case.
12358   if (MemVT.isVector() && IsLoadSrc)
12359     return false;
12360
12361   SmallVector<MemOpLink, 8> StoreNodes;
12362   // Find potential store merge candidates by searching through chain sub-DAG
12363   getStoreMergeCandidates(St, StoreNodes);
12364
12365   // Check if there is anything to merge.
12366   if (StoreNodes.size() < 2)
12367     return false;
12368
12369   // Sort the memory operands according to their distance from the
12370   // base pointer.
12371   std::sort(StoreNodes.begin(), StoreNodes.end(),
12372             [](MemOpLink LHS, MemOpLink RHS) {
12373               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12374             });
12375
12376   // Store Merge attempts to merge the lowest stores. This generally
12377   // works out as if successful, as the remaining stores are checked
12378   // after the first collection of stores is merged. However, in the
12379   // case that a non-mergeable store is found first, e.g., {p[-2],
12380   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12381   // mergeable cases. To prevent this, we prune such stores from the
12382   // front of StoreNodes here.
12383
12384   unsigned StartIdx = 0;
12385   while ((StartIdx + 1 < StoreNodes.size()) &&
12386          StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12387              StoreNodes[StartIdx + 1].OffsetFromBase)
12388     ++StartIdx;
12389
12390   // Bail if we don't have enough candidates to merge.
12391   if (StartIdx + 1 >= StoreNodes.size())
12392     return false;
12393
12394   if (StartIdx)
12395     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12396
12397   // Scan the memory operations on the chain and find the first non-consecutive
12398   // store memory address.
12399   unsigned NumConsecutiveStores = 0;
12400   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12401
12402   // Check that the addresses are consecutive starting from the second
12403   // element in the list of stores.
12404   for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12405     int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12406     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12407       break;
12408     NumConsecutiveStores = i + 1;
12409   }
12410
12411   if (NumConsecutiveStores < 2)
12412     return false;
12413
12414   // Check that we can merge these candidates without causing a cycle
12415   if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumConsecutiveStores))
12416     return false;
12417
12418
12419   // The node with the lowest store address.
12420   LLVMContext &Context = *DAG.getContext();
12421   const DataLayout &DL = DAG.getDataLayout();
12422
12423   // Store the constants into memory as one consecutive store.
12424   if (IsConstantSrc) {
12425     bool RV = false;
12426     while (NumConsecutiveStores > 1) {
12427       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12428       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12429       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12430       unsigned LastLegalType = 0;
12431       unsigned LastLegalVectorType = 0;
12432       bool NonZero = false;
12433       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12434         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12435         SDValue StoredVal = ST->getValue();
12436
12437         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12438           NonZero |= !C->isNullValue();
12439         } else if (ConstantFPSDNode *C =
12440                        dyn_cast<ConstantFPSDNode>(StoredVal)) {
12441           NonZero |= !C->getConstantFPValue()->isNullValue();
12442         } else {
12443           // Non-constant.
12444           break;
12445         }
12446
12447         // Find a legal type for the constant store.
12448         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12449         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12450         bool IsFast = false;
12451         if (TLI.isTypeLegal(StoreTy) &&
12452             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12453                                    FirstStoreAlign, &IsFast) &&
12454             IsFast) {
12455           LastLegalType = i + 1;
12456           // Or check whether a truncstore is legal.
12457         } else if (TLI.getTypeAction(Context, StoreTy) ==
12458                    TargetLowering::TypePromoteInteger) {
12459           EVT LegalizedStoredValueTy =
12460               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12461           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12462               TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12463                                      FirstStoreAS, FirstStoreAlign, &IsFast) &&
12464               IsFast) {
12465             LastLegalType = i + 1;
12466           }
12467         }
12468
12469         // We only use vectors if the constant is known to be zero or the target
12470         // allows it and the function is not marked with the noimplicitfloat
12471         // attribute.
12472         if ((!NonZero ||
12473              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12474             !NoVectors) {
12475           // Find a legal type for the vector store.
12476           EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12477           if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) &&
12478               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12479                                      FirstStoreAlign, &IsFast) &&
12480               IsFast)
12481             LastLegalVectorType = i + 1;
12482         }
12483       }
12484
12485       // Check if we found a legal integer type that creates a meaningful merge.
12486       if (LastLegalType < 2 && LastLegalVectorType < 2)
12487         break;
12488
12489       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12490       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12491
12492       bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12493                                                     true, UseVector);
12494       if (!Merged)
12495         break;
12496       // Remove merged stores for next iteration.
12497       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12498       RV = true;
12499       NumConsecutiveStores -= NumElem;
12500     }
12501     return RV;
12502   }
12503
12504   // When extracting multiple vector elements, try to store them
12505   // in one vector store rather than a sequence of scalar stores.
12506   if (IsExtractVecSrc) {
12507     bool RV = false;
12508     while (StoreNodes.size() >= 2) {
12509       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12510       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12511       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12512       unsigned NumStoresToMerge = 0;
12513       bool IsVec = MemVT.isVector();
12514       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12515         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12516         unsigned StoreValOpcode = St->getValue().getOpcode();
12517         // This restriction could be loosened.
12518         // Bail out if any stored values are not elements extracted from a
12519         // vector. It should be possible to handle mixed sources, but load
12520         // sources need more careful handling (see the block of code below that
12521         // handles consecutive loads).
12522         if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12523             StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12524           return false;
12525
12526         // Find a legal type for the vector store.
12527         unsigned Elts = i + 1;
12528         if (IsVec) {
12529           // When merging vector stores, get the total number of elements.
12530           Elts *= MemVT.getVectorNumElements();
12531         }
12532         EVT Ty =
12533             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12534         bool IsFast;
12535         if (TLI.isTypeLegal(Ty) &&
12536             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12537                                    FirstStoreAlign, &IsFast) &&
12538             IsFast)
12539           NumStoresToMerge = i + 1;
12540       }
12541
12542       bool Merged = MergeStoresOfConstantsOrVecElts(
12543           StoreNodes, MemVT, NumStoresToMerge, false, true);
12544       if (!Merged)
12545         break;
12546       // Remove merged stores for next iteration.
12547       StoreNodes.erase(StoreNodes.begin(),
12548                        StoreNodes.begin() + NumStoresToMerge);
12549       RV = true;
12550       NumConsecutiveStores -= NumStoresToMerge;
12551     }
12552     return RV;
12553   }
12554
12555   // Below we handle the case of multiple consecutive stores that
12556   // come from multiple consecutive loads. We merge them into a single
12557   // wide load and a single wide store.
12558
12559   // Look for load nodes which are used by the stored values.
12560   SmallVector<MemOpLink, 8> LoadNodes;
12561
12562   // Find acceptable loads. Loads need to have the same chain (token factor),
12563   // must not be zext, volatile, indexed, and they must be consecutive.
12564   BaseIndexOffset LdBasePtr;
12565   for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12566     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
12567     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12568     if (!Ld) break;
12569
12570     // Loads must only have one use.
12571     if (!Ld->hasNUsesOfValue(1, 0))
12572       break;
12573
12574     // The memory operands must not be volatile.
12575     if (Ld->isVolatile() || Ld->isIndexed())
12576       break;
12577
12578     // We do not accept ext loads.
12579     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12580       break;
12581
12582     // The stored memory type must be the same.
12583     if (Ld->getMemoryVT() != MemVT)
12584       break;
12585
12586     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12587     // If this is not the first ptr that we check.
12588     if (LdBasePtr.Base.getNode()) {
12589       // The base ptr must be the same.
12590       if (!LdPtr.equalBaseIndex(LdBasePtr))
12591         break;
12592     } else {
12593       // Check that all other base pointers are the same as this one.
12594       LdBasePtr = LdPtr;
12595     }
12596
12597     // We found a potential memory operand to merge.
12598     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
12599   }
12600
12601   if (LoadNodes.size() < 2)
12602     return false;
12603
12604   // If we have load/store pair instructions and we only have two values,
12605   // don't bother.
12606   unsigned RequiredAlignment;
12607   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12608       St->getAlignment() >= RequiredAlignment)
12609     return false;
12610   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12611   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12612   unsigned FirstStoreAlign = FirstInChain->getAlignment();
12613   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12614   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12615   unsigned FirstLoadAlign = FirstLoad->getAlignment();
12616
12617   // Scan the memory operations on the chain and find the first non-consecutive
12618   // load memory address. These variables hold the index in the store node
12619   // array.
12620   unsigned LastConsecutiveLoad = 0;
12621   // This variable refers to the size and not index in the array.
12622   unsigned LastLegalVectorType = 0;
12623   unsigned LastLegalIntegerType = 0;
12624   StartAddress = LoadNodes[0].OffsetFromBase;
12625   SDValue FirstChain = FirstLoad->getChain();
12626   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12627     // All loads must share the same chain.
12628     if (LoadNodes[i].MemNode->getChain() != FirstChain)
12629       break;
12630
12631     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12632     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12633       break;
12634     LastConsecutiveLoad = i;
12635     // Find a legal type for the vector store.
12636     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
12637     bool IsFastSt, IsFastLd;
12638     if (TLI.isTypeLegal(StoreTy) &&
12639         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12640                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
12641         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12642                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
12643       LastLegalVectorType = i + 1;
12644     }
12645
12646     // Find a legal type for the integer store.
12647     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
12648     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12649     if (TLI.isTypeLegal(StoreTy) &&
12650         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12651                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
12652         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12653                                FirstLoadAlign, &IsFastLd) && IsFastLd)
12654       LastLegalIntegerType = i + 1;
12655     // Or check whether a truncstore and extload is legal.
12656     else if (TLI.getTypeAction(Context, StoreTy) ==
12657              TargetLowering::TypePromoteInteger) {
12658       EVT LegalizedStoredValueTy =
12659         TLI.getTypeToTransformTo(Context, StoreTy);
12660       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12661           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12662           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12663           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12664           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12665                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12666           IsFastSt &&
12667           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12668                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12669           IsFastLd)
12670         LastLegalIntegerType = i+1;
12671     }
12672   }
12673
12674   // Only use vector types if the vector type is larger than the integer type.
12675   // If they are the same, use integers.
12676   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12677   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
12678
12679   // We add +1 here because the LastXXX variables refer to location while
12680   // the NumElem refers to array/index size.
12681   unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12682   NumElem = std::min(LastLegalType, NumElem);
12683
12684   if (NumElem < 2)
12685     return false;
12686
12687   // Find if it is better to use vectors or integers to load and store
12688   // to memory.
12689   EVT JointMemOpVT;
12690   if (UseVectorTy) {
12691     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12692   } else {
12693     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12694     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12695   }
12696
12697   SDLoc LoadDL(LoadNodes[0].MemNode);
12698   SDLoc StoreDL(StoreNodes[0].MemNode);
12699
12700   // The merged loads are required to have the same incoming chain, so
12701   // using the first's chain is acceptable.
12702   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12703                                 FirstLoad->getBasePtr(),
12704                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12705
12706   SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12707
12708   AddToWorklist(NewStoreChain.getNode());
12709
12710   SDValue NewStore =
12711       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12712                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12713
12714   // Transfer chain users from old loads to the new load.
12715   for (unsigned i = 0; i < NumElem; ++i) {
12716     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12717     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12718                                   SDValue(NewLoad.getNode(), 1));
12719   }
12720
12721   // Replace the all stores with the new store.
12722   for (unsigned i = 0; i < NumElem; ++i)
12723     CombineTo(StoreNodes[i].MemNode, NewStore);
12724   return true;
12725 }
12726
12727 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12728   SDLoc SL(ST);
12729   SDValue ReplStore;
12730
12731   // Replace the chain to avoid dependency.
12732   if (ST->isTruncatingStore()) {
12733     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12734                                   ST->getBasePtr(), ST->getMemoryVT(),
12735                                   ST->getMemOperand());
12736   } else {
12737     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12738                              ST->getMemOperand());
12739   }
12740
12741   // Create token to keep both nodes around.
12742   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12743                               MVT::Other, ST->getChain(), ReplStore);
12744
12745   // Make sure the new and old chains are cleaned up.
12746   AddToWorklist(Token.getNode());
12747
12748   // Don't add users to work list.
12749   return CombineTo(ST, Token, false);
12750 }
12751
12752 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12753   SDValue Value = ST->getValue();
12754   if (Value.getOpcode() == ISD::TargetConstantFP)
12755     return SDValue();
12756
12757   SDLoc DL(ST);
12758
12759   SDValue Chain = ST->getChain();
12760   SDValue Ptr = ST->getBasePtr();
12761
12762   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12763
12764   // NOTE: If the original store is volatile, this transform must not increase
12765   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12766   // processor operation but an i64 (which is not legal) requires two.  So the
12767   // transform should not be done in this case.
12768
12769   SDValue Tmp;
12770   switch (CFP->getSimpleValueType(0).SimpleTy) {
12771   default:
12772     llvm_unreachable("Unknown FP type");
12773   case MVT::f16:    // We don't do this for these yet.
12774   case MVT::f80:
12775   case MVT::f128:
12776   case MVT::ppcf128:
12777     return SDValue();
12778   case MVT::f32:
12779     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12780         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12781       ;
12782       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12783                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12784                             MVT::i32);
12785       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12786     }
12787
12788     return SDValue();
12789   case MVT::f64:
12790     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12791          !ST->isVolatile()) ||
12792         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12793       ;
12794       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12795                             getZExtValue(), SDLoc(CFP), MVT::i64);
12796       return DAG.getStore(Chain, DL, Tmp,
12797                           Ptr, ST->getMemOperand());
12798     }
12799
12800     if (!ST->isVolatile() &&
12801         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12802       // Many FP stores are not made apparent until after legalize, e.g. for
12803       // argument passing.  Since this is so common, custom legalize the
12804       // 64-bit integer store into two 32-bit stores.
12805       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12806       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12807       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12808       if (DAG.getDataLayout().isBigEndian())
12809         std::swap(Lo, Hi);
12810
12811       unsigned Alignment = ST->getAlignment();
12812       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12813       AAMDNodes AAInfo = ST->getAAInfo();
12814
12815       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12816                                  ST->getAlignment(), MMOFlags, AAInfo);
12817       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12818                         DAG.getConstant(4, DL, Ptr.getValueType()));
12819       Alignment = MinAlign(Alignment, 4U);
12820       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12821                                  ST->getPointerInfo().getWithOffset(4),
12822                                  Alignment, MMOFlags, AAInfo);
12823       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12824                          St0, St1);
12825     }
12826
12827     return SDValue();
12828   }
12829 }
12830
12831 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12832   StoreSDNode *ST  = cast<StoreSDNode>(N);
12833   SDValue Chain = ST->getChain();
12834   SDValue Value = ST->getValue();
12835   SDValue Ptr   = ST->getBasePtr();
12836
12837   // If this is a store of a bit convert, store the input value if the
12838   // resultant store does not need a higher alignment than the original.
12839   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12840       ST->isUnindexed()) {
12841     EVT SVT = Value.getOperand(0).getValueType();
12842     if (((!LegalOperations && !ST->isVolatile()) ||
12843          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12844         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12845       unsigned OrigAlign = ST->getAlignment();
12846       bool Fast = false;
12847       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12848                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12849           Fast) {
12850         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12851                             ST->getPointerInfo(), OrigAlign,
12852                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12853       }
12854     }
12855   }
12856
12857   // Turn 'store undef, Ptr' -> nothing.
12858   if (Value.isUndef() && ST->isUnindexed())
12859     return Chain;
12860
12861   // Try to infer better alignment information than the store already has.
12862   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12863     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12864       if (Align > ST->getAlignment()) {
12865         SDValue NewStore =
12866             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12867                               ST->getMemoryVT(), Align,
12868                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12869         if (NewStore.getNode() != N)
12870           return CombineTo(ST, NewStore, true);
12871       }
12872     }
12873   }
12874
12875   // Try transforming a pair floating point load / store ops to integer
12876   // load / store ops.
12877   if (SDValue NewST = TransformFPLoadStorePair(N))
12878     return NewST;
12879
12880   if (ST->isUnindexed()) {
12881     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12882     // adjacent stores.
12883     if (findBetterNeighborChains(ST)) {
12884       // replaceStoreChain uses CombineTo, which handled all of the worklist
12885       // manipulation. Return the original node to not do anything else.
12886       return SDValue(ST, 0);
12887     }
12888     Chain = ST->getChain();
12889   }
12890
12891   // Try transforming N to an indexed store.
12892   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12893     return SDValue(N, 0);
12894
12895   // FIXME: is there such a thing as a truncating indexed store?
12896   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12897       Value.getValueType().isInteger()) {
12898     // See if we can simplify the input to this truncstore with knowledge that
12899     // only the low bits are being used.  For example:
12900     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12901     SDValue Shorter = GetDemandedBits(
12902         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12903                                     ST->getMemoryVT().getScalarSizeInBits()));
12904     AddToWorklist(Value.getNode());
12905     if (Shorter.getNode())
12906       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12907                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12908
12909     // Otherwise, see if we can simplify the operation with
12910     // SimplifyDemandedBits, which only works if the value has a single use.
12911     if (SimplifyDemandedBits(
12912             Value,
12913             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12914                                  ST->getMemoryVT().getScalarSizeInBits()))) {
12915       // Re-visit the store if anything changed and the store hasn't been merged
12916       // with another node (N is deleted) SimplifyDemandedBits will add Value's
12917       // node back to the worklist if necessary, but we also need to re-visit
12918       // the Store node itself.
12919       if (N->getOpcode() != ISD::DELETED_NODE)
12920         AddToWorklist(N);
12921       return SDValue(N, 0);
12922     }
12923   }
12924
12925   // If this is a load followed by a store to the same location, then the store
12926   // is dead/noop.
12927   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12928     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12929         ST->isUnindexed() && !ST->isVolatile() &&
12930         // There can't be any side effects between the load and store, such as
12931         // a call or store.
12932         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12933       // The store is dead, remove it.
12934       return Chain;
12935     }
12936   }
12937
12938   // If this is a store followed by a store with the same value to the same
12939   // location, then the store is dead/noop.
12940   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12941     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12942         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12943         ST1->isUnindexed() && !ST1->isVolatile()) {
12944       // The store is dead, remove it.
12945       return Chain;
12946     }
12947   }
12948
12949   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12950   // truncating store.  We can do this even if this is already a truncstore.
12951   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12952       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12953       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12954                             ST->getMemoryVT())) {
12955     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12956                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12957   }
12958
12959   // Only perform this optimization before the types are legal, because we
12960   // don't want to perform this optimization on every DAGCombine invocation.
12961   if (!LegalTypes) {
12962     for (;;) {
12963       // There can be multiple store sequences on the same chain.
12964       // Keep trying to merge store sequences until we are unable to do so
12965       // or until we merge the last store on the chain.
12966       bool Changed = MergeConsecutiveStores(ST);
12967       if (!Changed) break;
12968       // Return N as merge only uses CombineTo and no worklist clean
12969       // up is necessary.
12970       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
12971         return SDValue(N, 0);
12972     }
12973   }
12974
12975   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12976   //
12977   // Make sure to do this only after attempting to merge stores in order to
12978   //  avoid changing the types of some subset of stores due to visit order,
12979   //  preventing their merging.
12980   if (isa<ConstantFPSDNode>(ST->getValue())) {
12981     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12982       return NewSt;
12983   }
12984
12985   if (SDValue NewSt = splitMergedValStore(ST))
12986     return NewSt;
12987
12988   return ReduceLoadOpStoreWidth(N);
12989 }
12990
12991 /// For the instruction sequence of store below, F and I values
12992 /// are bundled together as an i64 value before being stored into memory.
12993 /// Sometimes it is more efficent to generate separate stores for F and I,
12994 /// which can remove the bitwise instructions or sink them to colder places.
12995 ///
12996 ///   (store (or (zext (bitcast F to i32) to i64),
12997 ///              (shl (zext I to i64), 32)), addr)  -->
12998 ///   (store F, addr) and (store I, addr+4)
12999 ///
13000 /// Similarly, splitting for other merged store can also be beneficial, like:
13001 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13002 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13003 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13004 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13005 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13006 ///
13007 /// We allow each target to determine specifically which kind of splitting is
13008 /// supported.
13009 ///
13010 /// The store patterns are commonly seen from the simple code snippet below
13011 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13012 ///   void goo(const std::pair<int, float> &);
13013 ///   hoo() {
13014 ///     ...
13015 ///     goo(std::make_pair(tmp, ftmp));
13016 ///     ...
13017 ///   }
13018 ///
13019 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13020   if (OptLevel == CodeGenOpt::None)
13021     return SDValue();
13022
13023   SDValue Val = ST->getValue();
13024   SDLoc DL(ST);
13025
13026   // Match OR operand.
13027   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13028     return SDValue();
13029
13030   // Match SHL operand and get Lower and Higher parts of Val.
13031   SDValue Op1 = Val.getOperand(0);
13032   SDValue Op2 = Val.getOperand(1);
13033   SDValue Lo, Hi;
13034   if (Op1.getOpcode() != ISD::SHL) {
13035     std::swap(Op1, Op2);
13036     if (Op1.getOpcode() != ISD::SHL)
13037       return SDValue();
13038   }
13039   Lo = Op2;
13040   Hi = Op1.getOperand(0);
13041   if (!Op1.hasOneUse())
13042     return SDValue();
13043
13044   // Match shift amount to HalfValBitSize.
13045   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13046   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13047   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13048     return SDValue();
13049
13050   // Lo and Hi are zero-extended from int with size less equal than 32
13051   // to i64.
13052   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13053       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13054       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13055       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13056       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13057       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13058     return SDValue();
13059
13060   // Use the EVT of low and high parts before bitcast as the input
13061   // of target query.
13062   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13063                   ? Lo.getOperand(0).getValueType()
13064                   : Lo.getValueType();
13065   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13066                    ? Hi.getOperand(0).getValueType()
13067                    : Hi.getValueType();
13068   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13069     return SDValue();
13070
13071   // Start to split store.
13072   unsigned Alignment = ST->getAlignment();
13073   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13074   AAMDNodes AAInfo = ST->getAAInfo();
13075
13076   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13077   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13078   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13079   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13080
13081   SDValue Chain = ST->getChain();
13082   SDValue Ptr = ST->getBasePtr();
13083   // Lower value store.
13084   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13085                              ST->getAlignment(), MMOFlags, AAInfo);
13086   Ptr =
13087       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13088                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13089   // Higher value store.
13090   SDValue St1 =
13091       DAG.getStore(St0, DL, Hi, Ptr,
13092                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13093                    Alignment / 2, MMOFlags, AAInfo);
13094   return St1;
13095 }
13096
13097 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13098   SDValue InVec = N->getOperand(0);
13099   SDValue InVal = N->getOperand(1);
13100   SDValue EltNo = N->getOperand(2);
13101   SDLoc DL(N);
13102
13103   // If the inserted element is an UNDEF, just use the input vector.
13104   if (InVal.isUndef())
13105     return InVec;
13106
13107   EVT VT = InVec.getValueType();
13108
13109   // Check that we know which element is being inserted
13110   if (!isa<ConstantSDNode>(EltNo))
13111     return SDValue();
13112   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13113
13114   // Canonicalize insert_vector_elt dag nodes.
13115   // Example:
13116   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13117   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13118   //
13119   // Do this only if the child insert_vector node has one use; also
13120   // do this only if indices are both constants and Idx1 < Idx0.
13121   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13122       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13123     unsigned OtherElt =
13124       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
13125     if (Elt < OtherElt) {
13126       // Swap nodes.
13127       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13128                                   InVec.getOperand(0), InVal, EltNo);
13129       AddToWorklist(NewOp.getNode());
13130       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13131                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13132     }
13133   }
13134
13135   // If we can't generate a legal BUILD_VECTOR, exit
13136   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13137     return SDValue();
13138
13139   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13140   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13141   // vector elements.
13142   SmallVector<SDValue, 8> Ops;
13143   // Do not combine these two vectors if the output vector will not replace
13144   // the input vector.
13145   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13146     Ops.append(InVec.getNode()->op_begin(),
13147                InVec.getNode()->op_end());
13148   } else if (InVec.isUndef()) {
13149     unsigned NElts = VT.getVectorNumElements();
13150     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13151   } else {
13152     return SDValue();
13153   }
13154
13155   // Insert the element
13156   if (Elt < Ops.size()) {
13157     // All the operands of BUILD_VECTOR must have the same type;
13158     // we enforce that here.
13159     EVT OpVT = Ops[0].getValueType();
13160     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13161   }
13162
13163   // Return the new vector
13164   return DAG.getBuildVector(VT, DL, Ops);
13165 }
13166
13167 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13168     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13169   assert(!OriginalLoad->isVolatile());
13170
13171   EVT ResultVT = EVE->getValueType(0);
13172   EVT VecEltVT = InVecVT.getVectorElementType();
13173   unsigned Align = OriginalLoad->getAlignment();
13174   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13175       VecEltVT.getTypeForEVT(*DAG.getContext()));
13176
13177   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13178     return SDValue();
13179
13180   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13181     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13182   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13183     return SDValue();
13184
13185   Align = NewAlign;
13186
13187   SDValue NewPtr = OriginalLoad->getBasePtr();
13188   SDValue Offset;
13189   EVT PtrType = NewPtr.getValueType();
13190   MachinePointerInfo MPI;
13191   SDLoc DL(EVE);
13192   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13193     int Elt = ConstEltNo->getZExtValue();
13194     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13195     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13196     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13197   } else {
13198     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13199     Offset = DAG.getNode(
13200         ISD::MUL, DL, PtrType, Offset,
13201         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13202     MPI = OriginalLoad->getPointerInfo();
13203   }
13204   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13205
13206   // The replacement we need to do here is a little tricky: we need to
13207   // replace an extractelement of a load with a load.
13208   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13209   // Note that this replacement assumes that the extractvalue is the only
13210   // use of the load; that's okay because we don't want to perform this
13211   // transformation in other cases anyway.
13212   SDValue Load;
13213   SDValue Chain;
13214   if (ResultVT.bitsGT(VecEltVT)) {
13215     // If the result type of vextract is wider than the load, then issue an
13216     // extending load instead.
13217     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13218                                                   VecEltVT)
13219                                    ? ISD::ZEXTLOAD
13220                                    : ISD::EXTLOAD;
13221     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13222                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13223                           Align, OriginalLoad->getMemOperand()->getFlags(),
13224                           OriginalLoad->getAAInfo());
13225     Chain = Load.getValue(1);
13226   } else {
13227     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13228                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13229                        OriginalLoad->getAAInfo());
13230     Chain = Load.getValue(1);
13231     if (ResultVT.bitsLT(VecEltVT))
13232       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13233     else
13234       Load = DAG.getBitcast(ResultVT, Load);
13235   }
13236   WorklistRemover DeadNodes(*this);
13237   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13238   SDValue To[] = { Load, Chain };
13239   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13240   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13241   // worklist explicitly as well.
13242   AddToWorklist(Load.getNode());
13243   AddUsersToWorklist(Load.getNode()); // Add users too
13244   // Make sure to revisit this node to clean it up; it will usually be dead.
13245   AddToWorklist(EVE);
13246   ++OpsNarrowed;
13247   return SDValue(EVE, 0);
13248 }
13249
13250 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13251   // (vextract (scalar_to_vector val, 0) -> val
13252   SDValue InVec = N->getOperand(0);
13253   EVT VT = InVec.getValueType();
13254   EVT NVT = N->getValueType(0);
13255
13256   if (InVec.isUndef())
13257     return DAG.getUNDEF(NVT);
13258
13259   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13260     // Check if the result type doesn't match the inserted element type. A
13261     // SCALAR_TO_VECTOR may truncate the inserted element and the
13262     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13263     SDValue InOp = InVec.getOperand(0);
13264     if (InOp.getValueType() != NVT) {
13265       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13266       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13267     }
13268     return InOp;
13269   }
13270
13271   SDValue EltNo = N->getOperand(1);
13272   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13273
13274   // extract_vector_elt (build_vector x, y), 1 -> y
13275   if (ConstEltNo &&
13276       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13277       TLI.isTypeLegal(VT) &&
13278       (InVec.hasOneUse() ||
13279        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13280     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13281     EVT InEltVT = Elt.getValueType();
13282
13283     // Sometimes build_vector's scalar input types do not match result type.
13284     if (NVT == InEltVT)
13285       return Elt;
13286
13287     // TODO: It may be useful to truncate if free if the build_vector implicitly
13288     // converts.
13289   }
13290
13291   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13292   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13293       ConstEltNo->isNullValue() && VT.isInteger()) {
13294     SDValue BCSrc = InVec.getOperand(0);
13295     if (BCSrc.getValueType().isScalarInteger())
13296       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13297   }
13298
13299   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13300   //
13301   // This only really matters if the index is non-constant since other combines
13302   // on the constant elements already work.
13303   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13304       EltNo == InVec.getOperand(2)) {
13305     SDValue Elt = InVec.getOperand(1);
13306     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13307   }
13308
13309   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13310   // We only perform this optimization before the op legalization phase because
13311   // we may introduce new vector instructions which are not backed by TD
13312   // patterns. For example on AVX, extracting elements from a wide vector
13313   // without using extract_subvector. However, if we can find an underlying
13314   // scalar value, then we can always use that.
13315   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13316     int NumElem = VT.getVectorNumElements();
13317     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13318     // Find the new index to extract from.
13319     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13320
13321     // Extracting an undef index is undef.
13322     if (OrigElt == -1)
13323       return DAG.getUNDEF(NVT);
13324
13325     // Select the right vector half to extract from.
13326     SDValue SVInVec;
13327     if (OrigElt < NumElem) {
13328       SVInVec = InVec->getOperand(0);
13329     } else {
13330       SVInVec = InVec->getOperand(1);
13331       OrigElt -= NumElem;
13332     }
13333
13334     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13335       SDValue InOp = SVInVec.getOperand(OrigElt);
13336       if (InOp.getValueType() != NVT) {
13337         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13338         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13339       }
13340
13341       return InOp;
13342     }
13343
13344     // FIXME: We should handle recursing on other vector shuffles and
13345     // scalar_to_vector here as well.
13346
13347     if (!LegalOperations) {
13348       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13349       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13350                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13351     }
13352   }
13353
13354   bool BCNumEltsChanged = false;
13355   EVT ExtVT = VT.getVectorElementType();
13356   EVT LVT = ExtVT;
13357
13358   // If the result of load has to be truncated, then it's not necessarily
13359   // profitable.
13360   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13361     return SDValue();
13362
13363   if (InVec.getOpcode() == ISD::BITCAST) {
13364     // Don't duplicate a load with other uses.
13365     if (!InVec.hasOneUse())
13366       return SDValue();
13367
13368     EVT BCVT = InVec.getOperand(0).getValueType();
13369     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13370       return SDValue();
13371     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13372       BCNumEltsChanged = true;
13373     InVec = InVec.getOperand(0);
13374     ExtVT = BCVT.getVectorElementType();
13375   }
13376
13377   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13378   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13379       ISD::isNormalLoad(InVec.getNode()) &&
13380       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13381     SDValue Index = N->getOperand(1);
13382     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13383       if (!OrigLoad->isVolatile()) {
13384         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13385                                                              OrigLoad);
13386       }
13387     }
13388   }
13389
13390   // Perform only after legalization to ensure build_vector / vector_shuffle
13391   // optimizations have already been done.
13392   if (!LegalOperations) return SDValue();
13393
13394   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13395   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13396   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13397
13398   if (ConstEltNo) {
13399     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13400
13401     LoadSDNode *LN0 = nullptr;
13402     const ShuffleVectorSDNode *SVN = nullptr;
13403     if (ISD::isNormalLoad(InVec.getNode())) {
13404       LN0 = cast<LoadSDNode>(InVec);
13405     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13406                InVec.getOperand(0).getValueType() == ExtVT &&
13407                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13408       // Don't duplicate a load with other uses.
13409       if (!InVec.hasOneUse())
13410         return SDValue();
13411
13412       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13413     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13414       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13415       // =>
13416       // (load $addr+1*size)
13417
13418       // Don't duplicate a load with other uses.
13419       if (!InVec.hasOneUse())
13420         return SDValue();
13421
13422       // If the bit convert changed the number of elements, it is unsafe
13423       // to examine the mask.
13424       if (BCNumEltsChanged)
13425         return SDValue();
13426
13427       // Select the input vector, guarding against out of range extract vector.
13428       unsigned NumElems = VT.getVectorNumElements();
13429       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13430       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13431
13432       if (InVec.getOpcode() == ISD::BITCAST) {
13433         // Don't duplicate a load with other uses.
13434         if (!InVec.hasOneUse())
13435           return SDValue();
13436
13437         InVec = InVec.getOperand(0);
13438       }
13439       if (ISD::isNormalLoad(InVec.getNode())) {
13440         LN0 = cast<LoadSDNode>(InVec);
13441         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13442         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13443       }
13444     }
13445
13446     // Make sure we found a non-volatile load and the extractelement is
13447     // the only use.
13448     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13449       return SDValue();
13450
13451     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13452     if (Elt == -1)
13453       return DAG.getUNDEF(LVT);
13454
13455     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13456   }
13457
13458   return SDValue();
13459 }
13460
13461 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13462 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13463   // We perform this optimization post type-legalization because
13464   // the type-legalizer often scalarizes integer-promoted vectors.
13465   // Performing this optimization before may create bit-casts which
13466   // will be type-legalized to complex code sequences.
13467   // We perform this optimization only before the operation legalizer because we
13468   // may introduce illegal operations.
13469   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13470     return SDValue();
13471
13472   unsigned NumInScalars = N->getNumOperands();
13473   SDLoc DL(N);
13474   EVT VT = N->getValueType(0);
13475
13476   // Check to see if this is a BUILD_VECTOR of a bunch of values
13477   // which come from any_extend or zero_extend nodes. If so, we can create
13478   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13479   // optimizations. We do not handle sign-extend because we can't fill the sign
13480   // using shuffles.
13481   EVT SourceType = MVT::Other;
13482   bool AllAnyExt = true;
13483
13484   for (unsigned i = 0; i != NumInScalars; ++i) {
13485     SDValue In = N->getOperand(i);
13486     // Ignore undef inputs.
13487     if (In.isUndef()) continue;
13488
13489     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13490     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13491
13492     // Abort if the element is not an extension.
13493     if (!ZeroExt && !AnyExt) {
13494       SourceType = MVT::Other;
13495       break;
13496     }
13497
13498     // The input is a ZeroExt or AnyExt. Check the original type.
13499     EVT InTy = In.getOperand(0).getValueType();
13500
13501     // Check that all of the widened source types are the same.
13502     if (SourceType == MVT::Other)
13503       // First time.
13504       SourceType = InTy;
13505     else if (InTy != SourceType) {
13506       // Multiple income types. Abort.
13507       SourceType = MVT::Other;
13508       break;
13509     }
13510
13511     // Check if all of the extends are ANY_EXTENDs.
13512     AllAnyExt &= AnyExt;
13513   }
13514
13515   // In order to have valid types, all of the inputs must be extended from the
13516   // same source type and all of the inputs must be any or zero extend.
13517   // Scalar sizes must be a power of two.
13518   EVT OutScalarTy = VT.getScalarType();
13519   bool ValidTypes = SourceType != MVT::Other &&
13520                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13521                  isPowerOf2_32(SourceType.getSizeInBits());
13522
13523   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13524   // turn into a single shuffle instruction.
13525   if (!ValidTypes)
13526     return SDValue();
13527
13528   bool isLE = DAG.getDataLayout().isLittleEndian();
13529   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13530   assert(ElemRatio > 1 && "Invalid element size ratio");
13531   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13532                                DAG.getConstant(0, DL, SourceType);
13533
13534   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13535   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13536
13537   // Populate the new build_vector
13538   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13539     SDValue Cast = N->getOperand(i);
13540     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13541             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13542             Cast.isUndef()) && "Invalid cast opcode");
13543     SDValue In;
13544     if (Cast.isUndef())
13545       In = DAG.getUNDEF(SourceType);
13546     else
13547       In = Cast->getOperand(0);
13548     unsigned Index = isLE ? (i * ElemRatio) :
13549                             (i * ElemRatio + (ElemRatio - 1));
13550
13551     assert(Index < Ops.size() && "Invalid index");
13552     Ops[Index] = In;
13553   }
13554
13555   // The type of the new BUILD_VECTOR node.
13556   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13557   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13558          "Invalid vector size");
13559   // Check if the new vector type is legal.
13560   if (!isTypeLegal(VecVT)) return SDValue();
13561
13562   // Make the new BUILD_VECTOR.
13563   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13564
13565   // The new BUILD_VECTOR node has the potential to be further optimized.
13566   AddToWorklist(BV.getNode());
13567   // Bitcast to the desired type.
13568   return DAG.getBitcast(VT, BV);
13569 }
13570
13571 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13572   EVT VT = N->getValueType(0);
13573
13574   unsigned NumInScalars = N->getNumOperands();
13575   SDLoc DL(N);
13576
13577   EVT SrcVT = MVT::Other;
13578   unsigned Opcode = ISD::DELETED_NODE;
13579   unsigned NumDefs = 0;
13580
13581   for (unsigned i = 0; i != NumInScalars; ++i) {
13582     SDValue In = N->getOperand(i);
13583     unsigned Opc = In.getOpcode();
13584
13585     if (Opc == ISD::UNDEF)
13586       continue;
13587
13588     // If all scalar values are floats and converted from integers.
13589     if (Opcode == ISD::DELETED_NODE &&
13590         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13591       Opcode = Opc;
13592     }
13593
13594     if (Opc != Opcode)
13595       return SDValue();
13596
13597     EVT InVT = In.getOperand(0).getValueType();
13598
13599     // If all scalar values are typed differently, bail out. It's chosen to
13600     // simplify BUILD_VECTOR of integer types.
13601     if (SrcVT == MVT::Other)
13602       SrcVT = InVT;
13603     if (SrcVT != InVT)
13604       return SDValue();
13605     NumDefs++;
13606   }
13607
13608   // If the vector has just one element defined, it's not worth to fold it into
13609   // a vectorized one.
13610   if (NumDefs < 2)
13611     return SDValue();
13612
13613   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13614          && "Should only handle conversion from integer to float.");
13615   assert(SrcVT != MVT::Other && "Cannot determine source type!");
13616
13617   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13618
13619   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13620     return SDValue();
13621
13622   // Just because the floating-point vector type is legal does not necessarily
13623   // mean that the corresponding integer vector type is.
13624   if (!isTypeLegal(NVT))
13625     return SDValue();
13626
13627   SmallVector<SDValue, 8> Opnds;
13628   for (unsigned i = 0; i != NumInScalars; ++i) {
13629     SDValue In = N->getOperand(i);
13630
13631     if (In.isUndef())
13632       Opnds.push_back(DAG.getUNDEF(SrcVT));
13633     else
13634       Opnds.push_back(In.getOperand(0));
13635   }
13636   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13637   AddToWorklist(BV.getNode());
13638
13639   return DAG.getNode(Opcode, DL, VT, BV);
13640 }
13641
13642 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13643                                            ArrayRef<int> VectorMask,
13644                                            SDValue VecIn1, SDValue VecIn2,
13645                                            unsigned LeftIdx) {
13646   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13647   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13648
13649   EVT VT = N->getValueType(0);
13650   EVT InVT1 = VecIn1.getValueType();
13651   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13652
13653   unsigned Vec2Offset = InVT1.getVectorNumElements();
13654   unsigned NumElems = VT.getVectorNumElements();
13655   unsigned ShuffleNumElems = NumElems;
13656
13657   // We can't generate a shuffle node with mismatched input and output types.
13658   // Try to make the types match the type of the output.
13659   if (InVT1 != VT || InVT2 != VT) {
13660     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13661       // If the output vector length is a multiple of both input lengths,
13662       // we can concatenate them and pad the rest with undefs.
13663       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13664       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13665       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13666       ConcatOps[0] = VecIn1;
13667       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13668       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13669       VecIn2 = SDValue();
13670     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13671       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13672         return SDValue();
13673
13674       if (!VecIn2.getNode()) {
13675         // If we only have one input vector, and it's twice the size of the
13676         // output, split it in two.
13677         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13678                              DAG.getConstant(NumElems, DL, IdxTy));
13679         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13680         // Since we now have shorter input vectors, adjust the offset of the
13681         // second vector's start.
13682         Vec2Offset = NumElems;
13683       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13684         // VecIn1 is wider than the output, and we have another, possibly
13685         // smaller input. Pad the smaller input with undefs, shuffle at the
13686         // input vector width, and extract the output.
13687         // The shuffle type is different than VT, so check legality again.
13688         if (LegalOperations &&
13689             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13690           return SDValue();
13691
13692         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
13693         // lower it back into a BUILD_VECTOR. So if the inserted type is
13694         // illegal, don't even try.
13695         if (InVT1 != InVT2) {
13696           if (!TLI.isTypeLegal(InVT2))
13697             return SDValue();
13698           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13699                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13700         }
13701         ShuffleNumElems = NumElems * 2;
13702       } else {
13703         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13704         // than VecIn1. We can't handle this for now - this case will disappear
13705         // when we start sorting the vectors by type.
13706         return SDValue();
13707       }
13708     } else {
13709       // TODO: Support cases where the length mismatch isn't exactly by a
13710       // factor of 2.
13711       // TODO: Move this check upwards, so that if we have bad type
13712       // mismatches, we don't create any DAG nodes.
13713       return SDValue();
13714     }
13715   }
13716
13717   // Initialize mask to undef.
13718   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13719
13720   // Only need to run up to the number of elements actually used, not the
13721   // total number of elements in the shuffle - if we are shuffling a wider
13722   // vector, the high lanes should be set to undef.
13723   for (unsigned i = 0; i != NumElems; ++i) {
13724     if (VectorMask[i] <= 0)
13725       continue;
13726
13727     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13728     if (VectorMask[i] == (int)LeftIdx) {
13729       Mask[i] = ExtIndex;
13730     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13731       Mask[i] = Vec2Offset + ExtIndex;
13732     }
13733   }
13734
13735   // The type the input vectors may have changed above.
13736   InVT1 = VecIn1.getValueType();
13737
13738   // If we already have a VecIn2, it should have the same type as VecIn1.
13739   // If we don't, get an undef/zero vector of the appropriate type.
13740   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13741   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13742
13743   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13744   if (ShuffleNumElems > NumElems)
13745     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13746
13747   return Shuffle;
13748 }
13749
13750 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13751 // operations. If the types of the vectors we're extracting from allow it,
13752 // turn this into a vector_shuffle node.
13753 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13754   SDLoc DL(N);
13755   EVT VT = N->getValueType(0);
13756
13757   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13758   if (!isTypeLegal(VT))
13759     return SDValue();
13760
13761   // May only combine to shuffle after legalize if shuffle is legal.
13762   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13763     return SDValue();
13764
13765   bool UsesZeroVector = false;
13766   unsigned NumElems = N->getNumOperands();
13767
13768   // Record, for each element of the newly built vector, which input vector
13769   // that element comes from. -1 stands for undef, 0 for the zero vector,
13770   // and positive values for the input vectors.
13771   // VectorMask maps each element to its vector number, and VecIn maps vector
13772   // numbers to their initial SDValues.
13773
13774   SmallVector<int, 8> VectorMask(NumElems, -1);
13775   SmallVector<SDValue, 8> VecIn;
13776   VecIn.push_back(SDValue());
13777
13778   for (unsigned i = 0; i != NumElems; ++i) {
13779     SDValue Op = N->getOperand(i);
13780
13781     if (Op.isUndef())
13782       continue;
13783
13784     // See if we can use a blend with a zero vector.
13785     // TODO: Should we generalize this to a blend with an arbitrary constant
13786     // vector?
13787     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13788       UsesZeroVector = true;
13789       VectorMask[i] = 0;
13790       continue;
13791     }
13792
13793     // Not an undef or zero. If the input is something other than an
13794     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13795     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13796         !isa<ConstantSDNode>(Op.getOperand(1)))
13797       return SDValue();
13798
13799     SDValue ExtractedFromVec = Op.getOperand(0);
13800
13801     // All inputs must have the same element type as the output.
13802     if (VT.getVectorElementType() !=
13803         ExtractedFromVec.getValueType().getVectorElementType())
13804       return SDValue();
13805
13806     // Have we seen this input vector before?
13807     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13808     // a map back from SDValues to numbers isn't worth it.
13809     unsigned Idx = std::distance(
13810         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13811     if (Idx == VecIn.size())
13812       VecIn.push_back(ExtractedFromVec);
13813
13814     VectorMask[i] = Idx;
13815   }
13816
13817   // If we didn't find at least one input vector, bail out.
13818   if (VecIn.size() < 2)
13819     return SDValue();
13820
13821   // TODO: We want to sort the vectors by descending length, so that adjacent
13822   // pairs have similar length, and the longer vector is always first in the
13823   // pair.
13824
13825   // TODO: Should this fire if some of the input vectors has illegal type (like
13826   // it does now), or should we let legalization run its course first?
13827
13828   // Shuffle phase:
13829   // Take pairs of vectors, and shuffle them so that the result has elements
13830   // from these vectors in the correct places.
13831   // For example, given:
13832   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13833   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13834   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13835   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13836   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13837   // We will generate:
13838   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13839   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13840   SmallVector<SDValue, 4> Shuffles;
13841   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13842     unsigned LeftIdx = 2 * In + 1;
13843     SDValue VecLeft = VecIn[LeftIdx];
13844     SDValue VecRight =
13845         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13846
13847     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13848                                                 VecRight, LeftIdx))
13849       Shuffles.push_back(Shuffle);
13850     else
13851       return SDValue();
13852   }
13853
13854   // If we need the zero vector as an "ingredient" in the blend tree, add it
13855   // to the list of shuffles.
13856   if (UsesZeroVector)
13857     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13858                                       : DAG.getConstantFP(0.0, DL, VT));
13859
13860   // If we only have one shuffle, we're done.
13861   if (Shuffles.size() == 1)
13862     return Shuffles[0];
13863
13864   // Update the vector mask to point to the post-shuffle vectors.
13865   for (int &Vec : VectorMask)
13866     if (Vec == 0)
13867       Vec = Shuffles.size() - 1;
13868     else
13869       Vec = (Vec - 1) / 2;
13870
13871   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13872   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13873   // generate:
13874   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13875   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13876   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13877   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13878   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13879   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13880   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13881
13882   // Make sure the initial size of the shuffle list is even.
13883   if (Shuffles.size() % 2)
13884     Shuffles.push_back(DAG.getUNDEF(VT));
13885
13886   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13887     if (CurSize % 2) {
13888       Shuffles[CurSize] = DAG.getUNDEF(VT);
13889       CurSize++;
13890     }
13891     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13892       int Left = 2 * In;
13893       int Right = 2 * In + 1;
13894       SmallVector<int, 8> Mask(NumElems, -1);
13895       for (unsigned i = 0; i != NumElems; ++i) {
13896         if (VectorMask[i] == Left) {
13897           Mask[i] = i;
13898           VectorMask[i] = In;
13899         } else if (VectorMask[i] == Right) {
13900           Mask[i] = i + NumElems;
13901           VectorMask[i] = In;
13902         }
13903       }
13904
13905       Shuffles[In] =
13906           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13907     }
13908   }
13909
13910   return Shuffles[0];
13911 }
13912
13913 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13914   EVT VT = N->getValueType(0);
13915
13916   // A vector built entirely of undefs is undef.
13917   if (ISD::allOperandsUndef(N))
13918     return DAG.getUNDEF(VT);
13919
13920   // Check if we can express BUILD VECTOR via subvector extract.
13921   if (!LegalTypes && (N->getNumOperands() > 1)) {
13922     SDValue Op0 = N->getOperand(0);
13923     auto checkElem = [&](SDValue Op) -> uint64_t {
13924       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
13925           (Op0.getOperand(0) == Op.getOperand(0)))
13926         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
13927           return CNode->getZExtValue();
13928       return -1;
13929     };
13930
13931     int Offset = checkElem(Op0);
13932     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
13933       if (Offset + i != checkElem(N->getOperand(i))) {
13934         Offset = -1;
13935         break;
13936       }
13937     }
13938
13939     if ((Offset == 0) &&
13940         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
13941       return Op0.getOperand(0);
13942     if ((Offset != -1) &&
13943         ((Offset % N->getValueType(0).getVectorNumElements()) ==
13944          0)) // IDX must be multiple of output size.
13945       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
13946                          Op0.getOperand(0), Op0.getOperand(1));
13947   }
13948
13949   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13950     return V;
13951
13952   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13953     return V;
13954
13955   if (SDValue V = reduceBuildVecToShuffle(N))
13956     return V;
13957
13958   return SDValue();
13959 }
13960
13961 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13962   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13963   EVT OpVT = N->getOperand(0).getValueType();
13964
13965   // If the operands are legal vectors, leave them alone.
13966   if (TLI.isTypeLegal(OpVT))
13967     return SDValue();
13968
13969   SDLoc DL(N);
13970   EVT VT = N->getValueType(0);
13971   SmallVector<SDValue, 8> Ops;
13972
13973   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13974   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13975
13976   // Keep track of what we encounter.
13977   bool AnyInteger = false;
13978   bool AnyFP = false;
13979   for (const SDValue &Op : N->ops()) {
13980     if (ISD::BITCAST == Op.getOpcode() &&
13981         !Op.getOperand(0).getValueType().isVector())
13982       Ops.push_back(Op.getOperand(0));
13983     else if (ISD::UNDEF == Op.getOpcode())
13984       Ops.push_back(ScalarUndef);
13985     else
13986       return SDValue();
13987
13988     // Note whether we encounter an integer or floating point scalar.
13989     // If it's neither, bail out, it could be something weird like x86mmx.
13990     EVT LastOpVT = Ops.back().getValueType();
13991     if (LastOpVT.isFloatingPoint())
13992       AnyFP = true;
13993     else if (LastOpVT.isInteger())
13994       AnyInteger = true;
13995     else
13996       return SDValue();
13997   }
13998
13999   // If any of the operands is a floating point scalar bitcast to a vector,
14000   // use floating point types throughout, and bitcast everything.
14001   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14002   if (AnyFP) {
14003     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14004     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14005     if (AnyInteger) {
14006       for (SDValue &Op : Ops) {
14007         if (Op.getValueType() == SVT)
14008           continue;
14009         if (Op.isUndef())
14010           Op = ScalarUndef;
14011         else
14012           Op = DAG.getBitcast(SVT, Op);
14013       }
14014     }
14015   }
14016
14017   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14018                                VT.getSizeInBits() / SVT.getSizeInBits());
14019   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14020 }
14021
14022 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14023 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14024 // most two distinct vectors the same size as the result, attempt to turn this
14025 // into a legal shuffle.
14026 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14027   EVT VT = N->getValueType(0);
14028   EVT OpVT = N->getOperand(0).getValueType();
14029   int NumElts = VT.getVectorNumElements();
14030   int NumOpElts = OpVT.getVectorNumElements();
14031
14032   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14033   SmallVector<int, 8> Mask;
14034
14035   for (SDValue Op : N->ops()) {
14036     // Peek through any bitcast.
14037     while (Op.getOpcode() == ISD::BITCAST)
14038       Op = Op.getOperand(0);
14039
14040     // UNDEF nodes convert to UNDEF shuffle mask values.
14041     if (Op.isUndef()) {
14042       Mask.append((unsigned)NumOpElts, -1);
14043       continue;
14044     }
14045
14046     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14047       return SDValue();
14048
14049     // What vector are we extracting the subvector from and at what index?
14050     SDValue ExtVec = Op.getOperand(0);
14051
14052     // We want the EVT of the original extraction to correctly scale the
14053     // extraction index.
14054     EVT ExtVT = ExtVec.getValueType();
14055
14056     // Peek through any bitcast.
14057     while (ExtVec.getOpcode() == ISD::BITCAST)
14058       ExtVec = ExtVec.getOperand(0);
14059
14060     // UNDEF nodes convert to UNDEF shuffle mask values.
14061     if (ExtVec.isUndef()) {
14062       Mask.append((unsigned)NumOpElts, -1);
14063       continue;
14064     }
14065
14066     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14067       return SDValue();
14068     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14069
14070     // Ensure that we are extracting a subvector from a vector the same
14071     // size as the result.
14072     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14073       return SDValue();
14074
14075     // Scale the subvector index to account for any bitcast.
14076     int NumExtElts = ExtVT.getVectorNumElements();
14077     if (0 == (NumExtElts % NumElts))
14078       ExtIdx /= (NumExtElts / NumElts);
14079     else if (0 == (NumElts % NumExtElts))
14080       ExtIdx *= (NumElts / NumExtElts);
14081     else
14082       return SDValue();
14083
14084     // At most we can reference 2 inputs in the final shuffle.
14085     if (SV0.isUndef() || SV0 == ExtVec) {
14086       SV0 = ExtVec;
14087       for (int i = 0; i != NumOpElts; ++i)
14088         Mask.push_back(i + ExtIdx);
14089     } else if (SV1.isUndef() || SV1 == ExtVec) {
14090       SV1 = ExtVec;
14091       for (int i = 0; i != NumOpElts; ++i)
14092         Mask.push_back(i + ExtIdx + NumElts);
14093     } else {
14094       return SDValue();
14095     }
14096   }
14097
14098   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14099     return SDValue();
14100
14101   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14102                               DAG.getBitcast(VT, SV1), Mask);
14103 }
14104
14105 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14106   // If we only have one input vector, we don't need to do any concatenation.
14107   if (N->getNumOperands() == 1)
14108     return N->getOperand(0);
14109
14110   // Check if all of the operands are undefs.
14111   EVT VT = N->getValueType(0);
14112   if (ISD::allOperandsUndef(N))
14113     return DAG.getUNDEF(VT);
14114
14115   // Optimize concat_vectors where all but the first of the vectors are undef.
14116   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14117         return Op.isUndef();
14118       })) {
14119     SDValue In = N->getOperand(0);
14120     assert(In.getValueType().isVector() && "Must concat vectors");
14121
14122     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14123     if (In->getOpcode() == ISD::BITCAST &&
14124         !In->getOperand(0)->getValueType(0).isVector()) {
14125       SDValue Scalar = In->getOperand(0);
14126
14127       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14128       // look through the trunc so we can still do the transform:
14129       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14130       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14131           !TLI.isTypeLegal(Scalar.getValueType()) &&
14132           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14133         Scalar = Scalar->getOperand(0);
14134
14135       EVT SclTy = Scalar->getValueType(0);
14136
14137       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14138         return SDValue();
14139
14140       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14141       if (VNTNumElms < 2)
14142         return SDValue();
14143
14144       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14145       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14146         return SDValue();
14147
14148       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14149       return DAG.getBitcast(VT, Res);
14150     }
14151   }
14152
14153   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14154   // We have already tested above for an UNDEF only concatenation.
14155   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14156   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14157   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14158     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14159   };
14160   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14161     SmallVector<SDValue, 8> Opnds;
14162     EVT SVT = VT.getScalarType();
14163
14164     EVT MinVT = SVT;
14165     if (!SVT.isFloatingPoint()) {
14166       // If BUILD_VECTOR are from built from integer, they may have different
14167       // operand types. Get the smallest type and truncate all operands to it.
14168       bool FoundMinVT = false;
14169       for (const SDValue &Op : N->ops())
14170         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14171           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14172           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14173           FoundMinVT = true;
14174         }
14175       assert(FoundMinVT && "Concat vector type mismatch");
14176     }
14177
14178     for (const SDValue &Op : N->ops()) {
14179       EVT OpVT = Op.getValueType();
14180       unsigned NumElts = OpVT.getVectorNumElements();
14181
14182       if (ISD::UNDEF == Op.getOpcode())
14183         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14184
14185       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14186         if (SVT.isFloatingPoint()) {
14187           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14188           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14189         } else {
14190           for (unsigned i = 0; i != NumElts; ++i)
14191             Opnds.push_back(
14192                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14193         }
14194       }
14195     }
14196
14197     assert(VT.getVectorNumElements() == Opnds.size() &&
14198            "Concat vector type mismatch");
14199     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14200   }
14201
14202   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14203   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14204     return V;
14205
14206   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14207   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14208     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14209       return V;
14210
14211   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14212   // nodes often generate nop CONCAT_VECTOR nodes.
14213   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14214   // place the incoming vectors at the exact same location.
14215   SDValue SingleSource = SDValue();
14216   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14217
14218   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14219     SDValue Op = N->getOperand(i);
14220
14221     if (Op.isUndef())
14222       continue;
14223
14224     // Check if this is the identity extract:
14225     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14226       return SDValue();
14227
14228     // Find the single incoming vector for the extract_subvector.
14229     if (SingleSource.getNode()) {
14230       if (Op.getOperand(0) != SingleSource)
14231         return SDValue();
14232     } else {
14233       SingleSource = Op.getOperand(0);
14234
14235       // Check the source type is the same as the type of the result.
14236       // If not, this concat may extend the vector, so we can not
14237       // optimize it away.
14238       if (SingleSource.getValueType() != N->getValueType(0))
14239         return SDValue();
14240     }
14241
14242     unsigned IdentityIndex = i * PartNumElem;
14243     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14244     // The extract index must be constant.
14245     if (!CS)
14246       return SDValue();
14247
14248     // Check that we are reading from the identity index.
14249     if (CS->getZExtValue() != IdentityIndex)
14250       return SDValue();
14251   }
14252
14253   if (SingleSource.getNode())
14254     return SingleSource;
14255
14256   return SDValue();
14257 }
14258
14259 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14260   EVT NVT = N->getValueType(0);
14261   SDValue V = N->getOperand(0);
14262
14263   // Extract from UNDEF is UNDEF.
14264   if (V.isUndef())
14265     return DAG.getUNDEF(NVT);
14266
14267   // Combine:
14268   //    (extract_subvec (concat V1, V2, ...), i)
14269   // Into:
14270   //    Vi if possible
14271   // Only operand 0 is checked as 'concat' assumes all inputs of the same
14272   // type.
14273   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14274       isa<ConstantSDNode>(N->getOperand(1)) &&
14275       V->getOperand(0).getValueType() == NVT) {
14276     unsigned Idx = N->getConstantOperandVal(1);
14277     unsigned NumElems = NVT.getVectorNumElements();
14278     assert((Idx % NumElems) == 0 &&
14279            "IDX in concat is not a multiple of the result vector length.");
14280     return V->getOperand(Idx / NumElems);
14281   }
14282
14283   // Skip bitcasting
14284   if (V->getOpcode() == ISD::BITCAST)
14285     V = V.getOperand(0);
14286
14287   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14288     // Handle only simple case where vector being inserted and vector
14289     // being extracted are of same size.
14290     EVT SmallVT = V->getOperand(1).getValueType();
14291     if (!NVT.bitsEq(SmallVT))
14292       return SDValue();
14293
14294     // Only handle cases where both indexes are constants.
14295     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14296     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14297
14298     if (InsIdx && ExtIdx) {
14299       // Combine:
14300       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14301       // Into:
14302       //    indices are equal or bit offsets are equal => V1
14303       //    otherwise => (extract_subvec V1, ExtIdx)
14304       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14305           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14306         return DAG.getBitcast(NVT, V->getOperand(1));
14307       return DAG.getNode(
14308           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14309           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14310           N->getOperand(1));
14311     }
14312   }
14313
14314   return SDValue();
14315 }
14316
14317 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14318                                                  SDValue V, SelectionDAG &DAG) {
14319   SDLoc DL(V);
14320   EVT VT = V.getValueType();
14321
14322   switch (V.getOpcode()) {
14323   default:
14324     return V;
14325
14326   case ISD::CONCAT_VECTORS: {
14327     EVT OpVT = V->getOperand(0).getValueType();
14328     int OpSize = OpVT.getVectorNumElements();
14329     SmallBitVector OpUsedElements(OpSize, false);
14330     bool FoundSimplification = false;
14331     SmallVector<SDValue, 4> NewOps;
14332     NewOps.reserve(V->getNumOperands());
14333     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14334       SDValue Op = V->getOperand(i);
14335       bool OpUsed = false;
14336       for (int j = 0; j < OpSize; ++j)
14337         if (UsedElements[i * OpSize + j]) {
14338           OpUsedElements[j] = true;
14339           OpUsed = true;
14340         }
14341       NewOps.push_back(
14342           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14343                  : DAG.getUNDEF(OpVT));
14344       FoundSimplification |= Op == NewOps.back();
14345       OpUsedElements.reset();
14346     }
14347     if (FoundSimplification)
14348       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14349     return V;
14350   }
14351
14352   case ISD::INSERT_SUBVECTOR: {
14353     SDValue BaseV = V->getOperand(0);
14354     SDValue SubV = V->getOperand(1);
14355     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14356     if (!IdxN)
14357       return V;
14358
14359     int SubSize = SubV.getValueType().getVectorNumElements();
14360     int Idx = IdxN->getZExtValue();
14361     bool SubVectorUsed = false;
14362     SmallBitVector SubUsedElements(SubSize, false);
14363     for (int i = 0; i < SubSize; ++i)
14364       if (UsedElements[i + Idx]) {
14365         SubVectorUsed = true;
14366         SubUsedElements[i] = true;
14367         UsedElements[i + Idx] = false;
14368       }
14369
14370     // Now recurse on both the base and sub vectors.
14371     SDValue SimplifiedSubV =
14372         SubVectorUsed
14373             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14374             : DAG.getUNDEF(SubV.getValueType());
14375     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14376     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14377       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14378                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14379     return V;
14380   }
14381   }
14382 }
14383
14384 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14385                                        SDValue N1, SelectionDAG &DAG) {
14386   EVT VT = SVN->getValueType(0);
14387   int NumElts = VT.getVectorNumElements();
14388   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14389   for (int M : SVN->getMask())
14390     if (M >= 0 && M < NumElts)
14391       N0UsedElements[M] = true;
14392     else if (M >= NumElts)
14393       N1UsedElements[M - NumElts] = true;
14394
14395   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14396   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14397   if (S0 == N0 && S1 == N1)
14398     return SDValue();
14399
14400   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14401 }
14402
14403 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14404 // or turn a shuffle of a single concat into simpler shuffle then concat.
14405 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14406   EVT VT = N->getValueType(0);
14407   unsigned NumElts = VT.getVectorNumElements();
14408
14409   SDValue N0 = N->getOperand(0);
14410   SDValue N1 = N->getOperand(1);
14411   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14412
14413   SmallVector<SDValue, 4> Ops;
14414   EVT ConcatVT = N0.getOperand(0).getValueType();
14415   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14416   unsigned NumConcats = NumElts / NumElemsPerConcat;
14417
14418   // Special case: shuffle(concat(A,B)) can be more efficiently represented
14419   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14420   // half vector elements.
14421   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14422       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14423                   SVN->getMask().end(), [](int i) { return i == -1; })) {
14424     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14425                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14426     N1 = DAG.getUNDEF(ConcatVT);
14427     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14428   }
14429
14430   // Look at every vector that's inserted. We're looking for exact
14431   // subvector-sized copies from a concatenated vector
14432   for (unsigned I = 0; I != NumConcats; ++I) {
14433     // Make sure we're dealing with a copy.
14434     unsigned Begin = I * NumElemsPerConcat;
14435     bool AllUndef = true, NoUndef = true;
14436     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14437       if (SVN->getMaskElt(J) >= 0)
14438         AllUndef = false;
14439       else
14440         NoUndef = false;
14441     }
14442
14443     if (NoUndef) {
14444       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14445         return SDValue();
14446
14447       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14448         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14449           return SDValue();
14450
14451       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14452       if (FirstElt < N0.getNumOperands())
14453         Ops.push_back(N0.getOperand(FirstElt));
14454       else
14455         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14456
14457     } else if (AllUndef) {
14458       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14459     } else { // Mixed with general masks and undefs, can't do optimization.
14460       return SDValue();
14461     }
14462   }
14463
14464   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14465 }
14466
14467 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14468 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14469 //
14470 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14471 // a simplification in some sense, but it isn't appropriate in general: some
14472 // BUILD_VECTORs are substantially cheaper than others. The general case
14473 // of a BUILD_VECTOR requires inserting each element individually (or
14474 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14475 // all constants is a single constant pool load.  A BUILD_VECTOR where each
14476 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
14477 // are undef lowers to a small number of element insertions.
14478 //
14479 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14480 // We don't fold shuffles where one side is a non-zero constant, and we don't
14481 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14482 // non-constant operands. This seems to work out reasonably well in practice.
14483 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14484                                        SelectionDAG &DAG,
14485                                        const TargetLowering &TLI) {
14486   EVT VT = SVN->getValueType(0);
14487   unsigned NumElts = VT.getVectorNumElements();
14488   SDValue N0 = SVN->getOperand(0);
14489   SDValue N1 = SVN->getOperand(1);
14490
14491   if (!N0->hasOneUse() || !N1->hasOneUse())
14492     return SDValue();
14493   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14494   // discussed above.
14495   if (!N1.isUndef()) {
14496     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14497     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14498     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14499       return SDValue();
14500     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14501       return SDValue();
14502   }
14503
14504   SmallVector<SDValue, 8> Ops;
14505   SmallSet<SDValue, 16> DuplicateOps;
14506   for (int M : SVN->getMask()) {
14507     SDValue Op = DAG.getUNDEF(VT.getScalarType());
14508     if (M >= 0) {
14509       int Idx = M < (int)NumElts ? M : M - NumElts;
14510       SDValue &S = (M < (int)NumElts ? N0 : N1);
14511       if (S.getOpcode() == ISD::BUILD_VECTOR) {
14512         Op = S.getOperand(Idx);
14513       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14514         if (Idx == 0)
14515           Op = S.getOperand(0);
14516       } else {
14517         // Operand can't be combined - bail out.
14518         return SDValue();
14519       }
14520     }
14521
14522     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14523     // fine, but it's likely to generate low-quality code if the target can't
14524     // reconstruct an appropriate shuffle.
14525     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14526       if (!DuplicateOps.insert(Op).second)
14527         return SDValue();
14528
14529     Ops.push_back(Op);
14530   }
14531   // BUILD_VECTOR requires all inputs to be of the same type, find the
14532   // maximum type and extend them all.
14533   EVT SVT = VT.getScalarType();
14534   if (SVT.isInteger())
14535     for (SDValue &Op : Ops)
14536       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14537   if (SVT != VT.getScalarType())
14538     for (SDValue &Op : Ops)
14539       Op = TLI.isZExtFree(Op.getValueType(), SVT)
14540                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14541                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14542   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14543 }
14544
14545 // Match shuffles that can be converted to any_vector_extend_in_reg.
14546 // This is often generated during legalization.
14547 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14548 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
14549 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
14550                                      SelectionDAG &DAG,
14551                                      const TargetLowering &TLI,
14552                                      bool LegalOperations) {
14553   EVT VT = SVN->getValueType(0);
14554   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14555
14556   // TODO Add support for big-endian when we have a test case.
14557   if (!VT.isInteger() || IsBigEndian)
14558     return SDValue();
14559
14560   unsigned NumElts = VT.getVectorNumElements();
14561   unsigned EltSizeInBits = VT.getScalarSizeInBits();
14562   ArrayRef<int> Mask = SVN->getMask();
14563   SDValue N0 = SVN->getOperand(0);
14564
14565   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
14566   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
14567     for (unsigned i = 0; i != NumElts; ++i) {
14568       if (Mask[i] < 0)
14569         continue;
14570       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
14571         continue;
14572       return false;
14573     }
14574     return true;
14575   };
14576
14577   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
14578   // power-of-2 extensions as they are the most likely.
14579   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
14580     if (!isAnyExtend(Scale))
14581       continue;
14582
14583     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
14584     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
14585     if (!LegalOperations ||
14586         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
14587       return DAG.getBitcast(VT,
14588                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
14589   }
14590
14591   return SDValue();
14592 }
14593
14594 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
14595 // each source element of a large type into the lowest elements of a smaller
14596 // destination type. This is often generated during legalization.
14597 // If the source node itself was a '*_extend_vector_inreg' node then we should
14598 // then be able to remove it.
14599 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) {
14600   EVT VT = SVN->getValueType(0);
14601   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14602
14603   // TODO Add support for big-endian when we have a test case.
14604   if (!VT.isInteger() || IsBigEndian)
14605     return SDValue();
14606
14607   SDValue N0 = SVN->getOperand(0);
14608   while (N0.getOpcode() == ISD::BITCAST)
14609     N0 = N0.getOperand(0);
14610
14611   unsigned Opcode = N0.getOpcode();
14612   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
14613       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
14614       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
14615     return SDValue();
14616
14617   SDValue N00 = N0.getOperand(0);
14618   ArrayRef<int> Mask = SVN->getMask();
14619   unsigned NumElts = VT.getVectorNumElements();
14620   unsigned EltSizeInBits = VT.getScalarSizeInBits();
14621   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
14622
14623   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
14624   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
14625   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
14626   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
14627     for (unsigned i = 0; i != NumElts; ++i) {
14628       if (Mask[i] < 0)
14629         continue;
14630       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
14631         continue;
14632       return false;
14633     }
14634     return true;
14635   };
14636
14637   // At the moment we just handle the case where we've truncated back to the
14638   // same size as before the extension.
14639   // TODO: handle more extension/truncation cases as cases arise.
14640   if (EltSizeInBits != ExtSrcSizeInBits)
14641     return SDValue();
14642
14643   // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
14644   // power-of-2 truncations as they are the most likely.
14645   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
14646     if (isTruncate(Scale))
14647       return DAG.getBitcast(VT, N00);
14648
14649   return SDValue();
14650 }
14651
14652 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
14653   EVT VT = N->getValueType(0);
14654   unsigned NumElts = VT.getVectorNumElements();
14655
14656   SDValue N0 = N->getOperand(0);
14657   SDValue N1 = N->getOperand(1);
14658
14659   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
14660
14661   // Canonicalize shuffle undef, undef -> undef
14662   if (N0.isUndef() && N1.isUndef())
14663     return DAG.getUNDEF(VT);
14664
14665   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14666
14667   // Canonicalize shuffle v, v -> v, undef
14668   if (N0 == N1) {
14669     SmallVector<int, 8> NewMask;
14670     for (unsigned i = 0; i != NumElts; ++i) {
14671       int Idx = SVN->getMaskElt(i);
14672       if (Idx >= (int)NumElts) Idx -= NumElts;
14673       NewMask.push_back(Idx);
14674     }
14675     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
14676   }
14677
14678   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
14679   if (N0.isUndef())
14680     return DAG.getCommutedVectorShuffle(*SVN);
14681
14682   // Remove references to rhs if it is undef
14683   if (N1.isUndef()) {
14684     bool Changed = false;
14685     SmallVector<int, 8> NewMask;
14686     for (unsigned i = 0; i != NumElts; ++i) {
14687       int Idx = SVN->getMaskElt(i);
14688       if (Idx >= (int)NumElts) {
14689         Idx = -1;
14690         Changed = true;
14691       }
14692       NewMask.push_back(Idx);
14693     }
14694     if (Changed)
14695       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
14696   }
14697
14698   // If it is a splat, check if the argument vector is another splat or a
14699   // build_vector.
14700   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
14701     SDNode *V = N0.getNode();
14702
14703     // If this is a bit convert that changes the element type of the vector but
14704     // not the number of vector elements, look through it.  Be careful not to
14705     // look though conversions that change things like v4f32 to v2f64.
14706     if (V->getOpcode() == ISD::BITCAST) {
14707       SDValue ConvInput = V->getOperand(0);
14708       if (ConvInput.getValueType().isVector() &&
14709           ConvInput.getValueType().getVectorNumElements() == NumElts)
14710         V = ConvInput.getNode();
14711     }
14712
14713     if (V->getOpcode() == ISD::BUILD_VECTOR) {
14714       assert(V->getNumOperands() == NumElts &&
14715              "BUILD_VECTOR has wrong number of operands");
14716       SDValue Base;
14717       bool AllSame = true;
14718       for (unsigned i = 0; i != NumElts; ++i) {
14719         if (!V->getOperand(i).isUndef()) {
14720           Base = V->getOperand(i);
14721           break;
14722         }
14723       }
14724       // Splat of <u, u, u, u>, return <u, u, u, u>
14725       if (!Base.getNode())
14726         return N0;
14727       for (unsigned i = 0; i != NumElts; ++i) {
14728         if (V->getOperand(i) != Base) {
14729           AllSame = false;
14730           break;
14731         }
14732       }
14733       // Splat of <x, x, x, x>, return <x, x, x, x>
14734       if (AllSame)
14735         return N0;
14736
14737       // Canonicalize any other splat as a build_vector.
14738       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
14739       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
14740       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
14741
14742       // We may have jumped through bitcasts, so the type of the
14743       // BUILD_VECTOR may not match the type of the shuffle.
14744       if (V->getValueType(0) != VT)
14745         NewBV = DAG.getBitcast(VT, NewBV);
14746       return NewBV;
14747     }
14748   }
14749
14750   // There are various patterns used to build up a vector from smaller vectors,
14751   // subvectors, or elements. Scan chains of these and replace unused insertions
14752   // or components with undef.
14753   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
14754     return S;
14755
14756   // Match shuffles that can be converted to any_vector_extend_in_reg.
14757   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
14758     return V;
14759
14760   // Combine "truncate_vector_in_reg" style shuffles.
14761   if (SDValue V = combineTruncationShuffle(SVN, DAG))
14762     return V;
14763
14764   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
14765       Level < AfterLegalizeVectorOps &&
14766       (N1.isUndef() ||
14767       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14768        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
14769     if (SDValue V = partitionShuffleOfConcats(N, DAG))
14770       return V;
14771   }
14772
14773   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14774   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14775   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14776     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
14777       return Res;
14778
14779   // If this shuffle only has a single input that is a bitcasted shuffle,
14780   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
14781   // back to their original types.
14782   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
14783       N1.isUndef() && Level < AfterLegalizeVectorOps &&
14784       TLI.isTypeLegal(VT)) {
14785
14786     // Peek through the bitcast only if there is one user.
14787     SDValue BC0 = N0;
14788     while (BC0.getOpcode() == ISD::BITCAST) {
14789       if (!BC0.hasOneUse())
14790         break;
14791       BC0 = BC0.getOperand(0);
14792     }
14793
14794     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
14795       if (Scale == 1)
14796         return SmallVector<int, 8>(Mask.begin(), Mask.end());
14797
14798       SmallVector<int, 8> NewMask;
14799       for (int M : Mask)
14800         for (int s = 0; s != Scale; ++s)
14801           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
14802       return NewMask;
14803     };
14804
14805     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
14806       EVT SVT = VT.getScalarType();
14807       EVT InnerVT = BC0->getValueType(0);
14808       EVT InnerSVT = InnerVT.getScalarType();
14809
14810       // Determine which shuffle works with the smaller scalar type.
14811       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
14812       EVT ScaleSVT = ScaleVT.getScalarType();
14813
14814       if (TLI.isTypeLegal(ScaleVT) &&
14815           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
14816           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
14817
14818         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14819         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14820
14821         // Scale the shuffle masks to the smaller scalar type.
14822         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
14823         SmallVector<int, 8> InnerMask =
14824             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
14825         SmallVector<int, 8> OuterMask =
14826             ScaleShuffleMask(SVN->getMask(), OuterScale);
14827
14828         // Merge the shuffle masks.
14829         SmallVector<int, 8> NewMask;
14830         for (int M : OuterMask)
14831           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14832
14833         // Test for shuffle mask legality over both commutations.
14834         SDValue SV0 = BC0->getOperand(0);
14835         SDValue SV1 = BC0->getOperand(1);
14836         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14837         if (!LegalMask) {
14838           std::swap(SV0, SV1);
14839           ShuffleVectorSDNode::commuteMask(NewMask);
14840           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14841         }
14842
14843         if (LegalMask) {
14844           SV0 = DAG.getBitcast(ScaleVT, SV0);
14845           SV1 = DAG.getBitcast(ScaleVT, SV1);
14846           return DAG.getBitcast(
14847               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14848         }
14849       }
14850     }
14851   }
14852
14853   // Canonicalize shuffles according to rules:
14854   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14855   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14856   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14857   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14858       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14859       TLI.isTypeLegal(VT)) {
14860     // The incoming shuffle must be of the same type as the result of the
14861     // current shuffle.
14862     assert(N1->getOperand(0).getValueType() == VT &&
14863            "Shuffle types don't match");
14864
14865     SDValue SV0 = N1->getOperand(0);
14866     SDValue SV1 = N1->getOperand(1);
14867     bool HasSameOp0 = N0 == SV0;
14868     bool IsSV1Undef = SV1.isUndef();
14869     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14870       // Commute the operands of this shuffle so that next rule
14871       // will trigger.
14872       return DAG.getCommutedVectorShuffle(*SVN);
14873   }
14874
14875   // Try to fold according to rules:
14876   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14877   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14878   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14879   // Don't try to fold shuffles with illegal type.
14880   // Only fold if this shuffle is the only user of the other shuffle.
14881   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14882       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14883     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14884
14885     // Don't try to fold splats; they're likely to simplify somehow, or they
14886     // might be free.
14887     if (OtherSV->isSplat())
14888       return SDValue();
14889
14890     // The incoming shuffle must be of the same type as the result of the
14891     // current shuffle.
14892     assert(OtherSV->getOperand(0).getValueType() == VT &&
14893            "Shuffle types don't match");
14894
14895     SDValue SV0, SV1;
14896     SmallVector<int, 4> Mask;
14897     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14898     // operand, and SV1 as the second operand.
14899     for (unsigned i = 0; i != NumElts; ++i) {
14900       int Idx = SVN->getMaskElt(i);
14901       if (Idx < 0) {
14902         // Propagate Undef.
14903         Mask.push_back(Idx);
14904         continue;
14905       }
14906
14907       SDValue CurrentVec;
14908       if (Idx < (int)NumElts) {
14909         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14910         // shuffle mask to identify which vector is actually referenced.
14911         Idx = OtherSV->getMaskElt(Idx);
14912         if (Idx < 0) {
14913           // Propagate Undef.
14914           Mask.push_back(Idx);
14915           continue;
14916         }
14917
14918         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14919                                            : OtherSV->getOperand(1);
14920       } else {
14921         // This shuffle index references an element within N1.
14922         CurrentVec = N1;
14923       }
14924
14925       // Simple case where 'CurrentVec' is UNDEF.
14926       if (CurrentVec.isUndef()) {
14927         Mask.push_back(-1);
14928         continue;
14929       }
14930
14931       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14932       // will be the first or second operand of the combined shuffle.
14933       Idx = Idx % NumElts;
14934       if (!SV0.getNode() || SV0 == CurrentVec) {
14935         // Ok. CurrentVec is the left hand side.
14936         // Update the mask accordingly.
14937         SV0 = CurrentVec;
14938         Mask.push_back(Idx);
14939         continue;
14940       }
14941
14942       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14943       if (SV1.getNode() && SV1 != CurrentVec)
14944         return SDValue();
14945
14946       // Ok. CurrentVec is the right hand side.
14947       // Update the mask accordingly.
14948       SV1 = CurrentVec;
14949       Mask.push_back(Idx + NumElts);
14950     }
14951
14952     // Check if all indices in Mask are Undef. In case, propagate Undef.
14953     bool isUndefMask = true;
14954     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14955       isUndefMask &= Mask[i] < 0;
14956
14957     if (isUndefMask)
14958       return DAG.getUNDEF(VT);
14959
14960     if (!SV0.getNode())
14961       SV0 = DAG.getUNDEF(VT);
14962     if (!SV1.getNode())
14963       SV1 = DAG.getUNDEF(VT);
14964
14965     // Avoid introducing shuffles with illegal mask.
14966     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14967       ShuffleVectorSDNode::commuteMask(Mask);
14968
14969       if (!TLI.isShuffleMaskLegal(Mask, VT))
14970         return SDValue();
14971
14972       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14973       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14974       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14975       std::swap(SV0, SV1);
14976     }
14977
14978     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14979     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14980     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14981     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14982   }
14983
14984   return SDValue();
14985 }
14986
14987 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14988   SDValue InVal = N->getOperand(0);
14989   EVT VT = N->getValueType(0);
14990
14991   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14992   // with a VECTOR_SHUFFLE.
14993   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14994     SDValue InVec = InVal->getOperand(0);
14995     SDValue EltNo = InVal->getOperand(1);
14996
14997     // FIXME: We could support implicit truncation if the shuffle can be
14998     // scaled to a smaller vector scalar type.
14999     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15000     if (C0 && VT == InVec.getValueType() &&
15001         VT.getScalarType() == InVal.getValueType()) {
15002       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15003       int Elt = C0->getZExtValue();
15004       NewMask[0] = Elt;
15005
15006       if (TLI.isShuffleMaskLegal(NewMask, VT))
15007         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15008                                     NewMask);
15009     }
15010   }
15011
15012   return SDValue();
15013 }
15014
15015 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15016   EVT VT = N->getValueType(0);
15017   SDValue N0 = N->getOperand(0);
15018   SDValue N1 = N->getOperand(1);
15019   SDValue N2 = N->getOperand(2);
15020
15021   // If inserting an UNDEF, just return the original vector.
15022   if (N1.isUndef())
15023     return N0;
15024
15025   // If this is an insert of an extracted vector into an undef vector, we can
15026   // just use the input to the extract.
15027   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15028       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15029     return N1.getOperand(0);
15030
15031   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15032   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15033   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15034   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15035       N0.getOperand(1).getValueType() == N1.getValueType() &&
15036       N0.getOperand(2) == N2)
15037     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15038                        N1, N2);
15039
15040   if (!isa<ConstantSDNode>(N2))
15041     return SDValue();
15042
15043   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15044
15045   // Canonicalize insert_subvector dag nodes.
15046   // Example:
15047   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15048   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15049   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15050       N1.getValueType() == N0.getOperand(1).getValueType() &&
15051       isa<ConstantSDNode>(N0.getOperand(2))) {
15052     unsigned OtherIdx = cast<ConstantSDNode>(N0.getOperand(2))->getZExtValue();
15053     if (InsIdx < OtherIdx) {
15054       // Swap nodes.
15055       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15056                                   N0.getOperand(0), N1, N2);
15057       AddToWorklist(NewOp.getNode());
15058       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15059                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15060     }
15061   }
15062
15063   // If the input vector is a concatenation, and the insert replaces
15064   // one of the pieces, we can optimize into a single concat_vectors.
15065   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15066       N0.getOperand(0).getValueType() == N1.getValueType()) {
15067     unsigned Factor = N1.getValueType().getVectorNumElements();
15068
15069     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15070     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15071
15072     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15073   }
15074
15075   return SDValue();
15076 }
15077
15078 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15079   SDValue N0 = N->getOperand(0);
15080
15081   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15082   if (N0->getOpcode() == ISD::FP16_TO_FP)
15083     return N0->getOperand(0);
15084
15085   return SDValue();
15086 }
15087
15088 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15089   SDValue N0 = N->getOperand(0);
15090
15091   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15092   if (N0->getOpcode() == ISD::AND) {
15093     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15094     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15095       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15096                          N0.getOperand(0));
15097     }
15098   }
15099
15100   return SDValue();
15101 }
15102
15103 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15104 /// with the destination vector and a zero vector.
15105 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15106 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
15107 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15108   EVT VT = N->getValueType(0);
15109   SDValue LHS = N->getOperand(0);
15110   SDValue RHS = N->getOperand(1);
15111   SDLoc DL(N);
15112
15113   // Make sure we're not running after operation legalization where it
15114   // may have custom lowered the vector shuffles.
15115   if (LegalOperations)
15116     return SDValue();
15117
15118   if (N->getOpcode() != ISD::AND)
15119     return SDValue();
15120
15121   if (RHS.getOpcode() == ISD::BITCAST)
15122     RHS = RHS.getOperand(0);
15123
15124   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15125     return SDValue();
15126
15127   EVT RVT = RHS.getValueType();
15128   unsigned NumElts = RHS.getNumOperands();
15129
15130   // Attempt to create a valid clear mask, splitting the mask into
15131   // sub elements and checking to see if each is
15132   // all zeros or all ones - suitable for shuffle masking.
15133   auto BuildClearMask = [&](int Split) {
15134     int NumSubElts = NumElts * Split;
15135     int NumSubBits = RVT.getScalarSizeInBits() / Split;
15136
15137     SmallVector<int, 8> Indices;
15138     for (int i = 0; i != NumSubElts; ++i) {
15139       int EltIdx = i / Split;
15140       int SubIdx = i % Split;
15141       SDValue Elt = RHS.getOperand(EltIdx);
15142       if (Elt.isUndef()) {
15143         Indices.push_back(-1);
15144         continue;
15145       }
15146
15147       APInt Bits;
15148       if (isa<ConstantSDNode>(Elt))
15149         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15150       else if (isa<ConstantFPSDNode>(Elt))
15151         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15152       else
15153         return SDValue();
15154
15155       // Extract the sub element from the constant bit mask.
15156       if (DAG.getDataLayout().isBigEndian()) {
15157         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15158       } else {
15159         Bits.lshrInPlace(SubIdx * NumSubBits);
15160       }
15161
15162       if (Split > 1)
15163         Bits = Bits.trunc(NumSubBits);
15164
15165       if (Bits.isAllOnesValue())
15166         Indices.push_back(i);
15167       else if (Bits == 0)
15168         Indices.push_back(i + NumSubElts);
15169       else
15170         return SDValue();
15171     }
15172
15173     // Let's see if the target supports this vector_shuffle.
15174     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15175     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15176     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15177       return SDValue();
15178
15179     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15180     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15181                                                    DAG.getBitcast(ClearVT, LHS),
15182                                                    Zero, Indices));
15183   };
15184
15185   // Determine maximum split level (byte level masking).
15186   int MaxSplit = 1;
15187   if (RVT.getScalarSizeInBits() % 8 == 0)
15188     MaxSplit = RVT.getScalarSizeInBits() / 8;
15189
15190   for (int Split = 1; Split <= MaxSplit; ++Split)
15191     if (RVT.getScalarSizeInBits() % Split == 0)
15192       if (SDValue S = BuildClearMask(Split))
15193         return S;
15194
15195   return SDValue();
15196 }
15197
15198 /// Visit a binary vector operation, like ADD.
15199 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15200   assert(N->getValueType(0).isVector() &&
15201          "SimplifyVBinOp only works on vectors!");
15202
15203   SDValue LHS = N->getOperand(0);
15204   SDValue RHS = N->getOperand(1);
15205   SDValue Ops[] = {LHS, RHS};
15206
15207   // See if we can constant fold the vector operation.
15208   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15209           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15210     return Fold;
15211
15212   // Try to convert a constant mask AND into a shuffle clear mask.
15213   if (SDValue Shuffle = XformToShuffleWithZero(N))
15214     return Shuffle;
15215
15216   // Type legalization might introduce new shuffles in the DAG.
15217   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15218   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
15219   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15220       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15221       LHS.getOperand(1).isUndef() &&
15222       RHS.getOperand(1).isUndef()) {
15223     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15224     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15225
15226     if (SVN0->getMask().equals(SVN1->getMask())) {
15227       EVT VT = N->getValueType(0);
15228       SDValue UndefVector = LHS.getOperand(1);
15229       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15230                                      LHS.getOperand(0), RHS.getOperand(0),
15231                                      N->getFlags());
15232       AddUsersToWorklist(N);
15233       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15234                                   SVN0->getMask());
15235     }
15236   }
15237
15238   return SDValue();
15239 }
15240
15241 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15242                                     SDValue N2) {
15243   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15244
15245   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15246                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
15247
15248   // If we got a simplified select_cc node back from SimplifySelectCC, then
15249   // break it down into a new SETCC node, and a new SELECT node, and then return
15250   // the SELECT node, since we were called with a SELECT node.
15251   if (SCC.getNode()) {
15252     // Check to see if we got a select_cc back (to turn into setcc/select).
15253     // Otherwise, just return whatever node we got back, like fabs.
15254     if (SCC.getOpcode() == ISD::SELECT_CC) {
15255       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15256                                   N0.getValueType(),
15257                                   SCC.getOperand(0), SCC.getOperand(1),
15258                                   SCC.getOperand(4));
15259       AddToWorklist(SETCC.getNode());
15260       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15261                            SCC.getOperand(2), SCC.getOperand(3));
15262     }
15263
15264     return SCC;
15265   }
15266   return SDValue();
15267 }
15268
15269 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15270 /// being selected between, see if we can simplify the select.  Callers of this
15271 /// should assume that TheSelect is deleted if this returns true.  As such, they
15272 /// should return the appropriate thing (e.g. the node) back to the top-level of
15273 /// the DAG combiner loop to avoid it being looked at.
15274 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15275                                     SDValue RHS) {
15276
15277   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15278   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15279   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15280     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15281       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15282       SDValue Sqrt = RHS;
15283       ISD::CondCode CC;
15284       SDValue CmpLHS;
15285       const ConstantFPSDNode *Zero = nullptr;
15286
15287       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15288         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15289         CmpLHS = TheSelect->getOperand(0);
15290         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15291       } else {
15292         // SELECT or VSELECT
15293         SDValue Cmp = TheSelect->getOperand(0);
15294         if (Cmp.getOpcode() == ISD::SETCC) {
15295           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15296           CmpLHS = Cmp.getOperand(0);
15297           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15298         }
15299       }
15300       if (Zero && Zero->isZero() &&
15301           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15302           CC == ISD::SETULT || CC == ISD::SETLT)) {
15303         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15304         CombineTo(TheSelect, Sqrt);
15305         return true;
15306       }
15307     }
15308   }
15309   // Cannot simplify select with vector condition
15310   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15311
15312   // If this is a select from two identical things, try to pull the operation
15313   // through the select.
15314   if (LHS.getOpcode() != RHS.getOpcode() ||
15315       !LHS.hasOneUse() || !RHS.hasOneUse())
15316     return false;
15317
15318   // If this is a load and the token chain is identical, replace the select
15319   // of two loads with a load through a select of the address to load from.
15320   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15321   // constants have been dropped into the constant pool.
15322   if (LHS.getOpcode() == ISD::LOAD) {
15323     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15324     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15325
15326     // Token chains must be identical.
15327     if (LHS.getOperand(0) != RHS.getOperand(0) ||
15328         // Do not let this transformation reduce the number of volatile loads.
15329         LLD->isVolatile() || RLD->isVolatile() ||
15330         // FIXME: If either is a pre/post inc/dec load,
15331         // we'd need to split out the address adjustment.
15332         LLD->isIndexed() || RLD->isIndexed() ||
15333         // If this is an EXTLOAD, the VT's must match.
15334         LLD->getMemoryVT() != RLD->getMemoryVT() ||
15335         // If this is an EXTLOAD, the kind of extension must match.
15336         (LLD->getExtensionType() != RLD->getExtensionType() &&
15337          // The only exception is if one of the extensions is anyext.
15338          LLD->getExtensionType() != ISD::EXTLOAD &&
15339          RLD->getExtensionType() != ISD::EXTLOAD) ||
15340         // FIXME: this discards src value information.  This is
15341         // over-conservative. It would be beneficial to be able to remember
15342         // both potential memory locations.  Since we are discarding
15343         // src value info, don't do the transformation if the memory
15344         // locations are not in the default address space.
15345         LLD->getPointerInfo().getAddrSpace() != 0 ||
15346         RLD->getPointerInfo().getAddrSpace() != 0 ||
15347         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15348                                       LLD->getBasePtr().getValueType()))
15349       return false;
15350
15351     // Check that the select condition doesn't reach either load.  If so,
15352     // folding this will induce a cycle into the DAG.  If not, this is safe to
15353     // xform, so create a select of the addresses.
15354     SDValue Addr;
15355     if (TheSelect->getOpcode() == ISD::SELECT) {
15356       SDNode *CondNode = TheSelect->getOperand(0).getNode();
15357       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15358           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15359         return false;
15360       // The loads must not depend on one another.
15361       if (LLD->isPredecessorOf(RLD) ||
15362           RLD->isPredecessorOf(LLD))
15363         return false;
15364       Addr = DAG.getSelect(SDLoc(TheSelect),
15365                            LLD->getBasePtr().getValueType(),
15366                            TheSelect->getOperand(0), LLD->getBasePtr(),
15367                            RLD->getBasePtr());
15368     } else {  // Otherwise SELECT_CC
15369       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15370       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15371
15372       if ((LLD->hasAnyUseOfValue(1) &&
15373            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15374           (RLD->hasAnyUseOfValue(1) &&
15375            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15376         return false;
15377
15378       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15379                          LLD->getBasePtr().getValueType(),
15380                          TheSelect->getOperand(0),
15381                          TheSelect->getOperand(1),
15382                          LLD->getBasePtr(), RLD->getBasePtr(),
15383                          TheSelect->getOperand(4));
15384     }
15385
15386     SDValue Load;
15387     // It is safe to replace the two loads if they have different alignments,
15388     // but the new load must be the minimum (most restrictive) alignment of the
15389     // inputs.
15390     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15391     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15392     if (!RLD->isInvariant())
15393       MMOFlags &= ~MachineMemOperand::MOInvariant;
15394     if (!RLD->isDereferenceable())
15395       MMOFlags &= ~MachineMemOperand::MODereferenceable;
15396     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15397       // FIXME: Discards pointer and AA info.
15398       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15399                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15400                          MMOFlags);
15401     } else {
15402       // FIXME: Discards pointer and AA info.
15403       Load = DAG.getExtLoad(
15404           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15405                                                   : LLD->getExtensionType(),
15406           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15407           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15408     }
15409
15410     // Users of the select now use the result of the load.
15411     CombineTo(TheSelect, Load);
15412
15413     // Users of the old loads now use the new load's chain.  We know the
15414     // old-load value is dead now.
15415     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15416     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15417     return true;
15418   }
15419
15420   return false;
15421 }
15422
15423 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15424 /// bitwise 'and'.
15425 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15426                                             SDValue N1, SDValue N2, SDValue N3,
15427                                             ISD::CondCode CC) {
15428   // If this is a select where the false operand is zero and the compare is a
15429   // check of the sign bit, see if we can perform the "gzip trick":
15430   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15431   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15432   EVT XType = N0.getValueType();
15433   EVT AType = N2.getValueType();
15434   if (!isNullConstant(N3) || !XType.bitsGE(AType))
15435     return SDValue();
15436
15437   // If the comparison is testing for a positive value, we have to invert
15438   // the sign bit mask, so only do that transform if the target has a bitwise
15439   // 'and not' instruction (the invert is free).
15440   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15441     // (X > -1) ? A : 0
15442     // (X >  0) ? X : 0 <-- This is canonical signed max.
15443     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15444       return SDValue();
15445   } else if (CC == ISD::SETLT) {
15446     // (X <  0) ? A : 0
15447     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
15448     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15449       return SDValue();
15450   } else {
15451     return SDValue();
15452   }
15453
15454   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15455   // constant.
15456   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15457   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15458   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15459     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15460     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15461     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15462     AddToWorklist(Shift.getNode());
15463
15464     if (XType.bitsGT(AType)) {
15465       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15466       AddToWorklist(Shift.getNode());
15467     }
15468
15469     if (CC == ISD::SETGT)
15470       Shift = DAG.getNOT(DL, Shift, AType);
15471
15472     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15473   }
15474
15475   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15476   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15477   AddToWorklist(Shift.getNode());
15478
15479   if (XType.bitsGT(AType)) {
15480     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15481     AddToWorklist(Shift.getNode());
15482   }
15483
15484   if (CC == ISD::SETGT)
15485     Shift = DAG.getNOT(DL, Shift, AType);
15486
15487   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15488 }
15489
15490 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15491 /// where 'cond' is the comparison specified by CC.
15492 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15493                                       SDValue N2, SDValue N3, ISD::CondCode CC,
15494                                       bool NotExtCompare) {
15495   // (x ? y : y) -> y.
15496   if (N2 == N3) return N2;
15497
15498   EVT VT = N2.getValueType();
15499   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
15500   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15501
15502   // Determine if the condition we're dealing with is constant
15503   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
15504                               N0, N1, CC, DL, false);
15505   if (SCC.getNode()) AddToWorklist(SCC.getNode());
15506
15507   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
15508     // fold select_cc true, x, y -> x
15509     // fold select_cc false, x, y -> y
15510     return !SCCC->isNullValue() ? N2 : N3;
15511   }
15512
15513   // Check to see if we can simplify the select into an fabs node
15514   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
15515     // Allow either -0.0 or 0.0
15516     if (CFP->isZero()) {
15517       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
15518       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
15519           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
15520           N2 == N3.getOperand(0))
15521         return DAG.getNode(ISD::FABS, DL, VT, N0);
15522
15523       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
15524       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
15525           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
15526           N2.getOperand(0) == N3)
15527         return DAG.getNode(ISD::FABS, DL, VT, N3);
15528     }
15529   }
15530
15531   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
15532   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
15533   // in it.  This is a win when the constant is not otherwise available because
15534   // it replaces two constant pool loads with one.  We only do this if the FP
15535   // type is known to be legal, because if it isn't, then we are before legalize
15536   // types an we want the other legalization to happen first (e.g. to avoid
15537   // messing with soft float) and if the ConstantFP is not legal, because if
15538   // it is legal, we may not need to store the FP constant in a constant pool.
15539   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
15540     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
15541       if (TLI.isTypeLegal(N2.getValueType()) &&
15542           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
15543                TargetLowering::Legal &&
15544            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
15545            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
15546           // If both constants have multiple uses, then we won't need to do an
15547           // extra load, they are likely around in registers for other users.
15548           (TV->hasOneUse() || FV->hasOneUse())) {
15549         Constant *Elts[] = {
15550           const_cast<ConstantFP*>(FV->getConstantFPValue()),
15551           const_cast<ConstantFP*>(TV->getConstantFPValue())
15552         };
15553         Type *FPTy = Elts[0]->getType();
15554         const DataLayout &TD = DAG.getDataLayout();
15555
15556         // Create a ConstantArray of the two constants.
15557         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
15558         SDValue CPIdx =
15559             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
15560                                 TD.getPrefTypeAlignment(FPTy));
15561         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
15562
15563         // Get the offsets to the 0 and 1 element of the array so that we can
15564         // select between them.
15565         SDValue Zero = DAG.getIntPtrConstant(0, DL);
15566         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
15567         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
15568
15569         SDValue Cond = DAG.getSetCC(DL,
15570                                     getSetCCResultType(N0.getValueType()),
15571                                     N0, N1, CC);
15572         AddToWorklist(Cond.getNode());
15573         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
15574                                           Cond, One, Zero);
15575         AddToWorklist(CstOffset.getNode());
15576         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
15577                             CstOffset);
15578         AddToWorklist(CPIdx.getNode());
15579         return DAG.getLoad(
15580             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
15581             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
15582             Alignment);
15583       }
15584     }
15585
15586   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
15587     return V;
15588
15589   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
15590   // where y is has a single bit set.
15591   // A plaintext description would be, we can turn the SELECT_CC into an AND
15592   // when the condition can be materialized as an all-ones register.  Any
15593   // single bit-test can be materialized as an all-ones register with
15594   // shift-left and shift-right-arith.
15595   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
15596       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
15597     SDValue AndLHS = N0->getOperand(0);
15598     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15599     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
15600       // Shift the tested bit over the sign bit.
15601       const APInt &AndMask = ConstAndRHS->getAPIntValue();
15602       SDValue ShlAmt =
15603         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
15604                         getShiftAmountTy(AndLHS.getValueType()));
15605       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
15606
15607       // Now arithmetic right shift it all the way over, so the result is either
15608       // all-ones, or zero.
15609       SDValue ShrAmt =
15610         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
15611                         getShiftAmountTy(Shl.getValueType()));
15612       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
15613
15614       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
15615     }
15616   }
15617
15618   // fold select C, 16, 0 -> shl C, 4
15619   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
15620       TLI.getBooleanContents(N0.getValueType()) ==
15621           TargetLowering::ZeroOrOneBooleanContent) {
15622
15623     // If the caller doesn't want us to simplify this into a zext of a compare,
15624     // don't do it.
15625     if (NotExtCompare && N2C->isOne())
15626       return SDValue();
15627
15628     // Get a SetCC of the condition
15629     // NOTE: Don't create a SETCC if it's not legal on this target.
15630     if (!LegalOperations ||
15631         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
15632       SDValue Temp, SCC;
15633       // cast from setcc result type to select result type
15634       if (LegalTypes) {
15635         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
15636                             N0, N1, CC);
15637         if (N2.getValueType().bitsLT(SCC.getValueType()))
15638           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
15639                                         N2.getValueType());
15640         else
15641           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15642                              N2.getValueType(), SCC);
15643       } else {
15644         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
15645         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15646                            N2.getValueType(), SCC);
15647       }
15648
15649       AddToWorklist(SCC.getNode());
15650       AddToWorklist(Temp.getNode());
15651
15652       if (N2C->isOne())
15653         return Temp;
15654
15655       // shl setcc result by log2 n2c
15656       return DAG.getNode(
15657           ISD::SHL, DL, N2.getValueType(), Temp,
15658           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
15659                           getShiftAmountTy(Temp.getValueType())));
15660     }
15661   }
15662
15663   // Check to see if this is an integer abs.
15664   // select_cc setg[te] X,  0,  X, -X ->
15665   // select_cc setgt    X, -1,  X, -X ->
15666   // select_cc setl[te] X,  0, -X,  X ->
15667   // select_cc setlt    X,  1, -X,  X ->
15668   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
15669   if (N1C) {
15670     ConstantSDNode *SubC = nullptr;
15671     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
15672          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
15673         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
15674       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
15675     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
15676               (N1C->isOne() && CC == ISD::SETLT)) &&
15677              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
15678       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
15679
15680     EVT XType = N0.getValueType();
15681     if (SubC && SubC->isNullValue() && XType.isInteger()) {
15682       SDLoc DL(N0);
15683       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
15684                                   N0,
15685                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
15686                                          getShiftAmountTy(N0.getValueType())));
15687       SDValue Add = DAG.getNode(ISD::ADD, DL,
15688                                 XType, N0, Shift);
15689       AddToWorklist(Shift.getNode());
15690       AddToWorklist(Add.getNode());
15691       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
15692     }
15693   }
15694
15695   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
15696   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
15697   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
15698   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
15699   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
15700   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
15701   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
15702   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
15703   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15704     SDValue ValueOnZero = N2;
15705     SDValue Count = N3;
15706     // If the condition is NE instead of E, swap the operands.
15707     if (CC == ISD::SETNE)
15708       std::swap(ValueOnZero, Count);
15709     // Check if the value on zero is a constant equal to the bits in the type.
15710     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
15711       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
15712         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
15713         // legal, combine to just cttz.
15714         if ((Count.getOpcode() == ISD::CTTZ ||
15715              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
15716             N0 == Count.getOperand(0) &&
15717             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
15718           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
15719         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
15720         // legal, combine to just ctlz.
15721         if ((Count.getOpcode() == ISD::CTLZ ||
15722              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
15723             N0 == Count.getOperand(0) &&
15724             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
15725           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
15726       }
15727     }
15728   }
15729
15730   return SDValue();
15731 }
15732
15733 /// This is a stub for TargetLowering::SimplifySetCC.
15734 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
15735                                    ISD::CondCode Cond, const SDLoc &DL,
15736                                    bool foldBooleans) {
15737   TargetLowering::DAGCombinerInfo
15738     DagCombineInfo(DAG, Level, false, this);
15739   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
15740 }
15741
15742 /// Given an ISD::SDIV node expressing a divide by constant, return
15743 /// a DAG expression to select that will generate the same value by multiplying
15744 /// by a magic number.
15745 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15746 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
15747   // when optimising for minimum size, we don't want to expand a div to a mul
15748   // and a shift.
15749   if (DAG.getMachineFunction().getFunction()->optForMinSize())
15750     return SDValue();
15751
15752   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15753   if (!C)
15754     return SDValue();
15755
15756   // Avoid division by zero.
15757   if (C->isNullValue())
15758     return SDValue();
15759
15760   std::vector<SDNode*> Built;
15761   SDValue S =
15762       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15763
15764   for (SDNode *N : Built)
15765     AddToWorklist(N);
15766   return S;
15767 }
15768
15769 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
15770 /// DAG expression that will generate the same value by right shifting.
15771 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
15772   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15773   if (!C)
15774     return SDValue();
15775
15776   // Avoid division by zero.
15777   if (C->isNullValue())
15778     return SDValue();
15779
15780   std::vector<SDNode *> Built;
15781   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
15782
15783   for (SDNode *N : Built)
15784     AddToWorklist(N);
15785   return S;
15786 }
15787
15788 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
15789 /// expression that will generate the same value by multiplying by a magic
15790 /// number.
15791 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15792 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
15793   // when optimising for minimum size, we don't want to expand a div to a mul
15794   // and a shift.
15795   if (DAG.getMachineFunction().getFunction()->optForMinSize())
15796     return SDValue();
15797
15798   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15799   if (!C)
15800     return SDValue();
15801
15802   // Avoid division by zero.
15803   if (C->isNullValue())
15804     return SDValue();
15805
15806   std::vector<SDNode*> Built;
15807   SDValue S =
15808       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15809
15810   for (SDNode *N : Built)
15811     AddToWorklist(N);
15812   return S;
15813 }
15814
15815 /// Determines the LogBase2 value for a non-null input value using the
15816 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
15817 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
15818   EVT VT = V.getValueType();
15819   unsigned EltBits = VT.getScalarSizeInBits();
15820   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
15821   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
15822   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
15823   return LogBase2;
15824 }
15825
15826 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15827 /// For the reciprocal, we need to find the zero of the function:
15828 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
15829 ///     =>
15830 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
15831 ///     does not require additional intermediate precision]
15832 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
15833   if (Level >= AfterLegalizeDAG)
15834     return SDValue();
15835
15836   // TODO: Handle half and/or extended types?
15837   EVT VT = Op.getValueType();
15838   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15839     return SDValue();
15840
15841   // If estimates are explicitly disabled for this function, we're done.
15842   MachineFunction &MF = DAG.getMachineFunction();
15843   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
15844   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15845     return SDValue();
15846
15847   // Estimates may be explicitly enabled for this type with a custom number of
15848   // refinement steps.
15849   int Iterations = TLI.getDivRefinementSteps(VT, MF);
15850   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
15851     AddToWorklist(Est.getNode());
15852
15853     if (Iterations) {
15854       EVT VT = Op.getValueType();
15855       SDLoc DL(Op);
15856       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
15857
15858       // Newton iterations: Est = Est + Est (1 - Arg * Est)
15859       for (int i = 0; i < Iterations; ++i) {
15860         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
15861         AddToWorklist(NewEst.getNode());
15862
15863         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
15864         AddToWorklist(NewEst.getNode());
15865
15866         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15867         AddToWorklist(NewEst.getNode());
15868
15869         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
15870         AddToWorklist(Est.getNode());
15871       }
15872     }
15873     return Est;
15874   }
15875
15876   return SDValue();
15877 }
15878
15879 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15880 /// For the reciprocal sqrt, we need to find the zero of the function:
15881 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15882 ///     =>
15883 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
15884 /// As a result, we precompute A/2 prior to the iteration loop.
15885 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
15886                                          unsigned Iterations,
15887                                          SDNodeFlags *Flags, bool Reciprocal) {
15888   EVT VT = Arg.getValueType();
15889   SDLoc DL(Arg);
15890   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
15891
15892   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
15893   // this entire sequence requires only one FP constant.
15894   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
15895   AddToWorklist(HalfArg.getNode());
15896
15897   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15898   AddToWorklist(HalfArg.getNode());
15899
15900   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15901   for (unsigned i = 0; i < Iterations; ++i) {
15902     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15903     AddToWorklist(NewEst.getNode());
15904
15905     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15906     AddToWorklist(NewEst.getNode());
15907
15908     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15909     AddToWorklist(NewEst.getNode());
15910
15911     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15912     AddToWorklist(Est.getNode());
15913   }
15914
15915   // If non-reciprocal square root is requested, multiply the result by Arg.
15916   if (!Reciprocal) {
15917     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15918     AddToWorklist(Est.getNode());
15919   }
15920
15921   return Est;
15922 }
15923
15924 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15925 /// For the reciprocal sqrt, we need to find the zero of the function:
15926 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15927 ///     =>
15928 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15929 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15930                                          unsigned Iterations,
15931                                          SDNodeFlags *Flags, bool Reciprocal) {
15932   EVT VT = Arg.getValueType();
15933   SDLoc DL(Arg);
15934   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15935   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15936
15937   // This routine must enter the loop below to work correctly
15938   // when (Reciprocal == false).
15939   assert(Iterations > 0);
15940
15941   // Newton iterations for reciprocal square root:
15942   // E = (E * -0.5) * ((A * E) * E + -3.0)
15943   for (unsigned i = 0; i < Iterations; ++i) {
15944     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15945     AddToWorklist(AE.getNode());
15946
15947     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15948     AddToWorklist(AEE.getNode());
15949
15950     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15951     AddToWorklist(RHS.getNode());
15952
15953     // When calculating a square root at the last iteration build:
15954     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15955     // (notice a common subexpression)
15956     SDValue LHS;
15957     if (Reciprocal || (i + 1) < Iterations) {
15958       // RSQRT: LHS = (E * -0.5)
15959       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15960     } else {
15961       // SQRT: LHS = (A * E) * -0.5
15962       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15963     }
15964     AddToWorklist(LHS.getNode());
15965
15966     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15967     AddToWorklist(Est.getNode());
15968   }
15969
15970   return Est;
15971 }
15972
15973 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15974 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15975 /// Op can be zero.
15976 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15977                                            bool Reciprocal) {
15978   if (Level >= AfterLegalizeDAG)
15979     return SDValue();
15980
15981   // TODO: Handle half and/or extended types?
15982   EVT VT = Op.getValueType();
15983   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15984     return SDValue();
15985
15986   // If estimates are explicitly disabled for this function, we're done.
15987   MachineFunction &MF = DAG.getMachineFunction();
15988   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15989   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15990     return SDValue();
15991
15992   // Estimates may be explicitly enabled for this type with a custom number of
15993   // refinement steps.
15994   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15995
15996   bool UseOneConstNR = false;
15997   if (SDValue Est =
15998       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
15999                           Reciprocal)) {
16000     AddToWorklist(Est.getNode());
16001
16002     if (Iterations) {
16003       Est = UseOneConstNR
16004             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16005             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16006
16007       if (!Reciprocal) {
16008         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16009         // Select out this case and force the answer to 0.0.
16010         EVT VT = Op.getValueType();
16011         SDLoc DL(Op);
16012
16013         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16014         EVT CCVT = getSetCCResultType(VT);
16015         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16016         AddToWorklist(ZeroCmp.getNode());
16017
16018         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16019                           ZeroCmp, FPZero, Est);
16020         AddToWorklist(Est.getNode());
16021       }
16022     }
16023     return Est;
16024   }
16025
16026   return SDValue();
16027 }
16028
16029 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
16030   return buildSqrtEstimateImpl(Op, Flags, true);
16031 }
16032
16033 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
16034   return buildSqrtEstimateImpl(Op, Flags, false);
16035 }
16036
16037 /// Return true if base is a frame index, which is known not to alias with
16038 /// anything but itself.  Provides base object and offset as results.
16039 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16040                            const GlobalValue *&GV, const void *&CV) {
16041   // Assume it is a primitive operation.
16042   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16043
16044   // If it's an adding a simple constant then integrate the offset.
16045   if (Base.getOpcode() == ISD::ADD) {
16046     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16047       Base = Base.getOperand(0);
16048       Offset += C->getSExtValue();
16049     }
16050   }
16051
16052   // Return the underlying GlobalValue, and update the Offset.  Return false
16053   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16054   // by multiple nodes with different offsets.
16055   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16056     GV = G->getGlobal();
16057     Offset += G->getOffset();
16058     return false;
16059   }
16060
16061   // Return the underlying Constant value, and update the Offset.  Return false
16062   // for ConstantSDNodes since the same constant pool entry may be represented
16063   // by multiple nodes with different offsets.
16064   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16065     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16066                                          : (const void *)C->getConstVal();
16067     Offset += C->getOffset();
16068     return false;
16069   }
16070   // If it's any of the following then it can't alias with anything but itself.
16071   return isa<FrameIndexSDNode>(Base);
16072 }
16073
16074 /// Return true if there is any possibility that the two addresses overlap.
16075 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16076   // If they are the same then they must be aliases.
16077   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16078
16079   // If they are both volatile then they cannot be reordered.
16080   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16081
16082   // If one operation reads from invariant memory, and the other may store, they
16083   // cannot alias. These should really be checking the equivalent of mayWrite,
16084   // but it only matters for memory nodes other than load /store.
16085   if (Op0->isInvariant() && Op1->writeMem())
16086     return false;
16087
16088   if (Op1->isInvariant() && Op0->writeMem())
16089     return false;
16090
16091   // Gather base node and offset information.
16092   SDValue Base0, Base1;
16093   int64_t Offset0, Offset1;
16094   const GlobalValue *GV0, *GV1;
16095   const void *CV0, *CV1;
16096   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16097                                       Base0, Offset0, GV0, CV0);
16098   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16099                                       Base1, Offset1, GV1, CV1);
16100
16101   // If they have the same base address, then check to see if they overlap.
16102   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16103   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16104   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16105     return !((Offset0 + NumBytes0) <= Offset1 ||
16106              (Offset1 + NumBytes1) <= Offset0);
16107
16108   // It is possible for different frame indices to alias each other, mostly
16109   // when tail call optimization reuses return address slots for arguments.
16110   // To catch this case, look up the actual index of frame indices to compute
16111   // the real alias relationship.
16112   if (IsFrameIndex0 && IsFrameIndex1) {
16113     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16114     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16115     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16116     return !((Offset0 + NumBytes0) <= Offset1 ||
16117              (Offset1 + NumBytes1) <= Offset0);
16118   }
16119
16120   // Otherwise, if we know what the bases are, and they aren't identical, then
16121   // we know they cannot alias.
16122   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16123     return false;
16124
16125   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16126   // compared to the size and offset of the access, we may be able to prove they
16127   // do not alias. This check is conservative for now to catch cases created by
16128   // splitting vector types.
16129   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16130   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16131   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16132   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16133   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16134       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16135     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16136     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16137
16138     // There is no overlap between these relatively aligned accesses of similar
16139     // size. Return no alias.
16140     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16141         (OffAlign1 + NumBytes1) <= OffAlign0)
16142       return false;
16143   }
16144
16145   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16146                    ? CombinerGlobalAA
16147                    : DAG.getSubtarget().useAA();
16148 #ifndef NDEBUG
16149   if (CombinerAAOnlyFunc.getNumOccurrences() &&
16150       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16151     UseAA = false;
16152 #endif
16153
16154   if (UseAA &&
16155       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16156     // Use alias analysis information.
16157     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16158     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16159     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16160     AliasResult AAResult =
16161         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16162                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16163                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16164                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
16165     if (AAResult == NoAlias)
16166       return false;
16167   }
16168
16169   // Otherwise we have to assume they alias.
16170   return true;
16171 }
16172
16173 /// Walk up chain skipping non-aliasing memory nodes,
16174 /// looking for aliasing nodes and adding them to the Aliases vector.
16175 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16176                                    SmallVectorImpl<SDValue> &Aliases) {
16177   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
16178   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
16179
16180   // Get alias information for node.
16181   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16182
16183   // Starting off.
16184   Chains.push_back(OriginalChain);
16185   unsigned Depth = 0;
16186
16187   // Look at each chain and determine if it is an alias.  If so, add it to the
16188   // aliases list.  If not, then continue up the chain looking for the next
16189   // candidate.
16190   while (!Chains.empty()) {
16191     SDValue Chain = Chains.pop_back_val();
16192
16193     // For TokenFactor nodes, look at each operand and only continue up the
16194     // chain until we reach the depth limit.
16195     //
16196     // FIXME: The depth check could be made to return the last non-aliasing
16197     // chain we found before we hit a tokenfactor rather than the original
16198     // chain.
16199     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16200       Aliases.clear();
16201       Aliases.push_back(OriginalChain);
16202       return;
16203     }
16204
16205     // Don't bother if we've been before.
16206     if (!Visited.insert(Chain.getNode()).second)
16207       continue;
16208
16209     switch (Chain.getOpcode()) {
16210     case ISD::EntryToken:
16211       // Entry token is ideal chain operand, but handled in FindBetterChain.
16212       break;
16213
16214     case ISD::LOAD:
16215     case ISD::STORE: {
16216       // Get alias information for Chain.
16217       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16218           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16219
16220       // If chain is alias then stop here.
16221       if (!(IsLoad && IsOpLoad) &&
16222           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16223         Aliases.push_back(Chain);
16224       } else {
16225         // Look further up the chain.
16226         Chains.push_back(Chain.getOperand(0));
16227         ++Depth;
16228       }
16229       break;
16230     }
16231
16232     case ISD::TokenFactor:
16233       // We have to check each of the operands of the token factor for "small"
16234       // token factors, so we queue them up.  Adding the operands to the queue
16235       // (stack) in reverse order maintains the original order and increases the
16236       // likelihood that getNode will find a matching token factor (CSE.)
16237       if (Chain.getNumOperands() > 16) {
16238         Aliases.push_back(Chain);
16239         break;
16240       }
16241       for (unsigned n = Chain.getNumOperands(); n;)
16242         Chains.push_back(Chain.getOperand(--n));
16243       ++Depth;
16244       break;
16245
16246     case ISD::CopyFromReg:
16247       // Forward past CopyFromReg.
16248       Chains.push_back(Chain.getOperand(0));
16249       ++Depth;
16250       break;
16251
16252     default:
16253       // For all other instructions we will just have to take what we can get.
16254       Aliases.push_back(Chain);
16255       break;
16256     }
16257   }
16258 }
16259
16260 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16261 /// (aliasing node.)
16262 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16263   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
16264
16265   // Accumulate all the aliases to this node.
16266   GatherAllAliases(N, OldChain, Aliases);
16267
16268   // If no operands then chain to entry token.
16269   if (Aliases.size() == 0)
16270     return DAG.getEntryNode();
16271
16272   // If a single operand then chain to it.  We don't need to revisit it.
16273   if (Aliases.size() == 1)
16274     return Aliases[0];
16275
16276   // Construct a custom tailored token factor.
16277   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16278 }
16279
16280 // This function tries to collect a bunch of potentially interesting
16281 // nodes to improve the chains of, all at once. This might seem
16282 // redundant, as this function gets called when visiting every store
16283 // node, so why not let the work be done on each store as it's visited?
16284 //
16285 // I believe this is mainly important because MergeConsecutiveStores
16286 // is unable to deal with merging stores of different sizes, so unless
16287 // we improve the chains of all the potential candidates up-front
16288 // before running MergeConsecutiveStores, it might only see some of
16289 // the nodes that will eventually be candidates, and then not be able
16290 // to go from a partially-merged state to the desired final
16291 // fully-merged state.
16292 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16293   // This holds the base pointer, index, and the offset in bytes from the base
16294   // pointer.
16295   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16296
16297   // We must have a base and an offset.
16298   if (!BasePtr.Base.getNode())
16299     return false;
16300
16301   // Do not handle stores to undef base pointers.
16302   if (BasePtr.Base.isUndef())
16303     return false;
16304
16305   SmallVector<StoreSDNode *, 8> ChainedStores;
16306   ChainedStores.push_back(St);
16307
16308   // Walk up the chain and look for nodes with offsets from the same
16309   // base pointer. Stop when reaching an instruction with a different kind
16310   // or instruction which has a different base pointer.
16311   StoreSDNode *Index = St;
16312   while (Index) {
16313     // If the chain has more than one use, then we can't reorder the mem ops.
16314     if (Index != St && !SDValue(Index, 0)->hasOneUse())
16315       break;
16316
16317     if (Index->isVolatile() || Index->isIndexed())
16318       break;
16319
16320     // Find the base pointer and offset for this memory node.
16321     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16322
16323     // Check that the base pointer is the same as the original one.
16324     if (!Ptr.equalBaseIndex(BasePtr))
16325       break;
16326
16327     // Walk up the chain to find the next store node, ignoring any
16328     // intermediate loads. Any other kind of node will halt the loop.
16329     SDNode *NextInChain = Index->getChain().getNode();
16330     while (true) {
16331       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16332         // We found a store node. Use it for the next iteration.
16333         if (STn->isVolatile() || STn->isIndexed()) {
16334           Index = nullptr;
16335           break;
16336         }
16337         ChainedStores.push_back(STn);
16338         Index = STn;
16339         break;
16340       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16341         NextInChain = Ldn->getChain().getNode();
16342         continue;
16343       } else {
16344         Index = nullptr;
16345         break;
16346       }
16347     } // end while
16348   }
16349
16350   // At this point, ChainedStores lists all of the Store nodes
16351   // reachable by iterating up through chain nodes matching the above
16352   // conditions.  For each such store identified, try to find an
16353   // earlier chain to attach the store to which won't violate the
16354   // required ordering.
16355   bool MadeChangeToSt = false;
16356   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16357
16358   for (StoreSDNode *ChainedStore : ChainedStores) {
16359     SDValue Chain = ChainedStore->getChain();
16360     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16361
16362     if (Chain != BetterChain) {
16363       if (ChainedStore == St)
16364         MadeChangeToSt = true;
16365       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16366     }
16367   }
16368
16369   // Do all replacements after finding the replacements to make to avoid making
16370   // the chains more complicated by introducing new TokenFactors.
16371   for (auto Replacement : BetterChains)
16372     replaceStoreChain(Replacement.first, Replacement.second);
16373
16374   return MadeChangeToSt;
16375 }
16376
16377 /// This is the entry point for the file.
16378 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
16379                            CodeGenOpt::Level OptLevel) {
16380   /// This is the main entry point to this class.
16381   DAGCombiner(*this, AA, OptLevel).Run(Level);
16382 }