]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Merge ^/head r318380 through r318559.
[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/KnownBits.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include <algorithm>
44 using namespace llvm;
45
46 #define DEBUG_TYPE "dagcombine"
47
48 STATISTIC(NodesCombined   , "Number of dag nodes combined");
49 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
50 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
51 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
52 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
53 STATISTIC(SlicedLoads, "Number of load sliced");
54
55 namespace {
56   static cl::opt<bool>
57     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58                cl::desc("Enable DAG combiner's use of IR alias analysis"));
59
60   static cl::opt<bool>
61     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62                cl::desc("Enable DAG combiner's use of TBAA"));
63
64 #ifndef NDEBUG
65   static cl::opt<std::string>
66     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67                cl::desc("Only use DAG-combiner alias analysis in this"
68                         " function"));
69 #endif
70
71   /// Hidden option to stress test load slicing, i.e., when this option
72   /// is enabled, load slicing bypasses most of its profitability guards.
73   static cl::opt<bool>
74   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75                     cl::desc("Bypass the profitability model of load "
76                              "slicing"),
77                     cl::init(false));
78
79   static cl::opt<bool>
80     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
81                       cl::desc("DAG combiner may split indexing from loads"));
82
83 //------------------------------ DAGCombiner ---------------------------------//
84
85   class DAGCombiner {
86     SelectionDAG &DAG;
87     const TargetLowering &TLI;
88     CombineLevel Level;
89     CodeGenOpt::Level OptLevel;
90     bool LegalOperations;
91     bool LegalTypes;
92     bool ForCodeSize;
93
94     /// \brief Worklist of all of the nodes that need to be simplified.
95     ///
96     /// This must behave as a stack -- new nodes to process are pushed onto the
97     /// back and when processing we pop off of the back.
98     ///
99     /// The worklist will not contain duplicates but may contain null entries
100     /// due to nodes being deleted from the underlying DAG.
101     SmallVector<SDNode *, 64> Worklist;
102
103     /// \brief Mapping from an SDNode to its position on the worklist.
104     ///
105     /// This is used to find and remove nodes from the worklist (by nulling
106     /// them) when they are deleted from the underlying DAG. It relies on
107     /// stable indices of nodes within the worklist.
108     DenseMap<SDNode *, unsigned> WorklistMap;
109
110     /// \brief Set of nodes which have been combined (at least once).
111     ///
112     /// This is used to allow us to reliably add any operands of a DAG node
113     /// which have not yet been combined to the worklist.
114     SmallPtrSet<SDNode *, 32> CombinedNodes;
115
116     // AA - Used for DAG load/store alias analysis.
117     AliasAnalysis *AA;
118
119     /// When an instruction is simplified, add all users of the instruction to
120     /// the work lists because they might get more simplified now.
121     void AddUsersToWorklist(SDNode *N) {
122       for (SDNode *Node : N->uses())
123         AddToWorklist(Node);
124     }
125
126     /// Call the node-specific routine that folds each particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// Add to the worklist making sure its instance is at the back (next to be
131     /// processed.)
132     void AddToWorklist(SDNode *N) {
133       assert(N->getOpcode() != ISD::DELETED_NODE &&
134              "Deleted Node added to Worklist");
135
136       // Skip handle nodes as they can't usefully be combined and confuse the
137       // zero-use deletion strategy.
138       if (N->getOpcode() == ISD::HANDLENODE)
139         return;
140
141       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
142         Worklist.push_back(N);
143     }
144
145     /// Remove all instances of N from the worklist.
146     void removeFromWorklist(SDNode *N) {
147       CombinedNodes.erase(N);
148
149       auto It = WorklistMap.find(N);
150       if (It == WorklistMap.end())
151         return; // Not in the worklist.
152
153       // Null out the entry rather than erasing it to avoid a linear operation.
154       Worklist[It->second] = nullptr;
155       WorklistMap.erase(It);
156     }
157
158     void deleteAndRecombine(SDNode *N);
159     bool recursivelyDeleteUnusedNodes(SDNode *N);
160
161     /// Replaces all uses of the results of one DAG node with new values.
162     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163                       bool AddTo = true);
164
165     /// Replaces all uses of the results of one DAG node with new values.
166     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
167       return CombineTo(N, &Res, 1, AddTo);
168     }
169
170     /// Replaces all uses of the results of one DAG node with new values.
171     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
172                       bool AddTo = true) {
173       SDValue To[] = { Res0, Res1 };
174       return CombineTo(N, To, 2, AddTo);
175     }
176
177     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
178
179   private:
180     unsigned MaximumLegalStoreInBits;
181
182     /// Check the specified integer node value to see if it can be simplified or
183     /// if things it uses can be simplified by bit propagation.
184     /// If so, return true.
185     bool SimplifyDemandedBits(SDValue Op) {
186       unsigned BitWidth = Op.getScalarValueSizeInBits();
187       APInt Demanded = APInt::getAllOnesValue(BitWidth);
188       return SimplifyDemandedBits(Op, Demanded);
189     }
190
191     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
192
193     bool CombineToPreIndexedLoadStore(SDNode *N);
194     bool CombineToPostIndexedLoadStore(SDNode *N);
195     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
196     bool SliceUpLoad(SDNode *N);
197
198     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
199     ///   load.
200     ///
201     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
202     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
203     /// \param EltNo index of the vector element to load.
204     /// \param OriginalLoad load that EVE came from to be replaced.
205     /// \returns EVE on success SDValue() on failure.
206     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
207         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
208     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
209     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
210     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
211     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
212     SDValue PromoteIntBinOp(SDValue Op);
213     SDValue PromoteIntShiftOp(SDValue Op);
214     SDValue PromoteExtend(SDValue Op);
215     bool PromoteLoad(SDValue Op);
216
217     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
218                          SDValue ExtLoad, const SDLoc &DL,
219                          ISD::NodeType ExtType);
220
221     /// Call the node-specific routine that knows how to fold each
222     /// particular type of node. If that doesn't do anything, try the
223     /// target-specific DAG combines.
224     SDValue combine(SDNode *N);
225
226     // Visitation implementation - Implement dag node combining for different
227     // node types.  The semantics are as follows:
228     // Return Value:
229     //   SDValue.getNode() == 0 - No change was made
230     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
231     //   otherwise              - N should be replaced by the returned Operand.
232     //
233     SDValue visitTokenFactor(SDNode *N);
234     SDValue visitMERGE_VALUES(SDNode *N);
235     SDValue visitADD(SDNode *N);
236     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
237     SDValue visitSUB(SDNode *N);
238     SDValue visitADDC(SDNode *N);
239     SDValue visitUADDO(SDNode *N);
240     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
241     SDValue visitSUBC(SDNode *N);
242     SDValue visitUSUBO(SDNode *N);
243     SDValue visitADDE(SDNode *N);
244     SDValue visitADDCARRY(SDNode *N);
245     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
246     SDValue visitSUBE(SDNode *N);
247     SDValue visitSUBCARRY(SDNode *N);
248     SDValue visitMUL(SDNode *N);
249     SDValue useDivRem(SDNode *N);
250     SDValue visitSDIV(SDNode *N);
251     SDValue visitUDIV(SDNode *N);
252     SDValue visitREM(SDNode *N);
253     SDValue visitMULHU(SDNode *N);
254     SDValue visitMULHS(SDNode *N);
255     SDValue visitSMUL_LOHI(SDNode *N);
256     SDValue visitUMUL_LOHI(SDNode *N);
257     SDValue visitSMULO(SDNode *N);
258     SDValue visitUMULO(SDNode *N);
259     SDValue visitIMINMAX(SDNode *N);
260     SDValue visitAND(SDNode *N);
261     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
262     SDValue visitOR(SDNode *N);
263     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
264     SDValue visitXOR(SDNode *N);
265     SDValue SimplifyVBinOp(SDNode *N);
266     SDValue visitSHL(SDNode *N);
267     SDValue visitSRA(SDNode *N);
268     SDValue visitSRL(SDNode *N);
269     SDValue visitRotate(SDNode *N);
270     SDValue visitABS(SDNode *N);
271     SDValue visitBSWAP(SDNode *N);
272     SDValue visitBITREVERSE(SDNode *N);
273     SDValue visitCTLZ(SDNode *N);
274     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
275     SDValue visitCTTZ(SDNode *N);
276     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
277     SDValue visitCTPOP(SDNode *N);
278     SDValue visitSELECT(SDNode *N);
279     SDValue visitVSELECT(SDNode *N);
280     SDValue visitSELECT_CC(SDNode *N);
281     SDValue visitSETCC(SDNode *N);
282     SDValue visitSETCCE(SDNode *N);
283     SDValue visitSIGN_EXTEND(SDNode *N);
284     SDValue visitZERO_EXTEND(SDNode *N);
285     SDValue visitANY_EXTEND(SDNode *N);
286     SDValue visitAssertZext(SDNode *N);
287     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
288     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
289     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
290     SDValue visitTRUNCATE(SDNode *N);
291     SDValue visitBITCAST(SDNode *N);
292     SDValue visitBUILD_PAIR(SDNode *N);
293     SDValue visitFADD(SDNode *N);
294     SDValue visitFSUB(SDNode *N);
295     SDValue visitFMUL(SDNode *N);
296     SDValue visitFMA(SDNode *N);
297     SDValue visitFDIV(SDNode *N);
298     SDValue visitFREM(SDNode *N);
299     SDValue visitFSQRT(SDNode *N);
300     SDValue visitFCOPYSIGN(SDNode *N);
301     SDValue visitSINT_TO_FP(SDNode *N);
302     SDValue visitUINT_TO_FP(SDNode *N);
303     SDValue visitFP_TO_SINT(SDNode *N);
304     SDValue visitFP_TO_UINT(SDNode *N);
305     SDValue visitFP_ROUND(SDNode *N);
306     SDValue visitFP_ROUND_INREG(SDNode *N);
307     SDValue visitFP_EXTEND(SDNode *N);
308     SDValue visitFNEG(SDNode *N);
309     SDValue visitFABS(SDNode *N);
310     SDValue visitFCEIL(SDNode *N);
311     SDValue visitFTRUNC(SDNode *N);
312     SDValue visitFFLOOR(SDNode *N);
313     SDValue visitFMINNUM(SDNode *N);
314     SDValue visitFMAXNUM(SDNode *N);
315     SDValue visitBRCOND(SDNode *N);
316     SDValue visitBR_CC(SDNode *N);
317     SDValue visitLOAD(SDNode *N);
318
319     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
320     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
321
322     SDValue visitSTORE(SDNode *N);
323     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
324     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
325     SDValue visitBUILD_VECTOR(SDNode *N);
326     SDValue visitCONCAT_VECTORS(SDNode *N);
327     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
328     SDValue visitVECTOR_SHUFFLE(SDNode *N);
329     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
330     SDValue visitINSERT_SUBVECTOR(SDNode *N);
331     SDValue visitMLOAD(SDNode *N);
332     SDValue visitMSTORE(SDNode *N);
333     SDValue visitMGATHER(SDNode *N);
334     SDValue visitMSCATTER(SDNode *N);
335     SDValue visitFP_TO_FP16(SDNode *N);
336     SDValue visitFP16_TO_FP(SDNode *N);
337
338     SDValue visitFADDForFMACombine(SDNode *N);
339     SDValue visitFSUBForFMACombine(SDNode *N);
340     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
341
342     SDValue XformToShuffleWithZero(SDNode *N);
343     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
344                            SDValue RHS);
345
346     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
347
348     SDValue foldSelectOfConstants(SDNode *N);
349     SDValue foldBinOpIntoSelect(SDNode *BO);
350     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
351     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
352     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
353     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
354                              SDValue N2, SDValue N3, ISD::CondCode CC,
355                              bool NotExtCompare = false);
356     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
357                                    SDValue N2, SDValue N3, ISD::CondCode CC);
358     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
359                               const SDLoc &DL);
360     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
361                           const SDLoc &DL, bool foldBooleans = true);
362
363     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
364                            SDValue &CC) const;
365     bool isOneUseSetCC(SDValue N) const;
366
367     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
368                                          unsigned HiOp);
369     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
370     SDValue CombineExtLoad(SDNode *N);
371     SDValue combineRepeatedFPDivisors(SDNode *N);
372     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
373     SDValue BuildSDIV(SDNode *N);
374     SDValue BuildSDIVPow2(SDNode *N);
375     SDValue BuildUDIV(SDNode *N);
376     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
377     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
378     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
379     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
380     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
381     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
382                                 SDNodeFlags Flags, bool Reciprocal);
383     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
384                                 SDNodeFlags Flags, bool Reciprocal);
385     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
386                                bool DemandHighBits = true);
387     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
388     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
389                               SDValue InnerPos, SDValue InnerNeg,
390                               unsigned PosOpcode, unsigned NegOpcode,
391                               const SDLoc &DL);
392     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
393     SDValue MatchLoadCombine(SDNode *N);
394     SDValue ReduceLoadWidth(SDNode *N);
395     SDValue ReduceLoadOpStoreWidth(SDNode *N);
396     SDValue splitMergedValStore(StoreSDNode *ST);
397     SDValue TransformFPLoadStorePair(SDNode *N);
398     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
399     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
400     SDValue reduceBuildVecToShuffle(SDNode *N);
401     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
402                                   ArrayRef<int> VectorMask, SDValue VecIn1,
403                                   SDValue VecIn2, unsigned LeftIdx);
404     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
405
406     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
407
408     /// Walk up chain skipping non-aliasing memory nodes,
409     /// looking for aliasing nodes and adding them to the Aliases vector.
410     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
411                           SmallVectorImpl<SDValue> &Aliases);
412
413     /// Return true if there is any possibility that the two addresses overlap.
414     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
415
416     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
417     /// chain (aliasing node.)
418     SDValue FindBetterChain(SDNode *N, SDValue Chain);
419
420     /// Try to replace a store and any possibly adjacent stores on
421     /// consecutive chains with better chains. Return true only if St is
422     /// replaced.
423     ///
424     /// Notice that other chains may still be replaced even if the function
425     /// returns false.
426     bool findBetterNeighborChains(StoreSDNode *St);
427
428     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
429     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
430
431     /// Holds a pointer to an LSBaseSDNode as well as information on where it
432     /// is located in a sequence of memory operations connected by a chain.
433     struct MemOpLink {
434       MemOpLink(LSBaseSDNode *N, int64_t Offset)
435           : MemNode(N), OffsetFromBase(Offset) {}
436       // Ptr to the mem node.
437       LSBaseSDNode *MemNode;
438       // Offset from the base ptr.
439       int64_t OffsetFromBase;
440     };
441
442     /// This is a helper function for visitMUL to check the profitability
443     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
444     /// MulNode is the original multiply, AddNode is (add x, c1),
445     /// and ConstNode is c2.
446     bool isMulAddWithConstProfitable(SDNode *MulNode,
447                                      SDValue &AddNode,
448                                      SDValue &ConstNode);
449
450
451     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
452     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
453     /// the type of the loaded value to be extended.  LoadedVT returns the type
454     /// of the original loaded value.  NarrowLoad returns whether the load would
455     /// need to be narrowed in order to match.
456     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
457                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
458                           bool &NarrowLoad);
459
460     /// Helper function for MergeConsecutiveStores which merges the
461     /// component store chains.
462     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
463                                 unsigned NumStores);
464
465     /// This is a helper function for MergeConsecutiveStores. When the source
466     /// elements of the consecutive stores are all constants or all extracted
467     /// vector elements, try to merge them into one larger store.
468     /// \return True if a merged store was created.
469     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
470                                          EVT MemVT, unsigned NumStores,
471                                          bool IsConstantSrc, bool UseVector);
472
473     /// This is a helper function for MergeConsecutiveStores.
474     /// Stores that may be merged are placed in StoreNodes.
475     void getStoreMergeCandidates(StoreSDNode *St,
476                                  SmallVectorImpl<MemOpLink> &StoreNodes);
477
478     /// Helper function for MergeConsecutiveStores. Checks if
479     /// Candidate stores have indirect dependency through their
480     /// operands. \return True if safe to merge
481     bool checkMergeStoreCandidatesForDependencies(
482         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
483
484     /// Merge consecutive store operations into a wide store.
485     /// This optimization uses wide integers or vectors when possible.
486     /// \return number of stores that were merged into a merged store (the
487     /// affected nodes are stored as a prefix in \p StoreNodes).
488     bool MergeConsecutiveStores(StoreSDNode *N);
489
490     /// \brief Try to transform a truncation where C is a constant:
491     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
492     ///
493     /// \p N needs to be a truncation and its first operand an AND. Other
494     /// requirements are checked by the function (e.g. that trunc is
495     /// single-use) and if missed an empty SDValue is returned.
496     SDValue distributeTruncateThroughAnd(SDNode *N);
497
498   public:
499     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
500         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
501           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) {
502       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
503
504       MaximumLegalStoreInBits = 0;
505       for (MVT VT : MVT::all_valuetypes())
506         if (EVT(VT).isSimple() && VT != MVT::Other &&
507             TLI.isTypeLegal(EVT(VT)) &&
508             VT.getSizeInBits() >= MaximumLegalStoreInBits)
509           MaximumLegalStoreInBits = VT.getSizeInBits();
510     }
511
512     /// Runs the dag combiner on all nodes in the work list
513     void Run(CombineLevel AtLevel);
514
515     SelectionDAG &getDAG() const { return DAG; }
516
517     /// Returns a type large enough to hold any valid shift amount - before type
518     /// legalization these can be huge.
519     EVT getShiftAmountTy(EVT LHSTy) {
520       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
521       if (LHSTy.isVector())
522         return LHSTy;
523       auto &DL = DAG.getDataLayout();
524       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
525                         : TLI.getPointerTy(DL);
526     }
527
528     /// This method returns true if we are running before type legalization or
529     /// if the specified VT is legal.
530     bool isTypeLegal(const EVT &VT) {
531       if (!LegalTypes) return true;
532       return TLI.isTypeLegal(VT);
533     }
534
535     /// Convenience wrapper around TargetLowering::getSetCCResultType
536     EVT getSetCCResultType(EVT VT) const {
537       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
538     }
539   };
540 }
541
542
543 namespace {
544 /// This class is a DAGUpdateListener that removes any deleted
545 /// nodes from the worklist.
546 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
547   DAGCombiner &DC;
548 public:
549   explicit WorklistRemover(DAGCombiner &dc)
550     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
551
552   void NodeDeleted(SDNode *N, SDNode *E) override {
553     DC.removeFromWorklist(N);
554   }
555 };
556 }
557
558 //===----------------------------------------------------------------------===//
559 //  TargetLowering::DAGCombinerInfo implementation
560 //===----------------------------------------------------------------------===//
561
562 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
563   ((DAGCombiner*)DC)->AddToWorklist(N);
564 }
565
566 SDValue TargetLowering::DAGCombinerInfo::
567 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
568   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
569 }
570
571 SDValue TargetLowering::DAGCombinerInfo::
572 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
573   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
574 }
575
576
577 SDValue TargetLowering::DAGCombinerInfo::
578 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
579   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
580 }
581
582 void TargetLowering::DAGCombinerInfo::
583 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
584   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
585 }
586
587 //===----------------------------------------------------------------------===//
588 // Helper Functions
589 //===----------------------------------------------------------------------===//
590
591 void DAGCombiner::deleteAndRecombine(SDNode *N) {
592   removeFromWorklist(N);
593
594   // If the operands of this node are only used by the node, they will now be
595   // dead. Make sure to re-visit them and recursively delete dead nodes.
596   for (const SDValue &Op : N->ops())
597     // For an operand generating multiple values, one of the values may
598     // become dead allowing further simplification (e.g. split index
599     // arithmetic from an indexed load).
600     if (Op->hasOneUse() || Op->getNumValues() > 1)
601       AddToWorklist(Op.getNode());
602
603   DAG.DeleteNode(N);
604 }
605
606 /// Return 1 if we can compute the negated form of the specified expression for
607 /// the same cost as the expression itself, or 2 if we can compute the negated
608 /// form more cheaply than the expression itself.
609 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
610                                const TargetLowering &TLI,
611                                const TargetOptions *Options,
612                                unsigned Depth = 0) {
613   // fneg is removable even if it has multiple uses.
614   if (Op.getOpcode() == ISD::FNEG) return 2;
615
616   // Don't allow anything with multiple uses.
617   if (!Op.hasOneUse()) return 0;
618
619   // Don't recurse exponentially.
620   if (Depth > 6) return 0;
621
622   switch (Op.getOpcode()) {
623   default: return false;
624   case ISD::ConstantFP: {
625     if (!LegalOperations)
626       return 1;
627
628     // Don't invert constant FP values after legalization unless the target says
629     // the negated constant is legal.
630     EVT VT = Op.getValueType();
631     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
632       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
633   }
634   case ISD::FADD:
635     // FIXME: determine better conditions for this xform.
636     if (!Options->UnsafeFPMath) return 0;
637
638     // After operation legalization, it might not be legal to create new FSUBs.
639     if (LegalOperations &&
640         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
641       return 0;
642
643     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
644     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
645                                     Options, Depth + 1))
646       return V;
647     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
648     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
649                               Depth + 1);
650   case ISD::FSUB:
651     // We can't turn -(A-B) into B-A when we honor signed zeros.
652     if (!Options->NoSignedZerosFPMath &&
653         !Op.getNode()->getFlags().hasNoSignedZeros())
654       return 0;
655
656     // fold (fneg (fsub A, B)) -> (fsub B, A)
657     return 1;
658
659   case ISD::FMUL:
660   case ISD::FDIV:
661     if (Options->HonorSignDependentRoundingFPMath()) return 0;
662
663     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
664     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
665                                     Options, Depth + 1))
666       return V;
667
668     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
669                               Depth + 1);
670
671   case ISD::FP_EXTEND:
672   case ISD::FP_ROUND:
673   case ISD::FSIN:
674     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
675                               Depth + 1);
676   }
677 }
678
679 /// If isNegatibleForFree returns true, return the newly negated expression.
680 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
681                                     bool LegalOperations, unsigned Depth = 0) {
682   const TargetOptions &Options = DAG.getTarget().Options;
683   // fneg is removable even if it has multiple uses.
684   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
685
686   // Don't allow anything with multiple uses.
687   assert(Op.hasOneUse() && "Unknown reuse!");
688
689   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
690
691   const SDNodeFlags Flags = Op.getNode()->getFlags();
692
693   switch (Op.getOpcode()) {
694   default: llvm_unreachable("Unknown code");
695   case ISD::ConstantFP: {
696     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
697     V.changeSign();
698     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
699   }
700   case ISD::FADD:
701     // FIXME: determine better conditions for this xform.
702     assert(Options.UnsafeFPMath);
703
704     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
705     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
706                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
707       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
708                          GetNegatedExpression(Op.getOperand(0), DAG,
709                                               LegalOperations, Depth+1),
710                          Op.getOperand(1), Flags);
711     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
712     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
713                        GetNegatedExpression(Op.getOperand(1), DAG,
714                                             LegalOperations, Depth+1),
715                        Op.getOperand(0), Flags);
716   case ISD::FSUB:
717     // fold (fneg (fsub 0, B)) -> B
718     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
719       if (N0CFP->isZero())
720         return Op.getOperand(1);
721
722     // fold (fneg (fsub A, B)) -> (fsub B, A)
723     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
724                        Op.getOperand(1), Op.getOperand(0), Flags);
725
726   case ISD::FMUL:
727   case ISD::FDIV:
728     assert(!Options.HonorSignDependentRoundingFPMath());
729
730     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
731     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
732                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
733       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
734                          GetNegatedExpression(Op.getOperand(0), DAG,
735                                               LegalOperations, Depth+1),
736                          Op.getOperand(1), Flags);
737
738     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
739     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
740                        Op.getOperand(0),
741                        GetNegatedExpression(Op.getOperand(1), DAG,
742                                             LegalOperations, Depth+1), Flags);
743
744   case ISD::FP_EXTEND:
745   case ISD::FSIN:
746     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
747                        GetNegatedExpression(Op.getOperand(0), DAG,
748                                             LegalOperations, Depth+1));
749   case ISD::FP_ROUND:
750       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
751                          GetNegatedExpression(Op.getOperand(0), DAG,
752                                               LegalOperations, Depth+1),
753                          Op.getOperand(1));
754   }
755 }
756
757 // APInts must be the same size for most operations, this helper
758 // function zero extends the shorter of the pair so that they match.
759 // We provide an Offset so that we can create bitwidths that won't overflow.
760 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
761   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
762   LHS = LHS.zextOrSelf(Bits);
763   RHS = RHS.zextOrSelf(Bits);
764 }
765
766 // Return true if this node is a setcc, or is a select_cc
767 // that selects between the target values used for true and false, making it
768 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
769 // the appropriate nodes based on the type of node we are checking. This
770 // simplifies life a bit for the callers.
771 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
772                                     SDValue &CC) const {
773   if (N.getOpcode() == ISD::SETCC) {
774     LHS = N.getOperand(0);
775     RHS = N.getOperand(1);
776     CC  = N.getOperand(2);
777     return true;
778   }
779
780   if (N.getOpcode() != ISD::SELECT_CC ||
781       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
782       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
783     return false;
784
785   if (TLI.getBooleanContents(N.getValueType()) ==
786       TargetLowering::UndefinedBooleanContent)
787     return false;
788
789   LHS = N.getOperand(0);
790   RHS = N.getOperand(1);
791   CC  = N.getOperand(4);
792   return true;
793 }
794
795 /// Return true if this is a SetCC-equivalent operation with only one use.
796 /// If this is true, it allows the users to invert the operation for free when
797 /// it is profitable to do so.
798 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
799   SDValue N0, N1, N2;
800   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
801     return true;
802   return false;
803 }
804
805 // \brief Returns the SDNode if it is a constant float BuildVector
806 // or constant float.
807 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
808   if (isa<ConstantFPSDNode>(N))
809     return N.getNode();
810   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
811     return N.getNode();
812   return nullptr;
813 }
814
815 // Determines if it is a constant integer or a build vector of constant
816 // integers (and undefs).
817 // Do not permit build vector implicit truncation.
818 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
819   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
820     return !(Const->isOpaque() && NoOpaques);
821   if (N.getOpcode() != ISD::BUILD_VECTOR)
822     return false;
823   unsigned BitWidth = N.getScalarValueSizeInBits();
824   for (const SDValue &Op : N->op_values()) {
825     if (Op.isUndef())
826       continue;
827     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
828     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
829         (Const->isOpaque() && NoOpaques))
830       return false;
831   }
832   return true;
833 }
834
835 // Determines if it is a constant null integer or a splatted vector of a
836 // constant null integer (with no undefs).
837 // Build vector implicit truncation is not an issue for null values.
838 static bool isNullConstantOrNullSplatConstant(SDValue N) {
839   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
840     return Splat->isNullValue();
841   return false;
842 }
843
844 // Determines if it is a constant integer of one or a splatted vector of a
845 // constant integer of one (with no undefs).
846 // Do not permit build vector implicit truncation.
847 static bool isOneConstantOrOneSplatConstant(SDValue N) {
848   unsigned BitWidth = N.getScalarValueSizeInBits();
849   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
850     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
851   return false;
852 }
853
854 // Determines if it is a constant integer of all ones or a splatted vector of a
855 // constant integer of all ones (with no undefs).
856 // Do not permit build vector implicit truncation.
857 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
858   unsigned BitWidth = N.getScalarValueSizeInBits();
859   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
860     return Splat->isAllOnesValue() &&
861            Splat->getAPIntValue().getBitWidth() == BitWidth;
862   return false;
863 }
864
865 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
866 // undef's.
867 static bool isAnyConstantBuildVector(const SDNode *N) {
868   return ISD::isBuildVectorOfConstantSDNodes(N) ||
869          ISD::isBuildVectorOfConstantFPSDNodes(N);
870 }
871
872 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
873                                     SDValue N1) {
874   EVT VT = N0.getValueType();
875   if (N0.getOpcode() == Opc) {
876     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
877       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
878         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
879         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
880           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
881         return SDValue();
882       }
883       if (N0.hasOneUse()) {
884         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
885         // use
886         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
887         if (!OpNode.getNode())
888           return SDValue();
889         AddToWorklist(OpNode.getNode());
890         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
891       }
892     }
893   }
894
895   if (N1.getOpcode() == Opc) {
896     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
897       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
898         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
899         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
900           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
901         return SDValue();
902       }
903       if (N1.hasOneUse()) {
904         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
905         // use
906         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
907         if (!OpNode.getNode())
908           return SDValue();
909         AddToWorklist(OpNode.getNode());
910         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
911       }
912     }
913   }
914
915   return SDValue();
916 }
917
918 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
919                                bool AddTo) {
920   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
921   ++NodesCombined;
922   DEBUG(dbgs() << "\nReplacing.1 ";
923         N->dump(&DAG);
924         dbgs() << "\nWith: ";
925         To[0].getNode()->dump(&DAG);
926         dbgs() << " and " << NumTo-1 << " other values\n");
927   for (unsigned i = 0, e = NumTo; i != e; ++i)
928     assert((!To[i].getNode() ||
929             N->getValueType(i) == To[i].getValueType()) &&
930            "Cannot combine value to value of different type!");
931
932   WorklistRemover DeadNodes(*this);
933   DAG.ReplaceAllUsesWith(N, To);
934   if (AddTo) {
935     // Push the new nodes and any users onto the worklist
936     for (unsigned i = 0, e = NumTo; i != e; ++i) {
937       if (To[i].getNode()) {
938         AddToWorklist(To[i].getNode());
939         AddUsersToWorklist(To[i].getNode());
940       }
941     }
942   }
943
944   // Finally, if the node is now dead, remove it from the graph.  The node
945   // may not be dead if the replacement process recursively simplified to
946   // something else needing this node.
947   if (N->use_empty())
948     deleteAndRecombine(N);
949   return SDValue(N, 0);
950 }
951
952 void DAGCombiner::
953 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
954   // Replace all uses.  If any nodes become isomorphic to other nodes and
955   // are deleted, make sure to remove them from our worklist.
956   WorklistRemover DeadNodes(*this);
957   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
958
959   // Push the new node and any (possibly new) users onto the worklist.
960   AddToWorklist(TLO.New.getNode());
961   AddUsersToWorklist(TLO.New.getNode());
962
963   // Finally, if the node is now dead, remove it from the graph.  The node
964   // may not be dead if the replacement process recursively simplified to
965   // something else needing this node.
966   if (TLO.Old.getNode()->use_empty())
967     deleteAndRecombine(TLO.Old.getNode());
968 }
969
970 /// Check the specified integer node value to see if it can be simplified or if
971 /// things it uses can be simplified by bit propagation. If so, return true.
972 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
973   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
974   KnownBits Known;
975   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
976     return false;
977
978   // Revisit the node.
979   AddToWorklist(Op.getNode());
980
981   // Replace the old value with the new one.
982   ++NodesCombined;
983   DEBUG(dbgs() << "\nReplacing.2 ";
984         TLO.Old.getNode()->dump(&DAG);
985         dbgs() << "\nWith: ";
986         TLO.New.getNode()->dump(&DAG);
987         dbgs() << '\n');
988
989   CommitTargetLoweringOpt(TLO);
990   return true;
991 }
992
993 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
994   SDLoc DL(Load);
995   EVT VT = Load->getValueType(0);
996   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
997
998   DEBUG(dbgs() << "\nReplacing.9 ";
999         Load->dump(&DAG);
1000         dbgs() << "\nWith: ";
1001         Trunc.getNode()->dump(&DAG);
1002         dbgs() << '\n');
1003   WorklistRemover DeadNodes(*this);
1004   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1005   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1006   deleteAndRecombine(Load);
1007   AddToWorklist(Trunc.getNode());
1008 }
1009
1010 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1011   Replace = false;
1012   SDLoc DL(Op);
1013   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1014     LoadSDNode *LD = cast<LoadSDNode>(Op);
1015     EVT MemVT = LD->getMemoryVT();
1016     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1017       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1018                                                        : ISD::EXTLOAD)
1019       : LD->getExtensionType();
1020     Replace = true;
1021     return DAG.getExtLoad(ExtType, DL, PVT,
1022                           LD->getChain(), LD->getBasePtr(),
1023                           MemVT, LD->getMemOperand());
1024   }
1025
1026   unsigned Opc = Op.getOpcode();
1027   switch (Opc) {
1028   default: break;
1029   case ISD::AssertSext:
1030     return DAG.getNode(ISD::AssertSext, DL, PVT,
1031                        SExtPromoteOperand(Op.getOperand(0), PVT),
1032                        Op.getOperand(1));
1033   case ISD::AssertZext:
1034     return DAG.getNode(ISD::AssertZext, DL, PVT,
1035                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1036                        Op.getOperand(1));
1037   case ISD::Constant: {
1038     unsigned ExtOpc =
1039       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1040     return DAG.getNode(ExtOpc, DL, PVT, Op);
1041   }
1042   }
1043
1044   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1045     return SDValue();
1046   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1047 }
1048
1049 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1050   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1051     return SDValue();
1052   EVT OldVT = Op.getValueType();
1053   SDLoc DL(Op);
1054   bool Replace = false;
1055   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1056   if (!NewOp.getNode())
1057     return SDValue();
1058   AddToWorklist(NewOp.getNode());
1059
1060   if (Replace)
1061     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1062   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1063                      DAG.getValueType(OldVT));
1064 }
1065
1066 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1067   EVT OldVT = Op.getValueType();
1068   SDLoc DL(Op);
1069   bool Replace = false;
1070   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1071   if (!NewOp.getNode())
1072     return SDValue();
1073   AddToWorklist(NewOp.getNode());
1074
1075   if (Replace)
1076     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1077   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1078 }
1079
1080 /// Promote the specified integer binary operation if the target indicates it is
1081 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1082 /// i32 since i16 instructions are longer.
1083 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1084   if (!LegalOperations)
1085     return SDValue();
1086
1087   EVT VT = Op.getValueType();
1088   if (VT.isVector() || !VT.isInteger())
1089     return SDValue();
1090
1091   // If operation type is 'undesirable', e.g. i16 on x86, consider
1092   // promoting it.
1093   unsigned Opc = Op.getOpcode();
1094   if (TLI.isTypeDesirableForOp(Opc, VT))
1095     return SDValue();
1096
1097   EVT PVT = VT;
1098   // Consult target whether it is a good idea to promote this operation and
1099   // what's the right type to promote it to.
1100   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1101     assert(PVT != VT && "Don't know what type to promote to!");
1102
1103     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1104
1105     bool Replace0 = false;
1106     SDValue N0 = Op.getOperand(0);
1107     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1108
1109     bool Replace1 = false;
1110     SDValue N1 = Op.getOperand(1);
1111     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1112     SDLoc DL(Op);
1113
1114     SDValue RV =
1115         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1116
1117     // New replace instances of N0 and N1
1118     if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1119         NN0.getOpcode() != ISD::DELETED_NODE) {
1120       AddToWorklist(NN0.getNode());
1121       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1122     }
1123
1124     if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1125         NN1.getOpcode() != ISD::DELETED_NODE) {
1126       AddToWorklist(NN1.getNode());
1127       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1128     }
1129
1130     // Deal with Op being deleted.
1131     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1132       return RV;
1133   }
1134   return SDValue();
1135 }
1136
1137 /// Promote the specified integer shift operation if the target indicates it is
1138 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1139 /// i32 since i16 instructions are longer.
1140 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1141   if (!LegalOperations)
1142     return SDValue();
1143
1144   EVT VT = Op.getValueType();
1145   if (VT.isVector() || !VT.isInteger())
1146     return SDValue();
1147
1148   // If operation type is 'undesirable', e.g. i16 on x86, consider
1149   // promoting it.
1150   unsigned Opc = Op.getOpcode();
1151   if (TLI.isTypeDesirableForOp(Opc, VT))
1152     return SDValue();
1153
1154   EVT PVT = VT;
1155   // Consult target whether it is a good idea to promote this operation and
1156   // what's the right type to promote it to.
1157   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1158     assert(PVT != VT && "Don't know what type to promote to!");
1159
1160     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1161
1162     bool Replace = false;
1163     SDValue N0 = Op.getOperand(0);
1164     SDValue N1 = Op.getOperand(1);
1165     if (Opc == ISD::SRA)
1166       N0 = SExtPromoteOperand(N0, PVT);
1167     else if (Opc == ISD::SRL)
1168       N0 = ZExtPromoteOperand(N0, PVT);
1169     else
1170       N0 = PromoteOperand(N0, PVT, Replace);
1171
1172     if (!N0.getNode())
1173       return SDValue();
1174
1175     SDLoc DL(Op);
1176     SDValue RV =
1177         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1178
1179     AddToWorklist(N0.getNode());
1180     if (Replace)
1181       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1182
1183     // Deal with Op being deleted.
1184     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1185       return RV;
1186   }
1187   return SDValue();
1188 }
1189
1190 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1191   if (!LegalOperations)
1192     return SDValue();
1193
1194   EVT VT = Op.getValueType();
1195   if (VT.isVector() || !VT.isInteger())
1196     return SDValue();
1197
1198   // If operation type is 'undesirable', e.g. i16 on x86, consider
1199   // promoting it.
1200   unsigned Opc = Op.getOpcode();
1201   if (TLI.isTypeDesirableForOp(Opc, VT))
1202     return SDValue();
1203
1204   EVT PVT = VT;
1205   // Consult target whether it is a good idea to promote this operation and
1206   // what's the right type to promote it to.
1207   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1208     assert(PVT != VT && "Don't know what type to promote to!");
1209     // fold (aext (aext x)) -> (aext x)
1210     // fold (aext (zext x)) -> (zext x)
1211     // fold (aext (sext x)) -> (sext x)
1212     DEBUG(dbgs() << "\nPromoting ";
1213           Op.getNode()->dump(&DAG));
1214     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1215   }
1216   return SDValue();
1217 }
1218
1219 bool DAGCombiner::PromoteLoad(SDValue Op) {
1220   if (!LegalOperations)
1221     return false;
1222
1223   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1224     return false;
1225
1226   EVT VT = Op.getValueType();
1227   if (VT.isVector() || !VT.isInteger())
1228     return false;
1229
1230   // If operation type is 'undesirable', e.g. i16 on x86, consider
1231   // promoting it.
1232   unsigned Opc = Op.getOpcode();
1233   if (TLI.isTypeDesirableForOp(Opc, VT))
1234     return false;
1235
1236   EVT PVT = VT;
1237   // Consult target whether it is a good idea to promote this operation and
1238   // what's the right type to promote it to.
1239   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1240     assert(PVT != VT && "Don't know what type to promote to!");
1241
1242     SDLoc DL(Op);
1243     SDNode *N = Op.getNode();
1244     LoadSDNode *LD = cast<LoadSDNode>(N);
1245     EVT MemVT = LD->getMemoryVT();
1246     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1247       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1248                                                        : ISD::EXTLOAD)
1249       : LD->getExtensionType();
1250     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1251                                    LD->getChain(), LD->getBasePtr(),
1252                                    MemVT, LD->getMemOperand());
1253     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1254
1255     DEBUG(dbgs() << "\nPromoting ";
1256           N->dump(&DAG);
1257           dbgs() << "\nTo: ";
1258           Result.getNode()->dump(&DAG);
1259           dbgs() << '\n');
1260     WorklistRemover DeadNodes(*this);
1261     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1262     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1263     deleteAndRecombine(N);
1264     AddToWorklist(Result.getNode());
1265     return true;
1266   }
1267   return false;
1268 }
1269
1270 /// \brief Recursively delete a node which has no uses and any operands for
1271 /// which it is the only use.
1272 ///
1273 /// Note that this both deletes the nodes and removes them from the worklist.
1274 /// It also adds any nodes who have had a user deleted to the worklist as they
1275 /// may now have only one use and subject to other combines.
1276 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1277   if (!N->use_empty())
1278     return false;
1279
1280   SmallSetVector<SDNode *, 16> Nodes;
1281   Nodes.insert(N);
1282   do {
1283     N = Nodes.pop_back_val();
1284     if (!N)
1285       continue;
1286
1287     if (N->use_empty()) {
1288       for (const SDValue &ChildN : N->op_values())
1289         Nodes.insert(ChildN.getNode());
1290
1291       removeFromWorklist(N);
1292       DAG.DeleteNode(N);
1293     } else {
1294       AddToWorklist(N);
1295     }
1296   } while (!Nodes.empty());
1297   return true;
1298 }
1299
1300 //===----------------------------------------------------------------------===//
1301 //  Main DAG Combiner implementation
1302 //===----------------------------------------------------------------------===//
1303
1304 void DAGCombiner::Run(CombineLevel AtLevel) {
1305   // set the instance variables, so that the various visit routines may use it.
1306   Level = AtLevel;
1307   LegalOperations = Level >= AfterLegalizeVectorOps;
1308   LegalTypes = Level >= AfterLegalizeTypes;
1309
1310   // Add all the dag nodes to the worklist.
1311   for (SDNode &Node : DAG.allnodes())
1312     AddToWorklist(&Node);
1313
1314   // Create a dummy node (which is not added to allnodes), that adds a reference
1315   // to the root node, preventing it from being deleted, and tracking any
1316   // changes of the root.
1317   HandleSDNode Dummy(DAG.getRoot());
1318
1319   // While the worklist isn't empty, find a node and try to combine it.
1320   while (!WorklistMap.empty()) {
1321     SDNode *N;
1322     // The Worklist holds the SDNodes in order, but it may contain null entries.
1323     do {
1324       N = Worklist.pop_back_val();
1325     } while (!N);
1326
1327     bool GoodWorklistEntry = WorklistMap.erase(N);
1328     (void)GoodWorklistEntry;
1329     assert(GoodWorklistEntry &&
1330            "Found a worklist entry without a corresponding map entry!");
1331
1332     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1333     // N is deleted from the DAG, since they too may now be dead or may have a
1334     // reduced number of uses, allowing other xforms.
1335     if (recursivelyDeleteUnusedNodes(N))
1336       continue;
1337
1338     WorklistRemover DeadNodes(*this);
1339
1340     // If this combine is running after legalizing the DAG, re-legalize any
1341     // nodes pulled off the worklist.
1342     if (Level == AfterLegalizeDAG) {
1343       SmallSetVector<SDNode *, 16> UpdatedNodes;
1344       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1345
1346       for (SDNode *LN : UpdatedNodes) {
1347         AddToWorklist(LN);
1348         AddUsersToWorklist(LN);
1349       }
1350       if (!NIsValid)
1351         continue;
1352     }
1353
1354     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1355
1356     // Add any operands of the new node which have not yet been combined to the
1357     // worklist as well. Because the worklist uniques things already, this
1358     // won't repeatedly process the same operand.
1359     CombinedNodes.insert(N);
1360     for (const SDValue &ChildN : N->op_values())
1361       if (!CombinedNodes.count(ChildN.getNode()))
1362         AddToWorklist(ChildN.getNode());
1363
1364     SDValue RV = combine(N);
1365
1366     if (!RV.getNode())
1367       continue;
1368
1369     ++NodesCombined;
1370
1371     // If we get back the same node we passed in, rather than a new node or
1372     // zero, we know that the node must have defined multiple values and
1373     // CombineTo was used.  Since CombineTo takes care of the worklist
1374     // mechanics for us, we have no work to do in this case.
1375     if (RV.getNode() == N)
1376       continue;
1377
1378     assert(N->getOpcode() != ISD::DELETED_NODE &&
1379            RV.getOpcode() != ISD::DELETED_NODE &&
1380            "Node was deleted but visit returned new node!");
1381
1382     DEBUG(dbgs() << " ... into: ";
1383           RV.getNode()->dump(&DAG));
1384
1385     if (N->getNumValues() == RV.getNode()->getNumValues())
1386       DAG.ReplaceAllUsesWith(N, RV.getNode());
1387     else {
1388       assert(N->getValueType(0) == RV.getValueType() &&
1389              N->getNumValues() == 1 && "Type mismatch");
1390       DAG.ReplaceAllUsesWith(N, &RV);
1391     }
1392
1393     // Push the new node and any users onto the worklist
1394     AddToWorklist(RV.getNode());
1395     AddUsersToWorklist(RV.getNode());
1396
1397     // Finally, if the node is now dead, remove it from the graph.  The node
1398     // may not be dead if the replacement process recursively simplified to
1399     // something else needing this node. This will also take care of adding any
1400     // operands which have lost a user to the worklist.
1401     recursivelyDeleteUnusedNodes(N);
1402   }
1403
1404   // If the root changed (e.g. it was a dead load, update the root).
1405   DAG.setRoot(Dummy.getValue());
1406   DAG.RemoveDeadNodes();
1407 }
1408
1409 SDValue DAGCombiner::visit(SDNode *N) {
1410   switch (N->getOpcode()) {
1411   default: break;
1412   case ISD::TokenFactor:        return visitTokenFactor(N);
1413   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1414   case ISD::ADD:                return visitADD(N);
1415   case ISD::SUB:                return visitSUB(N);
1416   case ISD::ADDC:               return visitADDC(N);
1417   case ISD::UADDO:              return visitUADDO(N);
1418   case ISD::SUBC:               return visitSUBC(N);
1419   case ISD::USUBO:              return visitUSUBO(N);
1420   case ISD::ADDE:               return visitADDE(N);
1421   case ISD::ADDCARRY:           return visitADDCARRY(N);
1422   case ISD::SUBE:               return visitSUBE(N);
1423   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1424   case ISD::MUL:                return visitMUL(N);
1425   case ISD::SDIV:               return visitSDIV(N);
1426   case ISD::UDIV:               return visitUDIV(N);
1427   case ISD::SREM:
1428   case ISD::UREM:               return visitREM(N);
1429   case ISD::MULHU:              return visitMULHU(N);
1430   case ISD::MULHS:              return visitMULHS(N);
1431   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1432   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1433   case ISD::SMULO:              return visitSMULO(N);
1434   case ISD::UMULO:              return visitUMULO(N);
1435   case ISD::SMIN:
1436   case ISD::SMAX:
1437   case ISD::UMIN:
1438   case ISD::UMAX:               return visitIMINMAX(N);
1439   case ISD::AND:                return visitAND(N);
1440   case ISD::OR:                 return visitOR(N);
1441   case ISD::XOR:                return visitXOR(N);
1442   case ISD::SHL:                return visitSHL(N);
1443   case ISD::SRA:                return visitSRA(N);
1444   case ISD::SRL:                return visitSRL(N);
1445   case ISD::ROTR:
1446   case ISD::ROTL:               return visitRotate(N);
1447   case ISD::ABS:                return visitABS(N);
1448   case ISD::BSWAP:              return visitBSWAP(N);
1449   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1450   case ISD::CTLZ:               return visitCTLZ(N);
1451   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1452   case ISD::CTTZ:               return visitCTTZ(N);
1453   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1454   case ISD::CTPOP:              return visitCTPOP(N);
1455   case ISD::SELECT:             return visitSELECT(N);
1456   case ISD::VSELECT:            return visitVSELECT(N);
1457   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1458   case ISD::SETCC:              return visitSETCC(N);
1459   case ISD::SETCCE:             return visitSETCCE(N);
1460   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1461   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1462   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1463   case ISD::AssertZext:         return visitAssertZext(N);
1464   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1465   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1466   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1467   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1468   case ISD::BITCAST:            return visitBITCAST(N);
1469   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1470   case ISD::FADD:               return visitFADD(N);
1471   case ISD::FSUB:               return visitFSUB(N);
1472   case ISD::FMUL:               return visitFMUL(N);
1473   case ISD::FMA:                return visitFMA(N);
1474   case ISD::FDIV:               return visitFDIV(N);
1475   case ISD::FREM:               return visitFREM(N);
1476   case ISD::FSQRT:              return visitFSQRT(N);
1477   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1478   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1479   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1480   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1481   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1482   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1483   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1484   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1485   case ISD::FNEG:               return visitFNEG(N);
1486   case ISD::FABS:               return visitFABS(N);
1487   case ISD::FFLOOR:             return visitFFLOOR(N);
1488   case ISD::FMINNUM:            return visitFMINNUM(N);
1489   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1490   case ISD::FCEIL:              return visitFCEIL(N);
1491   case ISD::FTRUNC:             return visitFTRUNC(N);
1492   case ISD::BRCOND:             return visitBRCOND(N);
1493   case ISD::BR_CC:              return visitBR_CC(N);
1494   case ISD::LOAD:               return visitLOAD(N);
1495   case ISD::STORE:              return visitSTORE(N);
1496   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1497   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1498   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1499   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1500   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1501   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1502   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1503   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1504   case ISD::MGATHER:            return visitMGATHER(N);
1505   case ISD::MLOAD:              return visitMLOAD(N);
1506   case ISD::MSCATTER:           return visitMSCATTER(N);
1507   case ISD::MSTORE:             return visitMSTORE(N);
1508   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1509   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1510   }
1511   return SDValue();
1512 }
1513
1514 SDValue DAGCombiner::combine(SDNode *N) {
1515   SDValue RV = visit(N);
1516
1517   // If nothing happened, try a target-specific DAG combine.
1518   if (!RV.getNode()) {
1519     assert(N->getOpcode() != ISD::DELETED_NODE &&
1520            "Node was deleted but visit returned NULL!");
1521
1522     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1523         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1524
1525       // Expose the DAG combiner to the target combiner impls.
1526       TargetLowering::DAGCombinerInfo
1527         DagCombineInfo(DAG, Level, false, this);
1528
1529       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1530     }
1531   }
1532
1533   // If nothing happened still, try promoting the operation.
1534   if (!RV.getNode()) {
1535     switch (N->getOpcode()) {
1536     default: break;
1537     case ISD::ADD:
1538     case ISD::SUB:
1539     case ISD::MUL:
1540     case ISD::AND:
1541     case ISD::OR:
1542     case ISD::XOR:
1543       RV = PromoteIntBinOp(SDValue(N, 0));
1544       break;
1545     case ISD::SHL:
1546     case ISD::SRA:
1547     case ISD::SRL:
1548       RV = PromoteIntShiftOp(SDValue(N, 0));
1549       break;
1550     case ISD::SIGN_EXTEND:
1551     case ISD::ZERO_EXTEND:
1552     case ISD::ANY_EXTEND:
1553       RV = PromoteExtend(SDValue(N, 0));
1554       break;
1555     case ISD::LOAD:
1556       if (PromoteLoad(SDValue(N, 0)))
1557         RV = SDValue(N, 0);
1558       break;
1559     }
1560   }
1561
1562   // If N is a commutative binary node, try commuting it to enable more
1563   // sdisel CSE.
1564   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1565       N->getNumValues() == 1) {
1566     SDValue N0 = N->getOperand(0);
1567     SDValue N1 = N->getOperand(1);
1568
1569     // Constant operands are canonicalized to RHS.
1570     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1571       SDValue Ops[] = {N1, N0};
1572       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1573                                             N->getFlags());
1574       if (CSENode)
1575         return SDValue(CSENode, 0);
1576     }
1577   }
1578
1579   return RV;
1580 }
1581
1582 /// Given a node, return its input chain if it has one, otherwise return a null
1583 /// sd operand.
1584 static SDValue getInputChainForNode(SDNode *N) {
1585   if (unsigned NumOps = N->getNumOperands()) {
1586     if (N->getOperand(0).getValueType() == MVT::Other)
1587       return N->getOperand(0);
1588     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1589       return N->getOperand(NumOps-1);
1590     for (unsigned i = 1; i < NumOps-1; ++i)
1591       if (N->getOperand(i).getValueType() == MVT::Other)
1592         return N->getOperand(i);
1593   }
1594   return SDValue();
1595 }
1596
1597 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1598   // If N has two operands, where one has an input chain equal to the other,
1599   // the 'other' chain is redundant.
1600   if (N->getNumOperands() == 2) {
1601     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1602       return N->getOperand(0);
1603     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1604       return N->getOperand(1);
1605   }
1606
1607   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1608   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1609   SmallPtrSet<SDNode*, 16> SeenOps;
1610   bool Changed = false;             // If we should replace this token factor.
1611
1612   // Start out with this token factor.
1613   TFs.push_back(N);
1614
1615   // Iterate through token factors.  The TFs grows when new token factors are
1616   // encountered.
1617   for (unsigned i = 0; i < TFs.size(); ++i) {
1618     SDNode *TF = TFs[i];
1619
1620     // Check each of the operands.
1621     for (const SDValue &Op : TF->op_values()) {
1622
1623       switch (Op.getOpcode()) {
1624       case ISD::EntryToken:
1625         // Entry tokens don't need to be added to the list. They are
1626         // redundant.
1627         Changed = true;
1628         break;
1629
1630       case ISD::TokenFactor:
1631         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1632           // Queue up for processing.
1633           TFs.push_back(Op.getNode());
1634           // Clean up in case the token factor is removed.
1635           AddToWorklist(Op.getNode());
1636           Changed = true;
1637           break;
1638         }
1639         LLVM_FALLTHROUGH;
1640
1641       default:
1642         // Only add if it isn't already in the list.
1643         if (SeenOps.insert(Op.getNode()).second)
1644           Ops.push_back(Op);
1645         else
1646           Changed = true;
1647         break;
1648       }
1649     }
1650   }
1651
1652   // Remove Nodes that are chained to another node in the list. Do so
1653   // by walking up chains breath-first stopping when we've seen
1654   // another operand. In general we must climb to the EntryNode, but we can exit
1655   // early if we find all remaining work is associated with just one operand as
1656   // no further pruning is possible.
1657
1658   // List of nodes to search through and original Ops from which they originate.
1659   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1660   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1661   SmallPtrSet<SDNode *, 16> SeenChains;
1662   bool DidPruneOps = false;
1663
1664   unsigned NumLeftToConsider = 0;
1665   for (const SDValue &Op : Ops) {
1666     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1667     OpWorkCount.push_back(1);
1668   }
1669
1670   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1671     // If this is an Op, we can remove the op from the list. Remark any
1672     // search associated with it as from the current OpNumber.
1673     if (SeenOps.count(Op) != 0) {
1674       Changed = true;
1675       DidPruneOps = true;
1676       unsigned OrigOpNumber = 0;
1677       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1678         OrigOpNumber++;
1679       assert((OrigOpNumber != Ops.size()) &&
1680              "expected to find TokenFactor Operand");
1681       // Re-mark worklist from OrigOpNumber to OpNumber
1682       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1683         if (Worklist[i].second == OrigOpNumber) {
1684           Worklist[i].second = OpNumber;
1685         }
1686       }
1687       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1688       OpWorkCount[OrigOpNumber] = 0;
1689       NumLeftToConsider--;
1690     }
1691     // Add if it's a new chain
1692     if (SeenChains.insert(Op).second) {
1693       OpWorkCount[OpNumber]++;
1694       Worklist.push_back(std::make_pair(Op, OpNumber));
1695     }
1696   };
1697
1698   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1699     // We need at least be consider at least 2 Ops to prune.
1700     if (NumLeftToConsider <= 1)
1701       break;
1702     auto CurNode = Worklist[i].first;
1703     auto CurOpNumber = Worklist[i].second;
1704     assert((OpWorkCount[CurOpNumber] > 0) &&
1705            "Node should not appear in worklist");
1706     switch (CurNode->getOpcode()) {
1707     case ISD::EntryToken:
1708       // Hitting EntryToken is the only way for the search to terminate without
1709       // hitting
1710       // another operand's search. Prevent us from marking this operand
1711       // considered.
1712       NumLeftToConsider++;
1713       break;
1714     case ISD::TokenFactor:
1715       for (const SDValue &Op : CurNode->op_values())
1716         AddToWorklist(i, Op.getNode(), CurOpNumber);
1717       break;
1718     case ISD::CopyFromReg:
1719     case ISD::CopyToReg:
1720       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1721       break;
1722     default:
1723       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1724         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1725       break;
1726     }
1727     OpWorkCount[CurOpNumber]--;
1728     if (OpWorkCount[CurOpNumber] == 0)
1729       NumLeftToConsider--;
1730   }
1731
1732   // If we've changed things around then replace token factor.
1733   if (Changed) {
1734     SDValue Result;
1735     if (Ops.empty()) {
1736       // The entry token is the only possible outcome.
1737       Result = DAG.getEntryNode();
1738     } else {
1739       if (DidPruneOps) {
1740         SmallVector<SDValue, 8> PrunedOps;
1741         //
1742         for (const SDValue &Op : Ops) {
1743           if (SeenChains.count(Op.getNode()) == 0)
1744             PrunedOps.push_back(Op);
1745         }
1746         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1747       } else {
1748         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1749       }
1750     }
1751     return Result;
1752   }
1753   return SDValue();
1754 }
1755
1756 /// MERGE_VALUES can always be eliminated.
1757 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1758   WorklistRemover DeadNodes(*this);
1759   // Replacing results may cause a different MERGE_VALUES to suddenly
1760   // be CSE'd with N, and carry its uses with it. Iterate until no
1761   // uses remain, to ensure that the node can be safely deleted.
1762   // First add the users of this node to the work list so that they
1763   // can be tried again once they have new operands.
1764   AddUsersToWorklist(N);
1765   do {
1766     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1767       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1768   } while (!N->use_empty());
1769   deleteAndRecombine(N);
1770   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1771 }
1772
1773 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1774 /// ConstantSDNode pointer else nullptr.
1775 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1776   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1777   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1778 }
1779
1780 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1781   auto BinOpcode = BO->getOpcode();
1782   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1783           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1784           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1785           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1786           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1787           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1788           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1789           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1790           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1791          "Unexpected binary operator");
1792
1793   // Bail out if any constants are opaque because we can't constant fold those.
1794   SDValue C1 = BO->getOperand(1);
1795   if (!isConstantOrConstantVector(C1, true) &&
1796       !isConstantFPBuildVectorOrConstantFP(C1))
1797     return SDValue();
1798
1799   // Don't do this unless the old select is going away. We want to eliminate the
1800   // binary operator, not replace a binop with a select.
1801   // TODO: Handle ISD::SELECT_CC.
1802   SDValue Sel = BO->getOperand(0);
1803   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1804     return SDValue();
1805
1806   SDValue CT = Sel.getOperand(1);
1807   if (!isConstantOrConstantVector(CT, true) &&
1808       !isConstantFPBuildVectorOrConstantFP(CT))
1809     return SDValue();
1810
1811   SDValue CF = Sel.getOperand(2);
1812   if (!isConstantOrConstantVector(CF, true) &&
1813       !isConstantFPBuildVectorOrConstantFP(CF))
1814     return SDValue();
1815
1816   // We have a select-of-constants followed by a binary operator with a
1817   // constant. Eliminate the binop by pulling the constant math into the select.
1818   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1819   EVT VT = Sel.getValueType();
1820   SDLoc DL(Sel);
1821   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1822   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1823           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1824          "Failed to constant fold a binop with constant operands");
1825
1826   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1827   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1828           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1829          "Failed to constant fold a binop with constant operands");
1830
1831   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1832 }
1833
1834 SDValue DAGCombiner::visitADD(SDNode *N) {
1835   SDValue N0 = N->getOperand(0);
1836   SDValue N1 = N->getOperand(1);
1837   EVT VT = N0.getValueType();
1838   SDLoc DL(N);
1839
1840   // fold vector ops
1841   if (VT.isVector()) {
1842     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1843       return FoldedVOp;
1844
1845     // fold (add x, 0) -> x, vector edition
1846     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1847       return N0;
1848     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1849       return N1;
1850   }
1851
1852   // fold (add x, undef) -> undef
1853   if (N0.isUndef())
1854     return N0;
1855
1856   if (N1.isUndef())
1857     return N1;
1858
1859   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1860     // canonicalize constant to RHS
1861     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1862       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1863     // fold (add c1, c2) -> c1+c2
1864     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1865                                       N1.getNode());
1866   }
1867
1868   // fold (add x, 0) -> x
1869   if (isNullConstant(N1))
1870     return N0;
1871
1872   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1873     // fold ((c1-A)+c2) -> (c1+c2)-A
1874     if (N0.getOpcode() == ISD::SUB &&
1875         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1876       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1877       return DAG.getNode(ISD::SUB, DL, VT,
1878                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1879                          N0.getOperand(1));
1880     }
1881
1882     // add (sext i1 X), 1 -> zext (not i1 X)
1883     // We don't transform this pattern:
1884     //   add (zext i1 X), -1 -> sext (not i1 X)
1885     // because most (?) targets generate better code for the zext form.
1886     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1887         isOneConstantOrOneSplatConstant(N1)) {
1888       SDValue X = N0.getOperand(0);
1889       if ((!LegalOperations ||
1890            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1891             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1892           X.getScalarValueSizeInBits() == 1) {
1893         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1894         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1895       }
1896     }
1897   }
1898
1899   if (SDValue NewSel = foldBinOpIntoSelect(N))
1900     return NewSel;
1901
1902   // reassociate add
1903   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1904     return RADD;
1905
1906   // fold ((0-A) + B) -> B-A
1907   if (N0.getOpcode() == ISD::SUB &&
1908       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1909     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1910
1911   // fold (A + (0-B)) -> A-B
1912   if (N1.getOpcode() == ISD::SUB &&
1913       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1914     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1915
1916   // fold (A+(B-A)) -> B
1917   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1918     return N1.getOperand(0);
1919
1920   // fold ((B-A)+A) -> B
1921   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1922     return N0.getOperand(0);
1923
1924   // fold (A+(B-(A+C))) to (B-C)
1925   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1926       N0 == N1.getOperand(1).getOperand(0))
1927     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1928                        N1.getOperand(1).getOperand(1));
1929
1930   // fold (A+(B-(C+A))) to (B-C)
1931   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1932       N0 == N1.getOperand(1).getOperand(1))
1933     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1934                        N1.getOperand(1).getOperand(0));
1935
1936   // fold (A+((B-A)+or-C)) to (B+or-C)
1937   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1938       N1.getOperand(0).getOpcode() == ISD::SUB &&
1939       N0 == N1.getOperand(0).getOperand(1))
1940     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1941                        N1.getOperand(1));
1942
1943   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1944   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1945     SDValue N00 = N0.getOperand(0);
1946     SDValue N01 = N0.getOperand(1);
1947     SDValue N10 = N1.getOperand(0);
1948     SDValue N11 = N1.getOperand(1);
1949
1950     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1951       return DAG.getNode(ISD::SUB, DL, VT,
1952                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1953                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1954   }
1955
1956   if (SimplifyDemandedBits(SDValue(N, 0)))
1957     return SDValue(N, 0);
1958
1959   // fold (a+b) -> (a|b) iff a and b share no bits.
1960   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1961       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1962     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1963
1964   if (SDValue Combined = visitADDLike(N0, N1, N))
1965     return Combined;
1966
1967   if (SDValue Combined = visitADDLike(N1, N0, N))
1968     return Combined;
1969
1970   return SDValue();
1971 }
1972
1973 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
1974   EVT VT = N0.getValueType();
1975   SDLoc DL(LocReference);
1976
1977   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1978   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1979       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1980     return DAG.getNode(ISD::SUB, DL, VT, N0,
1981                        DAG.getNode(ISD::SHL, DL, VT,
1982                                    N1.getOperand(0).getOperand(1),
1983                                    N1.getOperand(1)));
1984
1985   if (N1.getOpcode() == ISD::AND) {
1986     SDValue AndOp0 = N1.getOperand(0);
1987     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1988     unsigned DestBits = VT.getScalarSizeInBits();
1989
1990     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1991     // and similar xforms where the inner op is either ~0 or 0.
1992     if (NumSignBits == DestBits &&
1993         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1994       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
1995   }
1996
1997   // add (sext i1), X -> sub X, (zext i1)
1998   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1999       N0.getOperand(0).getValueType() == MVT::i1 &&
2000       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2001     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2002     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2003   }
2004
2005   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2006   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2007     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2008     if (TN->getVT() == MVT::i1) {
2009       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2010                                  DAG.getConstant(1, DL, VT));
2011       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2012     }
2013   }
2014
2015   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2016   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2017     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2018                        N0, N1.getOperand(0), N1.getOperand(2));
2019
2020   return SDValue();
2021 }
2022
2023 SDValue DAGCombiner::visitADDC(SDNode *N) {
2024   SDValue N0 = N->getOperand(0);
2025   SDValue N1 = N->getOperand(1);
2026   EVT VT = N0.getValueType();
2027   SDLoc DL(N);
2028
2029   // If the flag result is dead, turn this into an ADD.
2030   if (!N->hasAnyUseOfValue(1))
2031     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2032                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2033
2034   // canonicalize constant to RHS.
2035   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2036   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2037   if (N0C && !N1C)
2038     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2039
2040   // fold (addc x, 0) -> x + no carry out
2041   if (isNullConstant(N1))
2042     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2043                                         DL, MVT::Glue));
2044
2045   // If it cannot overflow, transform into an add.
2046   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2047     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2048                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2049
2050   return SDValue();
2051 }
2052
2053 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2054   SDValue N0 = N->getOperand(0);
2055   SDValue N1 = N->getOperand(1);
2056   EVT VT = N0.getValueType();
2057   if (VT.isVector())
2058     return SDValue();
2059
2060   EVT CarryVT = N->getValueType(1);
2061   SDLoc DL(N);
2062
2063   // If the flag result is dead, turn this into an ADD.
2064   if (!N->hasAnyUseOfValue(1))
2065     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2066                      DAG.getUNDEF(CarryVT));
2067
2068   // canonicalize constant to RHS.
2069   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2070   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2071   if (N0C && !N1C)
2072     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2073
2074   // fold (uaddo x, 0) -> x + no carry out
2075   if (isNullConstant(N1))
2076     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2077
2078   // If it cannot overflow, transform into an add.
2079   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2080     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2081                      DAG.getConstant(0, DL, CarryVT));
2082
2083   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2084     return Combined;
2085
2086   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2087     return Combined;
2088
2089   return SDValue();
2090 }
2091
2092 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2093   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2094   // If Y + 1 cannot overflow.
2095   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2096     SDValue Y = N1.getOperand(0);
2097     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2098     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2099       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2100                          N1.getOperand(2));
2101   }
2102
2103   return SDValue();
2104 }
2105
2106 SDValue DAGCombiner::visitADDE(SDNode *N) {
2107   SDValue N0 = N->getOperand(0);
2108   SDValue N1 = N->getOperand(1);
2109   SDValue CarryIn = N->getOperand(2);
2110
2111   // canonicalize constant to RHS
2112   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2113   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2114   if (N0C && !N1C)
2115     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2116                        N1, N0, CarryIn);
2117
2118   // fold (adde x, y, false) -> (addc x, y)
2119   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2120     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2121
2122   return SDValue();
2123 }
2124
2125 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2126   SDValue N0 = N->getOperand(0);
2127   SDValue N1 = N->getOperand(1);
2128   SDValue CarryIn = N->getOperand(2);
2129   SDLoc DL(N);
2130
2131   // canonicalize constant to RHS
2132   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2133   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2134   if (N0C && !N1C)
2135     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2136
2137   // fold (addcarry x, y, false) -> (uaddo x, y)
2138   if (isNullConstant(CarryIn))
2139     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2140
2141   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2142     return Combined;
2143
2144   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2145     return Combined;
2146
2147   return SDValue();
2148 }
2149
2150 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2151                                        SDNode *N) {
2152   // Iff the flag result is dead:
2153   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2154   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::UADDO) &&
2155       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2156     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2157                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2158
2159   return SDValue();
2160 }
2161
2162 // Since it may not be valid to emit a fold to zero for vector initializers
2163 // check if we can before folding.
2164 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2165                              SelectionDAG &DAG, bool LegalOperations,
2166                              bool LegalTypes) {
2167   if (!VT.isVector())
2168     return DAG.getConstant(0, DL, VT);
2169   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2170     return DAG.getConstant(0, DL, VT);
2171   return SDValue();
2172 }
2173
2174 SDValue DAGCombiner::visitSUB(SDNode *N) {
2175   SDValue N0 = N->getOperand(0);
2176   SDValue N1 = N->getOperand(1);
2177   EVT VT = N0.getValueType();
2178   SDLoc DL(N);
2179
2180   // fold vector ops
2181   if (VT.isVector()) {
2182     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2183       return FoldedVOp;
2184
2185     // fold (sub x, 0) -> x, vector edition
2186     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2187       return N0;
2188   }
2189
2190   // fold (sub x, x) -> 0
2191   // FIXME: Refactor this and xor and other similar operations together.
2192   if (N0 == N1)
2193     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2194   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2195       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2196     // fold (sub c1, c2) -> c1-c2
2197     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2198                                       N1.getNode());
2199   }
2200
2201   if (SDValue NewSel = foldBinOpIntoSelect(N))
2202     return NewSel;
2203
2204   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2205
2206   // fold (sub x, c) -> (add x, -c)
2207   if (N1C) {
2208     return DAG.getNode(ISD::ADD, DL, VT, N0,
2209                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2210   }
2211
2212   if (isNullConstantOrNullSplatConstant(N0)) {
2213     unsigned BitWidth = VT.getScalarSizeInBits();
2214     // Right-shifting everything out but the sign bit followed by negation is
2215     // the same as flipping arithmetic/logical shift type without the negation:
2216     // -(X >>u 31) -> (X >>s 31)
2217     // -(X >>s 31) -> (X >>u 31)
2218     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2219       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2220       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2221         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2222         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2223           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2224       }
2225     }
2226
2227     // 0 - X --> 0 if the sub is NUW.
2228     if (N->getFlags().hasNoUnsignedWrap())
2229       return N0;
2230
2231     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2232       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2233       // N1 must be 0 because negating the minimum signed value is undefined.
2234       if (N->getFlags().hasNoSignedWrap())
2235         return N0;
2236
2237       // 0 - X --> X if X is 0 or the minimum signed value.
2238       return N1;
2239     }
2240   }
2241
2242   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2243   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2244     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2245
2246   // fold A-(A-B) -> B
2247   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2248     return N1.getOperand(1);
2249
2250   // fold (A+B)-A -> B
2251   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2252     return N0.getOperand(1);
2253
2254   // fold (A+B)-B -> A
2255   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2256     return N0.getOperand(0);
2257
2258   // fold C2-(A+C1) -> (C2-C1)-A
2259   if (N1.getOpcode() == ISD::ADD) {
2260     SDValue N11 = N1.getOperand(1);
2261     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2262         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2263       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2264       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2265     }
2266   }
2267
2268   // fold ((A+(B+or-C))-B) -> A+or-C
2269   if (N0.getOpcode() == ISD::ADD &&
2270       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2271        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2272       N0.getOperand(1).getOperand(0) == N1)
2273     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2274                        N0.getOperand(1).getOperand(1));
2275
2276   // fold ((A+(C+B))-B) -> A+C
2277   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2278       N0.getOperand(1).getOperand(1) == N1)
2279     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2280                        N0.getOperand(1).getOperand(0));
2281
2282   // fold ((A-(B-C))-C) -> A-B
2283   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2284       N0.getOperand(1).getOperand(1) == N1)
2285     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2286                        N0.getOperand(1).getOperand(0));
2287
2288   // If either operand of a sub is undef, the result is undef
2289   if (N0.isUndef())
2290     return N0;
2291   if (N1.isUndef())
2292     return N1;
2293
2294   // If the relocation model supports it, consider symbol offsets.
2295   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2296     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2297       // fold (sub Sym, c) -> Sym-c
2298       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2299         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2300                                     GA->getOffset() -
2301                                         (uint64_t)N1C->getSExtValue());
2302       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2303       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2304         if (GA->getGlobal() == GB->getGlobal())
2305           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2306                                  DL, VT);
2307     }
2308
2309   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2310   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2311     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2312     if (TN->getVT() == MVT::i1) {
2313       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2314                                  DAG.getConstant(1, DL, VT));
2315       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2316     }
2317   }
2318
2319   return SDValue();
2320 }
2321
2322 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2323   SDValue N0 = N->getOperand(0);
2324   SDValue N1 = N->getOperand(1);
2325   EVT VT = N0.getValueType();
2326   SDLoc DL(N);
2327
2328   // If the flag result is dead, turn this into an SUB.
2329   if (!N->hasAnyUseOfValue(1))
2330     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2331                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2332
2333   // fold (subc x, x) -> 0 + no borrow
2334   if (N0 == N1)
2335     return CombineTo(N, DAG.getConstant(0, DL, VT),
2336                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2337
2338   // fold (subc x, 0) -> x + no borrow
2339   if (isNullConstant(N1))
2340     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2341
2342   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2343   if (isAllOnesConstant(N0))
2344     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2345                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2346
2347   return SDValue();
2348 }
2349
2350 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2351   SDValue N0 = N->getOperand(0);
2352   SDValue N1 = N->getOperand(1);
2353   EVT VT = N0.getValueType();
2354   if (VT.isVector())
2355     return SDValue();
2356
2357   EVT CarryVT = N->getValueType(1);
2358   SDLoc DL(N);
2359
2360   // If the flag result is dead, turn this into an SUB.
2361   if (!N->hasAnyUseOfValue(1))
2362     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2363                      DAG.getUNDEF(CarryVT));
2364
2365   // fold (usubo x, x) -> 0 + no borrow
2366   if (N0 == N1)
2367     return CombineTo(N, DAG.getConstant(0, DL, VT),
2368                      DAG.getConstant(0, DL, CarryVT));
2369
2370   // fold (usubo x, 0) -> x + no borrow
2371   if (isNullConstant(N1))
2372     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2373
2374   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2375   if (isAllOnesConstant(N0))
2376     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2377                      DAG.getConstant(0, DL, CarryVT));
2378
2379   return SDValue();
2380 }
2381
2382 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2383   SDValue N0 = N->getOperand(0);
2384   SDValue N1 = N->getOperand(1);
2385   SDValue CarryIn = N->getOperand(2);
2386
2387   // fold (sube x, y, false) -> (subc x, y)
2388   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2389     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2390
2391   return SDValue();
2392 }
2393
2394 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2395   SDValue N0 = N->getOperand(0);
2396   SDValue N1 = N->getOperand(1);
2397   SDValue CarryIn = N->getOperand(2);
2398
2399   // fold (subcarry x, y, false) -> (usubo x, y)
2400   if (isNullConstant(CarryIn))
2401     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2402
2403   return SDValue();
2404 }
2405
2406 SDValue DAGCombiner::visitMUL(SDNode *N) {
2407   SDValue N0 = N->getOperand(0);
2408   SDValue N1 = N->getOperand(1);
2409   EVT VT = N0.getValueType();
2410
2411   // fold (mul x, undef) -> 0
2412   if (N0.isUndef() || N1.isUndef())
2413     return DAG.getConstant(0, SDLoc(N), VT);
2414
2415   bool N0IsConst = false;
2416   bool N1IsConst = false;
2417   bool N1IsOpaqueConst = false;
2418   bool N0IsOpaqueConst = false;
2419   APInt ConstValue0, ConstValue1;
2420   // fold vector ops
2421   if (VT.isVector()) {
2422     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2423       return FoldedVOp;
2424
2425     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2426     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2427   } else {
2428     N0IsConst = isa<ConstantSDNode>(N0);
2429     if (N0IsConst) {
2430       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2431       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2432     }
2433     N1IsConst = isa<ConstantSDNode>(N1);
2434     if (N1IsConst) {
2435       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2436       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2437     }
2438   }
2439
2440   // fold (mul c1, c2) -> c1*c2
2441   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2442     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2443                                       N0.getNode(), N1.getNode());
2444
2445   // canonicalize constant to RHS (vector doesn't have to splat)
2446   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2447      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2448     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2449   // fold (mul x, 0) -> 0
2450   if (N1IsConst && ConstValue1 == 0)
2451     return N1;
2452   // We require a splat of the entire scalar bit width for non-contiguous
2453   // bit patterns.
2454   bool IsFullSplat =
2455     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2456   // fold (mul x, 1) -> x
2457   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2458     return N0;
2459
2460   if (SDValue NewSel = foldBinOpIntoSelect(N))
2461     return NewSel;
2462
2463   // fold (mul x, -1) -> 0-x
2464   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2465     SDLoc DL(N);
2466     return DAG.getNode(ISD::SUB, DL, VT,
2467                        DAG.getConstant(0, DL, VT), N0);
2468   }
2469   // fold (mul x, (1 << c)) -> x << c
2470   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2471       IsFullSplat) {
2472     SDLoc DL(N);
2473     return DAG.getNode(ISD::SHL, DL, VT, N0,
2474                        DAG.getConstant(ConstValue1.logBase2(), DL,
2475                                        getShiftAmountTy(N0.getValueType())));
2476   }
2477   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2478   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2479       IsFullSplat) {
2480     unsigned Log2Val = (-ConstValue1).logBase2();
2481     SDLoc DL(N);
2482     // FIXME: If the input is something that is easily negated (e.g. a
2483     // single-use add), we should put the negate there.
2484     return DAG.getNode(ISD::SUB, DL, VT,
2485                        DAG.getConstant(0, DL, VT),
2486                        DAG.getNode(ISD::SHL, DL, VT, N0,
2487                             DAG.getConstant(Log2Val, DL,
2488                                       getShiftAmountTy(N0.getValueType()))));
2489   }
2490
2491   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2492   if (N0.getOpcode() == ISD::SHL &&
2493       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2494       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2495     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2496     if (isConstantOrConstantVector(C3))
2497       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2498   }
2499
2500   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2501   // use.
2502   {
2503     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2504
2505     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2506     if (N0.getOpcode() == ISD::SHL &&
2507         isConstantOrConstantVector(N0.getOperand(1)) &&
2508         N0.getNode()->hasOneUse()) {
2509       Sh = N0; Y = N1;
2510     } else if (N1.getOpcode() == ISD::SHL &&
2511                isConstantOrConstantVector(N1.getOperand(1)) &&
2512                N1.getNode()->hasOneUse()) {
2513       Sh = N1; Y = N0;
2514     }
2515
2516     if (Sh.getNode()) {
2517       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2518       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2519     }
2520   }
2521
2522   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2523   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2524       N0.getOpcode() == ISD::ADD &&
2525       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2526       isMulAddWithConstProfitable(N, N0, N1))
2527       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2528                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2529                                      N0.getOperand(0), N1),
2530                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2531                                      N0.getOperand(1), N1));
2532
2533   // reassociate mul
2534   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2535     return RMUL;
2536
2537   return SDValue();
2538 }
2539
2540 /// Return true if divmod libcall is available.
2541 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2542                                      const TargetLowering &TLI) {
2543   RTLIB::Libcall LC;
2544   EVT NodeType = Node->getValueType(0);
2545   if (!NodeType.isSimple())
2546     return false;
2547   switch (NodeType.getSimpleVT().SimpleTy) {
2548   default: return false; // No libcall for vector types.
2549   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2550   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2551   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2552   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2553   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2554   }
2555
2556   return TLI.getLibcallName(LC) != nullptr;
2557 }
2558
2559 /// Issue divrem if both quotient and remainder are needed.
2560 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2561   if (Node->use_empty())
2562     return SDValue(); // This is a dead node, leave it alone.
2563
2564   unsigned Opcode = Node->getOpcode();
2565   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2566   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2567
2568   // DivMod lib calls can still work on non-legal types if using lib-calls.
2569   EVT VT = Node->getValueType(0);
2570   if (VT.isVector() || !VT.isInteger())
2571     return SDValue();
2572
2573   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2574     return SDValue();
2575
2576   // If DIVREM is going to get expanded into a libcall,
2577   // but there is no libcall available, then don't combine.
2578   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2579       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2580     return SDValue();
2581
2582   // If div is legal, it's better to do the normal expansion
2583   unsigned OtherOpcode = 0;
2584   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2585     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2586     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2587       return SDValue();
2588   } else {
2589     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2590     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2591       return SDValue();
2592   }
2593
2594   SDValue Op0 = Node->getOperand(0);
2595   SDValue Op1 = Node->getOperand(1);
2596   SDValue combined;
2597   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2598          UE = Op0.getNode()->use_end(); UI != UE;) {
2599     SDNode *User = *UI++;
2600     if (User == Node || User->use_empty())
2601       continue;
2602     // Convert the other matching node(s), too;
2603     // otherwise, the DIVREM may get target-legalized into something
2604     // target-specific that we won't be able to recognize.
2605     unsigned UserOpc = User->getOpcode();
2606     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2607         User->getOperand(0) == Op0 &&
2608         User->getOperand(1) == Op1) {
2609       if (!combined) {
2610         if (UserOpc == OtherOpcode) {
2611           SDVTList VTs = DAG.getVTList(VT, VT);
2612           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2613         } else if (UserOpc == DivRemOpc) {
2614           combined = SDValue(User, 0);
2615         } else {
2616           assert(UserOpc == Opcode);
2617           continue;
2618         }
2619       }
2620       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2621         CombineTo(User, combined);
2622       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2623         CombineTo(User, combined.getValue(1));
2624     }
2625   }
2626   return combined;
2627 }
2628
2629 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2630   SDValue N0 = N->getOperand(0);
2631   SDValue N1 = N->getOperand(1);
2632   EVT VT = N->getValueType(0);
2633   SDLoc DL(N);
2634
2635   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2636     return DAG.getUNDEF(VT);
2637
2638   // undef / X -> 0
2639   // undef % X -> 0
2640   if (N0.isUndef())
2641     return DAG.getConstant(0, DL, VT);
2642
2643   return SDValue();
2644 }
2645
2646 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2647   SDValue N0 = N->getOperand(0);
2648   SDValue N1 = N->getOperand(1);
2649   EVT VT = N->getValueType(0);
2650
2651   // fold vector ops
2652   if (VT.isVector())
2653     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2654       return FoldedVOp;
2655
2656   SDLoc DL(N);
2657
2658   // fold (sdiv c1, c2) -> c1/c2
2659   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2660   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2661   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2662     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2663   // fold (sdiv X, 1) -> X
2664   if (N1C && N1C->isOne())
2665     return N0;
2666   // fold (sdiv X, -1) -> 0-X
2667   if (N1C && N1C->isAllOnesValue())
2668     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2669
2670   if (SDValue V = simplifyDivRem(N, DAG))
2671     return V;
2672
2673   if (SDValue NewSel = foldBinOpIntoSelect(N))
2674     return NewSel;
2675
2676   // If we know the sign bits of both operands are zero, strength reduce to a
2677   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2678   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2679     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2680
2681   // fold (sdiv X, pow2) -> simple ops after legalize
2682   // FIXME: We check for the exact bit here because the generic lowering gives
2683   // better results in that case. The target-specific lowering should learn how
2684   // to handle exact sdivs efficiently.
2685   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2686       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2687                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2688     // Target-specific implementation of sdiv x, pow2.
2689     if (SDValue Res = BuildSDIVPow2(N))
2690       return Res;
2691
2692     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2693
2694     // Splat the sign bit into the register
2695     SDValue SGN =
2696         DAG.getNode(ISD::SRA, DL, VT, N0,
2697                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2698                                     getShiftAmountTy(N0.getValueType())));
2699     AddToWorklist(SGN.getNode());
2700
2701     // Add (N0 < 0) ? abs2 - 1 : 0;
2702     SDValue SRL =
2703         DAG.getNode(ISD::SRL, DL, VT, SGN,
2704                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2705                                     getShiftAmountTy(SGN.getValueType())));
2706     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2707     AddToWorklist(SRL.getNode());
2708     AddToWorklist(ADD.getNode());    // Divide by pow2
2709     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2710                   DAG.getConstant(lg2, DL,
2711                                   getShiftAmountTy(ADD.getValueType())));
2712
2713     // If we're dividing by a positive value, we're done.  Otherwise, we must
2714     // negate the result.
2715     if (N1C->getAPIntValue().isNonNegative())
2716       return SRA;
2717
2718     AddToWorklist(SRA.getNode());
2719     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2720   }
2721
2722   // If integer divide is expensive and we satisfy the requirements, emit an
2723   // alternate sequence.  Targets may check function attributes for size/speed
2724   // trade-offs.
2725   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2726   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2727     if (SDValue Op = BuildSDIV(N))
2728       return Op;
2729
2730   // sdiv, srem -> sdivrem
2731   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2732   // true.  Otherwise, we break the simplification logic in visitREM().
2733   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2734     if (SDValue DivRem = useDivRem(N))
2735         return DivRem;
2736
2737   return SDValue();
2738 }
2739
2740 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2741   SDValue N0 = N->getOperand(0);
2742   SDValue N1 = N->getOperand(1);
2743   EVT VT = N->getValueType(0);
2744
2745   // fold vector ops
2746   if (VT.isVector())
2747     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2748       return FoldedVOp;
2749
2750   SDLoc DL(N);
2751
2752   // fold (udiv c1, c2) -> c1/c2
2753   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2754   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2755   if (N0C && N1C)
2756     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2757                                                     N0C, N1C))
2758       return Folded;
2759
2760   if (SDValue V = simplifyDivRem(N, DAG))
2761     return V;
2762
2763   if (SDValue NewSel = foldBinOpIntoSelect(N))
2764     return NewSel;
2765
2766   // fold (udiv x, (1 << c)) -> x >>u c
2767   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2768       DAG.isKnownToBeAPowerOfTwo(N1)) {
2769     SDValue LogBase2 = BuildLogBase2(N1, DL);
2770     AddToWorklist(LogBase2.getNode());
2771
2772     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2773     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2774     AddToWorklist(Trunc.getNode());
2775     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2776   }
2777
2778   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2779   if (N1.getOpcode() == ISD::SHL) {
2780     SDValue N10 = N1.getOperand(0);
2781     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2782         DAG.isKnownToBeAPowerOfTwo(N10)) {
2783       SDValue LogBase2 = BuildLogBase2(N10, DL);
2784       AddToWorklist(LogBase2.getNode());
2785
2786       EVT ADDVT = N1.getOperand(1).getValueType();
2787       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2788       AddToWorklist(Trunc.getNode());
2789       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2790       AddToWorklist(Add.getNode());
2791       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2792     }
2793   }
2794
2795   // fold (udiv x, c) -> alternate
2796   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2797   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2798     if (SDValue Op = BuildUDIV(N))
2799       return Op;
2800
2801   // sdiv, srem -> sdivrem
2802   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2803   // true.  Otherwise, we break the simplification logic in visitREM().
2804   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2805     if (SDValue DivRem = useDivRem(N))
2806         return DivRem;
2807
2808   return SDValue();
2809 }
2810
2811 // handles ISD::SREM and ISD::UREM
2812 SDValue DAGCombiner::visitREM(SDNode *N) {
2813   unsigned Opcode = N->getOpcode();
2814   SDValue N0 = N->getOperand(0);
2815   SDValue N1 = N->getOperand(1);
2816   EVT VT = N->getValueType(0);
2817   bool isSigned = (Opcode == ISD::SREM);
2818   SDLoc DL(N);
2819
2820   // fold (rem c1, c2) -> c1%c2
2821   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2822   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2823   if (N0C && N1C)
2824     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2825       return Folded;
2826
2827   if (SDValue V = simplifyDivRem(N, DAG))
2828     return V;
2829
2830   if (SDValue NewSel = foldBinOpIntoSelect(N))
2831     return NewSel;
2832
2833   if (isSigned) {
2834     // If we know the sign bits of both operands are zero, strength reduce to a
2835     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2836     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2837       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2838   } else {
2839     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2840     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2841       // fold (urem x, pow2) -> (and x, pow2-1)
2842       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2843       AddToWorklist(Add.getNode());
2844       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2845     }
2846     if (N1.getOpcode() == ISD::SHL &&
2847         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2848       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2849       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2850       AddToWorklist(Add.getNode());
2851       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2852     }
2853   }
2854
2855   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2856
2857   // If X/C can be simplified by the division-by-constant logic, lower
2858   // X%C to the equivalent of X-X/C*C.
2859   // To avoid mangling nodes, this simplification requires that the combine()
2860   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2861   // against this by skipping the simplification if isIntDivCheap().  When
2862   // div is not cheap, combine will not return a DIVREM.  Regardless,
2863   // checking cheapness here makes sense since the simplification results in
2864   // fatter code.
2865   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2866     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2867     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2868     AddToWorklist(Div.getNode());
2869     SDValue OptimizedDiv = combine(Div.getNode());
2870     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2871       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2872              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2873       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2874       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2875       AddToWorklist(Mul.getNode());
2876       return Sub;
2877     }
2878   }
2879
2880   // sdiv, srem -> sdivrem
2881   if (SDValue DivRem = useDivRem(N))
2882     return DivRem.getValue(1);
2883
2884   return SDValue();
2885 }
2886
2887 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2888   SDValue N0 = N->getOperand(0);
2889   SDValue N1 = N->getOperand(1);
2890   EVT VT = N->getValueType(0);
2891   SDLoc DL(N);
2892
2893   // fold (mulhs x, 0) -> 0
2894   if (isNullConstant(N1))
2895     return N1;
2896   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2897   if (isOneConstant(N1)) {
2898     SDLoc DL(N);
2899     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2900                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2901                                        getShiftAmountTy(N0.getValueType())));
2902   }
2903   // fold (mulhs x, undef) -> 0
2904   if (N0.isUndef() || N1.isUndef())
2905     return DAG.getConstant(0, SDLoc(N), VT);
2906
2907   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2908   // plus a shift.
2909   if (VT.isSimple() && !VT.isVector()) {
2910     MVT Simple = VT.getSimpleVT();
2911     unsigned SimpleSize = Simple.getSizeInBits();
2912     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2913     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2914       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2915       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2916       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2917       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2918             DAG.getConstant(SimpleSize, DL,
2919                             getShiftAmountTy(N1.getValueType())));
2920       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2921     }
2922   }
2923
2924   return SDValue();
2925 }
2926
2927 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2928   SDValue N0 = N->getOperand(0);
2929   SDValue N1 = N->getOperand(1);
2930   EVT VT = N->getValueType(0);
2931   SDLoc DL(N);
2932
2933   // fold (mulhu x, 0) -> 0
2934   if (isNullConstant(N1))
2935     return N1;
2936   // fold (mulhu x, 1) -> 0
2937   if (isOneConstant(N1))
2938     return DAG.getConstant(0, DL, N0.getValueType());
2939   // fold (mulhu x, undef) -> 0
2940   if (N0.isUndef() || N1.isUndef())
2941     return DAG.getConstant(0, DL, VT);
2942
2943   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2944   // plus a shift.
2945   if (VT.isSimple() && !VT.isVector()) {
2946     MVT Simple = VT.getSimpleVT();
2947     unsigned SimpleSize = Simple.getSizeInBits();
2948     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2949     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2950       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2951       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2952       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2953       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2954             DAG.getConstant(SimpleSize, DL,
2955                             getShiftAmountTy(N1.getValueType())));
2956       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2957     }
2958   }
2959
2960   return SDValue();
2961 }
2962
2963 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2964 /// give the opcodes for the two computations that are being performed. Return
2965 /// true if a simplification was made.
2966 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2967                                                 unsigned HiOp) {
2968   // If the high half is not needed, just compute the low half.
2969   bool HiExists = N->hasAnyUseOfValue(1);
2970   if (!HiExists &&
2971       (!LegalOperations ||
2972        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2973     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2974     return CombineTo(N, Res, Res);
2975   }
2976
2977   // If the low half is not needed, just compute the high half.
2978   bool LoExists = N->hasAnyUseOfValue(0);
2979   if (!LoExists &&
2980       (!LegalOperations ||
2981        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2982     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2983     return CombineTo(N, Res, Res);
2984   }
2985
2986   // If both halves are used, return as it is.
2987   if (LoExists && HiExists)
2988     return SDValue();
2989
2990   // If the two computed results can be simplified separately, separate them.
2991   if (LoExists) {
2992     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2993     AddToWorklist(Lo.getNode());
2994     SDValue LoOpt = combine(Lo.getNode());
2995     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2996         (!LegalOperations ||
2997          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2998       return CombineTo(N, LoOpt, LoOpt);
2999   }
3000
3001   if (HiExists) {
3002     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3003     AddToWorklist(Hi.getNode());
3004     SDValue HiOpt = combine(Hi.getNode());
3005     if (HiOpt.getNode() && HiOpt != Hi &&
3006         (!LegalOperations ||
3007          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3008       return CombineTo(N, HiOpt, HiOpt);
3009   }
3010
3011   return SDValue();
3012 }
3013
3014 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3015   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3016     return Res;
3017
3018   EVT VT = N->getValueType(0);
3019   SDLoc DL(N);
3020
3021   // If the type is twice as wide is legal, transform the mulhu to a wider
3022   // multiply plus a shift.
3023   if (VT.isSimple() && !VT.isVector()) {
3024     MVT Simple = VT.getSimpleVT();
3025     unsigned SimpleSize = Simple.getSizeInBits();
3026     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3027     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3028       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3029       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3030       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3031       // Compute the high part as N1.
3032       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3033             DAG.getConstant(SimpleSize, DL,
3034                             getShiftAmountTy(Lo.getValueType())));
3035       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3036       // Compute the low part as N0.
3037       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3038       return CombineTo(N, Lo, Hi);
3039     }
3040   }
3041
3042   return SDValue();
3043 }
3044
3045 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3046   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3047     return Res;
3048
3049   EVT VT = N->getValueType(0);
3050   SDLoc DL(N);
3051
3052   // If the type is twice as wide is legal, transform the mulhu to a wider
3053   // multiply plus a shift.
3054   if (VT.isSimple() && !VT.isVector()) {
3055     MVT Simple = VT.getSimpleVT();
3056     unsigned SimpleSize = Simple.getSizeInBits();
3057     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3058     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3059       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3060       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3061       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3062       // Compute the high part as N1.
3063       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3064             DAG.getConstant(SimpleSize, DL,
3065                             getShiftAmountTy(Lo.getValueType())));
3066       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3067       // Compute the low part as N0.
3068       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3069       return CombineTo(N, Lo, Hi);
3070     }
3071   }
3072
3073   return SDValue();
3074 }
3075
3076 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3077   // (smulo x, 2) -> (saddo x, x)
3078   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3079     if (C2->getAPIntValue() == 2)
3080       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3081                          N->getOperand(0), N->getOperand(0));
3082
3083   return SDValue();
3084 }
3085
3086 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3087   // (umulo x, 2) -> (uaddo x, x)
3088   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3089     if (C2->getAPIntValue() == 2)
3090       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3091                          N->getOperand(0), N->getOperand(0));
3092
3093   return SDValue();
3094 }
3095
3096 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3097   SDValue N0 = N->getOperand(0);
3098   SDValue N1 = N->getOperand(1);
3099   EVT VT = N0.getValueType();
3100
3101   // fold vector ops
3102   if (VT.isVector())
3103     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3104       return FoldedVOp;
3105
3106   // fold (add c1, c2) -> c1+c2
3107   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3108   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3109   if (N0C && N1C)
3110     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3111
3112   // canonicalize constant to RHS
3113   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3114      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3115     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3116
3117   return SDValue();
3118 }
3119
3120 /// If this is a binary operator with two operands of the same opcode, try to
3121 /// simplify it.
3122 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3123   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3124   EVT VT = N0.getValueType();
3125   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3126
3127   // Bail early if none of these transforms apply.
3128   if (N0.getNumOperands() == 0) return SDValue();
3129
3130   // For each of OP in AND/OR/XOR:
3131   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3132   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3133   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3134   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3135   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3136   //
3137   // do not sink logical op inside of a vector extend, since it may combine
3138   // into a vsetcc.
3139   EVT Op0VT = N0.getOperand(0).getValueType();
3140   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3141        N0.getOpcode() == ISD::SIGN_EXTEND ||
3142        N0.getOpcode() == ISD::BSWAP ||
3143        // Avoid infinite looping with PromoteIntBinOp.
3144        (N0.getOpcode() == ISD::ANY_EXTEND &&
3145         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3146        (N0.getOpcode() == ISD::TRUNCATE &&
3147         (!TLI.isZExtFree(VT, Op0VT) ||
3148          !TLI.isTruncateFree(Op0VT, VT)) &&
3149         TLI.isTypeLegal(Op0VT))) &&
3150       !VT.isVector() &&
3151       Op0VT == N1.getOperand(0).getValueType() &&
3152       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3153     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3154                                  N0.getOperand(0).getValueType(),
3155                                  N0.getOperand(0), N1.getOperand(0));
3156     AddToWorklist(ORNode.getNode());
3157     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3158   }
3159
3160   // For each of OP in SHL/SRL/SRA/AND...
3161   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3162   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3163   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3164   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3165        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3166       N0.getOperand(1) == N1.getOperand(1)) {
3167     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3168                                  N0.getOperand(0).getValueType(),
3169                                  N0.getOperand(0), N1.getOperand(0));
3170     AddToWorklist(ORNode.getNode());
3171     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3172                        ORNode, N0.getOperand(1));
3173   }
3174
3175   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3176   // Only perform this optimization up until type legalization, before
3177   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3178   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3179   // we don't want to undo this promotion.
3180   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3181   // on scalars.
3182   if ((N0.getOpcode() == ISD::BITCAST ||
3183        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3184        Level <= AfterLegalizeTypes) {
3185     SDValue In0 = N0.getOperand(0);
3186     SDValue In1 = N1.getOperand(0);
3187     EVT In0Ty = In0.getValueType();
3188     EVT In1Ty = In1.getValueType();
3189     SDLoc DL(N);
3190     // If both incoming values are integers, and the original types are the
3191     // same.
3192     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3193       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3194       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3195       AddToWorklist(Op.getNode());
3196       return BC;
3197     }
3198   }
3199
3200   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3201   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3202   // If both shuffles use the same mask, and both shuffle within a single
3203   // vector, then it is worthwhile to move the swizzle after the operation.
3204   // The type-legalizer generates this pattern when loading illegal
3205   // vector types from memory. In many cases this allows additional shuffle
3206   // optimizations.
3207   // There are other cases where moving the shuffle after the xor/and/or
3208   // is profitable even if shuffles don't perform a swizzle.
3209   // If both shuffles use the same mask, and both shuffles have the same first
3210   // or second operand, then it might still be profitable to move the shuffle
3211   // after the xor/and/or operation.
3212   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3213     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3214     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3215
3216     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3217            "Inputs to shuffles are not the same type");
3218
3219     // Check that both shuffles use the same mask. The masks are known to be of
3220     // the same length because the result vector type is the same.
3221     // Check also that shuffles have only one use to avoid introducing extra
3222     // instructions.
3223     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3224         SVN0->getMask().equals(SVN1->getMask())) {
3225       SDValue ShOp = N0->getOperand(1);
3226
3227       // Don't try to fold this node if it requires introducing a
3228       // build vector of all zeros that might be illegal at this stage.
3229       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3230         if (!LegalTypes)
3231           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3232         else
3233           ShOp = SDValue();
3234       }
3235
3236       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3237       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3238       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3239       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3240         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3241                                       N0->getOperand(0), N1->getOperand(0));
3242         AddToWorklist(NewNode.getNode());
3243         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3244                                     SVN0->getMask());
3245       }
3246
3247       // Don't try to fold this node if it requires introducing a
3248       // build vector of all zeros that might be illegal at this stage.
3249       ShOp = N0->getOperand(0);
3250       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3251         if (!LegalTypes)
3252           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3253         else
3254           ShOp = SDValue();
3255       }
3256
3257       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3258       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3259       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3260       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3261         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3262                                       N0->getOperand(1), N1->getOperand(1));
3263         AddToWorklist(NewNode.getNode());
3264         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3265                                     SVN0->getMask());
3266       }
3267     }
3268   }
3269
3270   return SDValue();
3271 }
3272
3273 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3274 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3275                                        const SDLoc &DL) {
3276   SDValue LL, LR, RL, RR, N0CC, N1CC;
3277   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3278       !isSetCCEquivalent(N1, RL, RR, N1CC))
3279     return SDValue();
3280
3281   assert(N0.getValueType() == N1.getValueType() &&
3282          "Unexpected operand types for bitwise logic op");
3283   assert(LL.getValueType() == LR.getValueType() &&
3284          RL.getValueType() == RR.getValueType() &&
3285          "Unexpected operand types for setcc");
3286
3287   // If we're here post-legalization or the logic op type is not i1, the logic
3288   // op type must match a setcc result type. Also, all folds require new
3289   // operations on the left and right operands, so those types must match.
3290   EVT VT = N0.getValueType();
3291   EVT OpVT = LL.getValueType();
3292   if (LegalOperations || VT != MVT::i1)
3293     if (VT != getSetCCResultType(OpVT))
3294       return SDValue();
3295   if (OpVT != RL.getValueType())
3296     return SDValue();
3297
3298   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3299   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3300   bool IsInteger = OpVT.isInteger();
3301   if (LR == RR && CC0 == CC1 && IsInteger) {
3302     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3303     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3304
3305     // All bits clear?
3306     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3307     // All sign bits clear?
3308     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3309     // Any bits set?
3310     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3311     // Any sign bits set?
3312     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3313
3314     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3315     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3316     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3317     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3318     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3319       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3320       AddToWorklist(Or.getNode());
3321       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3322     }
3323
3324     // All bits set?
3325     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3326     // All sign bits set?
3327     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3328     // Any bits clear?
3329     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3330     // Any sign bits clear?
3331     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3332
3333     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3334     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3335     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3336     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3337     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3338       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3339       AddToWorklist(And.getNode());
3340       return DAG.getSetCC(DL, VT, And, LR, CC1);
3341     }
3342   }
3343
3344   // TODO: What is the 'or' equivalent of this fold?
3345   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3346   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3347       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3348        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3349     SDValue One = DAG.getConstant(1, DL, OpVT);
3350     SDValue Two = DAG.getConstant(2, DL, OpVT);
3351     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3352     AddToWorklist(Add.getNode());
3353     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3354   }
3355
3356   // Try more general transforms if the predicates match and the only user of
3357   // the compares is the 'and' or 'or'.
3358   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3359       N0.hasOneUse() && N1.hasOneUse()) {
3360     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3361     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3362     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3363       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3364       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3365       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3366       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3367       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3368     }
3369   }
3370
3371   // Canonicalize equivalent operands to LL == RL.
3372   if (LL == RR && LR == RL) {
3373     CC1 = ISD::getSetCCSwappedOperands(CC1);
3374     std::swap(RL, RR);
3375   }
3376
3377   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3378   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3379   if (LL == RL && LR == RR) {
3380     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3381                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3382     if (NewCC != ISD::SETCC_INVALID &&
3383         (!LegalOperations ||
3384          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3385           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3386       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3387   }
3388
3389   return SDValue();
3390 }
3391
3392 /// This contains all DAGCombine rules which reduce two values combined by
3393 /// an And operation to a single value. This makes them reusable in the context
3394 /// of visitSELECT(). Rules involving constants are not included as
3395 /// visitSELECT() already handles those cases.
3396 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3397   EVT VT = N1.getValueType();
3398   SDLoc DL(N);
3399
3400   // fold (and x, undef) -> 0
3401   if (N0.isUndef() || N1.isUndef())
3402     return DAG.getConstant(0, DL, VT);
3403
3404   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3405     return V;
3406
3407   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3408       VT.getSizeInBits() <= 64) {
3409     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3410       APInt ADDC = ADDI->getAPIntValue();
3411       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3412         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3413         // immediate for an add, but it is legal if its top c2 bits are set,
3414         // transform the ADD so the immediate doesn't need to be materialized
3415         // in a register.
3416         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3417           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3418                                              SRLI->getZExtValue());
3419           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3420             ADDC |= Mask;
3421             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3422               SDLoc DL0(N0);
3423               SDValue NewAdd =
3424                 DAG.getNode(ISD::ADD, DL0, VT,
3425                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3426               CombineTo(N0.getNode(), NewAdd);
3427               // Return N so it doesn't get rechecked!
3428               return SDValue(N, 0);
3429             }
3430           }
3431         }
3432       }
3433     }
3434   }
3435
3436   // Reduce bit extract of low half of an integer to the narrower type.
3437   // (and (srl i64:x, K), KMask) ->
3438   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3439   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3440     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3441       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3442         unsigned Size = VT.getSizeInBits();
3443         const APInt &AndMask = CAnd->getAPIntValue();
3444         unsigned ShiftBits = CShift->getZExtValue();
3445
3446         // Bail out, this node will probably disappear anyway.
3447         if (ShiftBits == 0)
3448           return SDValue();
3449
3450         unsigned MaskBits = AndMask.countTrailingOnes();
3451         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3452
3453         if (AndMask.isMask() &&
3454             // Required bits must not span the two halves of the integer and
3455             // must fit in the half size type.
3456             (ShiftBits + MaskBits <= Size / 2) &&
3457             TLI.isNarrowingProfitable(VT, HalfVT) &&
3458             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3459             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3460             TLI.isTruncateFree(VT, HalfVT) &&
3461             TLI.isZExtFree(HalfVT, VT)) {
3462           // The isNarrowingProfitable is to avoid regressions on PPC and
3463           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3464           // on downstream users of this. Those patterns could probably be
3465           // extended to handle extensions mixed in.
3466
3467           SDValue SL(N0);
3468           assert(MaskBits <= Size);
3469
3470           // Extracting the highest bit of the low half.
3471           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3472           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3473                                       N0.getOperand(0));
3474
3475           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3476           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3477           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3478           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3479           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3480         }
3481       }
3482     }
3483   }
3484
3485   return SDValue();
3486 }
3487
3488 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3489                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3490                                    bool &NarrowLoad) {
3491   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3492
3493   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3494     return false;
3495
3496   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3497   LoadedVT = LoadN->getMemoryVT();
3498
3499   if (ExtVT == LoadedVT &&
3500       (!LegalOperations ||
3501        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3502     // ZEXTLOAD will match without needing to change the size of the value being
3503     // loaded.
3504     NarrowLoad = false;
3505     return true;
3506   }
3507
3508   // Do not change the width of a volatile load.
3509   if (LoadN->isVolatile())
3510     return false;
3511
3512   // Do not generate loads of non-round integer types since these can
3513   // be expensive (and would be wrong if the type is not byte sized).
3514   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3515     return false;
3516
3517   if (LegalOperations &&
3518       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3519     return false;
3520
3521   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3522     return false;
3523
3524   NarrowLoad = true;
3525   return true;
3526 }
3527
3528 SDValue DAGCombiner::visitAND(SDNode *N) {
3529   SDValue N0 = N->getOperand(0);
3530   SDValue N1 = N->getOperand(1);
3531   EVT VT = N1.getValueType();
3532
3533   // x & x --> x
3534   if (N0 == N1)
3535     return N0;
3536
3537   // fold vector ops
3538   if (VT.isVector()) {
3539     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3540       return FoldedVOp;
3541
3542     // fold (and x, 0) -> 0, vector edition
3543     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3544       // do not return N0, because undef node may exist in N0
3545       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3546                              SDLoc(N), N0.getValueType());
3547     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3548       // do not return N1, because undef node may exist in N1
3549       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3550                              SDLoc(N), N1.getValueType());
3551
3552     // fold (and x, -1) -> x, vector edition
3553     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3554       return N1;
3555     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3556       return N0;
3557   }
3558
3559   // fold (and c1, c2) -> c1&c2
3560   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3561   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3562   if (N0C && N1C && !N1C->isOpaque())
3563     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3564   // canonicalize constant to RHS
3565   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3566      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3567     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3568   // fold (and x, -1) -> x
3569   if (isAllOnesConstant(N1))
3570     return N0;
3571   // if (and x, c) is known to be zero, return 0
3572   unsigned BitWidth = VT.getScalarSizeInBits();
3573   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3574                                    APInt::getAllOnesValue(BitWidth)))
3575     return DAG.getConstant(0, SDLoc(N), VT);
3576
3577   if (SDValue NewSel = foldBinOpIntoSelect(N))
3578     return NewSel;
3579
3580   // reassociate and
3581   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3582     return RAND;
3583   // fold (and (or x, C), D) -> D if (C & D) == D
3584   if (N1C && N0.getOpcode() == ISD::OR)
3585     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3586       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3587         return N1;
3588   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3589   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3590     SDValue N0Op0 = N0.getOperand(0);
3591     APInt Mask = ~N1C->getAPIntValue();
3592     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3593     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3594       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3595                                  N0.getValueType(), N0Op0);
3596
3597       // Replace uses of the AND with uses of the Zero extend node.
3598       CombineTo(N, Zext);
3599
3600       // We actually want to replace all uses of the any_extend with the
3601       // zero_extend, to avoid duplicating things.  This will later cause this
3602       // AND to be folded.
3603       CombineTo(N0.getNode(), Zext);
3604       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3605     }
3606   }
3607   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3608   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3609   // already be zero by virtue of the width of the base type of the load.
3610   //
3611   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3612   // more cases.
3613   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3614        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3615        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3616        N0.getOperand(0).getResNo() == 0) ||
3617       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3618     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3619                                          N0 : N0.getOperand(0) );
3620
3621     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3622     // This can be a pure constant or a vector splat, in which case we treat the
3623     // vector as a scalar and use the splat value.
3624     APInt Constant = APInt::getNullValue(1);
3625     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3626       Constant = C->getAPIntValue();
3627     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3628       APInt SplatValue, SplatUndef;
3629       unsigned SplatBitSize;
3630       bool HasAnyUndefs;
3631       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3632                                              SplatBitSize, HasAnyUndefs);
3633       if (IsSplat) {
3634         // Undef bits can contribute to a possible optimisation if set, so
3635         // set them.
3636         SplatValue |= SplatUndef;
3637
3638         // The splat value may be something like "0x00FFFFFF", which means 0 for
3639         // the first vector value and FF for the rest, repeating. We need a mask
3640         // that will apply equally to all members of the vector, so AND all the
3641         // lanes of the constant together.
3642         EVT VT = Vector->getValueType(0);
3643         unsigned BitWidth = VT.getScalarSizeInBits();
3644
3645         // If the splat value has been compressed to a bitlength lower
3646         // than the size of the vector lane, we need to re-expand it to
3647         // the lane size.
3648         if (BitWidth > SplatBitSize)
3649           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3650                SplatBitSize < BitWidth;
3651                SplatBitSize = SplatBitSize * 2)
3652             SplatValue |= SplatValue.shl(SplatBitSize);
3653
3654         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3655         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3656         if (SplatBitSize % BitWidth == 0) {
3657           Constant = APInt::getAllOnesValue(BitWidth);
3658           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3659             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3660         }
3661       }
3662     }
3663
3664     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3665     // actually legal and isn't going to get expanded, else this is a false
3666     // optimisation.
3667     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3668                                                     Load->getValueType(0),
3669                                                     Load->getMemoryVT());
3670
3671     // Resize the constant to the same size as the original memory access before
3672     // extension. If it is still the AllOnesValue then this AND is completely
3673     // unneeded.
3674     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3675
3676     bool B;
3677     switch (Load->getExtensionType()) {
3678     default: B = false; break;
3679     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3680     case ISD::ZEXTLOAD:
3681     case ISD::NON_EXTLOAD: B = true; break;
3682     }
3683
3684     if (B && Constant.isAllOnesValue()) {
3685       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3686       // preserve semantics once we get rid of the AND.
3687       SDValue NewLoad(Load, 0);
3688
3689       // Fold the AND away. NewLoad may get replaced immediately.
3690       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3691
3692       if (Load->getExtensionType() == ISD::EXTLOAD) {
3693         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3694                               Load->getValueType(0), SDLoc(Load),
3695                               Load->getChain(), Load->getBasePtr(),
3696                               Load->getOffset(), Load->getMemoryVT(),
3697                               Load->getMemOperand());
3698         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3699         if (Load->getNumValues() == 3) {
3700           // PRE/POST_INC loads have 3 values.
3701           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3702                            NewLoad.getValue(2) };
3703           CombineTo(Load, To, 3, true);
3704         } else {
3705           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3706         }
3707       }
3708
3709       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3710     }
3711   }
3712
3713   // fold (and (load x), 255) -> (zextload x, i8)
3714   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3715   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3716   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3717                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3718                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3719     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3720     LoadSDNode *LN0 = HasAnyExt
3721       ? cast<LoadSDNode>(N0.getOperand(0))
3722       : cast<LoadSDNode>(N0);
3723     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3724         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3725       auto NarrowLoad = false;
3726       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3727       EVT ExtVT, LoadedVT;
3728       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3729                            NarrowLoad)) {
3730         if (!NarrowLoad) {
3731           SDValue NewLoad =
3732             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3733                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3734                            LN0->getMemOperand());
3735           AddToWorklist(N);
3736           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3737           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3738         } else {
3739           EVT PtrType = LN0->getOperand(1).getValueType();
3740
3741           unsigned Alignment = LN0->getAlignment();
3742           SDValue NewPtr = LN0->getBasePtr();
3743
3744           // For big endian targets, we need to add an offset to the pointer
3745           // to load the correct bytes.  For little endian systems, we merely
3746           // need to read fewer bytes from the same pointer.
3747           if (DAG.getDataLayout().isBigEndian()) {
3748             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3749             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3750             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3751             SDLoc DL(LN0);
3752             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3753                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3754             Alignment = MinAlign(Alignment, PtrOff);
3755           }
3756
3757           AddToWorklist(NewPtr.getNode());
3758
3759           SDValue Load = DAG.getExtLoad(
3760               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3761               LN0->getPointerInfo(), ExtVT, Alignment,
3762               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3763           AddToWorklist(N);
3764           CombineTo(LN0, Load, Load.getValue(1));
3765           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3766         }
3767       }
3768     }
3769   }
3770
3771   if (SDValue Combined = visitANDLike(N0, N1, N))
3772     return Combined;
3773
3774   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3775   if (N0.getOpcode() == N1.getOpcode())
3776     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3777       return Tmp;
3778
3779   // Masking the negated extension of a boolean is just the zero-extended
3780   // boolean:
3781   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3782   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3783   //
3784   // Note: the SimplifyDemandedBits fold below can make an information-losing
3785   // transform, and then we have no way to find this better fold.
3786   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3787     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3788     SDValue SubRHS = N0.getOperand(1);
3789     if (SubLHS && SubLHS->isNullValue()) {
3790       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3791           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3792         return SubRHS;
3793       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3794           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3795         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3796     }
3797   }
3798
3799   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3800   // fold (and (sra)) -> (and (srl)) when possible.
3801   if (SimplifyDemandedBits(SDValue(N, 0)))
3802     return SDValue(N, 0);
3803
3804   // fold (zext_inreg (extload x)) -> (zextload x)
3805   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3806     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3807     EVT MemVT = LN0->getMemoryVT();
3808     // If we zero all the possible extended bits, then we can turn this into
3809     // a zextload if we are running before legalize or the operation is legal.
3810     unsigned BitWidth = N1.getScalarValueSizeInBits();
3811     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3812                            BitWidth - MemVT.getScalarSizeInBits())) &&
3813         ((!LegalOperations && !LN0->isVolatile()) ||
3814          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3815       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3816                                        LN0->getChain(), LN0->getBasePtr(),
3817                                        MemVT, LN0->getMemOperand());
3818       AddToWorklist(N);
3819       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3820       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3821     }
3822   }
3823   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3824   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3825       N0.hasOneUse()) {
3826     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3827     EVT MemVT = LN0->getMemoryVT();
3828     // If we zero all the possible extended bits, then we can turn this into
3829     // a zextload if we are running before legalize or the operation is legal.
3830     unsigned BitWidth = N1.getScalarValueSizeInBits();
3831     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3832                            BitWidth - MemVT.getScalarSizeInBits())) &&
3833         ((!LegalOperations && !LN0->isVolatile()) ||
3834          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3835       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3836                                        LN0->getChain(), LN0->getBasePtr(),
3837                                        MemVT, LN0->getMemOperand());
3838       AddToWorklist(N);
3839       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3840       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3841     }
3842   }
3843   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3844   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3845     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3846                                            N0.getOperand(1), false))
3847       return BSwap;
3848   }
3849
3850   return SDValue();
3851 }
3852
3853 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3854 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3855                                         bool DemandHighBits) {
3856   if (!LegalOperations)
3857     return SDValue();
3858
3859   EVT VT = N->getValueType(0);
3860   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3861     return SDValue();
3862   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3863     return SDValue();
3864
3865   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3866   bool LookPassAnd0 = false;
3867   bool LookPassAnd1 = false;
3868   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3869       std::swap(N0, N1);
3870   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3871       std::swap(N0, N1);
3872   if (N0.getOpcode() == ISD::AND) {
3873     if (!N0.getNode()->hasOneUse())
3874       return SDValue();
3875     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3876     if (!N01C || N01C->getZExtValue() != 0xFF00)
3877       return SDValue();
3878     N0 = N0.getOperand(0);
3879     LookPassAnd0 = true;
3880   }
3881
3882   if (N1.getOpcode() == ISD::AND) {
3883     if (!N1.getNode()->hasOneUse())
3884       return SDValue();
3885     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3886     if (!N11C || N11C->getZExtValue() != 0xFF)
3887       return SDValue();
3888     N1 = N1.getOperand(0);
3889     LookPassAnd1 = true;
3890   }
3891
3892   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3893     std::swap(N0, N1);
3894   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3895     return SDValue();
3896   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3897     return SDValue();
3898
3899   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3900   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3901   if (!N01C || !N11C)
3902     return SDValue();
3903   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3904     return SDValue();
3905
3906   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3907   SDValue N00 = N0->getOperand(0);
3908   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3909     if (!N00.getNode()->hasOneUse())
3910       return SDValue();
3911     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3912     if (!N001C || N001C->getZExtValue() != 0xFF)
3913       return SDValue();
3914     N00 = N00.getOperand(0);
3915     LookPassAnd0 = true;
3916   }
3917
3918   SDValue N10 = N1->getOperand(0);
3919   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3920     if (!N10.getNode()->hasOneUse())
3921       return SDValue();
3922     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3923     if (!N101C || N101C->getZExtValue() != 0xFF00)
3924       return SDValue();
3925     N10 = N10.getOperand(0);
3926     LookPassAnd1 = true;
3927   }
3928
3929   if (N00 != N10)
3930     return SDValue();
3931
3932   // Make sure everything beyond the low halfword gets set to zero since the SRL
3933   // 16 will clear the top bits.
3934   unsigned OpSizeInBits = VT.getSizeInBits();
3935   if (DemandHighBits && OpSizeInBits > 16) {
3936     // If the left-shift isn't masked out then the only way this is a bswap is
3937     // if all bits beyond the low 8 are 0. In that case the entire pattern
3938     // reduces to a left shift anyway: leave it for other parts of the combiner.
3939     if (!LookPassAnd0)
3940       return SDValue();
3941
3942     // However, if the right shift isn't masked out then it might be because
3943     // it's not needed. See if we can spot that too.
3944     if (!LookPassAnd1 &&
3945         !DAG.MaskedValueIsZero(
3946             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3947       return SDValue();
3948   }
3949
3950   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3951   if (OpSizeInBits > 16) {
3952     SDLoc DL(N);
3953     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3954                       DAG.getConstant(OpSizeInBits - 16, DL,
3955                                       getShiftAmountTy(VT)));
3956   }
3957   return Res;
3958 }
3959
3960 /// Return true if the specified node is an element that makes up a 32-bit
3961 /// packed halfword byteswap.
3962 /// ((x & 0x000000ff) << 8) |
3963 /// ((x & 0x0000ff00) >> 8) |
3964 /// ((x & 0x00ff0000) << 8) |
3965 /// ((x & 0xff000000) >> 8)
3966 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3967   if (!N.getNode()->hasOneUse())
3968     return false;
3969
3970   unsigned Opc = N.getOpcode();
3971   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3972     return false;
3973
3974   SDValue N0 = N.getOperand(0);
3975   unsigned Opc0 = N0.getOpcode();
3976   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
3977     return false;
3978
3979   ConstantSDNode *N1C = nullptr;
3980   // SHL or SRL: look upstream for AND mask operand
3981   if (Opc == ISD::AND)
3982     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3983   else if (Opc0 == ISD::AND)
3984     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3985   if (!N1C)
3986     return false;
3987
3988   unsigned MaskByteOffset;
3989   switch (N1C->getZExtValue()) {
3990   default:
3991     return false;
3992   case 0xFF:       MaskByteOffset = 0; break;
3993   case 0xFF00:     MaskByteOffset = 1; break;
3994   case 0xFF0000:   MaskByteOffset = 2; break;
3995   case 0xFF000000: MaskByteOffset = 3; break;
3996   }
3997
3998   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3999   if (Opc == ISD::AND) {
4000     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4001       // (x >> 8) & 0xff
4002       // (x >> 8) & 0xff0000
4003       if (Opc0 != ISD::SRL)
4004         return false;
4005       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4006       if (!C || C->getZExtValue() != 8)
4007         return false;
4008     } else {
4009       // (x << 8) & 0xff00
4010       // (x << 8) & 0xff000000
4011       if (Opc0 != ISD::SHL)
4012         return false;
4013       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4014       if (!C || C->getZExtValue() != 8)
4015         return false;
4016     }
4017   } else if (Opc == ISD::SHL) {
4018     // (x & 0xff) << 8
4019     // (x & 0xff0000) << 8
4020     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4021       return false;
4022     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4023     if (!C || C->getZExtValue() != 8)
4024       return false;
4025   } else { // Opc == ISD::SRL
4026     // (x & 0xff00) >> 8
4027     // (x & 0xff000000) >> 8
4028     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4029       return false;
4030     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4031     if (!C || C->getZExtValue() != 8)
4032       return false;
4033   }
4034
4035   if (Parts[MaskByteOffset])
4036     return false;
4037
4038   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4039   return true;
4040 }
4041
4042 /// Match a 32-bit packed halfword bswap. That is
4043 /// ((x & 0x000000ff) << 8) |
4044 /// ((x & 0x0000ff00) >> 8) |
4045 /// ((x & 0x00ff0000) << 8) |
4046 /// ((x & 0xff000000) >> 8)
4047 /// => (rotl (bswap x), 16)
4048 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4049   if (!LegalOperations)
4050     return SDValue();
4051
4052   EVT VT = N->getValueType(0);
4053   if (VT != MVT::i32)
4054     return SDValue();
4055   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4056     return SDValue();
4057
4058   // Look for either
4059   // (or (or (and), (and)), (or (and), (and)))
4060   // (or (or (or (and), (and)), (and)), (and))
4061   if (N0.getOpcode() != ISD::OR)
4062     return SDValue();
4063   SDValue N00 = N0.getOperand(0);
4064   SDValue N01 = N0.getOperand(1);
4065   SDNode *Parts[4] = {};
4066
4067   if (N1.getOpcode() == ISD::OR &&
4068       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4069     // (or (or (and), (and)), (or (and), (and)))
4070     if (!isBSwapHWordElement(N00, Parts))
4071       return SDValue();
4072
4073     if (!isBSwapHWordElement(N01, Parts))
4074       return SDValue();
4075     SDValue N10 = N1.getOperand(0);
4076     if (!isBSwapHWordElement(N10, Parts))
4077       return SDValue();
4078     SDValue N11 = N1.getOperand(1);
4079     if (!isBSwapHWordElement(N11, Parts))
4080       return SDValue();
4081   } else {
4082     // (or (or (or (and), (and)), (and)), (and))
4083     if (!isBSwapHWordElement(N1, Parts))
4084       return SDValue();
4085     if (!isBSwapHWordElement(N01, Parts))
4086       return SDValue();
4087     if (N00.getOpcode() != ISD::OR)
4088       return SDValue();
4089     SDValue N000 = N00.getOperand(0);
4090     if (!isBSwapHWordElement(N000, Parts))
4091       return SDValue();
4092     SDValue N001 = N00.getOperand(1);
4093     if (!isBSwapHWordElement(N001, Parts))
4094       return SDValue();
4095   }
4096
4097   // Make sure the parts are all coming from the same node.
4098   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4099     return SDValue();
4100
4101   SDLoc DL(N);
4102   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4103                               SDValue(Parts[0], 0));
4104
4105   // Result of the bswap should be rotated by 16. If it's not legal, then
4106   // do  (x << 16) | (x >> 16).
4107   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4108   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4109     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4110   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4111     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4112   return DAG.getNode(ISD::OR, DL, VT,
4113                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4114                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4115 }
4116
4117 /// This contains all DAGCombine rules which reduce two values combined by
4118 /// an Or operation to a single value \see visitANDLike().
4119 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4120   EVT VT = N1.getValueType();
4121   SDLoc DL(N);
4122
4123   // fold (or x, undef) -> -1
4124   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4125     return DAG.getAllOnesConstant(DL, VT);
4126
4127   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4128     return V;
4129
4130   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4131   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4132       // Don't increase # computations.
4133       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4134     // We can only do this xform if we know that bits from X that are set in C2
4135     // but not in C1 are already zero.  Likewise for Y.
4136     if (const ConstantSDNode *N0O1C =
4137         getAsNonOpaqueConstant(N0.getOperand(1))) {
4138       if (const ConstantSDNode *N1O1C =
4139           getAsNonOpaqueConstant(N1.getOperand(1))) {
4140         // We can only do this xform if we know that bits from X that are set in
4141         // C2 but not in C1 are already zero.  Likewise for Y.
4142         const APInt &LHSMask = N0O1C->getAPIntValue();
4143         const APInt &RHSMask = N1O1C->getAPIntValue();
4144
4145         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4146             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4147           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4148                                   N0.getOperand(0), N1.getOperand(0));
4149           return DAG.getNode(ISD::AND, DL, VT, X,
4150                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4151         }
4152       }
4153     }
4154   }
4155
4156   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4157   if (N0.getOpcode() == ISD::AND &&
4158       N1.getOpcode() == ISD::AND &&
4159       N0.getOperand(0) == N1.getOperand(0) &&
4160       // Don't increase # computations.
4161       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4162     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4163                             N0.getOperand(1), N1.getOperand(1));
4164     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4165   }
4166
4167   return SDValue();
4168 }
4169
4170 SDValue DAGCombiner::visitOR(SDNode *N) {
4171   SDValue N0 = N->getOperand(0);
4172   SDValue N1 = N->getOperand(1);
4173   EVT VT = N1.getValueType();
4174
4175   // x | x --> x
4176   if (N0 == N1)
4177     return N0;
4178
4179   // fold vector ops
4180   if (VT.isVector()) {
4181     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4182       return FoldedVOp;
4183
4184     // fold (or x, 0) -> x, vector edition
4185     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4186       return N1;
4187     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4188       return N0;
4189
4190     // fold (or x, -1) -> -1, vector edition
4191     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4192       // do not return N0, because undef node may exist in N0
4193       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4194     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4195       // do not return N1, because undef node may exist in N1
4196       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4197
4198     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4199     // Do this only if the resulting shuffle is legal.
4200     if (isa<ShuffleVectorSDNode>(N0) &&
4201         isa<ShuffleVectorSDNode>(N1) &&
4202         // Avoid folding a node with illegal type.
4203         TLI.isTypeLegal(VT)) {
4204       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4205       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4206       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4207       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4208       // Ensure both shuffles have a zero input.
4209       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4210         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4211         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4212         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4213         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4214         bool CanFold = true;
4215         int NumElts = VT.getVectorNumElements();
4216         SmallVector<int, 4> Mask(NumElts);
4217
4218         for (int i = 0; i != NumElts; ++i) {
4219           int M0 = SV0->getMaskElt(i);
4220           int M1 = SV1->getMaskElt(i);
4221
4222           // Determine if either index is pointing to a zero vector.
4223           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4224           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4225
4226           // If one element is zero and the otherside is undef, keep undef.
4227           // This also handles the case that both are undef.
4228           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4229             Mask[i] = -1;
4230             continue;
4231           }
4232
4233           // Make sure only one of the elements is zero.
4234           if (M0Zero == M1Zero) {
4235             CanFold = false;
4236             break;
4237           }
4238
4239           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4240
4241           // We have a zero and non-zero element. If the non-zero came from
4242           // SV0 make the index a LHS index. If it came from SV1, make it
4243           // a RHS index. We need to mod by NumElts because we don't care
4244           // which operand it came from in the original shuffles.
4245           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4246         }
4247
4248         if (CanFold) {
4249           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4250           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4251
4252           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4253           if (!LegalMask) {
4254             std::swap(NewLHS, NewRHS);
4255             ShuffleVectorSDNode::commuteMask(Mask);
4256             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4257           }
4258
4259           if (LegalMask)
4260             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4261         }
4262       }
4263     }
4264   }
4265
4266   // fold (or c1, c2) -> c1|c2
4267   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4268   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4269   if (N0C && N1C && !N1C->isOpaque())
4270     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4271   // canonicalize constant to RHS
4272   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4273      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4274     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4275   // fold (or x, 0) -> x
4276   if (isNullConstant(N1))
4277     return N0;
4278   // fold (or x, -1) -> -1
4279   if (isAllOnesConstant(N1))
4280     return N1;
4281
4282   if (SDValue NewSel = foldBinOpIntoSelect(N))
4283     return NewSel;
4284
4285   // fold (or x, c) -> c iff (x & ~c) == 0
4286   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4287     return N1;
4288
4289   if (SDValue Combined = visitORLike(N0, N1, N))
4290     return Combined;
4291
4292   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4293   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4294     return BSwap;
4295   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4296     return BSwap;
4297
4298   // reassociate or
4299   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4300     return ROR;
4301
4302   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4303   // iff (c1 & c2) != 0.
4304   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4305     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4306       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4307         if (SDValue COR =
4308                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4309           return DAG.getNode(
4310               ISD::AND, SDLoc(N), VT,
4311               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4312         return SDValue();
4313       }
4314     }
4315   }
4316
4317   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4318   if (N0.getOpcode() == N1.getOpcode())
4319     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4320       return Tmp;
4321
4322   // See if this is some rotate idiom.
4323   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4324     return SDValue(Rot, 0);
4325
4326   if (SDValue Load = MatchLoadCombine(N))
4327     return Load;
4328
4329   // Simplify the operands using demanded-bits information.
4330   if (SimplifyDemandedBits(SDValue(N, 0)))
4331     return SDValue(N, 0);
4332
4333   return SDValue();
4334 }
4335
4336 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4337 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4338   if (Op.getOpcode() == ISD::AND) {
4339     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4340       Mask = Op.getOperand(1);
4341       Op = Op.getOperand(0);
4342     } else {
4343       return false;
4344     }
4345   }
4346
4347   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4348     Shift = Op;
4349     return true;
4350   }
4351
4352   return false;
4353 }
4354
4355 // Return true if we can prove that, whenever Neg and Pos are both in the
4356 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4357 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4358 //
4359 //     (or (shift1 X, Neg), (shift2 X, Pos))
4360 //
4361 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4362 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4363 // to consider shift amounts with defined behavior.
4364 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4365   // If EltSize is a power of 2 then:
4366   //
4367   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4368   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4369   //
4370   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4371   // for the stronger condition:
4372   //
4373   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4374   //
4375   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4376   // we can just replace Neg with Neg' for the rest of the function.
4377   //
4378   // In other cases we check for the even stronger condition:
4379   //
4380   //     Neg == EltSize - Pos                                    [B]
4381   //
4382   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4383   // behavior if Pos == 0 (and consequently Neg == EltSize).
4384   //
4385   // We could actually use [A] whenever EltSize is a power of 2, but the
4386   // only extra cases that it would match are those uninteresting ones
4387   // where Neg and Pos are never in range at the same time.  E.g. for
4388   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4389   // as well as (sub 32, Pos), but:
4390   //
4391   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4392   //
4393   // always invokes undefined behavior for 32-bit X.
4394   //
4395   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4396   unsigned MaskLoBits = 0;
4397   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4398     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4399       if (NegC->getAPIntValue() == EltSize - 1) {
4400         Neg = Neg.getOperand(0);
4401         MaskLoBits = Log2_64(EltSize);
4402       }
4403     }
4404   }
4405
4406   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4407   if (Neg.getOpcode() != ISD::SUB)
4408     return false;
4409   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4410   if (!NegC)
4411     return false;
4412   SDValue NegOp1 = Neg.getOperand(1);
4413
4414   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4415   // Pos'.  The truncation is redundant for the purpose of the equality.
4416   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4417     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4418       if (PosC->getAPIntValue() == EltSize - 1)
4419         Pos = Pos.getOperand(0);
4420
4421   // The condition we need is now:
4422   //
4423   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4424   //
4425   // If NegOp1 == Pos then we need:
4426   //
4427   //              EltSize & Mask == NegC & Mask
4428   //
4429   // (because "x & Mask" is a truncation and distributes through subtraction).
4430   APInt Width;
4431   if (Pos == NegOp1)
4432     Width = NegC->getAPIntValue();
4433
4434   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4435   // Then the condition we want to prove becomes:
4436   //
4437   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4438   //
4439   // which, again because "x & Mask" is a truncation, becomes:
4440   //
4441   //                NegC & Mask == (EltSize - PosC) & Mask
4442   //             EltSize & Mask == (NegC + PosC) & Mask
4443   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4444     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4445       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4446     else
4447       return false;
4448   } else
4449     return false;
4450
4451   // Now we just need to check that EltSize & Mask == Width & Mask.
4452   if (MaskLoBits)
4453     // EltSize & Mask is 0 since Mask is EltSize - 1.
4454     return Width.getLoBits(MaskLoBits) == 0;
4455   return Width == EltSize;
4456 }
4457
4458 // A subroutine of MatchRotate used once we have found an OR of two opposite
4459 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4460 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4461 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4462 // Neg with outer conversions stripped away.
4463 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4464                                        SDValue Neg, SDValue InnerPos,
4465                                        SDValue InnerNeg, unsigned PosOpcode,
4466                                        unsigned NegOpcode, const SDLoc &DL) {
4467   // fold (or (shl x, (*ext y)),
4468   //          (srl x, (*ext (sub 32, y)))) ->
4469   //   (rotl x, y) or (rotr x, (sub 32, y))
4470   //
4471   // fold (or (shl x, (*ext (sub 32, y))),
4472   //          (srl x, (*ext y))) ->
4473   //   (rotr x, y) or (rotl x, (sub 32, y))
4474   EVT VT = Shifted.getValueType();
4475   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4476     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4477     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4478                        HasPos ? Pos : Neg).getNode();
4479   }
4480
4481   return nullptr;
4482 }
4483
4484 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4485 // idioms for rotate, and if the target supports rotation instructions, generate
4486 // a rot[lr].
4487 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4488   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4489   EVT VT = LHS.getValueType();
4490   if (!TLI.isTypeLegal(VT)) return nullptr;
4491
4492   // The target must have at least one rotate flavor.
4493   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4494   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4495   if (!HasROTL && !HasROTR) return nullptr;
4496
4497   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4498   SDValue LHSShift;   // The shift.
4499   SDValue LHSMask;    // AND value if any.
4500   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4501     return nullptr; // Not part of a rotate.
4502
4503   SDValue RHSShift;   // The shift.
4504   SDValue RHSMask;    // AND value if any.
4505   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4506     return nullptr; // Not part of a rotate.
4507
4508   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4509     return nullptr;   // Not shifting the same value.
4510
4511   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4512     return nullptr;   // Shifts must disagree.
4513
4514   // Canonicalize shl to left side in a shl/srl pair.
4515   if (RHSShift.getOpcode() == ISD::SHL) {
4516     std::swap(LHS, RHS);
4517     std::swap(LHSShift, RHSShift);
4518     std::swap(LHSMask, RHSMask);
4519   }
4520
4521   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4522   SDValue LHSShiftArg = LHSShift.getOperand(0);
4523   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4524   SDValue RHSShiftArg = RHSShift.getOperand(0);
4525   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4526
4527   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4528   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4529   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4530     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4531     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4532     if ((LShVal + RShVal) != EltSizeInBits)
4533       return nullptr;
4534
4535     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4536                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4537
4538     // If there is an AND of either shifted operand, apply it to the result.
4539     if (LHSMask.getNode() || RHSMask.getNode()) {
4540       SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4541
4542       if (LHSMask.getNode()) {
4543         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4544         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4545                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4546                                        DAG.getConstant(RHSBits, DL, VT)));
4547       }
4548       if (RHSMask.getNode()) {
4549         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4550         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4551                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4552                                        DAG.getConstant(LHSBits, DL, VT)));
4553       }
4554
4555       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4556     }
4557
4558     return Rot.getNode();
4559   }
4560
4561   // If there is a mask here, and we have a variable shift, we can't be sure
4562   // that we're masking out the right stuff.
4563   if (LHSMask.getNode() || RHSMask.getNode())
4564     return nullptr;
4565
4566   // If the shift amount is sign/zext/any-extended just peel it off.
4567   SDValue LExtOp0 = LHSShiftAmt;
4568   SDValue RExtOp0 = RHSShiftAmt;
4569   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4570        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4571        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4572        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4573       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4574        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4575        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4576        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4577     LExtOp0 = LHSShiftAmt.getOperand(0);
4578     RExtOp0 = RHSShiftAmt.getOperand(0);
4579   }
4580
4581   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4582                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4583   if (TryL)
4584     return TryL;
4585
4586   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4587                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4588   if (TryR)
4589     return TryR;
4590
4591   return nullptr;
4592 }
4593
4594 namespace {
4595 /// Helper struct to parse and store a memory address as base + index + offset.
4596 /// We ignore sign extensions when it is safe to do so.
4597 /// The following two expressions are not equivalent. To differentiate we need
4598 /// to store whether there was a sign extension involved in the index
4599 /// computation.
4600 ///  (load (i64 add (i64 copyfromreg %c)
4601 ///                 (i64 signextend (add (i8 load %index)
4602 ///                                      (i8 1))))
4603 /// vs
4604 ///
4605 /// (load (i64 add (i64 copyfromreg %c)
4606 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
4607 ///                                         (i32 1)))))
4608 struct BaseIndexOffset {
4609   SDValue Base;
4610   SDValue Index;
4611   int64_t Offset;
4612   bool IsIndexSignExt;
4613
4614   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4615
4616   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4617                   bool IsIndexSignExt) :
4618     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4619
4620   bool equalBaseIndex(const BaseIndexOffset &Other) {
4621     return Other.Base == Base && Other.Index == Index &&
4622       Other.IsIndexSignExt == IsIndexSignExt;
4623   }
4624
4625   /// Parses tree in Ptr for base, index, offset addresses.
4626   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4627                                int64_t PartialOffset = 0) {
4628     bool IsIndexSignExt = false;
4629
4630     // Split up a folded GlobalAddress+Offset into its component parts.
4631     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4632       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4633         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4634                                                     SDLoc(GA),
4635                                                     GA->getValueType(0),
4636                                                     /*Offset=*/PartialOffset,
4637                                                     /*isTargetGA=*/false,
4638                                                     GA->getTargetFlags()),
4639                                SDValue(),
4640                                GA->getOffset(),
4641                                IsIndexSignExt);
4642       }
4643
4644     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4645     // instruction, then it could be just the BASE or everything else we don't
4646     // know how to handle. Just use Ptr as BASE and give up.
4647     if (Ptr->getOpcode() != ISD::ADD)
4648       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4649
4650     // We know that we have at least an ADD instruction. Try to pattern match
4651     // the simple case of BASE + OFFSET.
4652     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4653       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4654       return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4655     }
4656
4657     // Inside a loop the current BASE pointer is calculated using an ADD and a
4658     // MUL instruction. In this case Ptr is the actual BASE pointer.
4659     // (i64 add (i64 %array_ptr)
4660     //          (i64 mul (i64 %induction_var)
4661     //                   (i64 %element_size)))
4662     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4663       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4664
4665     // Look at Base + Index + Offset cases.
4666     SDValue Base = Ptr->getOperand(0);
4667     SDValue IndexOffset = Ptr->getOperand(1);
4668
4669     // Skip signextends.
4670     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4671       IndexOffset = IndexOffset->getOperand(0);
4672       IsIndexSignExt = true;
4673     }
4674
4675     // Either the case of Base + Index (no offset) or something else.
4676     if (IndexOffset->getOpcode() != ISD::ADD)
4677       return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4678
4679     // Now we have the case of Base + Index + offset.
4680     SDValue Index = IndexOffset->getOperand(0);
4681     SDValue Offset = IndexOffset->getOperand(1);
4682
4683     if (!isa<ConstantSDNode>(Offset))
4684       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4685
4686     // Ignore signextends.
4687     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4688       Index = Index->getOperand(0);
4689       IsIndexSignExt = true;
4690     } else IsIndexSignExt = false;
4691
4692     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4693     return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4694   }
4695 };
4696 } // namespace
4697
4698 namespace {
4699 /// Represents known origin of an individual byte in load combine pattern. The
4700 /// value of the byte is either constant zero or comes from memory.
4701 struct ByteProvider {
4702   // For constant zero providers Load is set to nullptr. For memory providers
4703   // Load represents the node which loads the byte from memory.
4704   // ByteOffset is the offset of the byte in the value produced by the load.
4705   LoadSDNode *Load;
4706   unsigned ByteOffset;
4707
4708   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4709
4710   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4711     return ByteProvider(Load, ByteOffset);
4712   }
4713   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4714
4715   bool isConstantZero() const { return !Load; }
4716   bool isMemory() const { return Load; }
4717
4718   bool operator==(const ByteProvider &Other) const {
4719     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4720   }
4721
4722 private:
4723   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4724       : Load(Load), ByteOffset(ByteOffset) {}
4725 };
4726
4727 /// Recursively traverses the expression calculating the origin of the requested
4728 /// byte of the given value. Returns None if the provider can't be calculated.
4729 ///
4730 /// For all the values except the root of the expression verifies that the value
4731 /// has exactly one use and if it's not true return None. This way if the origin
4732 /// of the byte is returned it's guaranteed that the values which contribute to
4733 /// the byte are not used outside of this expression.
4734 ///
4735 /// Because the parts of the expression are not allowed to have more than one
4736 /// use this function iterates over trees, not DAGs. So it never visits the same
4737 /// node more than once.
4738 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4739                                                    unsigned Depth,
4740                                                    bool Root = false) {
4741   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4742   if (Depth == 10)
4743     return None;
4744
4745   if (!Root && !Op.hasOneUse())
4746     return None;
4747
4748   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4749   unsigned BitWidth = Op.getValueSizeInBits();
4750   if (BitWidth % 8 != 0)
4751     return None;
4752   unsigned ByteWidth = BitWidth / 8;
4753   assert(Index < ByteWidth && "invalid index requested");
4754   (void) ByteWidth;
4755
4756   switch (Op.getOpcode()) {
4757   case ISD::OR: {
4758     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4759     if (!LHS)
4760       return None;
4761     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4762     if (!RHS)
4763       return None;
4764
4765     if (LHS->isConstantZero())
4766       return RHS;
4767     if (RHS->isConstantZero())
4768       return LHS;
4769     return None;
4770   }
4771   case ISD::SHL: {
4772     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4773     if (!ShiftOp)
4774       return None;
4775
4776     uint64_t BitShift = ShiftOp->getZExtValue();
4777     if (BitShift % 8 != 0)
4778       return None;
4779     uint64_t ByteShift = BitShift / 8;
4780
4781     return Index < ByteShift
4782                ? ByteProvider::getConstantZero()
4783                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4784                                        Depth + 1);
4785   }
4786   case ISD::ANY_EXTEND:
4787   case ISD::SIGN_EXTEND:
4788   case ISD::ZERO_EXTEND: {
4789     SDValue NarrowOp = Op->getOperand(0);
4790     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4791     if (NarrowBitWidth % 8 != 0)
4792       return None;
4793     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4794
4795     if (Index >= NarrowByteWidth)
4796       return Op.getOpcode() == ISD::ZERO_EXTEND
4797                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4798                  : None;
4799     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4800   }
4801   case ISD::BSWAP:
4802     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4803                                  Depth + 1);
4804   case ISD::LOAD: {
4805     auto L = cast<LoadSDNode>(Op.getNode());
4806     if (L->isVolatile() || L->isIndexed())
4807       return None;
4808
4809     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4810     if (NarrowBitWidth % 8 != 0)
4811       return None;
4812     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4813
4814     if (Index >= NarrowByteWidth)
4815       return L->getExtensionType() == ISD::ZEXTLOAD
4816                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4817                  : None;
4818     return ByteProvider::getMemory(L, Index);
4819   }
4820   }
4821
4822   return None;
4823 }
4824 } // namespace
4825
4826 /// Match a pattern where a wide type scalar value is loaded by several narrow
4827 /// loads and combined by shifts and ors. Fold it into a single load or a load
4828 /// and a BSWAP if the targets supports it.
4829 ///
4830 /// Assuming little endian target:
4831 ///  i8 *a = ...
4832 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4833 /// =>
4834 ///  i32 val = *((i32)a)
4835 ///
4836 ///  i8 *a = ...
4837 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4838 /// =>
4839 ///  i32 val = BSWAP(*((i32)a))
4840 ///
4841 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4842 /// interact well with the worklist mechanism. When a part of the pattern is
4843 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4844 /// but the root node of the pattern which triggers the load combine is not
4845 /// necessarily a direct user of the changed node. For example, once the address
4846 /// of t28 load is reassociated load combine won't be triggered:
4847 ///             t25: i32 = add t4, Constant:i32<2>
4848 ///           t26: i64 = sign_extend t25
4849 ///        t27: i64 = add t2, t26
4850 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4851 ///     t29: i32 = zero_extend t28
4852 ///   t32: i32 = shl t29, Constant:i8<8>
4853 /// t33: i32 = or t23, t32
4854 /// As a possible fix visitLoad can check if the load can be a part of a load
4855 /// combine pattern and add corresponding OR roots to the worklist.
4856 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4857   assert(N->getOpcode() == ISD::OR &&
4858          "Can only match load combining against OR nodes");
4859
4860   // Handles simple types only
4861   EVT VT = N->getValueType(0);
4862   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4863     return SDValue();
4864   unsigned ByteWidth = VT.getSizeInBits() / 8;
4865
4866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4867   // Before legalize we can introduce too wide illegal loads which will be later
4868   // split into legal sized loads. This enables us to combine i64 load by i8
4869   // patterns to a couple of i32 loads on 32 bit targets.
4870   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4871     return SDValue();
4872
4873   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4874     unsigned BW, unsigned i) { return i; };
4875   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4876     unsigned BW, unsigned i) { return BW - i - 1; };
4877
4878   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4879   auto MemoryByteOffset = [&] (ByteProvider P) {
4880     assert(P.isMemory() && "Must be a memory byte provider");
4881     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4882     assert(LoadBitWidth % 8 == 0 &&
4883            "can only analyze providers for individual bytes not bit");
4884     unsigned LoadByteWidth = LoadBitWidth / 8;
4885     return IsBigEndianTarget
4886             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4887             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4888   };
4889
4890   Optional<BaseIndexOffset> Base;
4891   SDValue Chain;
4892
4893   SmallSet<LoadSDNode *, 8> Loads;
4894   Optional<ByteProvider> FirstByteProvider;
4895   int64_t FirstOffset = INT64_MAX;
4896
4897   // Check if all the bytes of the OR we are looking at are loaded from the same
4898   // base address. Collect bytes offsets from Base address in ByteOffsets.
4899   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4900   for (unsigned i = 0; i < ByteWidth; i++) {
4901     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4902     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4903       return SDValue();
4904
4905     LoadSDNode *L = P->Load;
4906     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4907            "Must be enforced by calculateByteProvider");
4908     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4909
4910     // All loads must share the same chain
4911     SDValue LChain = L->getChain();
4912     if (!Chain)
4913       Chain = LChain;
4914     else if (Chain != LChain)
4915       return SDValue();
4916
4917     // Loads must share the same base address
4918     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4919     if (!Base)
4920       Base = Ptr;
4921     else if (!Base->equalBaseIndex(Ptr))
4922       return SDValue();
4923
4924     // Calculate the offset of the current byte from the base address
4925     int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
4926     ByteOffsets[i] = ByteOffsetFromBase;
4927
4928     // Remember the first byte load
4929     if (ByteOffsetFromBase < FirstOffset) {
4930       FirstByteProvider = P;
4931       FirstOffset = ByteOffsetFromBase;
4932     }
4933
4934     Loads.insert(L);
4935   }
4936   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4937          "memory, so there must be at least one load which produces the value");
4938   assert(Base && "Base address of the accessed memory location must be set");
4939   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4940
4941   // Check if the bytes of the OR we are looking at match with either big or
4942   // little endian value load
4943   bool BigEndian = true, LittleEndian = true;
4944   for (unsigned i = 0; i < ByteWidth; i++) {
4945     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4946     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4947     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4948     if (!BigEndian && !LittleEndian)
4949       return SDValue();
4950   }
4951   assert((BigEndian != LittleEndian) && "should be either or");
4952   assert(FirstByteProvider && "must be set");
4953
4954   // Ensure that the first byte is loaded from zero offset of the first load.
4955   // So the combined value can be loaded from the first load address.
4956   if (MemoryByteOffset(*FirstByteProvider) != 0)
4957     return SDValue();
4958   LoadSDNode *FirstLoad = FirstByteProvider->Load;
4959
4960   // The node we are looking at matches with the pattern, check if we can
4961   // replace it with a single load and bswap if needed.
4962
4963   // If the load needs byte swap check if the target supports it
4964   bool NeedsBswap = IsBigEndianTarget != BigEndian;
4965
4966   // Before legalize we can introduce illegal bswaps which will be later
4967   // converted to an explicit bswap sequence. This way we end up with a single
4968   // load and byte shuffling instead of several loads and byte shuffling.
4969   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4970     return SDValue();
4971
4972   // Check that a load of the wide type is both allowed and fast on the target
4973   bool Fast = false;
4974   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4975                                         VT, FirstLoad->getAddressSpace(),
4976                                         FirstLoad->getAlignment(), &Fast);
4977   if (!Allowed || !Fast)
4978     return SDValue();
4979
4980   SDValue NewLoad =
4981       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4982                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4983
4984   // Transfer chain users from old loads to the new load.
4985   for (LoadSDNode *L : Loads)
4986     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4987
4988   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4989 }
4990
4991 SDValue DAGCombiner::visitXOR(SDNode *N) {
4992   SDValue N0 = N->getOperand(0);
4993   SDValue N1 = N->getOperand(1);
4994   EVT VT = N0.getValueType();
4995
4996   // fold vector ops
4997   if (VT.isVector()) {
4998     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4999       return FoldedVOp;
5000
5001     // fold (xor x, 0) -> x, vector edition
5002     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5003       return N1;
5004     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5005       return N0;
5006   }
5007
5008   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5009   if (N0.isUndef() && N1.isUndef())
5010     return DAG.getConstant(0, SDLoc(N), VT);
5011   // fold (xor x, undef) -> undef
5012   if (N0.isUndef())
5013     return N0;
5014   if (N1.isUndef())
5015     return N1;
5016   // fold (xor c1, c2) -> c1^c2
5017   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5018   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5019   if (N0C && N1C)
5020     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5021   // canonicalize constant to RHS
5022   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5023      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5024     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5025   // fold (xor x, 0) -> x
5026   if (isNullConstant(N1))
5027     return N0;
5028
5029   if (SDValue NewSel = foldBinOpIntoSelect(N))
5030     return NewSel;
5031
5032   // reassociate xor
5033   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5034     return RXOR;
5035
5036   // fold !(x cc y) -> (x !cc y)
5037   SDValue LHS, RHS, CC;
5038   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5039     bool isInt = LHS.getValueType().isInteger();
5040     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5041                                                isInt);
5042
5043     if (!LegalOperations ||
5044         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5045       switch (N0.getOpcode()) {
5046       default:
5047         llvm_unreachable("Unhandled SetCC Equivalent!");
5048       case ISD::SETCC:
5049         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5050       case ISD::SELECT_CC:
5051         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5052                                N0.getOperand(3), NotCC);
5053       }
5054     }
5055   }
5056
5057   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5058   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5059       N0.getNode()->hasOneUse() &&
5060       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5061     SDValue V = N0.getOperand(0);
5062     SDLoc DL(N0);
5063     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5064                     DAG.getConstant(1, DL, V.getValueType()));
5065     AddToWorklist(V.getNode());
5066     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5067   }
5068
5069   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5070   if (isOneConstant(N1) && VT == MVT::i1 &&
5071       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5072     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5073     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5074       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5075       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5076       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5077       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5078       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5079     }
5080   }
5081   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5082   if (isAllOnesConstant(N1) &&
5083       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5084     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5085     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5086       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5087       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5088       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5089       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5090       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5091     }
5092   }
5093   // fold (xor (and x, y), y) -> (and (not x), y)
5094   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5095       N0->getOperand(1) == N1) {
5096     SDValue X = N0->getOperand(0);
5097     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5098     AddToWorklist(NotX.getNode());
5099     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5100   }
5101   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5102   if (N1C && N0.getOpcode() == ISD::XOR) {
5103     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5104       SDLoc DL(N);
5105       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5106                          DAG.getConstant(N1C->getAPIntValue() ^
5107                                          N00C->getAPIntValue(), DL, VT));
5108     }
5109     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5110       SDLoc DL(N);
5111       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5112                          DAG.getConstant(N1C->getAPIntValue() ^
5113                                          N01C->getAPIntValue(), DL, VT));
5114     }
5115   }
5116
5117   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5118   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5119   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5120       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5121       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5122     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5123       if (C->getAPIntValue() == (OpSizeInBits - 1))
5124         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5125   }
5126
5127   // fold (xor x, x) -> 0
5128   if (N0 == N1)
5129     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5130
5131   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5132   // Here is a concrete example of this equivalence:
5133   // i16   x ==  14
5134   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5135   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5136   //
5137   // =>
5138   //
5139   // i16     ~1      == 0b1111111111111110
5140   // i16 rol(~1, 14) == 0b1011111111111111
5141   //
5142   // Some additional tips to help conceptualize this transform:
5143   // - Try to see the operation as placing a single zero in a value of all ones.
5144   // - There exists no value for x which would allow the result to contain zero.
5145   // - Values of x larger than the bitwidth are undefined and do not require a
5146   //   consistent result.
5147   // - Pushing the zero left requires shifting one bits in from the right.
5148   // A rotate left of ~1 is a nice way of achieving the desired result.
5149   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5150       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5151     SDLoc DL(N);
5152     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5153                        N0.getOperand(1));
5154   }
5155
5156   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5157   if (N0.getOpcode() == N1.getOpcode())
5158     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5159       return Tmp;
5160
5161   // Simplify the expression using non-local knowledge.
5162   if (SimplifyDemandedBits(SDValue(N, 0)))
5163     return SDValue(N, 0);
5164
5165   return SDValue();
5166 }
5167
5168 /// Handle transforms common to the three shifts, when the shift amount is a
5169 /// constant.
5170 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5171   SDNode *LHS = N->getOperand(0).getNode();
5172   if (!LHS->hasOneUse()) return SDValue();
5173
5174   // We want to pull some binops through shifts, so that we have (and (shift))
5175   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5176   // thing happens with address calculations, so it's important to canonicalize
5177   // it.
5178   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5179
5180   switch (LHS->getOpcode()) {
5181   default: return SDValue();
5182   case ISD::OR:
5183   case ISD::XOR:
5184     HighBitSet = false; // We can only transform sra if the high bit is clear.
5185     break;
5186   case ISD::AND:
5187     HighBitSet = true;  // We can only transform sra if the high bit is set.
5188     break;
5189   case ISD::ADD:
5190     if (N->getOpcode() != ISD::SHL)
5191       return SDValue(); // only shl(add) not sr[al](add).
5192     HighBitSet = false; // We can only transform sra if the high bit is clear.
5193     break;
5194   }
5195
5196   // We require the RHS of the binop to be a constant and not opaque as well.
5197   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5198   if (!BinOpCst) return SDValue();
5199
5200   // FIXME: disable this unless the input to the binop is a shift by a constant
5201   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5202   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5203   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5204                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5205                  BinOpLHSVal->getOpcode() == ISD::SRL;
5206   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5207                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5208
5209   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5210       !isCopyOrSelect)
5211     return SDValue();
5212
5213   if (isCopyOrSelect && N->hasOneUse())
5214     return SDValue();
5215
5216   EVT VT = N->getValueType(0);
5217
5218   // If this is a signed shift right, and the high bit is modified by the
5219   // logical operation, do not perform the transformation. The highBitSet
5220   // boolean indicates the value of the high bit of the constant which would
5221   // cause it to be modified for this operation.
5222   if (N->getOpcode() == ISD::SRA) {
5223     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5224     if (BinOpRHSSignSet != HighBitSet)
5225       return SDValue();
5226   }
5227
5228   if (!TLI.isDesirableToCommuteWithShift(LHS))
5229     return SDValue();
5230
5231   // Fold the constants, shifting the binop RHS by the shift amount.
5232   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5233                                N->getValueType(0),
5234                                LHS->getOperand(1), N->getOperand(1));
5235   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5236
5237   // Create the new shift.
5238   SDValue NewShift = DAG.getNode(N->getOpcode(),
5239                                  SDLoc(LHS->getOperand(0)),
5240                                  VT, LHS->getOperand(0), N->getOperand(1));
5241
5242   // Create the new binop.
5243   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5244 }
5245
5246 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5247   assert(N->getOpcode() == ISD::TRUNCATE);
5248   assert(N->getOperand(0).getOpcode() == ISD::AND);
5249
5250   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5251   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5252     SDValue N01 = N->getOperand(0).getOperand(1);
5253     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5254       SDLoc DL(N);
5255       EVT TruncVT = N->getValueType(0);
5256       SDValue N00 = N->getOperand(0).getOperand(0);
5257       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5258       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5259       AddToWorklist(Trunc00.getNode());
5260       AddToWorklist(Trunc01.getNode());
5261       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5262     }
5263   }
5264
5265   return SDValue();
5266 }
5267
5268 SDValue DAGCombiner::visitRotate(SDNode *N) {
5269   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5270   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5271       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5272     if (SDValue NewOp1 =
5273             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5274       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5275                          N->getOperand(0), NewOp1);
5276   }
5277   return SDValue();
5278 }
5279
5280 SDValue DAGCombiner::visitSHL(SDNode *N) {
5281   SDValue N0 = N->getOperand(0);
5282   SDValue N1 = N->getOperand(1);
5283   EVT VT = N0.getValueType();
5284   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5285
5286   // fold vector ops
5287   if (VT.isVector()) {
5288     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5289       return FoldedVOp;
5290
5291     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5292     // If setcc produces all-one true value then:
5293     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5294     if (N1CV && N1CV->isConstant()) {
5295       if (N0.getOpcode() == ISD::AND) {
5296         SDValue N00 = N0->getOperand(0);
5297         SDValue N01 = N0->getOperand(1);
5298         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5299
5300         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5301             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5302                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5303           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5304                                                      N01CV, N1CV))
5305             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5306         }
5307       }
5308     }
5309   }
5310
5311   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5312
5313   // fold (shl c1, c2) -> c1<<c2
5314   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5315   if (N0C && N1C && !N1C->isOpaque())
5316     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5317   // fold (shl 0, x) -> 0
5318   if (isNullConstantOrNullSplatConstant(N0))
5319     return N0;
5320   // fold (shl x, c >= size(x)) -> undef
5321   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5322     return DAG.getUNDEF(VT);
5323   // fold (shl x, 0) -> x
5324   if (N1C && N1C->isNullValue())
5325     return N0;
5326   // fold (shl undef, x) -> 0
5327   if (N0.isUndef())
5328     return DAG.getConstant(0, SDLoc(N), VT);
5329
5330   if (SDValue NewSel = foldBinOpIntoSelect(N))
5331     return NewSel;
5332
5333   // if (shl x, c) is known to be zero, return 0
5334   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5335                             APInt::getAllOnesValue(OpSizeInBits)))
5336     return DAG.getConstant(0, SDLoc(N), VT);
5337   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5338   if (N1.getOpcode() == ISD::TRUNCATE &&
5339       N1.getOperand(0).getOpcode() == ISD::AND) {
5340     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5341       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5342   }
5343
5344   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5345     return SDValue(N, 0);
5346
5347   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5348   if (N1C && N0.getOpcode() == ISD::SHL) {
5349     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5350       SDLoc DL(N);
5351       APInt c1 = N0C1->getAPIntValue();
5352       APInt c2 = N1C->getAPIntValue();
5353       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5354
5355       APInt Sum = c1 + c2;
5356       if (Sum.uge(OpSizeInBits))
5357         return DAG.getConstant(0, DL, VT);
5358
5359       return DAG.getNode(
5360           ISD::SHL, DL, VT, N0.getOperand(0),
5361           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5362     }
5363   }
5364
5365   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5366   // For this to be valid, the second form must not preserve any of the bits
5367   // that are shifted out by the inner shift in the first form.  This means
5368   // the outer shift size must be >= the number of bits added by the ext.
5369   // As a corollary, we don't care what kind of ext it is.
5370   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5371               N0.getOpcode() == ISD::ANY_EXTEND ||
5372               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5373       N0.getOperand(0).getOpcode() == ISD::SHL) {
5374     SDValue N0Op0 = N0.getOperand(0);
5375     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5376       APInt c1 = N0Op0C1->getAPIntValue();
5377       APInt c2 = N1C->getAPIntValue();
5378       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5379
5380       EVT InnerShiftVT = N0Op0.getValueType();
5381       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5382       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5383         SDLoc DL(N0);
5384         APInt Sum = c1 + c2;
5385         if (Sum.uge(OpSizeInBits))
5386           return DAG.getConstant(0, DL, VT);
5387
5388         return DAG.getNode(
5389             ISD::SHL, DL, VT,
5390             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5391             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5392       }
5393     }
5394   }
5395
5396   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5397   // Only fold this if the inner zext has no other uses to avoid increasing
5398   // the total number of instructions.
5399   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5400       N0.getOperand(0).getOpcode() == ISD::SRL) {
5401     SDValue N0Op0 = N0.getOperand(0);
5402     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5403       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5404         uint64_t c1 = N0Op0C1->getZExtValue();
5405         uint64_t c2 = N1C->getZExtValue();
5406         if (c1 == c2) {
5407           SDValue NewOp0 = N0.getOperand(0);
5408           EVT CountVT = NewOp0.getOperand(1).getValueType();
5409           SDLoc DL(N);
5410           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5411                                        NewOp0,
5412                                        DAG.getConstant(c2, DL, CountVT));
5413           AddToWorklist(NewSHL.getNode());
5414           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5415         }
5416       }
5417     }
5418   }
5419
5420   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5421   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5422   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5423       N0->getFlags().hasExact()) {
5424     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5425       uint64_t C1 = N0C1->getZExtValue();
5426       uint64_t C2 = N1C->getZExtValue();
5427       SDLoc DL(N);
5428       if (C1 <= C2)
5429         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5430                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5431       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5432                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5433     }
5434   }
5435
5436   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5437   //                               (and (srl x, (sub c1, c2), MASK)
5438   // Only fold this if the inner shift has no other uses -- if it does, folding
5439   // this will increase the total number of instructions.
5440   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5441     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5442       uint64_t c1 = N0C1->getZExtValue();
5443       if (c1 < OpSizeInBits) {
5444         uint64_t c2 = N1C->getZExtValue();
5445         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5446         SDValue Shift;
5447         if (c2 > c1) {
5448           Mask <<= c2 - c1;
5449           SDLoc DL(N);
5450           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5451                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5452         } else {
5453           Mask.lshrInPlace(c1 - c2);
5454           SDLoc DL(N);
5455           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5456                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5457         }
5458         SDLoc DL(N0);
5459         return DAG.getNode(ISD::AND, DL, VT, Shift,
5460                            DAG.getConstant(Mask, DL, VT));
5461       }
5462     }
5463   }
5464
5465   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5466   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5467       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5468     SDLoc DL(N);
5469     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5470     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5471     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5472   }
5473
5474   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5475   // Variant of version done on multiply, except mul by a power of 2 is turned
5476   // into a shift.
5477   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5478       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5479       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5480     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5481     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5482     AddToWorklist(Shl0.getNode());
5483     AddToWorklist(Shl1.getNode());
5484     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5485   }
5486
5487   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5488   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5489       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5490       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5491     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5492     if (isConstantOrConstantVector(Shl))
5493       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5494   }
5495
5496   if (N1C && !N1C->isOpaque())
5497     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5498       return NewSHL;
5499
5500   return SDValue();
5501 }
5502
5503 SDValue DAGCombiner::visitSRA(SDNode *N) {
5504   SDValue N0 = N->getOperand(0);
5505   SDValue N1 = N->getOperand(1);
5506   EVT VT = N0.getValueType();
5507   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5508
5509   // Arithmetic shifting an all-sign-bit value is a no-op.
5510   // fold (sra 0, x) -> 0
5511   // fold (sra -1, x) -> -1
5512   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5513     return N0;
5514
5515   // fold vector ops
5516   if (VT.isVector())
5517     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5518       return FoldedVOp;
5519
5520   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5521
5522   // fold (sra c1, c2) -> (sra c1, c2)
5523   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5524   if (N0C && N1C && !N1C->isOpaque())
5525     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5526   // fold (sra x, c >= size(x)) -> undef
5527   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5528     return DAG.getUNDEF(VT);
5529   // fold (sra x, 0) -> x
5530   if (N1C && N1C->isNullValue())
5531     return N0;
5532
5533   if (SDValue NewSel = foldBinOpIntoSelect(N))
5534     return NewSel;
5535
5536   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5537   // sext_inreg.
5538   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5539     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5540     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5541     if (VT.isVector())
5542       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5543                                ExtVT, VT.getVectorNumElements());
5544     if ((!LegalOperations ||
5545          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5546       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5547                          N0.getOperand(0), DAG.getValueType(ExtVT));
5548   }
5549
5550   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5551   if (N1C && N0.getOpcode() == ISD::SRA) {
5552     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5553       SDLoc DL(N);
5554       APInt c1 = N0C1->getAPIntValue();
5555       APInt c2 = N1C->getAPIntValue();
5556       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5557
5558       APInt Sum = c1 + c2;
5559       if (Sum.uge(OpSizeInBits))
5560         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5561
5562       return DAG.getNode(
5563           ISD::SRA, DL, VT, N0.getOperand(0),
5564           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5565     }
5566   }
5567
5568   // fold (sra (shl X, m), (sub result_size, n))
5569   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5570   // result_size - n != m.
5571   // If truncate is free for the target sext(shl) is likely to result in better
5572   // code.
5573   if (N0.getOpcode() == ISD::SHL && N1C) {
5574     // Get the two constanst of the shifts, CN0 = m, CN = n.
5575     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5576     if (N01C) {
5577       LLVMContext &Ctx = *DAG.getContext();
5578       // Determine what the truncate's result bitsize and type would be.
5579       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5580
5581       if (VT.isVector())
5582         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5583
5584       // Determine the residual right-shift amount.
5585       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5586
5587       // If the shift is not a no-op (in which case this should be just a sign
5588       // extend already), the truncated to type is legal, sign_extend is legal
5589       // on that type, and the truncate to that type is both legal and free,
5590       // perform the transform.
5591       if ((ShiftAmt > 0) &&
5592           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5593           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5594           TLI.isTruncateFree(VT, TruncVT)) {
5595
5596         SDLoc DL(N);
5597         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5598             getShiftAmountTy(N0.getOperand(0).getValueType()));
5599         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5600                                     N0.getOperand(0), Amt);
5601         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5602                                     Shift);
5603         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5604                            N->getValueType(0), Trunc);
5605       }
5606     }
5607   }
5608
5609   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5610   if (N1.getOpcode() == ISD::TRUNCATE &&
5611       N1.getOperand(0).getOpcode() == ISD::AND) {
5612     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5613       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5614   }
5615
5616   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5617   //      if c1 is equal to the number of bits the trunc removes
5618   if (N0.getOpcode() == ISD::TRUNCATE &&
5619       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5620        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5621       N0.getOperand(0).hasOneUse() &&
5622       N0.getOperand(0).getOperand(1).hasOneUse() &&
5623       N1C) {
5624     SDValue N0Op0 = N0.getOperand(0);
5625     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5626       unsigned LargeShiftVal = LargeShift->getZExtValue();
5627       EVT LargeVT = N0Op0.getValueType();
5628
5629       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5630         SDLoc DL(N);
5631         SDValue Amt =
5632           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5633                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5634         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5635                                   N0Op0.getOperand(0), Amt);
5636         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5637       }
5638     }
5639   }
5640
5641   // Simplify, based on bits shifted out of the LHS.
5642   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5643     return SDValue(N, 0);
5644
5645
5646   // If the sign bit is known to be zero, switch this to a SRL.
5647   if (DAG.SignBitIsZero(N0))
5648     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5649
5650   if (N1C && !N1C->isOpaque())
5651     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5652       return NewSRA;
5653
5654   return SDValue();
5655 }
5656
5657 SDValue DAGCombiner::visitSRL(SDNode *N) {
5658   SDValue N0 = N->getOperand(0);
5659   SDValue N1 = N->getOperand(1);
5660   EVT VT = N0.getValueType();
5661   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5662
5663   // fold vector ops
5664   if (VT.isVector())
5665     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5666       return FoldedVOp;
5667
5668   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5669
5670   // fold (srl c1, c2) -> c1 >>u c2
5671   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5672   if (N0C && N1C && !N1C->isOpaque())
5673     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5674   // fold (srl 0, x) -> 0
5675   if (isNullConstantOrNullSplatConstant(N0))
5676     return N0;
5677   // fold (srl x, c >= size(x)) -> undef
5678   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5679     return DAG.getUNDEF(VT);
5680   // fold (srl x, 0) -> x
5681   if (N1C && N1C->isNullValue())
5682     return N0;
5683
5684   if (SDValue NewSel = foldBinOpIntoSelect(N))
5685     return NewSel;
5686
5687   // if (srl x, c) is known to be zero, return 0
5688   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5689                                    APInt::getAllOnesValue(OpSizeInBits)))
5690     return DAG.getConstant(0, SDLoc(N), VT);
5691
5692   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5693   if (N1C && N0.getOpcode() == ISD::SRL) {
5694     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5695       SDLoc DL(N);
5696       APInt c1 = N0C1->getAPIntValue();
5697       APInt c2 = N1C->getAPIntValue();
5698       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5699
5700       APInt Sum = c1 + c2;
5701       if (Sum.uge(OpSizeInBits))
5702         return DAG.getConstant(0, DL, VT);
5703
5704       return DAG.getNode(
5705           ISD::SRL, DL, VT, N0.getOperand(0),
5706           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5707     }
5708   }
5709
5710   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5711   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5712       N0.getOperand(0).getOpcode() == ISD::SRL) {
5713     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5714       uint64_t c1 = N001C->getZExtValue();
5715       uint64_t c2 = N1C->getZExtValue();
5716       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5717       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5718       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5719       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5720       if (c1 + OpSizeInBits == InnerShiftSize) {
5721         SDLoc DL(N0);
5722         if (c1 + c2 >= InnerShiftSize)
5723           return DAG.getConstant(0, DL, VT);
5724         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5725                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5726                                        N0.getOperand(0).getOperand(0),
5727                                        DAG.getConstant(c1 + c2, DL,
5728                                                        ShiftCountVT)));
5729       }
5730     }
5731   }
5732
5733   // fold (srl (shl x, c), c) -> (and x, cst2)
5734   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5735       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5736     SDLoc DL(N);
5737     SDValue Mask =
5738         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5739     AddToWorklist(Mask.getNode());
5740     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5741   }
5742
5743   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5744   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5745     // Shifting in all undef bits?
5746     EVT SmallVT = N0.getOperand(0).getValueType();
5747     unsigned BitSize = SmallVT.getScalarSizeInBits();
5748     if (N1C->getZExtValue() >= BitSize)
5749       return DAG.getUNDEF(VT);
5750
5751     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5752       uint64_t ShiftAmt = N1C->getZExtValue();
5753       SDLoc DL0(N0);
5754       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5755                                        N0.getOperand(0),
5756                           DAG.getConstant(ShiftAmt, DL0,
5757                                           getShiftAmountTy(SmallVT)));
5758       AddToWorklist(SmallShift.getNode());
5759       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5760       SDLoc DL(N);
5761       return DAG.getNode(ISD::AND, DL, VT,
5762                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5763                          DAG.getConstant(Mask, DL, VT));
5764     }
5765   }
5766
5767   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5768   // bit, which is unmodified by sra.
5769   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5770     if (N0.getOpcode() == ISD::SRA)
5771       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5772   }
5773
5774   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5775   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5776       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5777     KnownBits Known;
5778     DAG.computeKnownBits(N0.getOperand(0), Known);
5779
5780     // If any of the input bits are KnownOne, then the input couldn't be all
5781     // zeros, thus the result of the srl will always be zero.
5782     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5783
5784     // If all of the bits input the to ctlz node are known to be zero, then
5785     // the result of the ctlz is "32" and the result of the shift is one.
5786     APInt UnknownBits = ~Known.Zero;
5787     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5788
5789     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5790     if (UnknownBits.isPowerOf2()) {
5791       // Okay, we know that only that the single bit specified by UnknownBits
5792       // could be set on input to the CTLZ node. If this bit is set, the SRL
5793       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5794       // to an SRL/XOR pair, which is likely to simplify more.
5795       unsigned ShAmt = UnknownBits.countTrailingZeros();
5796       SDValue Op = N0.getOperand(0);
5797
5798       if (ShAmt) {
5799         SDLoc DL(N0);
5800         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5801                   DAG.getConstant(ShAmt, DL,
5802                                   getShiftAmountTy(Op.getValueType())));
5803         AddToWorklist(Op.getNode());
5804       }
5805
5806       SDLoc DL(N);
5807       return DAG.getNode(ISD::XOR, DL, VT,
5808                          Op, DAG.getConstant(1, DL, VT));
5809     }
5810   }
5811
5812   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5813   if (N1.getOpcode() == ISD::TRUNCATE &&
5814       N1.getOperand(0).getOpcode() == ISD::AND) {
5815     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5816       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5817   }
5818
5819   // fold operands of srl based on knowledge that the low bits are not
5820   // demanded.
5821   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5822     return SDValue(N, 0);
5823
5824   if (N1C && !N1C->isOpaque())
5825     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5826       return NewSRL;
5827
5828   // Attempt to convert a srl of a load into a narrower zero-extending load.
5829   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5830     return NarrowLoad;
5831
5832   // Here is a common situation. We want to optimize:
5833   //
5834   //   %a = ...
5835   //   %b = and i32 %a, 2
5836   //   %c = srl i32 %b, 1
5837   //   brcond i32 %c ...
5838   //
5839   // into
5840   //
5841   //   %a = ...
5842   //   %b = and %a, 2
5843   //   %c = setcc eq %b, 0
5844   //   brcond %c ...
5845   //
5846   // However when after the source operand of SRL is optimized into AND, the SRL
5847   // itself may not be optimized further. Look for it and add the BRCOND into
5848   // the worklist.
5849   if (N->hasOneUse()) {
5850     SDNode *Use = *N->use_begin();
5851     if (Use->getOpcode() == ISD::BRCOND)
5852       AddToWorklist(Use);
5853     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5854       // Also look pass the truncate.
5855       Use = *Use->use_begin();
5856       if (Use->getOpcode() == ISD::BRCOND)
5857         AddToWorklist(Use);
5858     }
5859   }
5860
5861   return SDValue();
5862 }
5863
5864 SDValue DAGCombiner::visitABS(SDNode *N) {
5865   SDValue N0 = N->getOperand(0);
5866   EVT VT = N->getValueType(0);
5867
5868   // fold (abs c1) -> c2
5869   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5870     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5871   // fold (abs (abs x)) -> (abs x)
5872   if (N0.getOpcode() == ISD::ABS)
5873     return N0;
5874   // fold (abs x) -> x iff not-negative
5875   if (DAG.SignBitIsZero(N0))
5876     return N0;
5877   return SDValue();
5878 }
5879
5880 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5881   SDValue N0 = N->getOperand(0);
5882   EVT VT = N->getValueType(0);
5883
5884   // fold (bswap c1) -> c2
5885   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5886     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5887   // fold (bswap (bswap x)) -> x
5888   if (N0.getOpcode() == ISD::BSWAP)
5889     return N0->getOperand(0);
5890   return SDValue();
5891 }
5892
5893 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5894   SDValue N0 = N->getOperand(0);
5895   EVT VT = N->getValueType(0);
5896
5897   // fold (bitreverse c1) -> c2
5898   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5899     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5900   // fold (bitreverse (bitreverse x)) -> x
5901   if (N0.getOpcode() == ISD::BITREVERSE)
5902     return N0.getOperand(0);
5903   return SDValue();
5904 }
5905
5906 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5907   SDValue N0 = N->getOperand(0);
5908   EVT VT = N->getValueType(0);
5909
5910   // fold (ctlz c1) -> c2
5911   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5912     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5913   return SDValue();
5914 }
5915
5916 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5917   SDValue N0 = N->getOperand(0);
5918   EVT VT = N->getValueType(0);
5919
5920   // fold (ctlz_zero_undef c1) -> c2
5921   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5922     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5923   return SDValue();
5924 }
5925
5926 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5927   SDValue N0 = N->getOperand(0);
5928   EVT VT = N->getValueType(0);
5929
5930   // fold (cttz c1) -> c2
5931   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5932     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5933   return SDValue();
5934 }
5935
5936 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5937   SDValue N0 = N->getOperand(0);
5938   EVT VT = N->getValueType(0);
5939
5940   // fold (cttz_zero_undef c1) -> c2
5941   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5942     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5943   return SDValue();
5944 }
5945
5946 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5947   SDValue N0 = N->getOperand(0);
5948   EVT VT = N->getValueType(0);
5949
5950   // fold (ctpop c1) -> c2
5951   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5952     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5953   return SDValue();
5954 }
5955
5956
5957 /// \brief Generate Min/Max node
5958 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5959                                    SDValue RHS, SDValue True, SDValue False,
5960                                    ISD::CondCode CC, const TargetLowering &TLI,
5961                                    SelectionDAG &DAG) {
5962   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5963     return SDValue();
5964
5965   switch (CC) {
5966   case ISD::SETOLT:
5967   case ISD::SETOLE:
5968   case ISD::SETLT:
5969   case ISD::SETLE:
5970   case ISD::SETULT:
5971   case ISD::SETULE: {
5972     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5973     if (TLI.isOperationLegal(Opcode, VT))
5974       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5975     return SDValue();
5976   }
5977   case ISD::SETOGT:
5978   case ISD::SETOGE:
5979   case ISD::SETGT:
5980   case ISD::SETGE:
5981   case ISD::SETUGT:
5982   case ISD::SETUGE: {
5983     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5984     if (TLI.isOperationLegal(Opcode, VT))
5985       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5986     return SDValue();
5987   }
5988   default:
5989     return SDValue();
5990   }
5991 }
5992
5993 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5994   SDValue Cond = N->getOperand(0);
5995   SDValue N1 = N->getOperand(1);
5996   SDValue N2 = N->getOperand(2);
5997   EVT VT = N->getValueType(0);
5998   EVT CondVT = Cond.getValueType();
5999   SDLoc DL(N);
6000
6001   if (!VT.isInteger())
6002     return SDValue();
6003
6004   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6005   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6006   if (!C1 || !C2)
6007     return SDValue();
6008
6009   // Only do this before legalization to avoid conflicting with target-specific
6010   // transforms in the other direction (create a select from a zext/sext). There
6011   // is also a target-independent combine here in DAGCombiner in the other
6012   // direction for (select Cond, -1, 0) when the condition is not i1.
6013   if (CondVT == MVT::i1 && !LegalOperations) {
6014     if (C1->isNullValue() && C2->isOne()) {
6015       // select Cond, 0, 1 --> zext (!Cond)
6016       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6017       if (VT != MVT::i1)
6018         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6019       return NotCond;
6020     }
6021     if (C1->isNullValue() && C2->isAllOnesValue()) {
6022       // select Cond, 0, -1 --> sext (!Cond)
6023       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6024       if (VT != MVT::i1)
6025         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6026       return NotCond;
6027     }
6028     if (C1->isOne() && C2->isNullValue()) {
6029       // select Cond, 1, 0 --> zext (Cond)
6030       if (VT != MVT::i1)
6031         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6032       return Cond;
6033     }
6034     if (C1->isAllOnesValue() && C2->isNullValue()) {
6035       // select Cond, -1, 0 --> sext (Cond)
6036       if (VT != MVT::i1)
6037         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6038       return Cond;
6039     }
6040
6041     // For any constants that differ by 1, we can transform the select into an
6042     // extend and add. Use a target hook because some targets may prefer to
6043     // transform in the other direction.
6044     if (TLI.convertSelectOfConstantsToMath()) {
6045       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6046         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6047         if (VT != MVT::i1)
6048           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6049         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6050       }
6051       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6052         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6053         if (VT != MVT::i1)
6054           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6055         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6056       }
6057     }
6058
6059     return SDValue();
6060   }
6061
6062   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6063   // We can't do this reliably if integer based booleans have different contents
6064   // to floating point based booleans. This is because we can't tell whether we
6065   // have an integer-based boolean or a floating-point-based boolean unless we
6066   // can find the SETCC that produced it and inspect its operands. This is
6067   // fairly easy if C is the SETCC node, but it can potentially be
6068   // undiscoverable (or not reasonably discoverable). For example, it could be
6069   // in another basic block or it could require searching a complicated
6070   // expression.
6071   if (CondVT.isInteger() &&
6072       TLI.getBooleanContents(false, true) ==
6073           TargetLowering::ZeroOrOneBooleanContent &&
6074       TLI.getBooleanContents(false, false) ==
6075           TargetLowering::ZeroOrOneBooleanContent &&
6076       C1->isNullValue() && C2->isOne()) {
6077     SDValue NotCond =
6078         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6079     if (VT.bitsEq(CondVT))
6080       return NotCond;
6081     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6082   }
6083
6084   return SDValue();
6085 }
6086
6087 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6088   SDValue N0 = N->getOperand(0);
6089   SDValue N1 = N->getOperand(1);
6090   SDValue N2 = N->getOperand(2);
6091   EVT VT = N->getValueType(0);
6092   EVT VT0 = N0.getValueType();
6093
6094   // fold (select C, X, X) -> X
6095   if (N1 == N2)
6096     return N1;
6097   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6098     // fold (select true, X, Y) -> X
6099     // fold (select false, X, Y) -> Y
6100     return !N0C->isNullValue() ? N1 : N2;
6101   }
6102   // fold (select X, X, Y) -> (or X, Y)
6103   // fold (select X, 1, Y) -> (or C, Y)
6104   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6105     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6106
6107   if (SDValue V = foldSelectOfConstants(N))
6108     return V;
6109
6110   // fold (select C, 0, X) -> (and (not C), X)
6111   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6112     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6113     AddToWorklist(NOTNode.getNode());
6114     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6115   }
6116   // fold (select C, X, 1) -> (or (not C), X)
6117   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6118     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6119     AddToWorklist(NOTNode.getNode());
6120     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6121   }
6122   // fold (select X, Y, X) -> (and X, Y)
6123   // fold (select X, Y, 0) -> (and X, Y)
6124   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6125     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6126
6127   // If we can fold this based on the true/false value, do so.
6128   if (SimplifySelectOps(N, N1, N2))
6129     return SDValue(N, 0);  // Don't revisit N.
6130
6131   if (VT0 == MVT::i1) {
6132     // The code in this block deals with the following 2 equivalences:
6133     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6134     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6135     // The target can specify its preferred form with the
6136     // shouldNormalizeToSelectSequence() callback. However we always transform
6137     // to the right anyway if we find the inner select exists in the DAG anyway
6138     // and we always transform to the left side if we know that we can further
6139     // optimize the combination of the conditions.
6140     bool normalizeToSequence
6141       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6142     // select (and Cond0, Cond1), X, Y
6143     //   -> select Cond0, (select Cond1, X, Y), Y
6144     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6145       SDValue Cond0 = N0->getOperand(0);
6146       SDValue Cond1 = N0->getOperand(1);
6147       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6148                                         N1.getValueType(), Cond1, N1, N2);
6149       if (normalizeToSequence || !InnerSelect.use_empty())
6150         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6151                            InnerSelect, N2);
6152     }
6153     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6154     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6155       SDValue Cond0 = N0->getOperand(0);
6156       SDValue Cond1 = N0->getOperand(1);
6157       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6158                                         N1.getValueType(), Cond1, N1, N2);
6159       if (normalizeToSequence || !InnerSelect.use_empty())
6160         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6161                            InnerSelect);
6162     }
6163
6164     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6165     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6166       SDValue N1_0 = N1->getOperand(0);
6167       SDValue N1_1 = N1->getOperand(1);
6168       SDValue N1_2 = N1->getOperand(2);
6169       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6170         // Create the actual and node if we can generate good code for it.
6171         if (!normalizeToSequence) {
6172           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6173                                     N0, N1_0);
6174           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6175                              N1_1, N2);
6176         }
6177         // Otherwise see if we can optimize the "and" to a better pattern.
6178         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6179           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6180                              N1_1, N2);
6181       }
6182     }
6183     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6184     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6185       SDValue N2_0 = N2->getOperand(0);
6186       SDValue N2_1 = N2->getOperand(1);
6187       SDValue N2_2 = N2->getOperand(2);
6188       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6189         // Create the actual or node if we can generate good code for it.
6190         if (!normalizeToSequence) {
6191           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6192                                    N0, N2_0);
6193           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6194                              N1, N2_2);
6195         }
6196         // Otherwise see if we can optimize to a better pattern.
6197         if (SDValue Combined = visitORLike(N0, N2_0, N))
6198           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6199                              N1, N2_2);
6200       }
6201     }
6202   }
6203
6204   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6205   if (VT0 == MVT::i1) {
6206     if (N0->getOpcode() == ISD::XOR) {
6207       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6208         SDValue Cond0 = N0->getOperand(0);
6209         if (C->isOne())
6210           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6211                              Cond0, N2, N1);
6212       }
6213     }
6214   }
6215
6216   // fold selects based on a setcc into other things, such as min/max/abs
6217   if (N0.getOpcode() == ISD::SETCC) {
6218     // select x, y (fcmp lt x, y) -> fminnum x, y
6219     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6220     //
6221     // This is OK if we don't care about what happens if either operand is a
6222     // NaN.
6223     //
6224
6225     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6226     // no signed zeros as well as no nans.
6227     const TargetOptions &Options = DAG.getTarget().Options;
6228     if (Options.UnsafeFPMath &&
6229         VT.isFloatingPoint() && N0.hasOneUse() &&
6230         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6231       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6232
6233       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6234                                                 N0.getOperand(1), N1, N2, CC,
6235                                                 TLI, DAG))
6236         return FMinMax;
6237     }
6238
6239     if ((!LegalOperations &&
6240          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6241         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6242       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6243                          N0.getOperand(0), N0.getOperand(1),
6244                          N1, N2, N0.getOperand(2));
6245     return SimplifySelect(SDLoc(N), N0, N1, N2);
6246   }
6247
6248   return SDValue();
6249 }
6250
6251 static
6252 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6253   SDLoc DL(N);
6254   EVT LoVT, HiVT;
6255   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6256
6257   // Split the inputs.
6258   SDValue Lo, Hi, LL, LH, RL, RH;
6259   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6260   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6261
6262   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6263   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6264
6265   return std::make_pair(Lo, Hi);
6266 }
6267
6268 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6269 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6270 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6271   SDLoc DL(N);
6272   SDValue Cond = N->getOperand(0);
6273   SDValue LHS = N->getOperand(1);
6274   SDValue RHS = N->getOperand(2);
6275   EVT VT = N->getValueType(0);
6276   int NumElems = VT.getVectorNumElements();
6277   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6278          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6279          Cond.getOpcode() == ISD::BUILD_VECTOR);
6280
6281   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6282   // binary ones here.
6283   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6284     return SDValue();
6285
6286   // We're sure we have an even number of elements due to the
6287   // concat_vectors we have as arguments to vselect.
6288   // Skip BV elements until we find one that's not an UNDEF
6289   // After we find an UNDEF element, keep looping until we get to half the
6290   // length of the BV and see if all the non-undef nodes are the same.
6291   ConstantSDNode *BottomHalf = nullptr;
6292   for (int i = 0; i < NumElems / 2; ++i) {
6293     if (Cond->getOperand(i)->isUndef())
6294       continue;
6295
6296     if (BottomHalf == nullptr)
6297       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6298     else if (Cond->getOperand(i).getNode() != BottomHalf)
6299       return SDValue();
6300   }
6301
6302   // Do the same for the second half of the BuildVector
6303   ConstantSDNode *TopHalf = nullptr;
6304   for (int i = NumElems / 2; i < NumElems; ++i) {
6305     if (Cond->getOperand(i)->isUndef())
6306       continue;
6307
6308     if (TopHalf == nullptr)
6309       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6310     else if (Cond->getOperand(i).getNode() != TopHalf)
6311       return SDValue();
6312   }
6313
6314   assert(TopHalf && BottomHalf &&
6315          "One half of the selector was all UNDEFs and the other was all the "
6316          "same value. This should have been addressed before this function.");
6317   return DAG.getNode(
6318       ISD::CONCAT_VECTORS, DL, VT,
6319       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6320       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6321 }
6322
6323 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6324
6325   if (Level >= AfterLegalizeTypes)
6326     return SDValue();
6327
6328   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6329   SDValue Mask = MSC->getMask();
6330   SDValue Data  = MSC->getValue();
6331   SDLoc DL(N);
6332
6333   // If the MSCATTER data type requires splitting and the mask is provided by a
6334   // SETCC, then split both nodes and its operands before legalization. This
6335   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6336   // and enables future optimizations (e.g. min/max pattern matching on X86).
6337   if (Mask.getOpcode() != ISD::SETCC)
6338     return SDValue();
6339
6340   // Check if any splitting is required.
6341   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6342       TargetLowering::TypeSplitVector)
6343     return SDValue();
6344   SDValue MaskLo, MaskHi, Lo, Hi;
6345   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6346
6347   EVT LoVT, HiVT;
6348   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6349
6350   SDValue Chain = MSC->getChain();
6351
6352   EVT MemoryVT = MSC->getMemoryVT();
6353   unsigned Alignment = MSC->getOriginalAlignment();
6354
6355   EVT LoMemVT, HiMemVT;
6356   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6357
6358   SDValue DataLo, DataHi;
6359   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6360
6361   SDValue BasePtr = MSC->getBasePtr();
6362   SDValue IndexLo, IndexHi;
6363   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6364
6365   MachineMemOperand *MMO = DAG.getMachineFunction().
6366     getMachineMemOperand(MSC->getPointerInfo(),
6367                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6368                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6369
6370   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6371   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6372                             DL, OpsLo, MMO);
6373
6374   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6375   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6376                             DL, OpsHi, MMO);
6377
6378   AddToWorklist(Lo.getNode());
6379   AddToWorklist(Hi.getNode());
6380
6381   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6382 }
6383
6384 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6385
6386   if (Level >= AfterLegalizeTypes)
6387     return SDValue();
6388
6389   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6390   SDValue Mask = MST->getMask();
6391   SDValue Data  = MST->getValue();
6392   EVT VT = Data.getValueType();
6393   SDLoc DL(N);
6394
6395   // If the MSTORE data type requires splitting and the mask is provided by a
6396   // SETCC, then split both nodes and its operands before legalization. This
6397   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6398   // and enables future optimizations (e.g. min/max pattern matching on X86).
6399   if (Mask.getOpcode() == ISD::SETCC) {
6400
6401     // Check if any splitting is required.
6402     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6403         TargetLowering::TypeSplitVector)
6404       return SDValue();
6405
6406     SDValue MaskLo, MaskHi, Lo, Hi;
6407     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6408
6409     SDValue Chain = MST->getChain();
6410     SDValue Ptr   = MST->getBasePtr();
6411
6412     EVT MemoryVT = MST->getMemoryVT();
6413     unsigned Alignment = MST->getOriginalAlignment();
6414
6415     // if Alignment is equal to the vector size,
6416     // take the half of it for the second part
6417     unsigned SecondHalfAlignment =
6418       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6419
6420     EVT LoMemVT, HiMemVT;
6421     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6422
6423     SDValue DataLo, DataHi;
6424     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6425
6426     MachineMemOperand *MMO = DAG.getMachineFunction().
6427       getMachineMemOperand(MST->getPointerInfo(),
6428                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6429                            Alignment, MST->getAAInfo(), MST->getRanges());
6430
6431     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6432                             MST->isTruncatingStore(),
6433                             MST->isCompressingStore());
6434
6435     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6436                                      MST->isCompressingStore());
6437
6438     MMO = DAG.getMachineFunction().
6439       getMachineMemOperand(MST->getPointerInfo(),
6440                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6441                            SecondHalfAlignment, MST->getAAInfo(),
6442                            MST->getRanges());
6443
6444     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6445                             MST->isTruncatingStore(),
6446                             MST->isCompressingStore());
6447
6448     AddToWorklist(Lo.getNode());
6449     AddToWorklist(Hi.getNode());
6450
6451     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6452   }
6453   return SDValue();
6454 }
6455
6456 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6457
6458   if (Level >= AfterLegalizeTypes)
6459     return SDValue();
6460
6461   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6462   SDValue Mask = MGT->getMask();
6463   SDLoc DL(N);
6464
6465   // If the MGATHER result requires splitting and the mask is provided by a
6466   // SETCC, then split both nodes and its operands before legalization. This
6467   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6468   // and enables future optimizations (e.g. min/max pattern matching on X86).
6469
6470   if (Mask.getOpcode() != ISD::SETCC)
6471     return SDValue();
6472
6473   EVT VT = N->getValueType(0);
6474
6475   // Check if any splitting is required.
6476   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6477       TargetLowering::TypeSplitVector)
6478     return SDValue();
6479
6480   SDValue MaskLo, MaskHi, Lo, Hi;
6481   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6482
6483   SDValue Src0 = MGT->getValue();
6484   SDValue Src0Lo, Src0Hi;
6485   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6486
6487   EVT LoVT, HiVT;
6488   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6489
6490   SDValue Chain = MGT->getChain();
6491   EVT MemoryVT = MGT->getMemoryVT();
6492   unsigned Alignment = MGT->getOriginalAlignment();
6493
6494   EVT LoMemVT, HiMemVT;
6495   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6496
6497   SDValue BasePtr = MGT->getBasePtr();
6498   SDValue Index = MGT->getIndex();
6499   SDValue IndexLo, IndexHi;
6500   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6501
6502   MachineMemOperand *MMO = DAG.getMachineFunction().
6503     getMachineMemOperand(MGT->getPointerInfo(),
6504                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6505                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6506
6507   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6508   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6509                             MMO);
6510
6511   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6512   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6513                             MMO);
6514
6515   AddToWorklist(Lo.getNode());
6516   AddToWorklist(Hi.getNode());
6517
6518   // Build a factor node to remember that this load is independent of the
6519   // other one.
6520   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6521                       Hi.getValue(1));
6522
6523   // Legalized the chain result - switch anything that used the old chain to
6524   // use the new one.
6525   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6526
6527   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6528
6529   SDValue RetOps[] = { GatherRes, Chain };
6530   return DAG.getMergeValues(RetOps, DL);
6531 }
6532
6533 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6534
6535   if (Level >= AfterLegalizeTypes)
6536     return SDValue();
6537
6538   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6539   SDValue Mask = MLD->getMask();
6540   SDLoc DL(N);
6541
6542   // If the MLOAD result requires splitting and the mask is provided by a
6543   // SETCC, then split both nodes and its operands before legalization. This
6544   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6545   // and enables future optimizations (e.g. min/max pattern matching on X86).
6546
6547   if (Mask.getOpcode() == ISD::SETCC) {
6548     EVT VT = N->getValueType(0);
6549
6550     // Check if any splitting is required.
6551     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6552         TargetLowering::TypeSplitVector)
6553       return SDValue();
6554
6555     SDValue MaskLo, MaskHi, Lo, Hi;
6556     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6557
6558     SDValue Src0 = MLD->getSrc0();
6559     SDValue Src0Lo, Src0Hi;
6560     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6561
6562     EVT LoVT, HiVT;
6563     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6564
6565     SDValue Chain = MLD->getChain();
6566     SDValue Ptr   = MLD->getBasePtr();
6567     EVT MemoryVT = MLD->getMemoryVT();
6568     unsigned Alignment = MLD->getOriginalAlignment();
6569
6570     // if Alignment is equal to the vector size,
6571     // take the half of it for the second part
6572     unsigned SecondHalfAlignment =
6573       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6574          Alignment/2 : Alignment;
6575
6576     EVT LoMemVT, HiMemVT;
6577     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6578
6579     MachineMemOperand *MMO = DAG.getMachineFunction().
6580     getMachineMemOperand(MLD->getPointerInfo(),
6581                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6582                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6583
6584     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6585                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6586
6587     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6588                                      MLD->isExpandingLoad());
6589
6590     MMO = DAG.getMachineFunction().
6591     getMachineMemOperand(MLD->getPointerInfo(),
6592                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6593                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6594
6595     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6596                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6597
6598     AddToWorklist(Lo.getNode());
6599     AddToWorklist(Hi.getNode());
6600
6601     // Build a factor node to remember that this load is independent of the
6602     // other one.
6603     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6604                         Hi.getValue(1));
6605
6606     // Legalized the chain result - switch anything that used the old chain to
6607     // use the new one.
6608     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6609
6610     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6611
6612     SDValue RetOps[] = { LoadRes, Chain };
6613     return DAG.getMergeValues(RetOps, DL);
6614   }
6615   return SDValue();
6616 }
6617
6618 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6619   SDValue N0 = N->getOperand(0);
6620   SDValue N1 = N->getOperand(1);
6621   SDValue N2 = N->getOperand(2);
6622   SDLoc DL(N);
6623
6624   // fold (vselect C, X, X) -> X
6625   if (N1 == N2)
6626     return N1;
6627
6628   // Canonicalize integer abs.
6629   // vselect (setg[te] X,  0),  X, -X ->
6630   // vselect (setgt    X, -1),  X, -X ->
6631   // vselect (setl[te] X,  0), -X,  X ->
6632   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6633   if (N0.getOpcode() == ISD::SETCC) {
6634     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6635     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6636     bool isAbs = false;
6637     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6638
6639     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6640          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6641         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6642       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6643     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6644              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6645       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6646
6647     if (isAbs) {
6648       EVT VT = LHS.getValueType();
6649       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6650         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6651
6652       SDValue Shift = DAG.getNode(
6653           ISD::SRA, DL, VT, LHS,
6654           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6655       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6656       AddToWorklist(Shift.getNode());
6657       AddToWorklist(Add.getNode());
6658       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6659     }
6660   }
6661
6662   if (SimplifySelectOps(N, N1, N2))
6663     return SDValue(N, 0);  // Don't revisit N.
6664
6665   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6666   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6667     return N1;
6668   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6669   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6670     return N2;
6671
6672   // The ConvertSelectToConcatVector function is assuming both the above
6673   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6674   // and addressed.
6675   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6676       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6677       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6678     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6679       return CV;
6680   }
6681
6682   return SDValue();
6683 }
6684
6685 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6686   SDValue N0 = N->getOperand(0);
6687   SDValue N1 = N->getOperand(1);
6688   SDValue N2 = N->getOperand(2);
6689   SDValue N3 = N->getOperand(3);
6690   SDValue N4 = N->getOperand(4);
6691   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6692
6693   // fold select_cc lhs, rhs, x, x, cc -> x
6694   if (N2 == N3)
6695     return N2;
6696
6697   // Determine if the condition we're dealing with is constant
6698   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6699                                   CC, SDLoc(N), false)) {
6700     AddToWorklist(SCC.getNode());
6701
6702     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6703       if (!SCCC->isNullValue())
6704         return N2;    // cond always true -> true val
6705       else
6706         return N3;    // cond always false -> false val
6707     } else if (SCC->isUndef()) {
6708       // When the condition is UNDEF, just return the first operand. This is
6709       // coherent the DAG creation, no setcc node is created in this case
6710       return N2;
6711     } else if (SCC.getOpcode() == ISD::SETCC) {
6712       // Fold to a simpler select_cc
6713       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6714                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6715                          SCC.getOperand(2));
6716     }
6717   }
6718
6719   // If we can fold this based on the true/false value, do so.
6720   if (SimplifySelectOps(N, N2, N3))
6721     return SDValue(N, 0);  // Don't revisit N.
6722
6723   // fold select_cc into other things, such as min/max/abs
6724   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6725 }
6726
6727 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6728   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6729                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6730                        SDLoc(N));
6731 }
6732
6733 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6734   SDValue LHS = N->getOperand(0);
6735   SDValue RHS = N->getOperand(1);
6736   SDValue Carry = N->getOperand(2);
6737   SDValue Cond = N->getOperand(3);
6738
6739   // If Carry is false, fold to a regular SETCC.
6740   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6741     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6742
6743   return SDValue();
6744 }
6745
6746 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6747 /// a build_vector of constants.
6748 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6749 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6750 /// Vector extends are not folded if operations are legal; this is to
6751 /// avoid introducing illegal build_vector dag nodes.
6752 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6753                                          SelectionDAG &DAG, bool LegalTypes,
6754                                          bool LegalOperations) {
6755   unsigned Opcode = N->getOpcode();
6756   SDValue N0 = N->getOperand(0);
6757   EVT VT = N->getValueType(0);
6758
6759   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6760          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6761          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6762          && "Expected EXTEND dag node in input!");
6763
6764   // fold (sext c1) -> c1
6765   // fold (zext c1) -> c1
6766   // fold (aext c1) -> c1
6767   if (isa<ConstantSDNode>(N0))
6768     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6769
6770   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6771   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6772   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6773   EVT SVT = VT.getScalarType();
6774   if (!(VT.isVector() &&
6775       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6776       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6777     return nullptr;
6778
6779   // We can fold this node into a build_vector.
6780   unsigned VTBits = SVT.getSizeInBits();
6781   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6782   SmallVector<SDValue, 8> Elts;
6783   unsigned NumElts = VT.getVectorNumElements();
6784   SDLoc DL(N);
6785
6786   for (unsigned i=0; i != NumElts; ++i) {
6787     SDValue Op = N0->getOperand(i);
6788     if (Op->isUndef()) {
6789       Elts.push_back(DAG.getUNDEF(SVT));
6790       continue;
6791     }
6792
6793     SDLoc DL(Op);
6794     // Get the constant value and if needed trunc it to the size of the type.
6795     // Nodes like build_vector might have constants wider than the scalar type.
6796     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6797     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6798       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6799     else
6800       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6801   }
6802
6803   return DAG.getBuildVector(VT, DL, Elts).getNode();
6804 }
6805
6806 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6807 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6808 // transformation. Returns true if extension are possible and the above
6809 // mentioned transformation is profitable.
6810 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6811                                     unsigned ExtOpc,
6812                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6813                                     const TargetLowering &TLI) {
6814   bool HasCopyToRegUses = false;
6815   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6816   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6817                             UE = N0.getNode()->use_end();
6818        UI != UE; ++UI) {
6819     SDNode *User = *UI;
6820     if (User == N)
6821       continue;
6822     if (UI.getUse().getResNo() != N0.getResNo())
6823       continue;
6824     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6825     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6826       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6827       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6828         // Sign bits will be lost after a zext.
6829         return false;
6830       bool Add = false;
6831       for (unsigned i = 0; i != 2; ++i) {
6832         SDValue UseOp = User->getOperand(i);
6833         if (UseOp == N0)
6834           continue;
6835         if (!isa<ConstantSDNode>(UseOp))
6836           return false;
6837         Add = true;
6838       }
6839       if (Add)
6840         ExtendNodes.push_back(User);
6841       continue;
6842     }
6843     // If truncates aren't free and there are users we can't
6844     // extend, it isn't worthwhile.
6845     if (!isTruncFree)
6846       return false;
6847     // Remember if this value is live-out.
6848     if (User->getOpcode() == ISD::CopyToReg)
6849       HasCopyToRegUses = true;
6850   }
6851
6852   if (HasCopyToRegUses) {
6853     bool BothLiveOut = false;
6854     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6855          UI != UE; ++UI) {
6856       SDUse &Use = UI.getUse();
6857       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6858         BothLiveOut = true;
6859         break;
6860       }
6861     }
6862     if (BothLiveOut)
6863       // Both unextended and extended values are live out. There had better be
6864       // a good reason for the transformation.
6865       return ExtendNodes.size();
6866   }
6867   return true;
6868 }
6869
6870 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6871                                   SDValue Trunc, SDValue ExtLoad,
6872                                   const SDLoc &DL, ISD::NodeType ExtType) {
6873   // Extend SetCC uses if necessary.
6874   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6875     SDNode *SetCC = SetCCs[i];
6876     SmallVector<SDValue, 4> Ops;
6877
6878     for (unsigned j = 0; j != 2; ++j) {
6879       SDValue SOp = SetCC->getOperand(j);
6880       if (SOp == Trunc)
6881         Ops.push_back(ExtLoad);
6882       else
6883         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6884     }
6885
6886     Ops.push_back(SetCC->getOperand(2));
6887     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6888   }
6889 }
6890
6891 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6892 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6893   SDValue N0 = N->getOperand(0);
6894   EVT DstVT = N->getValueType(0);
6895   EVT SrcVT = N0.getValueType();
6896
6897   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6898           N->getOpcode() == ISD::ZERO_EXTEND) &&
6899          "Unexpected node type (not an extend)!");
6900
6901   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6902   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6903   //   (v8i32 (sext (v8i16 (load x))))
6904   // into:
6905   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6906   //                          (v4i32 (sextload (x + 16)))))
6907   // Where uses of the original load, i.e.:
6908   //   (v8i16 (load x))
6909   // are replaced with:
6910   //   (v8i16 (truncate
6911   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6912   //                            (v4i32 (sextload (x + 16)))))))
6913   //
6914   // This combine is only applicable to illegal, but splittable, vectors.
6915   // All legal types, and illegal non-vector types, are handled elsewhere.
6916   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6917   //
6918   if (N0->getOpcode() != ISD::LOAD)
6919     return SDValue();
6920
6921   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6922
6923   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6924       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6925       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6926     return SDValue();
6927
6928   SmallVector<SDNode *, 4> SetCCs;
6929   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6930     return SDValue();
6931
6932   ISD::LoadExtType ExtType =
6933       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6934
6935   // Try to split the vector types to get down to legal types.
6936   EVT SplitSrcVT = SrcVT;
6937   EVT SplitDstVT = DstVT;
6938   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6939          SplitSrcVT.getVectorNumElements() > 1) {
6940     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6941     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6942   }
6943
6944   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6945     return SDValue();
6946
6947   SDLoc DL(N);
6948   const unsigned NumSplits =
6949       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6950   const unsigned Stride = SplitSrcVT.getStoreSize();
6951   SmallVector<SDValue, 4> Loads;
6952   SmallVector<SDValue, 4> Chains;
6953
6954   SDValue BasePtr = LN0->getBasePtr();
6955   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6956     const unsigned Offset = Idx * Stride;
6957     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6958
6959     SDValue SplitLoad = DAG.getExtLoad(
6960         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6961         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6962         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6963
6964     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6965                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6966
6967     Loads.push_back(SplitLoad.getValue(0));
6968     Chains.push_back(SplitLoad.getValue(1));
6969   }
6970
6971   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6972   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6973
6974   // Simplify TF.
6975   AddToWorklist(NewChain.getNode());
6976
6977   CombineTo(N, NewValue);
6978
6979   // Replace uses of the original load (before extension)
6980   // with a truncate of the concatenated sextloaded vectors.
6981   SDValue Trunc =
6982       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6983   CombineTo(N0.getNode(), Trunc, NewChain);
6984   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6985                   (ISD::NodeType)N->getOpcode());
6986   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6987 }
6988
6989 /// If we're narrowing or widening the result of a vector select and the final
6990 /// size is the same size as a setcc (compare) feeding the select, then try to
6991 /// apply the cast operation to the select's operands because matching vector
6992 /// sizes for a select condition and other operands should be more efficient.
6993 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
6994   unsigned CastOpcode = Cast->getOpcode();
6995   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
6996           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
6997           CastOpcode == ISD::FP_ROUND) &&
6998          "Unexpected opcode for vector select narrowing/widening");
6999
7000   // We only do this transform before legal ops because the pattern may be
7001   // obfuscated by target-specific operations after legalization. Do not create
7002   // an illegal select op, however, because that may be difficult to lower.
7003   EVT VT = Cast->getValueType(0);
7004   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7005     return SDValue();
7006
7007   SDValue VSel = Cast->getOperand(0);
7008   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7009       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7010     return SDValue();
7011
7012   // Does the setcc have the same vector size as the casted select?
7013   SDValue SetCC = VSel.getOperand(0);
7014   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7015   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7016     return SDValue();
7017
7018   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7019   SDValue A = VSel.getOperand(1);
7020   SDValue B = VSel.getOperand(2);
7021   SDValue CastA, CastB;
7022   SDLoc DL(Cast);
7023   if (CastOpcode == ISD::FP_ROUND) {
7024     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7025     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7026     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7027   } else {
7028     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7029     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7030   }
7031   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7032 }
7033
7034 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7035   SDValue N0 = N->getOperand(0);
7036   EVT VT = N->getValueType(0);
7037   SDLoc DL(N);
7038
7039   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7040                                               LegalOperations))
7041     return SDValue(Res, 0);
7042
7043   // fold (sext (sext x)) -> (sext x)
7044   // fold (sext (aext x)) -> (sext x)
7045   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7046     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7047
7048   if (N0.getOpcode() == ISD::TRUNCATE) {
7049     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7050     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7051     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7052       SDNode *oye = N0.getOperand(0).getNode();
7053       if (NarrowLoad.getNode() != N0.getNode()) {
7054         CombineTo(N0.getNode(), NarrowLoad);
7055         // CombineTo deleted the truncate, if needed, but not what's under it.
7056         AddToWorklist(oye);
7057       }
7058       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7059     }
7060
7061     // See if the value being truncated is already sign extended.  If so, just
7062     // eliminate the trunc/sext pair.
7063     SDValue Op = N0.getOperand(0);
7064     unsigned OpBits   = Op.getScalarValueSizeInBits();
7065     unsigned MidBits  = N0.getScalarValueSizeInBits();
7066     unsigned DestBits = VT.getScalarSizeInBits();
7067     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7068
7069     if (OpBits == DestBits) {
7070       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7071       // bits, it is already ready.
7072       if (NumSignBits > DestBits-MidBits)
7073         return Op;
7074     } else if (OpBits < DestBits) {
7075       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7076       // bits, just sext from i32.
7077       if (NumSignBits > OpBits-MidBits)
7078         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7079     } else {
7080       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7081       // bits, just truncate to i32.
7082       if (NumSignBits > OpBits-MidBits)
7083         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7084     }
7085
7086     // fold (sext (truncate x)) -> (sextinreg x).
7087     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7088                                                  N0.getValueType())) {
7089       if (OpBits < DestBits)
7090         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7091       else if (OpBits > DestBits)
7092         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7093       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7094                          DAG.getValueType(N0.getValueType()));
7095     }
7096   }
7097
7098   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7099   // Only generate vector extloads when 1) they're legal, and 2) they are
7100   // deemed desirable by the target.
7101   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7102       ((!LegalOperations && !VT.isVector() &&
7103         !cast<LoadSDNode>(N0)->isVolatile()) ||
7104        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7105     bool DoXform = true;
7106     SmallVector<SDNode*, 4> SetCCs;
7107     if (!N0.hasOneUse())
7108       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7109     if (VT.isVector())
7110       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7111     if (DoXform) {
7112       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7113       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7114                                        LN0->getBasePtr(), N0.getValueType(),
7115                                        LN0->getMemOperand());
7116       CombineTo(N, ExtLoad);
7117       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7118                                   N0.getValueType(), ExtLoad);
7119       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7120       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7121       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7122     }
7123   }
7124
7125   // fold (sext (load x)) to multiple smaller sextloads.
7126   // Only on illegal but splittable vectors.
7127   if (SDValue ExtLoad = CombineExtLoad(N))
7128     return ExtLoad;
7129
7130   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7131   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7132   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7133       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7134     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7135     EVT MemVT = LN0->getMemoryVT();
7136     if ((!LegalOperations && !LN0->isVolatile()) ||
7137         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7138       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7139                                        LN0->getBasePtr(), MemVT,
7140                                        LN0->getMemOperand());
7141       CombineTo(N, ExtLoad);
7142       CombineTo(N0.getNode(),
7143                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7144                             N0.getValueType(), ExtLoad),
7145                 ExtLoad.getValue(1));
7146       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7147     }
7148   }
7149
7150   // fold (sext (and/or/xor (load x), cst)) ->
7151   //      (and/or/xor (sextload x), (sext cst))
7152   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7153        N0.getOpcode() == ISD::XOR) &&
7154       isa<LoadSDNode>(N0.getOperand(0)) &&
7155       N0.getOperand(1).getOpcode() == ISD::Constant &&
7156       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7157       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7158     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7159     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7160       bool DoXform = true;
7161       SmallVector<SDNode*, 4> SetCCs;
7162       if (!N0.hasOneUse())
7163         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7164                                           SetCCs, TLI);
7165       if (DoXform) {
7166         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7167                                          LN0->getChain(), LN0->getBasePtr(),
7168                                          LN0->getMemoryVT(),
7169                                          LN0->getMemOperand());
7170         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7171         Mask = Mask.sext(VT.getSizeInBits());
7172         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7173                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7174         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7175                                     SDLoc(N0.getOperand(0)),
7176                                     N0.getOperand(0).getValueType(), ExtLoad);
7177         CombineTo(N, And);
7178         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7179         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7180         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7181       }
7182     }
7183   }
7184
7185   if (N0.getOpcode() == ISD::SETCC) {
7186     SDValue N00 = N0.getOperand(0);
7187     SDValue N01 = N0.getOperand(1);
7188     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7189     EVT N00VT = N0.getOperand(0).getValueType();
7190
7191     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7192     // Only do this before legalize for now.
7193     if (VT.isVector() && !LegalOperations &&
7194         TLI.getBooleanContents(N00VT) ==
7195             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7196       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7197       // of the same size as the compared operands. Only optimize sext(setcc())
7198       // if this is the case.
7199       EVT SVT = getSetCCResultType(N00VT);
7200
7201       // We know that the # elements of the results is the same as the
7202       // # elements of the compare (and the # elements of the compare result
7203       // for that matter).  Check to see that they are the same size.  If so,
7204       // we know that the element size of the sext'd result matches the
7205       // element size of the compare operands.
7206       if (VT.getSizeInBits() == SVT.getSizeInBits())
7207         return DAG.getSetCC(DL, VT, N00, N01, CC);
7208
7209       // If the desired elements are smaller or larger than the source
7210       // elements, we can use a matching integer vector type and then
7211       // truncate/sign extend.
7212       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7213       if (SVT == MatchingVecType) {
7214         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7215         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7216       }
7217     }
7218
7219     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7220     // Here, T can be 1 or -1, depending on the type of the setcc and
7221     // getBooleanContents().
7222     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7223
7224     // To determine the "true" side of the select, we need to know the high bit
7225     // of the value returned by the setcc if it evaluates to true.
7226     // If the type of the setcc is i1, then the true case of the select is just
7227     // sext(i1 1), that is, -1.
7228     // If the type of the setcc is larger (say, i8) then the value of the high
7229     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7230     // of the appropriate width.
7231     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7232                                            : TLI.getConstTrueVal(DAG, VT, DL);
7233     SDValue Zero = DAG.getConstant(0, DL, VT);
7234     if (SDValue SCC =
7235             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7236       return SCC;
7237
7238     if (!VT.isVector()) {
7239       EVT SetCCVT = getSetCCResultType(N00VT);
7240       // Don't do this transform for i1 because there's a select transform
7241       // that would reverse it.
7242       // TODO: We should not do this transform at all without a target hook
7243       // because a sext is likely cheaper than a select?
7244       if (SetCCVT.getScalarSizeInBits() != 1 &&
7245           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7246         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7247         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7248       }
7249     }
7250   }
7251
7252   // fold (sext x) -> (zext x) if the sign bit is known zero.
7253   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7254       DAG.SignBitIsZero(N0))
7255     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7256
7257   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7258     return NewVSel;
7259
7260   return SDValue();
7261 }
7262
7263 // isTruncateOf - If N is a truncate of some other value, return true, record
7264 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7265 // This function computes KnownBits to avoid a duplicated call to
7266 // computeKnownBits in the caller.
7267 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7268                          KnownBits &Known) {
7269   if (N->getOpcode() == ISD::TRUNCATE) {
7270     Op = N->getOperand(0);
7271     DAG.computeKnownBits(Op, Known);
7272     return true;
7273   }
7274
7275   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7276       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7277     return false;
7278
7279   SDValue Op0 = N->getOperand(0);
7280   SDValue Op1 = N->getOperand(1);
7281   assert(Op0.getValueType() == Op1.getValueType());
7282
7283   if (isNullConstant(Op0))
7284     Op = Op1;
7285   else if (isNullConstant(Op1))
7286     Op = Op0;
7287   else
7288     return false;
7289
7290   DAG.computeKnownBits(Op, Known);
7291
7292   if (!(Known.Zero | 1).isAllOnesValue())
7293     return false;
7294
7295   return true;
7296 }
7297
7298 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7299   SDValue N0 = N->getOperand(0);
7300   EVT VT = N->getValueType(0);
7301
7302   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7303                                               LegalOperations))
7304     return SDValue(Res, 0);
7305
7306   // fold (zext (zext x)) -> (zext x)
7307   // fold (zext (aext x)) -> (zext x)
7308   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7309     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7310                        N0.getOperand(0));
7311
7312   // fold (zext (truncate x)) -> (zext x) or
7313   //      (zext (truncate x)) -> (truncate x)
7314   // This is valid when the truncated bits of x are already zero.
7315   // FIXME: We should extend this to work for vectors too.
7316   SDValue Op;
7317   KnownBits Known;
7318   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7319     APInt TruncatedBits =
7320       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7321       APInt(Op.getValueSizeInBits(), 0) :
7322       APInt::getBitsSet(Op.getValueSizeInBits(),
7323                         N0.getValueSizeInBits(),
7324                         std::min(Op.getValueSizeInBits(),
7325                                  VT.getSizeInBits()));
7326     if (TruncatedBits.isSubsetOf(Known.Zero))
7327       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7328   }
7329
7330   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7331   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7332   if (N0.getOpcode() == ISD::TRUNCATE) {
7333     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7334       SDNode *oye = N0.getOperand(0).getNode();
7335       if (NarrowLoad.getNode() != N0.getNode()) {
7336         CombineTo(N0.getNode(), NarrowLoad);
7337         // CombineTo deleted the truncate, if needed, but not what's under it.
7338         AddToWorklist(oye);
7339       }
7340       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7341     }
7342   }
7343
7344   // fold (zext (truncate x)) -> (and x, mask)
7345   if (N0.getOpcode() == ISD::TRUNCATE) {
7346     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7347     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7348     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7349       SDNode *oye = N0.getOperand(0).getNode();
7350       if (NarrowLoad.getNode() != N0.getNode()) {
7351         CombineTo(N0.getNode(), NarrowLoad);
7352         // CombineTo deleted the truncate, if needed, but not what's under it.
7353         AddToWorklist(oye);
7354       }
7355       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7356     }
7357
7358     EVT SrcVT = N0.getOperand(0).getValueType();
7359     EVT MinVT = N0.getValueType();
7360
7361     // Try to mask before the extension to avoid having to generate a larger mask,
7362     // possibly over several sub-vectors.
7363     if (SrcVT.bitsLT(VT)) {
7364       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7365                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7366         SDValue Op = N0.getOperand(0);
7367         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7368         AddToWorklist(Op.getNode());
7369         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7370       }
7371     }
7372
7373     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7374       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7375       AddToWorklist(Op.getNode());
7376       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7377     }
7378   }
7379
7380   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7381   // if either of the casts is not free.
7382   if (N0.getOpcode() == ISD::AND &&
7383       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7384       N0.getOperand(1).getOpcode() == ISD::Constant &&
7385       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7386                            N0.getValueType()) ||
7387        !TLI.isZExtFree(N0.getValueType(), VT))) {
7388     SDValue X = N0.getOperand(0).getOperand(0);
7389     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7390     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7391     Mask = Mask.zext(VT.getSizeInBits());
7392     SDLoc DL(N);
7393     return DAG.getNode(ISD::AND, DL, VT,
7394                        X, DAG.getConstant(Mask, DL, VT));
7395   }
7396
7397   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7398   // Only generate vector extloads when 1) they're legal, and 2) they are
7399   // deemed desirable by the target.
7400   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7401       ((!LegalOperations && !VT.isVector() &&
7402         !cast<LoadSDNode>(N0)->isVolatile()) ||
7403        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7404     bool DoXform = true;
7405     SmallVector<SDNode*, 4> SetCCs;
7406     if (!N0.hasOneUse())
7407       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7408     if (VT.isVector())
7409       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7410     if (DoXform) {
7411       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7412       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7413                                        LN0->getChain(),
7414                                        LN0->getBasePtr(), N0.getValueType(),
7415                                        LN0->getMemOperand());
7416
7417       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7418                                   N0.getValueType(), ExtLoad);
7419       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7420
7421       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7422                       ISD::ZERO_EXTEND);
7423       CombineTo(N, ExtLoad);
7424       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7425     }
7426   }
7427
7428   // fold (zext (load x)) to multiple smaller zextloads.
7429   // Only on illegal but splittable vectors.
7430   if (SDValue ExtLoad = CombineExtLoad(N))
7431     return ExtLoad;
7432
7433   // fold (zext (and/or/xor (load x), cst)) ->
7434   //      (and/or/xor (zextload x), (zext cst))
7435   // Unless (and (load x) cst) will match as a zextload already and has
7436   // additional users.
7437   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7438        N0.getOpcode() == ISD::XOR) &&
7439       isa<LoadSDNode>(N0.getOperand(0)) &&
7440       N0.getOperand(1).getOpcode() == ISD::Constant &&
7441       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7442       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7443     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7444     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7445       bool DoXform = true;
7446       SmallVector<SDNode*, 4> SetCCs;
7447       if (!N0.hasOneUse()) {
7448         if (N0.getOpcode() == ISD::AND) {
7449           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7450           auto NarrowLoad = false;
7451           EVT LoadResultTy = AndC->getValueType(0);
7452           EVT ExtVT, LoadedVT;
7453           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7454                                NarrowLoad))
7455             DoXform = false;
7456         }
7457         if (DoXform)
7458           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7459                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7460       }
7461       if (DoXform) {
7462         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7463                                          LN0->getChain(), LN0->getBasePtr(),
7464                                          LN0->getMemoryVT(),
7465                                          LN0->getMemOperand());
7466         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7467         Mask = Mask.zext(VT.getSizeInBits());
7468         SDLoc DL(N);
7469         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7470                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7471         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7472                                     SDLoc(N0.getOperand(0)),
7473                                     N0.getOperand(0).getValueType(), ExtLoad);
7474         CombineTo(N, And);
7475         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7476         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
7477                         ISD::ZERO_EXTEND);
7478         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7479       }
7480     }
7481   }
7482
7483   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7484   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7485   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7486       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7487     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7488     EVT MemVT = LN0->getMemoryVT();
7489     if ((!LegalOperations && !LN0->isVolatile()) ||
7490         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7491       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7492                                        LN0->getChain(),
7493                                        LN0->getBasePtr(), MemVT,
7494                                        LN0->getMemOperand());
7495       CombineTo(N, ExtLoad);
7496       CombineTo(N0.getNode(),
7497                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7498                             ExtLoad),
7499                 ExtLoad.getValue(1));
7500       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7501     }
7502   }
7503
7504   if (N0.getOpcode() == ISD::SETCC) {
7505     // Only do this before legalize for now.
7506     if (!LegalOperations && VT.isVector() &&
7507         N0.getValueType().getVectorElementType() == MVT::i1) {
7508       EVT N00VT = N0.getOperand(0).getValueType();
7509       if (getSetCCResultType(N00VT) == N0.getValueType())
7510         return SDValue();
7511
7512       // We know that the # elements of the results is the same as the #
7513       // elements of the compare (and the # elements of the compare result for
7514       // that matter). Check to see that they are the same size. If so, we know
7515       // that the element size of the sext'd result matches the element size of
7516       // the compare operands.
7517       SDLoc DL(N);
7518       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7519       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7520         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7521         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7522                                      N0.getOperand(1), N0.getOperand(2));
7523         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7524       }
7525
7526       // If the desired elements are smaller or larger than the source
7527       // elements we can use a matching integer vector type and then
7528       // truncate/sign extend.
7529       EVT MatchingElementType = EVT::getIntegerVT(
7530           *DAG.getContext(), N00VT.getScalarSizeInBits());
7531       EVT MatchingVectorType = EVT::getVectorVT(
7532           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7533       SDValue VsetCC =
7534           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7535                       N0.getOperand(1), N0.getOperand(2));
7536       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7537                          VecOnes);
7538     }
7539
7540     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7541     SDLoc DL(N);
7542     if (SDValue SCC = SimplifySelectCC(
7543             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7544             DAG.getConstant(0, DL, VT),
7545             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7546       return SCC;
7547   }
7548
7549   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7550   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7551       isa<ConstantSDNode>(N0.getOperand(1)) &&
7552       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7553       N0.hasOneUse()) {
7554     SDValue ShAmt = N0.getOperand(1);
7555     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7556     if (N0.getOpcode() == ISD::SHL) {
7557       SDValue InnerZExt = N0.getOperand(0);
7558       // If the original shl may be shifting out bits, do not perform this
7559       // transformation.
7560       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7561         InnerZExt.getOperand(0).getValueSizeInBits();
7562       if (ShAmtVal > KnownZeroBits)
7563         return SDValue();
7564     }
7565
7566     SDLoc DL(N);
7567
7568     // Ensure that the shift amount is wide enough for the shifted value.
7569     if (VT.getSizeInBits() >= 256)
7570       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7571
7572     return DAG.getNode(N0.getOpcode(), DL, VT,
7573                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7574                        ShAmt);
7575   }
7576
7577   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7578     return NewVSel;
7579
7580   return SDValue();
7581 }
7582
7583 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7584   SDValue N0 = N->getOperand(0);
7585   EVT VT = N->getValueType(0);
7586
7587   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7588                                               LegalOperations))
7589     return SDValue(Res, 0);
7590
7591   // fold (aext (aext x)) -> (aext x)
7592   // fold (aext (zext x)) -> (zext x)
7593   // fold (aext (sext x)) -> (sext x)
7594   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7595       N0.getOpcode() == ISD::ZERO_EXTEND ||
7596       N0.getOpcode() == ISD::SIGN_EXTEND)
7597     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7598
7599   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7600   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7601   if (N0.getOpcode() == ISD::TRUNCATE) {
7602     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7603       SDNode *oye = N0.getOperand(0).getNode();
7604       if (NarrowLoad.getNode() != N0.getNode()) {
7605         CombineTo(N0.getNode(), NarrowLoad);
7606         // CombineTo deleted the truncate, if needed, but not what's under it.
7607         AddToWorklist(oye);
7608       }
7609       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7610     }
7611   }
7612
7613   // fold (aext (truncate x))
7614   if (N0.getOpcode() == ISD::TRUNCATE)
7615     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7616
7617   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7618   // if the trunc is not free.
7619   if (N0.getOpcode() == ISD::AND &&
7620       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7621       N0.getOperand(1).getOpcode() == ISD::Constant &&
7622       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7623                           N0.getValueType())) {
7624     SDLoc DL(N);
7625     SDValue X = N0.getOperand(0).getOperand(0);
7626     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7627     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7628     Mask = Mask.zext(VT.getSizeInBits());
7629     return DAG.getNode(ISD::AND, DL, VT,
7630                        X, DAG.getConstant(Mask, DL, VT));
7631   }
7632
7633   // fold (aext (load x)) -> (aext (truncate (extload x)))
7634   // None of the supported targets knows how to perform load and any_ext
7635   // on vectors in one instruction.  We only perform this transformation on
7636   // scalars.
7637   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7638       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7639       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7640     bool DoXform = true;
7641     SmallVector<SDNode*, 4> SetCCs;
7642     if (!N0.hasOneUse())
7643       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7644     if (DoXform) {
7645       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7646       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7647                                        LN0->getChain(),
7648                                        LN0->getBasePtr(), N0.getValueType(),
7649                                        LN0->getMemOperand());
7650       CombineTo(N, ExtLoad);
7651       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7652                                   N0.getValueType(), ExtLoad);
7653       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7654       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7655                       ISD::ANY_EXTEND);
7656       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7657     }
7658   }
7659
7660   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7661   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7662   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7663   if (N0.getOpcode() == ISD::LOAD &&
7664       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7665       N0.hasOneUse()) {
7666     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7667     ISD::LoadExtType ExtType = LN0->getExtensionType();
7668     EVT MemVT = LN0->getMemoryVT();
7669     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7670       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7671                                        VT, LN0->getChain(), LN0->getBasePtr(),
7672                                        MemVT, LN0->getMemOperand());
7673       CombineTo(N, ExtLoad);
7674       CombineTo(N0.getNode(),
7675                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7676                             N0.getValueType(), ExtLoad),
7677                 ExtLoad.getValue(1));
7678       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7679     }
7680   }
7681
7682   if (N0.getOpcode() == ISD::SETCC) {
7683     // For vectors:
7684     // aext(setcc) -> vsetcc
7685     // aext(setcc) -> truncate(vsetcc)
7686     // aext(setcc) -> aext(vsetcc)
7687     // Only do this before legalize for now.
7688     if (VT.isVector() && !LegalOperations) {
7689       EVT N0VT = N0.getOperand(0).getValueType();
7690         // We know that the # elements of the results is the same as the
7691         // # elements of the compare (and the # elements of the compare result
7692         // for that matter).  Check to see that they are the same size.  If so,
7693         // we know that the element size of the sext'd result matches the
7694         // element size of the compare operands.
7695       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7696         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7697                              N0.getOperand(1),
7698                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7699       // If the desired elements are smaller or larger than the source
7700       // elements we can use a matching integer vector type and then
7701       // truncate/any extend
7702       else {
7703         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7704         SDValue VsetCC =
7705           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7706                         N0.getOperand(1),
7707                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7708         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7709       }
7710     }
7711
7712     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7713     SDLoc DL(N);
7714     if (SDValue SCC = SimplifySelectCC(
7715             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7716             DAG.getConstant(0, DL, VT),
7717             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7718       return SCC;
7719   }
7720
7721   return SDValue();
7722 }
7723
7724 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7725   SDValue N0 = N->getOperand(0);
7726   SDValue N1 = N->getOperand(1);
7727   EVT EVT = cast<VTSDNode>(N1)->getVT();
7728
7729   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7730   if (N0.getOpcode() == ISD::AssertZext &&
7731       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7732     return N0;
7733
7734   return SDValue();
7735 }
7736
7737 /// See if the specified operand can be simplified with the knowledge that only
7738 /// the bits specified by Mask are used.  If so, return the simpler operand,
7739 /// otherwise return a null SDValue.
7740 ///
7741 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7742 /// simplify nodes with multiple uses more aggressively.)
7743 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7744   switch (V.getOpcode()) {
7745   default: break;
7746   case ISD::Constant: {
7747     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7748     assert(CV && "Const value should be ConstSDNode.");
7749     const APInt &CVal = CV->getAPIntValue();
7750     APInt NewVal = CVal & Mask;
7751     if (NewVal != CVal)
7752       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7753     break;
7754   }
7755   case ISD::OR:
7756   case ISD::XOR:
7757     // If the LHS or RHS don't contribute bits to the or, drop them.
7758     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7759       return V.getOperand(1);
7760     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7761       return V.getOperand(0);
7762     break;
7763   case ISD::SRL:
7764     // Only look at single-use SRLs.
7765     if (!V.getNode()->hasOneUse())
7766       break;
7767     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7768       // See if we can recursively simplify the LHS.
7769       unsigned Amt = RHSC->getZExtValue();
7770
7771       // Watch out for shift count overflow though.
7772       if (Amt >= Mask.getBitWidth()) break;
7773       APInt NewMask = Mask << Amt;
7774       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7775         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7776                            SimplifyLHS, V.getOperand(1));
7777     }
7778     break;
7779   case ISD::AND: {
7780     // X & -1 -> X (ignoring bits which aren't demanded).
7781     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7782     if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7783       return V.getOperand(0);
7784     break;
7785   }
7786   }
7787   return SDValue();
7788 }
7789
7790 /// If the result of a wider load is shifted to right of N  bits and then
7791 /// truncated to a narrower type and where N is a multiple of number of bits of
7792 /// the narrower type, transform it to a narrower load from address + N / num of
7793 /// bits of new type. If the result is to be extended, also fold the extension
7794 /// to form a extending load.
7795 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7796   unsigned Opc = N->getOpcode();
7797
7798   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7799   SDValue N0 = N->getOperand(0);
7800   EVT VT = N->getValueType(0);
7801   EVT ExtVT = VT;
7802
7803   // This transformation isn't valid for vector loads.
7804   if (VT.isVector())
7805     return SDValue();
7806
7807   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7808   // extended to VT.
7809   if (Opc == ISD::SIGN_EXTEND_INREG) {
7810     ExtType = ISD::SEXTLOAD;
7811     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7812   } else if (Opc == ISD::SRL) {
7813     // Another special-case: SRL is basically zero-extending a narrower value.
7814     ExtType = ISD::ZEXTLOAD;
7815     N0 = SDValue(N, 0);
7816     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7817     if (!N01) return SDValue();
7818     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7819                               VT.getSizeInBits() - N01->getZExtValue());
7820   }
7821   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7822     return SDValue();
7823
7824   unsigned EVTBits = ExtVT.getSizeInBits();
7825
7826   // Do not generate loads of non-round integer types since these can
7827   // be expensive (and would be wrong if the type is not byte sized).
7828   if (!ExtVT.isRound())
7829     return SDValue();
7830
7831   unsigned ShAmt = 0;
7832   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7833     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7834       ShAmt = N01->getZExtValue();
7835       // Is the shift amount a multiple of size of VT?
7836       if ((ShAmt & (EVTBits-1)) == 0) {
7837         N0 = N0.getOperand(0);
7838         // Is the load width a multiple of size of VT?
7839         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7840           return SDValue();
7841       }
7842
7843       // At this point, we must have a load or else we can't do the transform.
7844       if (!isa<LoadSDNode>(N0)) return SDValue();
7845
7846       // Because a SRL must be assumed to *need* to zero-extend the high bits
7847       // (as opposed to anyext the high bits), we can't combine the zextload
7848       // lowering of SRL and an sextload.
7849       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7850         return SDValue();
7851
7852       // If the shift amount is larger than the input type then we're not
7853       // accessing any of the loaded bytes.  If the load was a zextload/extload
7854       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7855       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7856         return SDValue();
7857     }
7858   }
7859
7860   // If the load is shifted left (and the result isn't shifted back right),
7861   // we can fold the truncate through the shift.
7862   unsigned ShLeftAmt = 0;
7863   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7864       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7865     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7866       ShLeftAmt = N01->getZExtValue();
7867       N0 = N0.getOperand(0);
7868     }
7869   }
7870
7871   // If we haven't found a load, we can't narrow it.  Don't transform one with
7872   // multiple uses, this would require adding a new load.
7873   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7874     return SDValue();
7875
7876   // Don't change the width of a volatile load.
7877   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7878   if (LN0->isVolatile())
7879     return SDValue();
7880
7881   // Verify that we are actually reducing a load width here.
7882   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7883     return SDValue();
7884
7885   // For the transform to be legal, the load must produce only two values
7886   // (the value loaded and the chain).  Don't transform a pre-increment
7887   // load, for example, which produces an extra value.  Otherwise the
7888   // transformation is not equivalent, and the downstream logic to replace
7889   // uses gets things wrong.
7890   if (LN0->getNumValues() > 2)
7891     return SDValue();
7892
7893   // If the load that we're shrinking is an extload and we're not just
7894   // discarding the extension we can't simply shrink the load. Bail.
7895   // TODO: It would be possible to merge the extensions in some cases.
7896   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7897       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7898     return SDValue();
7899
7900   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7901     return SDValue();
7902
7903   EVT PtrType = N0.getOperand(1).getValueType();
7904
7905   if (PtrType == MVT::Untyped || PtrType.isExtended())
7906     // It's not possible to generate a constant of extended or untyped type.
7907     return SDValue();
7908
7909   // For big endian targets, we need to adjust the offset to the pointer to
7910   // load the correct bytes.
7911   if (DAG.getDataLayout().isBigEndian()) {
7912     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7913     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7914     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7915   }
7916
7917   uint64_t PtrOff = ShAmt / 8;
7918   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7919   SDLoc DL(LN0);
7920   // The original load itself didn't wrap, so an offset within it doesn't.
7921   SDNodeFlags Flags;
7922   Flags.setNoUnsignedWrap(true);
7923   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7924                                PtrType, LN0->getBasePtr(),
7925                                DAG.getConstant(PtrOff, DL, PtrType),
7926                                Flags);
7927   AddToWorklist(NewPtr.getNode());
7928
7929   SDValue Load;
7930   if (ExtType == ISD::NON_EXTLOAD)
7931     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7932                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7933                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7934   else
7935     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7936                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7937                           NewAlign, LN0->getMemOperand()->getFlags(),
7938                           LN0->getAAInfo());
7939
7940   // Replace the old load's chain with the new load's chain.
7941   WorklistRemover DeadNodes(*this);
7942   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7943
7944   // Shift the result left, if we've swallowed a left shift.
7945   SDValue Result = Load;
7946   if (ShLeftAmt != 0) {
7947     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7948     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7949       ShImmTy = VT;
7950     // If the shift amount is as large as the result size (but, presumably,
7951     // no larger than the source) then the useful bits of the result are
7952     // zero; we can't simply return the shortened shift, because the result
7953     // of that operation is undefined.
7954     SDLoc DL(N0);
7955     if (ShLeftAmt >= VT.getSizeInBits())
7956       Result = DAG.getConstant(0, DL, VT);
7957     else
7958       Result = DAG.getNode(ISD::SHL, DL, VT,
7959                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7960   }
7961
7962   // Return the new loaded value.
7963   return Result;
7964 }
7965
7966 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7967   SDValue N0 = N->getOperand(0);
7968   SDValue N1 = N->getOperand(1);
7969   EVT VT = N->getValueType(0);
7970   EVT EVT = cast<VTSDNode>(N1)->getVT();
7971   unsigned VTBits = VT.getScalarSizeInBits();
7972   unsigned EVTBits = EVT.getScalarSizeInBits();
7973
7974   if (N0.isUndef())
7975     return DAG.getUNDEF(VT);
7976
7977   // fold (sext_in_reg c1) -> c1
7978   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7979     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7980
7981   // If the input is already sign extended, just drop the extension.
7982   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7983     return N0;
7984
7985   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7986   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7987       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7988     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7989                        N0.getOperand(0), N1);
7990
7991   // fold (sext_in_reg (sext x)) -> (sext x)
7992   // fold (sext_in_reg (aext x)) -> (sext x)
7993   // if x is small enough.
7994   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7995     SDValue N00 = N0.getOperand(0);
7996     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7997         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7998       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7999   }
8000
8001   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8002   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8003        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8004        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8005       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8006     if (!LegalOperations ||
8007         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8008       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8009   }
8010
8011   // fold (sext_in_reg (zext x)) -> (sext x)
8012   // iff we are extending the source sign bit.
8013   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8014     SDValue N00 = N0.getOperand(0);
8015     if (N00.getScalarValueSizeInBits() == EVTBits &&
8016         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8017       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8018   }
8019
8020   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8021   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8022     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8023
8024   // fold operands of sext_in_reg based on knowledge that the top bits are not
8025   // demanded.
8026   if (SimplifyDemandedBits(SDValue(N, 0)))
8027     return SDValue(N, 0);
8028
8029   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8030   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8031   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8032     return NarrowLoad;
8033
8034   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8035   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8036   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8037   if (N0.getOpcode() == ISD::SRL) {
8038     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8039       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8040         // We can turn this into an SRA iff the input to the SRL is already sign
8041         // extended enough.
8042         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8043         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8044           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8045                              N0.getOperand(0), N0.getOperand(1));
8046       }
8047   }
8048
8049   // fold (sext_inreg (extload x)) -> (sextload x)
8050   if (ISD::isEXTLoad(N0.getNode()) &&
8051       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8052       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8053       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8054        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8055     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8056     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8057                                      LN0->getChain(),
8058                                      LN0->getBasePtr(), EVT,
8059                                      LN0->getMemOperand());
8060     CombineTo(N, ExtLoad);
8061     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8062     AddToWorklist(ExtLoad.getNode());
8063     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8064   }
8065   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8066   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8067       N0.hasOneUse() &&
8068       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8069       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8070        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8071     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8072     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8073                                      LN0->getChain(),
8074                                      LN0->getBasePtr(), EVT,
8075                                      LN0->getMemOperand());
8076     CombineTo(N, ExtLoad);
8077     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8078     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8079   }
8080
8081   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8082   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8083     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8084                                            N0.getOperand(1), false))
8085       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8086                          BSwap, N1);
8087   }
8088
8089   return SDValue();
8090 }
8091
8092 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8093   SDValue N0 = N->getOperand(0);
8094   EVT VT = N->getValueType(0);
8095
8096   if (N0.isUndef())
8097     return DAG.getUNDEF(VT);
8098
8099   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8100                                               LegalOperations))
8101     return SDValue(Res, 0);
8102
8103   return SDValue();
8104 }
8105
8106 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8107   SDValue N0 = N->getOperand(0);
8108   EVT VT = N->getValueType(0);
8109
8110   if (N0.isUndef())
8111     return DAG.getUNDEF(VT);
8112
8113   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8114                                               LegalOperations))
8115     return SDValue(Res, 0);
8116
8117   return SDValue();
8118 }
8119
8120 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8121   SDValue N0 = N->getOperand(0);
8122   EVT VT = N->getValueType(0);
8123   bool isLE = DAG.getDataLayout().isLittleEndian();
8124
8125   // noop truncate
8126   if (N0.getValueType() == N->getValueType(0))
8127     return N0;
8128   // fold (truncate c1) -> c1
8129   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8130     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8131   // fold (truncate (truncate x)) -> (truncate x)
8132   if (N0.getOpcode() == ISD::TRUNCATE)
8133     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8134   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8135   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8136       N0.getOpcode() == ISD::SIGN_EXTEND ||
8137       N0.getOpcode() == ISD::ANY_EXTEND) {
8138     // if the source is smaller than the dest, we still need an extend.
8139     if (N0.getOperand(0).getValueType().bitsLT(VT))
8140       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8141     // if the source is larger than the dest, than we just need the truncate.
8142     if (N0.getOperand(0).getValueType().bitsGT(VT))
8143       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8144     // if the source and dest are the same type, we can drop both the extend
8145     // and the truncate.
8146     return N0.getOperand(0);
8147   }
8148
8149   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8150   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8151     return SDValue();
8152
8153   // Fold extract-and-trunc into a narrow extract. For example:
8154   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8155   //   i32 y = TRUNCATE(i64 x)
8156   //        -- becomes --
8157   //   v16i8 b = BITCAST (v2i64 val)
8158   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8159   //
8160   // Note: We only run this optimization after type legalization (which often
8161   // creates this pattern) and before operation legalization after which
8162   // we need to be more careful about the vector instructions that we generate.
8163   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8164       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8165
8166     EVT VecTy = N0.getOperand(0).getValueType();
8167     EVT ExTy = N0.getValueType();
8168     EVT TrTy = N->getValueType(0);
8169
8170     unsigned NumElem = VecTy.getVectorNumElements();
8171     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8172
8173     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8174     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8175
8176     SDValue EltNo = N0->getOperand(1);
8177     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8178       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8179       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8180       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8181
8182       SDLoc DL(N);
8183       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8184                          DAG.getBitcast(NVT, N0.getOperand(0)),
8185                          DAG.getConstant(Index, DL, IndexTy));
8186     }
8187   }
8188
8189   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8190   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8191     EVT SrcVT = N0.getValueType();
8192     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8193         TLI.isTruncateFree(SrcVT, VT)) {
8194       SDLoc SL(N0);
8195       SDValue Cond = N0.getOperand(0);
8196       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8197       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8198       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8199     }
8200   }
8201
8202   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8203   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8204       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8205       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8206     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
8207       uint64_t Amt = CAmt->getZExtValue();
8208       unsigned Size = VT.getScalarSizeInBits();
8209
8210       if (Amt < Size) {
8211         SDLoc SL(N);
8212         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8213
8214         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8215         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
8216                            DAG.getConstant(Amt, SL, AmtVT));
8217       }
8218     }
8219   }
8220
8221   // Fold a series of buildvector, bitcast, and truncate if possible.
8222   // For example fold
8223   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8224   //   (2xi32 (buildvector x, y)).
8225   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8226       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8227       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8228       N0.getOperand(0).hasOneUse()) {
8229
8230     SDValue BuildVect = N0.getOperand(0);
8231     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8232     EVT TruncVecEltTy = VT.getVectorElementType();
8233
8234     // Check that the element types match.
8235     if (BuildVectEltTy == TruncVecEltTy) {
8236       // Now we only need to compute the offset of the truncated elements.
8237       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8238       unsigned TruncVecNumElts = VT.getVectorNumElements();
8239       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8240
8241       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8242              "Invalid number of elements");
8243
8244       SmallVector<SDValue, 8> Opnds;
8245       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8246         Opnds.push_back(BuildVect.getOperand(i));
8247
8248       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8249     }
8250   }
8251
8252   // See if we can simplify the input to this truncate through knowledge that
8253   // only the low bits are being used.
8254   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8255   // Currently we only perform this optimization on scalars because vectors
8256   // may have different active low bits.
8257   if (!VT.isVector()) {
8258     if (SDValue Shorter =
8259             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8260                                                      VT.getSizeInBits())))
8261       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8262   }
8263
8264   // fold (truncate (load x)) -> (smaller load x)
8265   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8266   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8267     if (SDValue Reduced = ReduceLoadWidth(N))
8268       return Reduced;
8269
8270     // Handle the case where the load remains an extending load even
8271     // after truncation.
8272     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8273       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8274       if (!LN0->isVolatile() &&
8275           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8276         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8277                                          VT, LN0->getChain(), LN0->getBasePtr(),
8278                                          LN0->getMemoryVT(),
8279                                          LN0->getMemOperand());
8280         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8281         return NewLoad;
8282       }
8283     }
8284   }
8285
8286   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8287   // where ... are all 'undef'.
8288   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8289     SmallVector<EVT, 8> VTs;
8290     SDValue V;
8291     unsigned Idx = 0;
8292     unsigned NumDefs = 0;
8293
8294     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8295       SDValue X = N0.getOperand(i);
8296       if (!X.isUndef()) {
8297         V = X;
8298         Idx = i;
8299         NumDefs++;
8300       }
8301       // Stop if more than one members are non-undef.
8302       if (NumDefs > 1)
8303         break;
8304       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8305                                      VT.getVectorElementType(),
8306                                      X.getValueType().getVectorNumElements()));
8307     }
8308
8309     if (NumDefs == 0)
8310       return DAG.getUNDEF(VT);
8311
8312     if (NumDefs == 1) {
8313       assert(V.getNode() && "The single defined operand is empty!");
8314       SmallVector<SDValue, 8> Opnds;
8315       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8316         if (i != Idx) {
8317           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8318           continue;
8319         }
8320         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8321         AddToWorklist(NV.getNode());
8322         Opnds.push_back(NV);
8323       }
8324       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8325     }
8326   }
8327
8328   // Fold truncate of a bitcast of a vector to an extract of the low vector
8329   // element.
8330   //
8331   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8332   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8333     SDValue VecSrc = N0.getOperand(0);
8334     EVT SrcVT = VecSrc.getValueType();
8335     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8336         (!LegalOperations ||
8337          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8338       SDLoc SL(N);
8339
8340       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8341       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8342                          VecSrc, DAG.getConstant(0, SL, IdxVT));
8343     }
8344   }
8345
8346   // Simplify the operands using demanded-bits information.
8347   if (!VT.isVector() &&
8348       SimplifyDemandedBits(SDValue(N, 0)))
8349     return SDValue(N, 0);
8350
8351   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8352   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8353   // When the adde's carry is not used.
8354   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8355       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8356       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8357     SDLoc SL(N);
8358     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8359     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8360     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8361     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8362   }
8363
8364   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8365     return NewVSel;
8366
8367   return SDValue();
8368 }
8369
8370 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8371   SDValue Elt = N->getOperand(i);
8372   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8373     return Elt.getNode();
8374   return Elt.getOperand(Elt.getResNo()).getNode();
8375 }
8376
8377 /// build_pair (load, load) -> load
8378 /// if load locations are consecutive.
8379 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8380   assert(N->getOpcode() == ISD::BUILD_PAIR);
8381
8382   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8383   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8384   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8385       LD1->getAddressSpace() != LD2->getAddressSpace())
8386     return SDValue();
8387   EVT LD1VT = LD1->getValueType(0);
8388   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8389   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8390       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8391     unsigned Align = LD1->getAlignment();
8392     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8393         VT.getTypeForEVT(*DAG.getContext()));
8394
8395     if (NewAlign <= Align &&
8396         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8397       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8398                          LD1->getPointerInfo(), Align);
8399   }
8400
8401   return SDValue();
8402 }
8403
8404 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8405   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8406   // and Lo parts; on big-endian machines it doesn't.
8407   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8408 }
8409
8410 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8411                                     const TargetLowering &TLI) {
8412   // If this is not a bitcast to an FP type or if the target doesn't have
8413   // IEEE754-compliant FP logic, we're done.
8414   EVT VT = N->getValueType(0);
8415   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8416     return SDValue();
8417
8418   // TODO: Use splat values for the constant-checking below and remove this
8419   // restriction.
8420   SDValue N0 = N->getOperand(0);
8421   EVT SourceVT = N0.getValueType();
8422   if (SourceVT.isVector())
8423     return SDValue();
8424
8425   unsigned FPOpcode;
8426   APInt SignMask;
8427   switch (N0.getOpcode()) {
8428   case ISD::AND:
8429     FPOpcode = ISD::FABS;
8430     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8431     break;
8432   case ISD::XOR:
8433     FPOpcode = ISD::FNEG;
8434     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8435     break;
8436   // TODO: ISD::OR --> ISD::FNABS?
8437   default:
8438     return SDValue();
8439   }
8440
8441   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8442   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8443   SDValue LogicOp0 = N0.getOperand(0);
8444   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8445   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8446       LogicOp0.getOpcode() == ISD::BITCAST &&
8447       LogicOp0->getOperand(0).getValueType() == VT)
8448     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8449
8450   return SDValue();
8451 }
8452
8453 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8454   SDValue N0 = N->getOperand(0);
8455   EVT VT = N->getValueType(0);
8456
8457   if (N0.isUndef())
8458     return DAG.getUNDEF(VT);
8459
8460   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8461   // Only do this before legalize, since afterward the target may be depending
8462   // on the bitconvert.
8463   // First check to see if this is all constant.
8464   if (!LegalTypes &&
8465       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8466       VT.isVector()) {
8467     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8468
8469     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8470     assert(!DestEltVT.isVector() &&
8471            "Element type of vector ValueType must not be vector!");
8472     if (isSimple)
8473       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8474   }
8475
8476   // If the input is a constant, let getNode fold it.
8477   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8478     // If we can't allow illegal operations, we need to check that this is just
8479     // a fp -> int or int -> conversion and that the resulting operation will
8480     // be legal.
8481     if (!LegalOperations ||
8482         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8483          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8484         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8485          TLI.isOperationLegal(ISD::Constant, VT)))
8486       return DAG.getBitcast(VT, N0);
8487   }
8488
8489   // (conv (conv x, t1), t2) -> (conv x, t2)
8490   if (N0.getOpcode() == ISD::BITCAST)
8491     return DAG.getBitcast(VT, N0.getOperand(0));
8492
8493   // fold (conv (load x)) -> (load (conv*)x)
8494   // If the resultant load doesn't need a higher alignment than the original!
8495   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8496       // Do not change the width of a volatile load.
8497       !cast<LoadSDNode>(N0)->isVolatile() &&
8498       // Do not remove the cast if the types differ in endian layout.
8499       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8500           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8501       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8502       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8503     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8504     unsigned OrigAlign = LN0->getAlignment();
8505
8506     bool Fast = false;
8507     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8508                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8509         Fast) {
8510       SDValue Load =
8511           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8512                       LN0->getPointerInfo(), OrigAlign,
8513                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8514       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8515       return Load;
8516     }
8517   }
8518
8519   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8520     return V;
8521
8522   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8523   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8524   //
8525   // For ppc_fp128:
8526   // fold (bitcast (fneg x)) ->
8527   //     flipbit = signbit
8528   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8529   //
8530   // fold (bitcast (fabs x)) ->
8531   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8532   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8533   // This often reduces constant pool loads.
8534   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8535        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8536       N0.getNode()->hasOneUse() && VT.isInteger() &&
8537       !VT.isVector() && !N0.getValueType().isVector()) {
8538     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8539     AddToWorklist(NewConv.getNode());
8540
8541     SDLoc DL(N);
8542     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8543       assert(VT.getSizeInBits() == 128);
8544       SDValue SignBit = DAG.getConstant(
8545           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8546       SDValue FlipBit;
8547       if (N0.getOpcode() == ISD::FNEG) {
8548         FlipBit = SignBit;
8549         AddToWorklist(FlipBit.getNode());
8550       } else {
8551         assert(N0.getOpcode() == ISD::FABS);
8552         SDValue Hi =
8553             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8554                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8555                                               SDLoc(NewConv)));
8556         AddToWorklist(Hi.getNode());
8557         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8558         AddToWorklist(FlipBit.getNode());
8559       }
8560       SDValue FlipBits =
8561           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8562       AddToWorklist(FlipBits.getNode());
8563       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8564     }
8565     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8566     if (N0.getOpcode() == ISD::FNEG)
8567       return DAG.getNode(ISD::XOR, DL, VT,
8568                          NewConv, DAG.getConstant(SignBit, DL, VT));
8569     assert(N0.getOpcode() == ISD::FABS);
8570     return DAG.getNode(ISD::AND, DL, VT,
8571                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8572   }
8573
8574   // fold (bitconvert (fcopysign cst, x)) ->
8575   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8576   // Note that we don't handle (copysign x, cst) because this can always be
8577   // folded to an fneg or fabs.
8578   //
8579   // For ppc_fp128:
8580   // fold (bitcast (fcopysign cst, x)) ->
8581   //     flipbit = (and (extract_element
8582   //                     (xor (bitcast cst), (bitcast x)), 0),
8583   //                    signbit)
8584   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8585   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8586       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8587       VT.isInteger() && !VT.isVector()) {
8588     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8589     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8590     if (isTypeLegal(IntXVT)) {
8591       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8592       AddToWorklist(X.getNode());
8593
8594       // If X has a different width than the result/lhs, sext it or truncate it.
8595       unsigned VTWidth = VT.getSizeInBits();
8596       if (OrigXWidth < VTWidth) {
8597         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8598         AddToWorklist(X.getNode());
8599       } else if (OrigXWidth > VTWidth) {
8600         // To get the sign bit in the right place, we have to shift it right
8601         // before truncating.
8602         SDLoc DL(X);
8603         X = DAG.getNode(ISD::SRL, DL,
8604                         X.getValueType(), X,
8605                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8606                                         X.getValueType()));
8607         AddToWorklist(X.getNode());
8608         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8609         AddToWorklist(X.getNode());
8610       }
8611
8612       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8613         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8614         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8615         AddToWorklist(Cst.getNode());
8616         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8617         AddToWorklist(X.getNode());
8618         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8619         AddToWorklist(XorResult.getNode());
8620         SDValue XorResult64 = DAG.getNode(
8621             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8622             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8623                                   SDLoc(XorResult)));
8624         AddToWorklist(XorResult64.getNode());
8625         SDValue FlipBit =
8626             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8627                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8628         AddToWorklist(FlipBit.getNode());
8629         SDValue FlipBits =
8630             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8631         AddToWorklist(FlipBits.getNode());
8632         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8633       }
8634       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8635       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8636                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8637       AddToWorklist(X.getNode());
8638
8639       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8640       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8641                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8642       AddToWorklist(Cst.getNode());
8643
8644       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8645     }
8646   }
8647
8648   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8649   if (N0.getOpcode() == ISD::BUILD_PAIR)
8650     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8651       return CombineLD;
8652
8653   // Remove double bitcasts from shuffles - this is often a legacy of
8654   // XformToShuffleWithZero being used to combine bitmaskings (of
8655   // float vectors bitcast to integer vectors) into shuffles.
8656   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8657   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8658       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8659       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8660       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8661     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8662
8663     // If operands are a bitcast, peek through if it casts the original VT.
8664     // If operands are a constant, just bitcast back to original VT.
8665     auto PeekThroughBitcast = [&](SDValue Op) {
8666       if (Op.getOpcode() == ISD::BITCAST &&
8667           Op.getOperand(0).getValueType() == VT)
8668         return SDValue(Op.getOperand(0));
8669       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8670           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8671         return DAG.getBitcast(VT, Op);
8672       return SDValue();
8673     };
8674
8675     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8676     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8677     if (!(SV0 && SV1))
8678       return SDValue();
8679
8680     int MaskScale =
8681         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8682     SmallVector<int, 8> NewMask;
8683     for (int M : SVN->getMask())
8684       for (int i = 0; i != MaskScale; ++i)
8685         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8686
8687     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8688     if (!LegalMask) {
8689       std::swap(SV0, SV1);
8690       ShuffleVectorSDNode::commuteMask(NewMask);
8691       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8692     }
8693
8694     if (LegalMask)
8695       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8696   }
8697
8698   return SDValue();
8699 }
8700
8701 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8702   EVT VT = N->getValueType(0);
8703   return CombineConsecutiveLoads(N, VT);
8704 }
8705
8706 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8707 /// operands. DstEltVT indicates the destination element value type.
8708 SDValue DAGCombiner::
8709 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8710   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8711
8712   // If this is already the right type, we're done.
8713   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8714
8715   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8716   unsigned DstBitSize = DstEltVT.getSizeInBits();
8717
8718   // If this is a conversion of N elements of one type to N elements of another
8719   // type, convert each element.  This handles FP<->INT cases.
8720   if (SrcBitSize == DstBitSize) {
8721     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8722                               BV->getValueType(0).getVectorNumElements());
8723
8724     // Due to the FP element handling below calling this routine recursively,
8725     // we can end up with a scalar-to-vector node here.
8726     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8727       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8728                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8729
8730     SmallVector<SDValue, 8> Ops;
8731     for (SDValue Op : BV->op_values()) {
8732       // If the vector element type is not legal, the BUILD_VECTOR operands
8733       // are promoted and implicitly truncated.  Make that explicit here.
8734       if (Op.getValueType() != SrcEltVT)
8735         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8736       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8737       AddToWorklist(Ops.back().getNode());
8738     }
8739     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8740   }
8741
8742   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8743   // handle annoying details of growing/shrinking FP values, we convert them to
8744   // int first.
8745   if (SrcEltVT.isFloatingPoint()) {
8746     // Convert the input float vector to a int vector where the elements are the
8747     // same sizes.
8748     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8749     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8750     SrcEltVT = IntVT;
8751   }
8752
8753   // Now we know the input is an integer vector.  If the output is a FP type,
8754   // convert to integer first, then to FP of the right size.
8755   if (DstEltVT.isFloatingPoint()) {
8756     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8757     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8758
8759     // Next, convert to FP elements of the same size.
8760     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8761   }
8762
8763   SDLoc DL(BV);
8764
8765   // Okay, we know the src/dst types are both integers of differing types.
8766   // Handling growing first.
8767   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8768   if (SrcBitSize < DstBitSize) {
8769     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8770
8771     SmallVector<SDValue, 8> Ops;
8772     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8773          i += NumInputsPerOutput) {
8774       bool isLE = DAG.getDataLayout().isLittleEndian();
8775       APInt NewBits = APInt(DstBitSize, 0);
8776       bool EltIsUndef = true;
8777       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8778         // Shift the previously computed bits over.
8779         NewBits <<= SrcBitSize;
8780         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8781         if (Op.isUndef()) continue;
8782         EltIsUndef = false;
8783
8784         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8785                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8786       }
8787
8788       if (EltIsUndef)
8789         Ops.push_back(DAG.getUNDEF(DstEltVT));
8790       else
8791         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8792     }
8793
8794     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8795     return DAG.getBuildVector(VT, DL, Ops);
8796   }
8797
8798   // Finally, this must be the case where we are shrinking elements: each input
8799   // turns into multiple outputs.
8800   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8801   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8802                             NumOutputsPerInput*BV->getNumOperands());
8803   SmallVector<SDValue, 8> Ops;
8804
8805   for (const SDValue &Op : BV->op_values()) {
8806     if (Op.isUndef()) {
8807       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8808       continue;
8809     }
8810
8811     APInt OpVal = cast<ConstantSDNode>(Op)->
8812                   getAPIntValue().zextOrTrunc(SrcBitSize);
8813
8814     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8815       APInt ThisVal = OpVal.trunc(DstBitSize);
8816       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8817       OpVal.lshrInPlace(DstBitSize);
8818     }
8819
8820     // For big endian targets, swap the order of the pieces of each element.
8821     if (DAG.getDataLayout().isBigEndian())
8822       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8823   }
8824
8825   return DAG.getBuildVector(VT, DL, Ops);
8826 }
8827
8828 static bool isContractable(SDNode *N) {
8829   SDNodeFlags F = N->getFlags();
8830   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8831 }
8832
8833 /// Try to perform FMA combining on a given FADD node.
8834 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8835   SDValue N0 = N->getOperand(0);
8836   SDValue N1 = N->getOperand(1);
8837   EVT VT = N->getValueType(0);
8838   SDLoc SL(N);
8839
8840   const TargetOptions &Options = DAG.getTarget().Options;
8841
8842   // Floating-point multiply-add with intermediate rounding.
8843   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8844
8845   // Floating-point multiply-add without intermediate rounding.
8846   bool HasFMA =
8847       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8848       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8849
8850   // No valid opcode, do not combine.
8851   if (!HasFMAD && !HasFMA)
8852     return SDValue();
8853
8854   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8855                               Options.UnsafeFPMath || HasFMAD);
8856   // If the addition is not contractable, do not combine.
8857   if (!AllowFusionGlobally && !isContractable(N))
8858     return SDValue();
8859
8860   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8861   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8862     return SDValue();
8863
8864   // Always prefer FMAD to FMA for precision.
8865   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8866   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8867   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8868
8869   // Is the node an FMUL and contractable either due to global flags or
8870   // SDNodeFlags.
8871   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8872     if (N.getOpcode() != ISD::FMUL)
8873       return false;
8874     return AllowFusionGlobally || isContractable(N.getNode());
8875   };
8876   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8877   // prefer to fold the multiply with fewer uses.
8878   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8879     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8880       std::swap(N0, N1);
8881   }
8882
8883   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8884   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8885     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8886                        N0.getOperand(0), N0.getOperand(1), N1);
8887   }
8888
8889   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8890   // Note: Commutes FADD operands.
8891   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8892     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8893                        N1.getOperand(0), N1.getOperand(1), N0);
8894   }
8895
8896   // Look through FP_EXTEND nodes to do more combining.
8897   if (LookThroughFPExt) {
8898     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8899     if (N0.getOpcode() == ISD::FP_EXTEND) {
8900       SDValue N00 = N0.getOperand(0);
8901       if (isContractableFMUL(N00))
8902         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8903                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8904                                        N00.getOperand(0)),
8905                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8906                                        N00.getOperand(1)), N1);
8907     }
8908
8909     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8910     // Note: Commutes FADD operands.
8911     if (N1.getOpcode() == ISD::FP_EXTEND) {
8912       SDValue N10 = N1.getOperand(0);
8913       if (isContractableFMUL(N10))
8914         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8915                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8916                                        N10.getOperand(0)),
8917                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8918                                        N10.getOperand(1)), N0);
8919     }
8920   }
8921
8922   // More folding opportunities when target permits.
8923   if (Aggressive) {
8924     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8925     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8926     // are currently only supported on binary nodes.
8927     if (Options.UnsafeFPMath &&
8928         N0.getOpcode() == PreferredFusedOpcode &&
8929         N0.getOperand(2).getOpcode() == ISD::FMUL &&
8930         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8931       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8932                          N0.getOperand(0), N0.getOperand(1),
8933                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8934                                      N0.getOperand(2).getOperand(0),
8935                                      N0.getOperand(2).getOperand(1),
8936                                      N1));
8937     }
8938
8939     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8940     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8941     // are currently only supported on binary nodes.
8942     if (Options.UnsafeFPMath &&
8943         N1->getOpcode() == PreferredFusedOpcode &&
8944         N1.getOperand(2).getOpcode() == ISD::FMUL &&
8945         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
8946       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8947                          N1.getOperand(0), N1.getOperand(1),
8948                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8949                                      N1.getOperand(2).getOperand(0),
8950                                      N1.getOperand(2).getOperand(1),
8951                                      N0));
8952     }
8953
8954     if (LookThroughFPExt) {
8955       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8956       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8957       auto FoldFAddFMAFPExtFMul = [&] (
8958           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8959         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8960                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8961                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8962                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8963                                        Z));
8964       };
8965       if (N0.getOpcode() == PreferredFusedOpcode) {
8966         SDValue N02 = N0.getOperand(2);
8967         if (N02.getOpcode() == ISD::FP_EXTEND) {
8968           SDValue N020 = N02.getOperand(0);
8969           if (isContractableFMUL(N020))
8970             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8971                                         N020.getOperand(0), N020.getOperand(1),
8972                                         N1);
8973         }
8974       }
8975
8976       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8977       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8978       // FIXME: This turns two single-precision and one double-precision
8979       // operation into two double-precision operations, which might not be
8980       // interesting for all targets, especially GPUs.
8981       auto FoldFAddFPExtFMAFMul = [&] (
8982           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8983         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8984                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8985                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8986                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8987                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8988                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8989                                        Z));
8990       };
8991       if (N0.getOpcode() == ISD::FP_EXTEND) {
8992         SDValue N00 = N0.getOperand(0);
8993         if (N00.getOpcode() == PreferredFusedOpcode) {
8994           SDValue N002 = N00.getOperand(2);
8995           if (isContractableFMUL(N002))
8996             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8997                                         N002.getOperand(0), N002.getOperand(1),
8998                                         N1);
8999         }
9000       }
9001
9002       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9003       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9004       if (N1.getOpcode() == PreferredFusedOpcode) {
9005         SDValue N12 = N1.getOperand(2);
9006         if (N12.getOpcode() == ISD::FP_EXTEND) {
9007           SDValue N120 = N12.getOperand(0);
9008           if (isContractableFMUL(N120))
9009             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9010                                         N120.getOperand(0), N120.getOperand(1),
9011                                         N0);
9012         }
9013       }
9014
9015       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9016       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9017       // FIXME: This turns two single-precision and one double-precision
9018       // operation into two double-precision operations, which might not be
9019       // interesting for all targets, especially GPUs.
9020       if (N1.getOpcode() == ISD::FP_EXTEND) {
9021         SDValue N10 = N1.getOperand(0);
9022         if (N10.getOpcode() == PreferredFusedOpcode) {
9023           SDValue N102 = N10.getOperand(2);
9024           if (isContractableFMUL(N102))
9025             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9026                                         N102.getOperand(0), N102.getOperand(1),
9027                                         N0);
9028         }
9029       }
9030     }
9031   }
9032
9033   return SDValue();
9034 }
9035
9036 /// Try to perform FMA combining on a given FSUB node.
9037 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9038   SDValue N0 = N->getOperand(0);
9039   SDValue N1 = N->getOperand(1);
9040   EVT VT = N->getValueType(0);
9041   SDLoc SL(N);
9042
9043   const TargetOptions &Options = DAG.getTarget().Options;
9044   // Floating-point multiply-add with intermediate rounding.
9045   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9046
9047   // Floating-point multiply-add without intermediate rounding.
9048   bool HasFMA =
9049       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9050       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9051
9052   // No valid opcode, do not combine.
9053   if (!HasFMAD && !HasFMA)
9054     return SDValue();
9055
9056   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9057                               Options.UnsafeFPMath || HasFMAD);
9058   // If the subtraction is not contractable, do not combine.
9059   if (!AllowFusionGlobally && !isContractable(N))
9060     return SDValue();
9061
9062   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9063   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9064     return SDValue();
9065
9066   // Always prefer FMAD to FMA for precision.
9067   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9068   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9069   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9070
9071   // Is the node an FMUL and contractable either due to global flags or
9072   // SDNodeFlags.
9073   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9074     if (N.getOpcode() != ISD::FMUL)
9075       return false;
9076     return AllowFusionGlobally || isContractable(N.getNode());
9077   };
9078
9079   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9080   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9081     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9082                        N0.getOperand(0), N0.getOperand(1),
9083                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9084   }
9085
9086   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9087   // Note: Commutes FSUB operands.
9088   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9089     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9090                        DAG.getNode(ISD::FNEG, SL, VT,
9091                                    N1.getOperand(0)),
9092                        N1.getOperand(1), N0);
9093
9094   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9095   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9096       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9097     SDValue N00 = N0.getOperand(0).getOperand(0);
9098     SDValue N01 = N0.getOperand(0).getOperand(1);
9099     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9100                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9101                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9102   }
9103
9104   // Look through FP_EXTEND nodes to do more combining.
9105   if (LookThroughFPExt) {
9106     // fold (fsub (fpext (fmul x, y)), z)
9107     //   -> (fma (fpext x), (fpext y), (fneg z))
9108     if (N0.getOpcode() == ISD::FP_EXTEND) {
9109       SDValue N00 = N0.getOperand(0);
9110       if (isContractableFMUL(N00))
9111         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9112                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9113                                        N00.getOperand(0)),
9114                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9115                                        N00.getOperand(1)),
9116                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9117     }
9118
9119     // fold (fsub x, (fpext (fmul y, z)))
9120     //   -> (fma (fneg (fpext y)), (fpext z), x)
9121     // Note: Commutes FSUB operands.
9122     if (N1.getOpcode() == ISD::FP_EXTEND) {
9123       SDValue N10 = N1.getOperand(0);
9124       if (isContractableFMUL(N10))
9125         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9126                            DAG.getNode(ISD::FNEG, SL, VT,
9127                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9128                                                    N10.getOperand(0))),
9129                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9130                                        N10.getOperand(1)),
9131                            N0);
9132     }
9133
9134     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9135     //   -> (fneg (fma (fpext x), (fpext y), z))
9136     // Note: This could be removed with appropriate canonicalization of the
9137     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9138     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9139     // from implementing the canonicalization in visitFSUB.
9140     if (N0.getOpcode() == ISD::FP_EXTEND) {
9141       SDValue N00 = N0.getOperand(0);
9142       if (N00.getOpcode() == ISD::FNEG) {
9143         SDValue N000 = N00.getOperand(0);
9144         if (isContractableFMUL(N000)) {
9145           return DAG.getNode(ISD::FNEG, SL, VT,
9146                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9147                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9148                                                      N000.getOperand(0)),
9149                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9150                                                      N000.getOperand(1)),
9151                                          N1));
9152         }
9153       }
9154     }
9155
9156     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9157     //   -> (fneg (fma (fpext x)), (fpext y), z)
9158     // Note: This could be removed with appropriate canonicalization of the
9159     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9160     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9161     // from implementing the canonicalization in visitFSUB.
9162     if (N0.getOpcode() == ISD::FNEG) {
9163       SDValue N00 = N0.getOperand(0);
9164       if (N00.getOpcode() == ISD::FP_EXTEND) {
9165         SDValue N000 = N00.getOperand(0);
9166         if (isContractableFMUL(N000)) {
9167           return DAG.getNode(ISD::FNEG, SL, VT,
9168                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9169                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9170                                                      N000.getOperand(0)),
9171                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9172                                                      N000.getOperand(1)),
9173                                          N1));
9174         }
9175       }
9176     }
9177
9178   }
9179
9180   // More folding opportunities when target permits.
9181   if (Aggressive) {
9182     // fold (fsub (fma x, y, (fmul u, v)), z)
9183     //   -> (fma x, y (fma u, v, (fneg z)))
9184     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9185     // are currently only supported on binary nodes.
9186     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9187         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9188         N0.getOperand(2)->hasOneUse()) {
9189       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9190                          N0.getOperand(0), N0.getOperand(1),
9191                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9192                                      N0.getOperand(2).getOperand(0),
9193                                      N0.getOperand(2).getOperand(1),
9194                                      DAG.getNode(ISD::FNEG, SL, VT,
9195                                                  N1)));
9196     }
9197
9198     // fold (fsub x, (fma y, z, (fmul u, v)))
9199     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9200     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9201     // are currently only supported on binary nodes.
9202     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9203         isContractableFMUL(N1.getOperand(2))) {
9204       SDValue N20 = N1.getOperand(2).getOperand(0);
9205       SDValue N21 = N1.getOperand(2).getOperand(1);
9206       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9207                          DAG.getNode(ISD::FNEG, SL, VT,
9208                                      N1.getOperand(0)),
9209                          N1.getOperand(1),
9210                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9211                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9212
9213                                      N21, N0));
9214     }
9215
9216     if (LookThroughFPExt) {
9217       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9218       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9219       if (N0.getOpcode() == PreferredFusedOpcode) {
9220         SDValue N02 = N0.getOperand(2);
9221         if (N02.getOpcode() == ISD::FP_EXTEND) {
9222           SDValue N020 = N02.getOperand(0);
9223           if (isContractableFMUL(N020))
9224             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9225                                N0.getOperand(0), N0.getOperand(1),
9226                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9227                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9228                                                        N020.getOperand(0)),
9229                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9230                                                        N020.getOperand(1)),
9231                                            DAG.getNode(ISD::FNEG, SL, VT,
9232                                                        N1)));
9233         }
9234       }
9235
9236       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9237       //   -> (fma (fpext x), (fpext y),
9238       //           (fma (fpext u), (fpext v), (fneg z)))
9239       // FIXME: This turns two single-precision and one double-precision
9240       // operation into two double-precision operations, which might not be
9241       // interesting for all targets, especially GPUs.
9242       if (N0.getOpcode() == ISD::FP_EXTEND) {
9243         SDValue N00 = N0.getOperand(0);
9244         if (N00.getOpcode() == PreferredFusedOpcode) {
9245           SDValue N002 = N00.getOperand(2);
9246           if (isContractableFMUL(N002))
9247             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9248                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9249                                            N00.getOperand(0)),
9250                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9251                                            N00.getOperand(1)),
9252                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9253                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9254                                                        N002.getOperand(0)),
9255                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9256                                                        N002.getOperand(1)),
9257                                            DAG.getNode(ISD::FNEG, SL, VT,
9258                                                        N1)));
9259         }
9260       }
9261
9262       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9263       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9264       if (N1.getOpcode() == PreferredFusedOpcode &&
9265         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9266         SDValue N120 = N1.getOperand(2).getOperand(0);
9267         if (isContractableFMUL(N120)) {
9268           SDValue N1200 = N120.getOperand(0);
9269           SDValue N1201 = N120.getOperand(1);
9270           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9271                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9272                              N1.getOperand(1),
9273                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9274                                          DAG.getNode(ISD::FNEG, SL, VT,
9275                                              DAG.getNode(ISD::FP_EXTEND, SL,
9276                                                          VT, N1200)),
9277                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9278                                                      N1201),
9279                                          N0));
9280         }
9281       }
9282
9283       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9284       //   -> (fma (fneg (fpext y)), (fpext z),
9285       //           (fma (fneg (fpext u)), (fpext v), x))
9286       // FIXME: This turns two single-precision and one double-precision
9287       // operation into two double-precision operations, which might not be
9288       // interesting for all targets, especially GPUs.
9289       if (N1.getOpcode() == ISD::FP_EXTEND &&
9290         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9291         SDValue N100 = N1.getOperand(0).getOperand(0);
9292         SDValue N101 = N1.getOperand(0).getOperand(1);
9293         SDValue N102 = N1.getOperand(0).getOperand(2);
9294         if (isContractableFMUL(N102)) {
9295           SDValue N1020 = N102.getOperand(0);
9296           SDValue N1021 = N102.getOperand(1);
9297           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9298                              DAG.getNode(ISD::FNEG, SL, VT,
9299                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9300                                                      N100)),
9301                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9302                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9303                                          DAG.getNode(ISD::FNEG, SL, VT,
9304                                              DAG.getNode(ISD::FP_EXTEND, SL,
9305                                                          VT, N1020)),
9306                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9307                                                      N1021),
9308                                          N0));
9309         }
9310       }
9311     }
9312   }
9313
9314   return SDValue();
9315 }
9316
9317 /// Try to perform FMA combining on a given FMUL node based on the distributive
9318 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9319 /// subtraction instead of addition).
9320 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9321   SDValue N0 = N->getOperand(0);
9322   SDValue N1 = N->getOperand(1);
9323   EVT VT = N->getValueType(0);
9324   SDLoc SL(N);
9325
9326   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9327
9328   const TargetOptions &Options = DAG.getTarget().Options;
9329
9330   // The transforms below are incorrect when x == 0 and y == inf, because the
9331   // intermediate multiplication produces a nan.
9332   if (!Options.NoInfsFPMath)
9333     return SDValue();
9334
9335   // Floating-point multiply-add without intermediate rounding.
9336   bool HasFMA =
9337       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9338       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9339       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9340
9341   // Floating-point multiply-add with intermediate rounding. This can result
9342   // in a less precise result due to the changed rounding order.
9343   bool HasFMAD = Options.UnsafeFPMath &&
9344                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9345
9346   // No valid opcode, do not combine.
9347   if (!HasFMAD && !HasFMA)
9348     return SDValue();
9349
9350   // Always prefer FMAD to FMA for precision.
9351   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9352   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9353
9354   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9355   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9356   auto FuseFADD = [&](SDValue X, SDValue Y) {
9357     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9358       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9359       if (XC1 && XC1->isExactlyValue(+1.0))
9360         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9361       if (XC1 && XC1->isExactlyValue(-1.0))
9362         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9363                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9364     }
9365     return SDValue();
9366   };
9367
9368   if (SDValue FMA = FuseFADD(N0, N1))
9369     return FMA;
9370   if (SDValue FMA = FuseFADD(N1, N0))
9371     return FMA;
9372
9373   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9374   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9375   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9376   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9377   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9378     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9379       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9380       if (XC0 && XC0->isExactlyValue(+1.0))
9381         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9382                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9383                            Y);
9384       if (XC0 && XC0->isExactlyValue(-1.0))
9385         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9386                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9387                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9388
9389       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9390       if (XC1 && XC1->isExactlyValue(+1.0))
9391         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9392                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9393       if (XC1 && XC1->isExactlyValue(-1.0))
9394         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9395     }
9396     return SDValue();
9397   };
9398
9399   if (SDValue FMA = FuseFSUB(N0, N1))
9400     return FMA;
9401   if (SDValue FMA = FuseFSUB(N1, N0))
9402     return FMA;
9403
9404   return SDValue();
9405 }
9406
9407 static bool isFMulNegTwo(SDValue &N) {
9408   if (N.getOpcode() != ISD::FMUL)
9409     return false;
9410   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9411     return CFP->isExactlyValue(-2.0);
9412   return false;
9413 }
9414
9415 SDValue DAGCombiner::visitFADD(SDNode *N) {
9416   SDValue N0 = N->getOperand(0);
9417   SDValue N1 = N->getOperand(1);
9418   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9419   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9420   EVT VT = N->getValueType(0);
9421   SDLoc DL(N);
9422   const TargetOptions &Options = DAG.getTarget().Options;
9423   const SDNodeFlags Flags = N->getFlags();
9424
9425   // fold vector ops
9426   if (VT.isVector())
9427     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9428       return FoldedVOp;
9429
9430   // fold (fadd c1, c2) -> c1 + c2
9431   if (N0CFP && N1CFP)
9432     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9433
9434   // canonicalize constant to RHS
9435   if (N0CFP && !N1CFP)
9436     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9437
9438   if (SDValue NewSel = foldBinOpIntoSelect(N))
9439     return NewSel;
9440
9441   // fold (fadd A, (fneg B)) -> (fsub A, B)
9442   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9443       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9444     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9445                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9446
9447   // fold (fadd (fneg A), B) -> (fsub B, A)
9448   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9449       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9450     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9451                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9452
9453   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9454   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9455   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9456       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9457     bool N1IsFMul = isFMulNegTwo(N1);
9458     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9459     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9460     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9461   }
9462
9463   // FIXME: Auto-upgrade the target/function-level option.
9464   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9465     // fold (fadd A, 0) -> A
9466     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9467       if (N1C->isZero())
9468         return N0;
9469   }
9470
9471   // If 'unsafe math' is enabled, fold lots of things.
9472   if (Options.UnsafeFPMath) {
9473     // No FP constant should be created after legalization as Instruction
9474     // Selection pass has a hard time dealing with FP constants.
9475     bool AllowNewConst = (Level < AfterLegalizeDAG);
9476
9477     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9478     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9479         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9480       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9481                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9482                                      Flags),
9483                          Flags);
9484
9485     // If allowed, fold (fadd (fneg x), x) -> 0.0
9486     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9487       return DAG.getConstantFP(0.0, DL, VT);
9488
9489     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9490     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9491       return DAG.getConstantFP(0.0, DL, VT);
9492
9493     // We can fold chains of FADD's of the same value into multiplications.
9494     // This transform is not safe in general because we are reducing the number
9495     // of rounding steps.
9496     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9497       if (N0.getOpcode() == ISD::FMUL) {
9498         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9499         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9500
9501         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9502         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9503           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9504                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9505           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9506         }
9507
9508         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9509         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9510             N1.getOperand(0) == N1.getOperand(1) &&
9511             N0.getOperand(0) == N1.getOperand(0)) {
9512           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9513                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9514           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9515         }
9516       }
9517
9518       if (N1.getOpcode() == ISD::FMUL) {
9519         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9520         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9521
9522         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9523         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9524           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9525                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9526           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9527         }
9528
9529         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9530         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9531             N0.getOperand(0) == N0.getOperand(1) &&
9532             N1.getOperand(0) == N0.getOperand(0)) {
9533           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9534                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9535           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9536         }
9537       }
9538
9539       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9540         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9541         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9542         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9543             (N0.getOperand(0) == N1)) {
9544           return DAG.getNode(ISD::FMUL, DL, VT,
9545                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9546         }
9547       }
9548
9549       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9550         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9551         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9552         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9553             N1.getOperand(0) == N0) {
9554           return DAG.getNode(ISD::FMUL, DL, VT,
9555                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9556         }
9557       }
9558
9559       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9560       if (AllowNewConst &&
9561           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9562           N0.getOperand(0) == N0.getOperand(1) &&
9563           N1.getOperand(0) == N1.getOperand(1) &&
9564           N0.getOperand(0) == N1.getOperand(0)) {
9565         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9566                            DAG.getConstantFP(4.0, DL, VT), Flags);
9567       }
9568     }
9569   } // enable-unsafe-fp-math
9570
9571   // FADD -> FMA combines:
9572   if (SDValue Fused = visitFADDForFMACombine(N)) {
9573     AddToWorklist(Fused.getNode());
9574     return Fused;
9575   }
9576   return SDValue();
9577 }
9578
9579 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9580   SDValue N0 = N->getOperand(0);
9581   SDValue N1 = N->getOperand(1);
9582   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9583   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9584   EVT VT = N->getValueType(0);
9585   SDLoc DL(N);
9586   const TargetOptions &Options = DAG.getTarget().Options;
9587   const SDNodeFlags Flags = N->getFlags();
9588
9589   // fold vector ops
9590   if (VT.isVector())
9591     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9592       return FoldedVOp;
9593
9594   // fold (fsub c1, c2) -> c1-c2
9595   if (N0CFP && N1CFP)
9596     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9597
9598   if (SDValue NewSel = foldBinOpIntoSelect(N))
9599     return NewSel;
9600
9601   // fold (fsub A, (fneg B)) -> (fadd A, B)
9602   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9603     return DAG.getNode(ISD::FADD, DL, VT, N0,
9604                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9605
9606   // FIXME: Auto-upgrade the target/function-level option.
9607   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9608     // (fsub 0, B) -> -B
9609     if (N0CFP && N0CFP->isZero()) {
9610       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9611         return GetNegatedExpression(N1, DAG, LegalOperations);
9612       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9613         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9614     }
9615   }
9616
9617   // If 'unsafe math' is enabled, fold lots of things.
9618   if (Options.UnsafeFPMath) {
9619     // (fsub A, 0) -> A
9620     if (N1CFP && N1CFP->isZero())
9621       return N0;
9622
9623     // (fsub x, x) -> 0.0
9624     if (N0 == N1)
9625       return DAG.getConstantFP(0.0f, DL, VT);
9626
9627     // (fsub x, (fadd x, y)) -> (fneg y)
9628     // (fsub x, (fadd y, x)) -> (fneg y)
9629     if (N1.getOpcode() == ISD::FADD) {
9630       SDValue N10 = N1->getOperand(0);
9631       SDValue N11 = N1->getOperand(1);
9632
9633       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9634         return GetNegatedExpression(N11, DAG, LegalOperations);
9635
9636       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9637         return GetNegatedExpression(N10, DAG, LegalOperations);
9638     }
9639   }
9640
9641   // FSUB -> FMA combines:
9642   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9643     AddToWorklist(Fused.getNode());
9644     return Fused;
9645   }
9646
9647   return SDValue();
9648 }
9649
9650 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9651   SDValue N0 = N->getOperand(0);
9652   SDValue N1 = N->getOperand(1);
9653   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9654   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9655   EVT VT = N->getValueType(0);
9656   SDLoc DL(N);
9657   const TargetOptions &Options = DAG.getTarget().Options;
9658   const SDNodeFlags Flags = N->getFlags();
9659
9660   // fold vector ops
9661   if (VT.isVector()) {
9662     // This just handles C1 * C2 for vectors. Other vector folds are below.
9663     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9664       return FoldedVOp;
9665   }
9666
9667   // fold (fmul c1, c2) -> c1*c2
9668   if (N0CFP && N1CFP)
9669     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9670
9671   // canonicalize constant to RHS
9672   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9673      !isConstantFPBuildVectorOrConstantFP(N1))
9674     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9675
9676   // fold (fmul A, 1.0) -> A
9677   if (N1CFP && N1CFP->isExactlyValue(1.0))
9678     return N0;
9679
9680   if (SDValue NewSel = foldBinOpIntoSelect(N))
9681     return NewSel;
9682
9683   if (Options.UnsafeFPMath) {
9684     // fold (fmul A, 0) -> 0
9685     if (N1CFP && N1CFP->isZero())
9686       return N1;
9687
9688     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9689     if (N0.getOpcode() == ISD::FMUL) {
9690       // Fold scalars or any vector constants (not just splats).
9691       // This fold is done in general by InstCombine, but extra fmul insts
9692       // may have been generated during lowering.
9693       SDValue N00 = N0.getOperand(0);
9694       SDValue N01 = N0.getOperand(1);
9695       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9696       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9697       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9698
9699       // Check 1: Make sure that the first operand of the inner multiply is NOT
9700       // a constant. Otherwise, we may induce infinite looping.
9701       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9702         // Check 2: Make sure that the second operand of the inner multiply and
9703         // the second operand of the outer multiply are constants.
9704         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9705             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9706           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9707           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9708         }
9709       }
9710     }
9711
9712     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9713     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9714     // during an early run of DAGCombiner can prevent folding with fmuls
9715     // inserted during lowering.
9716     if (N0.getOpcode() == ISD::FADD &&
9717         (N0.getOperand(0) == N0.getOperand(1)) &&
9718         N0.hasOneUse()) {
9719       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9720       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9721       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9722     }
9723   }
9724
9725   // fold (fmul X, 2.0) -> (fadd X, X)
9726   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9727     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9728
9729   // fold (fmul X, -1.0) -> (fneg X)
9730   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9731     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9732       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9733
9734   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9735   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9736     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9737       // Both can be negated for free, check to see if at least one is cheaper
9738       // negated.
9739       if (LHSNeg == 2 || RHSNeg == 2)
9740         return DAG.getNode(ISD::FMUL, DL, VT,
9741                            GetNegatedExpression(N0, DAG, LegalOperations),
9742                            GetNegatedExpression(N1, DAG, LegalOperations),
9743                            Flags);
9744     }
9745   }
9746
9747   // FMUL -> FMA combines:
9748   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9749     AddToWorklist(Fused.getNode());
9750     return Fused;
9751   }
9752
9753   return SDValue();
9754 }
9755
9756 SDValue DAGCombiner::visitFMA(SDNode *N) {
9757   SDValue N0 = N->getOperand(0);
9758   SDValue N1 = N->getOperand(1);
9759   SDValue N2 = N->getOperand(2);
9760   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9761   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9762   EVT VT = N->getValueType(0);
9763   SDLoc DL(N);
9764   const TargetOptions &Options = DAG.getTarget().Options;
9765
9766   // Constant fold FMA.
9767   if (isa<ConstantFPSDNode>(N0) &&
9768       isa<ConstantFPSDNode>(N1) &&
9769       isa<ConstantFPSDNode>(N2)) {
9770     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9771   }
9772
9773   if (Options.UnsafeFPMath) {
9774     if (N0CFP && N0CFP->isZero())
9775       return N2;
9776     if (N1CFP && N1CFP->isZero())
9777       return N2;
9778   }
9779   // TODO: The FMA node should have flags that propagate to these nodes.
9780   if (N0CFP && N0CFP->isExactlyValue(1.0))
9781     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9782   if (N1CFP && N1CFP->isExactlyValue(1.0))
9783     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9784
9785   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9786   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9787      !isConstantFPBuildVectorOrConstantFP(N1))
9788     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9789
9790   // TODO: FMA nodes should have flags that propagate to the created nodes.
9791   // For now, create a Flags object for use with all unsafe math transforms.
9792   SDNodeFlags Flags;
9793   Flags.setUnsafeAlgebra(true);
9794
9795   if (Options.UnsafeFPMath) {
9796     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9797     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9798         isConstantFPBuildVectorOrConstantFP(N1) &&
9799         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9800       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9801                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9802                                      Flags), Flags);
9803     }
9804
9805     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9806     if (N0.getOpcode() == ISD::FMUL &&
9807         isConstantFPBuildVectorOrConstantFP(N1) &&
9808         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9809       return DAG.getNode(ISD::FMA, DL, VT,
9810                          N0.getOperand(0),
9811                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9812                                      Flags),
9813                          N2);
9814     }
9815   }
9816
9817   // (fma x, 1, y) -> (fadd x, y)
9818   // (fma x, -1, y) -> (fadd (fneg x), y)
9819   if (N1CFP) {
9820     if (N1CFP->isExactlyValue(1.0))
9821       // TODO: The FMA node should have flags that propagate to this node.
9822       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9823
9824     if (N1CFP->isExactlyValue(-1.0) &&
9825         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9826       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9827       AddToWorklist(RHSNeg.getNode());
9828       // TODO: The FMA node should have flags that propagate to this node.
9829       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9830     }
9831   }
9832
9833   if (Options.UnsafeFPMath) {
9834     // (fma x, c, x) -> (fmul x, (c+1))
9835     if (N1CFP && N0 == N2) {
9836       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9837                          DAG.getNode(ISD::FADD, DL, VT, N1,
9838                                      DAG.getConstantFP(1.0, DL, VT), Flags),
9839                          Flags);
9840     }
9841
9842     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9843     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9844       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9845                          DAG.getNode(ISD::FADD, DL, VT, N1,
9846                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
9847                          Flags);
9848     }
9849   }
9850
9851   return SDValue();
9852 }
9853
9854 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9855 // reciprocal.
9856 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9857 // Notice that this is not always beneficial. One reason is different targets
9858 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9859 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9860 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9861 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9862   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9863   const SDNodeFlags Flags = N->getFlags();
9864   if (!UnsafeMath && !Flags.hasAllowReciprocal())
9865     return SDValue();
9866
9867   // Skip if current node is a reciprocal.
9868   SDValue N0 = N->getOperand(0);
9869   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9870   if (N0CFP && N0CFP->isExactlyValue(1.0))
9871     return SDValue();
9872
9873   // Exit early if the target does not want this transform or if there can't
9874   // possibly be enough uses of the divisor to make the transform worthwhile.
9875   SDValue N1 = N->getOperand(1);
9876   unsigned MinUses = TLI.combineRepeatedFPDivisors();
9877   if (!MinUses || N1->use_size() < MinUses)
9878     return SDValue();
9879
9880   // Find all FDIV users of the same divisor.
9881   // Use a set because duplicates may be present in the user list.
9882   SetVector<SDNode *> Users;
9883   for (auto *U : N1->uses()) {
9884     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9885       // This division is eligible for optimization only if global unsafe math
9886       // is enabled or if this division allows reciprocal formation.
9887       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
9888         Users.insert(U);
9889     }
9890   }
9891
9892   // Now that we have the actual number of divisor uses, make sure it meets
9893   // the minimum threshold specified by the target.
9894   if (Users.size() < MinUses)
9895     return SDValue();
9896
9897   EVT VT = N->getValueType(0);
9898   SDLoc DL(N);
9899   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9900   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9901
9902   // Dividend / Divisor -> Dividend * Reciprocal
9903   for (auto *U : Users) {
9904     SDValue Dividend = U->getOperand(0);
9905     if (Dividend != FPOne) {
9906       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9907                                     Reciprocal, Flags);
9908       CombineTo(U, NewNode);
9909     } else if (U != Reciprocal.getNode()) {
9910       // In the absence of fast-math-flags, this user node is always the
9911       // same node as Reciprocal, but with FMF they may be different nodes.
9912       CombineTo(U, Reciprocal);
9913     }
9914   }
9915   return SDValue(N, 0);  // N was replaced.
9916 }
9917
9918 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9919   SDValue N0 = N->getOperand(0);
9920   SDValue N1 = N->getOperand(1);
9921   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9922   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9923   EVT VT = N->getValueType(0);
9924   SDLoc DL(N);
9925   const TargetOptions &Options = DAG.getTarget().Options;
9926   SDNodeFlags Flags = N->getFlags();
9927
9928   // fold vector ops
9929   if (VT.isVector())
9930     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9931       return FoldedVOp;
9932
9933   // fold (fdiv c1, c2) -> c1/c2
9934   if (N0CFP && N1CFP)
9935     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9936
9937   if (SDValue NewSel = foldBinOpIntoSelect(N))
9938     return NewSel;
9939
9940   if (Options.UnsafeFPMath) {
9941     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9942     if (N1CFP) {
9943       // Compute the reciprocal 1.0 / c2.
9944       const APFloat &N1APF = N1CFP->getValueAPF();
9945       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
9946       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
9947       // Only do the transform if the reciprocal is a legal fp immediate that
9948       // isn't too nasty (eg NaN, denormal, ...).
9949       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
9950           (!LegalOperations ||
9951            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
9952            // backend)... we should handle this gracefully after Legalize.
9953            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
9954            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
9955            TLI.isFPImmLegal(Recip, VT)))
9956         return DAG.getNode(ISD::FMUL, DL, VT, N0,
9957                            DAG.getConstantFP(Recip, DL, VT), Flags);
9958     }
9959
9960     // If this FDIV is part of a reciprocal square root, it may be folded
9961     // into a target-specific square root estimate instruction.
9962     if (N1.getOpcode() == ISD::FSQRT) {
9963       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
9964         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9965       }
9966     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
9967                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9968       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9969                                           Flags)) {
9970         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
9971         AddToWorklist(RV.getNode());
9972         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9973       }
9974     } else if (N1.getOpcode() == ISD::FP_ROUND &&
9975                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9976       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9977                                           Flags)) {
9978         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9979         AddToWorklist(RV.getNode());
9980         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9981       }
9982     } else if (N1.getOpcode() == ISD::FMUL) {
9983       // Look through an FMUL. Even though this won't remove the FDIV directly,
9984       // it's still worthwhile to get rid of the FSQRT if possible.
9985       SDValue SqrtOp;
9986       SDValue OtherOp;
9987       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9988         SqrtOp = N1.getOperand(0);
9989         OtherOp = N1.getOperand(1);
9990       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9991         SqrtOp = N1.getOperand(1);
9992         OtherOp = N1.getOperand(0);
9993       }
9994       if (SqrtOp.getNode()) {
9995         // We found a FSQRT, so try to make this fold:
9996         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9997         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9998           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9999           AddToWorklist(RV.getNode());
10000           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10001         }
10002       }
10003     }
10004
10005     // Fold into a reciprocal estimate and multiply instead of a real divide.
10006     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10007       AddToWorklist(RV.getNode());
10008       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10009     }
10010   }
10011
10012   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10013   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10014     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10015       // Both can be negated for free, check to see if at least one is cheaper
10016       // negated.
10017       if (LHSNeg == 2 || RHSNeg == 2)
10018         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10019                            GetNegatedExpression(N0, DAG, LegalOperations),
10020                            GetNegatedExpression(N1, DAG, LegalOperations),
10021                            Flags);
10022     }
10023   }
10024
10025   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10026     return CombineRepeatedDivisors;
10027
10028   return SDValue();
10029 }
10030
10031 SDValue DAGCombiner::visitFREM(SDNode *N) {
10032   SDValue N0 = N->getOperand(0);
10033   SDValue N1 = N->getOperand(1);
10034   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10035   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10036   EVT VT = N->getValueType(0);
10037
10038   // fold (frem c1, c2) -> fmod(c1,c2)
10039   if (N0CFP && N1CFP)
10040     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10041
10042   if (SDValue NewSel = foldBinOpIntoSelect(N))
10043     return NewSel;
10044
10045   return SDValue();
10046 }
10047
10048 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10049   if (!DAG.getTarget().Options.UnsafeFPMath)
10050     return SDValue();
10051
10052   SDValue N0 = N->getOperand(0);
10053   if (TLI.isFsqrtCheap(N0, DAG))
10054     return SDValue();
10055
10056   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10057   // For now, create a Flags object for use with all unsafe math transforms.
10058   SDNodeFlags Flags;
10059   Flags.setUnsafeAlgebra(true);
10060   return buildSqrtEstimate(N0, Flags);
10061 }
10062
10063 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10064 /// copysign(x, fp_round(y)) -> copysign(x, y)
10065 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10066   SDValue N1 = N->getOperand(1);
10067   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10068        N1.getOpcode() == ISD::FP_ROUND)) {
10069     // Do not optimize out type conversion of f128 type yet.
10070     // For some targets like x86_64, configuration is changed to keep one f128
10071     // value in one SSE register, but instruction selection cannot handle
10072     // FCOPYSIGN on SSE registers yet.
10073     EVT N1VT = N1->getValueType(0);
10074     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10075     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10076   }
10077   return false;
10078 }
10079
10080 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10081   SDValue N0 = N->getOperand(0);
10082   SDValue N1 = N->getOperand(1);
10083   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10084   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10085   EVT VT = N->getValueType(0);
10086
10087   if (N0CFP && N1CFP) // Constant fold
10088     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10089
10090   if (N1CFP) {
10091     const APFloat &V = N1CFP->getValueAPF();
10092     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10093     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10094     if (!V.isNegative()) {
10095       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10096         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10097     } else {
10098       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10099         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10100                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10101     }
10102   }
10103
10104   // copysign(fabs(x), y) -> copysign(x, y)
10105   // copysign(fneg(x), y) -> copysign(x, y)
10106   // copysign(copysign(x,z), y) -> copysign(x, y)
10107   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10108       N0.getOpcode() == ISD::FCOPYSIGN)
10109     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10110
10111   // copysign(x, abs(y)) -> abs(x)
10112   if (N1.getOpcode() == ISD::FABS)
10113     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10114
10115   // copysign(x, copysign(y,z)) -> copysign(x, z)
10116   if (N1.getOpcode() == ISD::FCOPYSIGN)
10117     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10118
10119   // copysign(x, fp_extend(y)) -> copysign(x, y)
10120   // copysign(x, fp_round(y)) -> copysign(x, y)
10121   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10122     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10123
10124   return SDValue();
10125 }
10126
10127 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10128   SDValue N0 = N->getOperand(0);
10129   EVT VT = N->getValueType(0);
10130   EVT OpVT = N0.getValueType();
10131
10132   // fold (sint_to_fp c1) -> c1fp
10133   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10134       // ...but only if the target supports immediate floating-point values
10135       (!LegalOperations ||
10136        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10137     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10138
10139   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10140   // but UINT_TO_FP is legal on this target, try to convert.
10141   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10142       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10143     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10144     if (DAG.SignBitIsZero(N0))
10145       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10146   }
10147
10148   // The next optimizations are desirable only if SELECT_CC can be lowered.
10149   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10150     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10151     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10152         !VT.isVector() &&
10153         (!LegalOperations ||
10154          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10155       SDLoc DL(N);
10156       SDValue Ops[] =
10157         { N0.getOperand(0), N0.getOperand(1),
10158           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10159           N0.getOperand(2) };
10160       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10161     }
10162
10163     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10164     //      (select_cc x, y, 1.0, 0.0,, cc)
10165     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10166         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10167         (!LegalOperations ||
10168          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10169       SDLoc DL(N);
10170       SDValue Ops[] =
10171         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10172           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10173           N0.getOperand(0).getOperand(2) };
10174       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10175     }
10176   }
10177
10178   return SDValue();
10179 }
10180
10181 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10182   SDValue N0 = N->getOperand(0);
10183   EVT VT = N->getValueType(0);
10184   EVT OpVT = N0.getValueType();
10185
10186   // fold (uint_to_fp c1) -> c1fp
10187   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10188       // ...but only if the target supports immediate floating-point values
10189       (!LegalOperations ||
10190        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10191     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10192
10193   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10194   // but SINT_TO_FP is legal on this target, try to convert.
10195   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10196       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10197     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10198     if (DAG.SignBitIsZero(N0))
10199       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10200   }
10201
10202   // The next optimizations are desirable only if SELECT_CC can be lowered.
10203   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10204     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10205
10206     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10207         (!LegalOperations ||
10208          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10209       SDLoc DL(N);
10210       SDValue Ops[] =
10211         { N0.getOperand(0), N0.getOperand(1),
10212           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10213           N0.getOperand(2) };
10214       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10215     }
10216   }
10217
10218   return SDValue();
10219 }
10220
10221 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10222 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10223   SDValue N0 = N->getOperand(0);
10224   EVT VT = N->getValueType(0);
10225
10226   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10227     return SDValue();
10228
10229   SDValue Src = N0.getOperand(0);
10230   EVT SrcVT = Src.getValueType();
10231   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10232   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10233
10234   // We can safely assume the conversion won't overflow the output range,
10235   // because (for example) (uint8_t)18293.f is undefined behavior.
10236
10237   // Since we can assume the conversion won't overflow, our decision as to
10238   // whether the input will fit in the float should depend on the minimum
10239   // of the input range and output range.
10240
10241   // This means this is also safe for a signed input and unsigned output, since
10242   // a negative input would lead to undefined behavior.
10243   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10244   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10245   unsigned ActualSize = std::min(InputSize, OutputSize);
10246   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10247
10248   // We can only fold away the float conversion if the input range can be
10249   // represented exactly in the float range.
10250   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10251     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10252       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10253                                                        : ISD::ZERO_EXTEND;
10254       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10255     }
10256     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10257       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10258     return DAG.getBitcast(VT, Src);
10259   }
10260   return SDValue();
10261 }
10262
10263 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10264   SDValue N0 = N->getOperand(0);
10265   EVT VT = N->getValueType(0);
10266
10267   // fold (fp_to_sint c1fp) -> c1
10268   if (isConstantFPBuildVectorOrConstantFP(N0))
10269     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10270
10271   return FoldIntToFPToInt(N, DAG);
10272 }
10273
10274 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10275   SDValue N0 = N->getOperand(0);
10276   EVT VT = N->getValueType(0);
10277
10278   // fold (fp_to_uint c1fp) -> c1
10279   if (isConstantFPBuildVectorOrConstantFP(N0))
10280     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10281
10282   return FoldIntToFPToInt(N, DAG);
10283 }
10284
10285 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10286   SDValue N0 = N->getOperand(0);
10287   SDValue N1 = N->getOperand(1);
10288   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10289   EVT VT = N->getValueType(0);
10290
10291   // fold (fp_round c1fp) -> c1fp
10292   if (N0CFP)
10293     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10294
10295   // fold (fp_round (fp_extend x)) -> x
10296   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10297     return N0.getOperand(0);
10298
10299   // fold (fp_round (fp_round x)) -> (fp_round x)
10300   if (N0.getOpcode() == ISD::FP_ROUND) {
10301     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10302     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10303
10304     // Skip this folding if it results in an fp_round from f80 to f16.
10305     //
10306     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10307     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10308     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10309     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10310     // x86.
10311     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10312       return SDValue();
10313
10314     // If the first fp_round isn't a value preserving truncation, it might
10315     // introduce a tie in the second fp_round, that wouldn't occur in the
10316     // single-step fp_round we want to fold to.
10317     // In other words, double rounding isn't the same as rounding.
10318     // Also, this is a value preserving truncation iff both fp_round's are.
10319     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10320       SDLoc DL(N);
10321       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10322                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10323     }
10324   }
10325
10326   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10327   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10328     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10329                               N0.getOperand(0), N1);
10330     AddToWorklist(Tmp.getNode());
10331     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10332                        Tmp, N0.getOperand(1));
10333   }
10334
10335   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10336     return NewVSel;
10337
10338   return SDValue();
10339 }
10340
10341 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10342   SDValue N0 = N->getOperand(0);
10343   EVT VT = N->getValueType(0);
10344   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10345   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10346
10347   // fold (fp_round_inreg c1fp) -> c1fp
10348   if (N0CFP && isTypeLegal(EVT)) {
10349     SDLoc DL(N);
10350     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10351     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10352   }
10353
10354   return SDValue();
10355 }
10356
10357 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10358   SDValue N0 = N->getOperand(0);
10359   EVT VT = N->getValueType(0);
10360
10361   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10362   if (N->hasOneUse() &&
10363       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10364     return SDValue();
10365
10366   // fold (fp_extend c1fp) -> c1fp
10367   if (isConstantFPBuildVectorOrConstantFP(N0))
10368     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10369
10370   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10371   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10372       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10373     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10374
10375   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10376   // value of X.
10377   if (N0.getOpcode() == ISD::FP_ROUND
10378       && N0.getConstantOperandVal(1) == 1) {
10379     SDValue In = N0.getOperand(0);
10380     if (In.getValueType() == VT) return In;
10381     if (VT.bitsLT(In.getValueType()))
10382       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10383                          In, N0.getOperand(1));
10384     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10385   }
10386
10387   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10388   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10389        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10390     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10391     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10392                                      LN0->getChain(),
10393                                      LN0->getBasePtr(), N0.getValueType(),
10394                                      LN0->getMemOperand());
10395     CombineTo(N, ExtLoad);
10396     CombineTo(N0.getNode(),
10397               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10398                           N0.getValueType(), ExtLoad,
10399                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10400               ExtLoad.getValue(1));
10401     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10402   }
10403
10404   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10405     return NewVSel;
10406
10407   return SDValue();
10408 }
10409
10410 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10411   SDValue N0 = N->getOperand(0);
10412   EVT VT = N->getValueType(0);
10413
10414   // fold (fceil c1) -> fceil(c1)
10415   if (isConstantFPBuildVectorOrConstantFP(N0))
10416     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10417
10418   return SDValue();
10419 }
10420
10421 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10422   SDValue N0 = N->getOperand(0);
10423   EVT VT = N->getValueType(0);
10424
10425   // fold (ftrunc c1) -> ftrunc(c1)
10426   if (isConstantFPBuildVectorOrConstantFP(N0))
10427     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10428
10429   return SDValue();
10430 }
10431
10432 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10433   SDValue N0 = N->getOperand(0);
10434   EVT VT = N->getValueType(0);
10435
10436   // fold (ffloor c1) -> ffloor(c1)
10437   if (isConstantFPBuildVectorOrConstantFP(N0))
10438     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10439
10440   return SDValue();
10441 }
10442
10443 // FIXME: FNEG and FABS have a lot in common; refactor.
10444 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10445   SDValue N0 = N->getOperand(0);
10446   EVT VT = N->getValueType(0);
10447
10448   // Constant fold FNEG.
10449   if (isConstantFPBuildVectorOrConstantFP(N0))
10450     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10451
10452   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10453                          &DAG.getTarget().Options))
10454     return GetNegatedExpression(N0, DAG, LegalOperations);
10455
10456   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10457   // constant pool values.
10458   if (!TLI.isFNegFree(VT) &&
10459       N0.getOpcode() == ISD::BITCAST &&
10460       N0.getNode()->hasOneUse()) {
10461     SDValue Int = N0.getOperand(0);
10462     EVT IntVT = Int.getValueType();
10463     if (IntVT.isInteger() && !IntVT.isVector()) {
10464       APInt SignMask;
10465       if (N0.getValueType().isVector()) {
10466         // For a vector, get a mask such as 0x80... per scalar element
10467         // and splat it.
10468         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10469         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10470       } else {
10471         // For a scalar, just generate 0x80...
10472         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10473       }
10474       SDLoc DL0(N0);
10475       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10476                         DAG.getConstant(SignMask, DL0, IntVT));
10477       AddToWorklist(Int.getNode());
10478       return DAG.getBitcast(VT, Int);
10479     }
10480   }
10481
10482   // (fneg (fmul c, x)) -> (fmul -c, x)
10483   if (N0.getOpcode() == ISD::FMUL &&
10484       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10485     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10486     if (CFP1) {
10487       APFloat CVal = CFP1->getValueAPF();
10488       CVal.changeSign();
10489       if (Level >= AfterLegalizeDAG &&
10490           (TLI.isFPImmLegal(CVal, VT) ||
10491            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10492         return DAG.getNode(
10493             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10494             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10495             N0->getFlags());
10496     }
10497   }
10498
10499   return SDValue();
10500 }
10501
10502 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10503   SDValue N0 = N->getOperand(0);
10504   SDValue N1 = N->getOperand(1);
10505   EVT VT = N->getValueType(0);
10506   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10507   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10508
10509   if (N0CFP && N1CFP) {
10510     const APFloat &C0 = N0CFP->getValueAPF();
10511     const APFloat &C1 = N1CFP->getValueAPF();
10512     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10513   }
10514
10515   // Canonicalize to constant on RHS.
10516   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10517      !isConstantFPBuildVectorOrConstantFP(N1))
10518     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10519
10520   return SDValue();
10521 }
10522
10523 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10524   SDValue N0 = N->getOperand(0);
10525   SDValue N1 = N->getOperand(1);
10526   EVT VT = N->getValueType(0);
10527   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10528   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10529
10530   if (N0CFP && N1CFP) {
10531     const APFloat &C0 = N0CFP->getValueAPF();
10532     const APFloat &C1 = N1CFP->getValueAPF();
10533     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10534   }
10535
10536   // Canonicalize to constant on RHS.
10537   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10538      !isConstantFPBuildVectorOrConstantFP(N1))
10539     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10540
10541   return SDValue();
10542 }
10543
10544 SDValue DAGCombiner::visitFABS(SDNode *N) {
10545   SDValue N0 = N->getOperand(0);
10546   EVT VT = N->getValueType(0);
10547
10548   // fold (fabs c1) -> fabs(c1)
10549   if (isConstantFPBuildVectorOrConstantFP(N0))
10550     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10551
10552   // fold (fabs (fabs x)) -> (fabs x)
10553   if (N0.getOpcode() == ISD::FABS)
10554     return N->getOperand(0);
10555
10556   // fold (fabs (fneg x)) -> (fabs x)
10557   // fold (fabs (fcopysign x, y)) -> (fabs x)
10558   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10559     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10560
10561   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10562   // constant pool values.
10563   if (!TLI.isFAbsFree(VT) &&
10564       N0.getOpcode() == ISD::BITCAST &&
10565       N0.getNode()->hasOneUse()) {
10566     SDValue Int = N0.getOperand(0);
10567     EVT IntVT = Int.getValueType();
10568     if (IntVT.isInteger() && !IntVT.isVector()) {
10569       APInt SignMask;
10570       if (N0.getValueType().isVector()) {
10571         // For a vector, get a mask such as 0x7f... per scalar element
10572         // and splat it.
10573         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10574         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10575       } else {
10576         // For a scalar, just generate 0x7f...
10577         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10578       }
10579       SDLoc DL(N0);
10580       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10581                         DAG.getConstant(SignMask, DL, IntVT));
10582       AddToWorklist(Int.getNode());
10583       return DAG.getBitcast(N->getValueType(0), Int);
10584     }
10585   }
10586
10587   return SDValue();
10588 }
10589
10590 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10591   SDValue Chain = N->getOperand(0);
10592   SDValue N1 = N->getOperand(1);
10593   SDValue N2 = N->getOperand(2);
10594
10595   // If N is a constant we could fold this into a fallthrough or unconditional
10596   // branch. However that doesn't happen very often in normal code, because
10597   // Instcombine/SimplifyCFG should have handled the available opportunities.
10598   // If we did this folding here, it would be necessary to update the
10599   // MachineBasicBlock CFG, which is awkward.
10600
10601   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10602   // on the target.
10603   if (N1.getOpcode() == ISD::SETCC &&
10604       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10605                                    N1.getOperand(0).getValueType())) {
10606     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10607                        Chain, N1.getOperand(2),
10608                        N1.getOperand(0), N1.getOperand(1), N2);
10609   }
10610
10611   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10612       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10613        (N1.getOperand(0).hasOneUse() &&
10614         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10615     SDNode *Trunc = nullptr;
10616     if (N1.getOpcode() == ISD::TRUNCATE) {
10617       // Look pass the truncate.
10618       Trunc = N1.getNode();
10619       N1 = N1.getOperand(0);
10620     }
10621
10622     // Match this pattern so that we can generate simpler code:
10623     //
10624     //   %a = ...
10625     //   %b = and i32 %a, 2
10626     //   %c = srl i32 %b, 1
10627     //   brcond i32 %c ...
10628     //
10629     // into
10630     //
10631     //   %a = ...
10632     //   %b = and i32 %a, 2
10633     //   %c = setcc eq %b, 0
10634     //   brcond %c ...
10635     //
10636     // This applies only when the AND constant value has one bit set and the
10637     // SRL constant is equal to the log2 of the AND constant. The back-end is
10638     // smart enough to convert the result into a TEST/JMP sequence.
10639     SDValue Op0 = N1.getOperand(0);
10640     SDValue Op1 = N1.getOperand(1);
10641
10642     if (Op0.getOpcode() == ISD::AND &&
10643         Op1.getOpcode() == ISD::Constant) {
10644       SDValue AndOp1 = Op0.getOperand(1);
10645
10646       if (AndOp1.getOpcode() == ISD::Constant) {
10647         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10648
10649         if (AndConst.isPowerOf2() &&
10650             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10651           SDLoc DL(N);
10652           SDValue SetCC =
10653             DAG.getSetCC(DL,
10654                          getSetCCResultType(Op0.getValueType()),
10655                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10656                          ISD::SETNE);
10657
10658           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10659                                           MVT::Other, Chain, SetCC, N2);
10660           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10661           // will convert it back to (X & C1) >> C2.
10662           CombineTo(N, NewBRCond, false);
10663           // Truncate is dead.
10664           if (Trunc)
10665             deleteAndRecombine(Trunc);
10666           // Replace the uses of SRL with SETCC
10667           WorklistRemover DeadNodes(*this);
10668           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10669           deleteAndRecombine(N1.getNode());
10670           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10671         }
10672       }
10673     }
10674
10675     if (Trunc)
10676       // Restore N1 if the above transformation doesn't match.
10677       N1 = N->getOperand(1);
10678   }
10679
10680   // Transform br(xor(x, y)) -> br(x != y)
10681   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10682   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10683     SDNode *TheXor = N1.getNode();
10684     SDValue Op0 = TheXor->getOperand(0);
10685     SDValue Op1 = TheXor->getOperand(1);
10686     if (Op0.getOpcode() == Op1.getOpcode()) {
10687       // Avoid missing important xor optimizations.
10688       if (SDValue Tmp = visitXOR(TheXor)) {
10689         if (Tmp.getNode() != TheXor) {
10690           DEBUG(dbgs() << "\nReplacing.8 ";
10691                 TheXor->dump(&DAG);
10692                 dbgs() << "\nWith: ";
10693                 Tmp.getNode()->dump(&DAG);
10694                 dbgs() << '\n');
10695           WorklistRemover DeadNodes(*this);
10696           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10697           deleteAndRecombine(TheXor);
10698           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10699                              MVT::Other, Chain, Tmp, N2);
10700         }
10701
10702         // visitXOR has changed XOR's operands or replaced the XOR completely,
10703         // bail out.
10704         return SDValue(N, 0);
10705       }
10706     }
10707
10708     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10709       bool Equal = false;
10710       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10711           Op0.getOpcode() == ISD::XOR) {
10712         TheXor = Op0.getNode();
10713         Equal = true;
10714       }
10715
10716       EVT SetCCVT = N1.getValueType();
10717       if (LegalTypes)
10718         SetCCVT = getSetCCResultType(SetCCVT);
10719       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10720                                    SetCCVT,
10721                                    Op0, Op1,
10722                                    Equal ? ISD::SETEQ : ISD::SETNE);
10723       // Replace the uses of XOR with SETCC
10724       WorklistRemover DeadNodes(*this);
10725       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10726       deleteAndRecombine(N1.getNode());
10727       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10728                          MVT::Other, Chain, SetCC, N2);
10729     }
10730   }
10731
10732   return SDValue();
10733 }
10734
10735 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10736 //
10737 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10738   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10739   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10740
10741   // If N is a constant we could fold this into a fallthrough or unconditional
10742   // branch. However that doesn't happen very often in normal code, because
10743   // Instcombine/SimplifyCFG should have handled the available opportunities.
10744   // If we did this folding here, it would be necessary to update the
10745   // MachineBasicBlock CFG, which is awkward.
10746
10747   // Use SimplifySetCC to simplify SETCC's.
10748   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10749                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10750                                false);
10751   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10752
10753   // fold to a simpler setcc
10754   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10755     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10756                        N->getOperand(0), Simp.getOperand(2),
10757                        Simp.getOperand(0), Simp.getOperand(1),
10758                        N->getOperand(4));
10759
10760   return SDValue();
10761 }
10762
10763 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10764 /// and that N may be folded in the load / store addressing mode.
10765 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10766                                     SelectionDAG &DAG,
10767                                     const TargetLowering &TLI) {
10768   EVT VT;
10769   unsigned AS;
10770
10771   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10772     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10773       return false;
10774     VT = LD->getMemoryVT();
10775     AS = LD->getAddressSpace();
10776   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10777     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10778       return false;
10779     VT = ST->getMemoryVT();
10780     AS = ST->getAddressSpace();
10781   } else
10782     return false;
10783
10784   TargetLowering::AddrMode AM;
10785   if (N->getOpcode() == ISD::ADD) {
10786     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10787     if (Offset)
10788       // [reg +/- imm]
10789       AM.BaseOffs = Offset->getSExtValue();
10790     else
10791       // [reg +/- reg]
10792       AM.Scale = 1;
10793   } else if (N->getOpcode() == ISD::SUB) {
10794     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10795     if (Offset)
10796       // [reg +/- imm]
10797       AM.BaseOffs = -Offset->getSExtValue();
10798     else
10799       // [reg +/- reg]
10800       AM.Scale = 1;
10801   } else
10802     return false;
10803
10804   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10805                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10806 }
10807
10808 /// Try turning a load/store into a pre-indexed load/store when the base
10809 /// pointer is an add or subtract and it has other uses besides the load/store.
10810 /// After the transformation, the new indexed load/store has effectively folded
10811 /// the add/subtract in and all of its other uses are redirected to the
10812 /// new load/store.
10813 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10814   if (Level < AfterLegalizeDAG)
10815     return false;
10816
10817   bool isLoad = true;
10818   SDValue Ptr;
10819   EVT VT;
10820   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10821     if (LD->isIndexed())
10822       return false;
10823     VT = LD->getMemoryVT();
10824     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10825         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10826       return false;
10827     Ptr = LD->getBasePtr();
10828   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10829     if (ST->isIndexed())
10830       return false;
10831     VT = ST->getMemoryVT();
10832     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10833         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10834       return false;
10835     Ptr = ST->getBasePtr();
10836     isLoad = false;
10837   } else {
10838     return false;
10839   }
10840
10841   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10842   // out.  There is no reason to make this a preinc/predec.
10843   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10844       Ptr.getNode()->hasOneUse())
10845     return false;
10846
10847   // Ask the target to do addressing mode selection.
10848   SDValue BasePtr;
10849   SDValue Offset;
10850   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10851   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10852     return false;
10853
10854   // Backends without true r+i pre-indexed forms may need to pass a
10855   // constant base with a variable offset so that constant coercion
10856   // will work with the patterns in canonical form.
10857   bool Swapped = false;
10858   if (isa<ConstantSDNode>(BasePtr)) {
10859     std::swap(BasePtr, Offset);
10860     Swapped = true;
10861   }
10862
10863   // Don't create a indexed load / store with zero offset.
10864   if (isNullConstant(Offset))
10865     return false;
10866
10867   // Try turning it into a pre-indexed load / store except when:
10868   // 1) The new base ptr is a frame index.
10869   // 2) If N is a store and the new base ptr is either the same as or is a
10870   //    predecessor of the value being stored.
10871   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10872   //    that would create a cycle.
10873   // 4) All uses are load / store ops that use it as old base ptr.
10874
10875   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
10876   // (plus the implicit offset) to a register to preinc anyway.
10877   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10878     return false;
10879
10880   // Check #2.
10881   if (!isLoad) {
10882     SDValue Val = cast<StoreSDNode>(N)->getValue();
10883     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10884       return false;
10885   }
10886
10887   // Caches for hasPredecessorHelper.
10888   SmallPtrSet<const SDNode *, 32> Visited;
10889   SmallVector<const SDNode *, 16> Worklist;
10890   Worklist.push_back(N);
10891
10892   // If the offset is a constant, there may be other adds of constants that
10893   // can be folded with this one. We should do this to avoid having to keep
10894   // a copy of the original base pointer.
10895   SmallVector<SDNode *, 16> OtherUses;
10896   if (isa<ConstantSDNode>(Offset))
10897     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10898                               UE = BasePtr.getNode()->use_end();
10899          UI != UE; ++UI) {
10900       SDUse &Use = UI.getUse();
10901       // Skip the use that is Ptr and uses of other results from BasePtr's
10902       // node (important for nodes that return multiple results).
10903       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10904         continue;
10905
10906       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10907         continue;
10908
10909       if (Use.getUser()->getOpcode() != ISD::ADD &&
10910           Use.getUser()->getOpcode() != ISD::SUB) {
10911         OtherUses.clear();
10912         break;
10913       }
10914
10915       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10916       if (!isa<ConstantSDNode>(Op1)) {
10917         OtherUses.clear();
10918         break;
10919       }
10920
10921       // FIXME: In some cases, we can be smarter about this.
10922       if (Op1.getValueType() != Offset.getValueType()) {
10923         OtherUses.clear();
10924         break;
10925       }
10926
10927       OtherUses.push_back(Use.getUser());
10928     }
10929
10930   if (Swapped)
10931     std::swap(BasePtr, Offset);
10932
10933   // Now check for #3 and #4.
10934   bool RealUse = false;
10935
10936   for (SDNode *Use : Ptr.getNode()->uses()) {
10937     if (Use == N)
10938       continue;
10939     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10940       return false;
10941
10942     // If Ptr may be folded in addressing mode of other use, then it's
10943     // not profitable to do this transformation.
10944     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
10945       RealUse = true;
10946   }
10947
10948   if (!RealUse)
10949     return false;
10950
10951   SDValue Result;
10952   if (isLoad)
10953     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10954                                 BasePtr, Offset, AM);
10955   else
10956     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10957                                  BasePtr, Offset, AM);
10958   ++PreIndexedNodes;
10959   ++NodesCombined;
10960   DEBUG(dbgs() << "\nReplacing.4 ";
10961         N->dump(&DAG);
10962         dbgs() << "\nWith: ";
10963         Result.getNode()->dump(&DAG);
10964         dbgs() << '\n');
10965   WorklistRemover DeadNodes(*this);
10966   if (isLoad) {
10967     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10968     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10969   } else {
10970     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10971   }
10972
10973   // Finally, since the node is now dead, remove it from the graph.
10974   deleteAndRecombine(N);
10975
10976   if (Swapped)
10977     std::swap(BasePtr, Offset);
10978
10979   // Replace other uses of BasePtr that can be updated to use Ptr
10980   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10981     unsigned OffsetIdx = 1;
10982     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10983       OffsetIdx = 0;
10984     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10985            BasePtr.getNode() && "Expected BasePtr operand");
10986
10987     // We need to replace ptr0 in the following expression:
10988     //   x0 * offset0 + y0 * ptr0 = t0
10989     // knowing that
10990     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10991     //
10992     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10993     // indexed load/store and the expresion that needs to be re-written.
10994     //
10995     // Therefore, we have:
10996     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10997
10998     ConstantSDNode *CN =
10999       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11000     int X0, X1, Y0, Y1;
11001     const APInt &Offset0 = CN->getAPIntValue();
11002     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11003
11004     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11005     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11006     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11007     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11008
11009     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11010
11011     APInt CNV = Offset0;
11012     if (X0 < 0) CNV = -CNV;
11013     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11014     else CNV = CNV - Offset1;
11015
11016     SDLoc DL(OtherUses[i]);
11017
11018     // We can now generate the new expression.
11019     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11020     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11021
11022     SDValue NewUse = DAG.getNode(Opcode,
11023                                  DL,
11024                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11025     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11026     deleteAndRecombine(OtherUses[i]);
11027   }
11028
11029   // Replace the uses of Ptr with uses of the updated base value.
11030   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11031   deleteAndRecombine(Ptr.getNode());
11032
11033   return true;
11034 }
11035
11036 /// Try to combine a load/store with a add/sub of the base pointer node into a
11037 /// post-indexed load/store. The transformation folded the add/subtract into the
11038 /// new indexed load/store effectively and all of its uses are redirected to the
11039 /// new load/store.
11040 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11041   if (Level < AfterLegalizeDAG)
11042     return false;
11043
11044   bool isLoad = true;
11045   SDValue Ptr;
11046   EVT VT;
11047   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11048     if (LD->isIndexed())
11049       return false;
11050     VT = LD->getMemoryVT();
11051     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11052         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11053       return false;
11054     Ptr = LD->getBasePtr();
11055   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11056     if (ST->isIndexed())
11057       return false;
11058     VT = ST->getMemoryVT();
11059     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11060         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11061       return false;
11062     Ptr = ST->getBasePtr();
11063     isLoad = false;
11064   } else {
11065     return false;
11066   }
11067
11068   if (Ptr.getNode()->hasOneUse())
11069     return false;
11070
11071   for (SDNode *Op : Ptr.getNode()->uses()) {
11072     if (Op == N ||
11073         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11074       continue;
11075
11076     SDValue BasePtr;
11077     SDValue Offset;
11078     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11079     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11080       // Don't create a indexed load / store with zero offset.
11081       if (isNullConstant(Offset))
11082         continue;
11083
11084       // Try turning it into a post-indexed load / store except when
11085       // 1) All uses are load / store ops that use it as base ptr (and
11086       //    it may be folded as addressing mmode).
11087       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11088       //    nor a successor of N. Otherwise, if Op is folded that would
11089       //    create a cycle.
11090
11091       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11092         continue;
11093
11094       // Check for #1.
11095       bool TryNext = false;
11096       for (SDNode *Use : BasePtr.getNode()->uses()) {
11097         if (Use == Ptr.getNode())
11098           continue;
11099
11100         // If all the uses are load / store addresses, then don't do the
11101         // transformation.
11102         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11103           bool RealUse = false;
11104           for (SDNode *UseUse : Use->uses()) {
11105             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11106               RealUse = true;
11107           }
11108
11109           if (!RealUse) {
11110             TryNext = true;
11111             break;
11112           }
11113         }
11114       }
11115
11116       if (TryNext)
11117         continue;
11118
11119       // Check for #2
11120       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11121         SDValue Result = isLoad
11122           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11123                                BasePtr, Offset, AM)
11124           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11125                                 BasePtr, Offset, AM);
11126         ++PostIndexedNodes;
11127         ++NodesCombined;
11128         DEBUG(dbgs() << "\nReplacing.5 ";
11129               N->dump(&DAG);
11130               dbgs() << "\nWith: ";
11131               Result.getNode()->dump(&DAG);
11132               dbgs() << '\n');
11133         WorklistRemover DeadNodes(*this);
11134         if (isLoad) {
11135           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11136           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11137         } else {
11138           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11139         }
11140
11141         // Finally, since the node is now dead, remove it from the graph.
11142         deleteAndRecombine(N);
11143
11144         // Replace the uses of Use with uses of the updated base value.
11145         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11146                                       Result.getValue(isLoad ? 1 : 0));
11147         deleteAndRecombine(Op);
11148         return true;
11149       }
11150     }
11151   }
11152
11153   return false;
11154 }
11155
11156 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11157 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11158   ISD::MemIndexedMode AM = LD->getAddressingMode();
11159   assert(AM != ISD::UNINDEXED);
11160   SDValue BP = LD->getOperand(1);
11161   SDValue Inc = LD->getOperand(2);
11162
11163   // Some backends use TargetConstants for load offsets, but don't expect
11164   // TargetConstants in general ADD nodes. We can convert these constants into
11165   // regular Constants (if the constant is not opaque).
11166   assert((Inc.getOpcode() != ISD::TargetConstant ||
11167           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11168          "Cannot split out indexing using opaque target constants");
11169   if (Inc.getOpcode() == ISD::TargetConstant) {
11170     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11171     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11172                           ConstInc->getValueType(0));
11173   }
11174
11175   unsigned Opc =
11176       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11177   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11178 }
11179
11180 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11181   LoadSDNode *LD  = cast<LoadSDNode>(N);
11182   SDValue Chain = LD->getChain();
11183   SDValue Ptr   = LD->getBasePtr();
11184
11185   // If load is not volatile and there are no uses of the loaded value (and
11186   // the updated indexed value in case of indexed loads), change uses of the
11187   // chain value into uses of the chain input (i.e. delete the dead load).
11188   if (!LD->isVolatile()) {
11189     if (N->getValueType(1) == MVT::Other) {
11190       // Unindexed loads.
11191       if (!N->hasAnyUseOfValue(0)) {
11192         // It's not safe to use the two value CombineTo variant here. e.g.
11193         // v1, chain2 = load chain1, loc
11194         // v2, chain3 = load chain2, loc
11195         // v3         = add v2, c
11196         // Now we replace use of chain2 with chain1.  This makes the second load
11197         // isomorphic to the one we are deleting, and thus makes this load live.
11198         DEBUG(dbgs() << "\nReplacing.6 ";
11199               N->dump(&DAG);
11200               dbgs() << "\nWith chain: ";
11201               Chain.getNode()->dump(&DAG);
11202               dbgs() << "\n");
11203         WorklistRemover DeadNodes(*this);
11204         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11205         AddUsersToWorklist(Chain.getNode());
11206         if (N->use_empty())
11207           deleteAndRecombine(N);
11208
11209         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11210       }
11211     } else {
11212       // Indexed loads.
11213       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11214
11215       // If this load has an opaque TargetConstant offset, then we cannot split
11216       // the indexing into an add/sub directly (that TargetConstant may not be
11217       // valid for a different type of node, and we cannot convert an opaque
11218       // target constant into a regular constant).
11219       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11220                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11221
11222       if (!N->hasAnyUseOfValue(0) &&
11223           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11224         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11225         SDValue Index;
11226         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11227           Index = SplitIndexingFromLoad(LD);
11228           // Try to fold the base pointer arithmetic into subsequent loads and
11229           // stores.
11230           AddUsersToWorklist(N);
11231         } else
11232           Index = DAG.getUNDEF(N->getValueType(1));
11233         DEBUG(dbgs() << "\nReplacing.7 ";
11234               N->dump(&DAG);
11235               dbgs() << "\nWith: ";
11236               Undef.getNode()->dump(&DAG);
11237               dbgs() << " and 2 other values\n");
11238         WorklistRemover DeadNodes(*this);
11239         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11240         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11241         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11242         deleteAndRecombine(N);
11243         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11244       }
11245     }
11246   }
11247
11248   // If this load is directly stored, replace the load value with the stored
11249   // value.
11250   // TODO: Handle store large -> read small portion.
11251   // TODO: Handle TRUNCSTORE/LOADEXT
11252   if (OptLevel != CodeGenOpt::None &&
11253       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11254     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11255       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11256       if (PrevST->getBasePtr() == Ptr &&
11257           PrevST->getValue().getValueType() == N->getValueType(0))
11258         return CombineTo(N, PrevST->getOperand(1), Chain);
11259     }
11260   }
11261
11262   // Try to infer better alignment information than the load already has.
11263   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11264     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11265       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11266         SDValue NewLoad = DAG.getExtLoad(
11267             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11268             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11269             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11270         if (NewLoad.getNode() != N)
11271           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11272       }
11273     }
11274   }
11275
11276   if (LD->isUnindexed()) {
11277     // Walk up chain skipping non-aliasing memory nodes.
11278     SDValue BetterChain = FindBetterChain(N, Chain);
11279
11280     // If there is a better chain.
11281     if (Chain != BetterChain) {
11282       SDValue ReplLoad;
11283
11284       // Replace the chain to void dependency.
11285       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11286         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11287                                BetterChain, Ptr, LD->getMemOperand());
11288       } else {
11289         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11290                                   LD->getValueType(0),
11291                                   BetterChain, Ptr, LD->getMemoryVT(),
11292                                   LD->getMemOperand());
11293       }
11294
11295       // Create token factor to keep old chain connected.
11296       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11297                                   MVT::Other, Chain, ReplLoad.getValue(1));
11298
11299       // Make sure the new and old chains are cleaned up.
11300       AddToWorklist(Token.getNode());
11301
11302       // Replace uses with load result and token factor. Don't add users
11303       // to work list.
11304       return CombineTo(N, ReplLoad.getValue(0), Token, false);
11305     }
11306   }
11307
11308   // Try transforming N to an indexed load.
11309   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11310     return SDValue(N, 0);
11311
11312   // Try to slice up N to more direct loads if the slices are mapped to
11313   // different register banks or pairing can take place.
11314   if (SliceUpLoad(N))
11315     return SDValue(N, 0);
11316
11317   return SDValue();
11318 }
11319
11320 namespace {
11321 /// \brief Helper structure used to slice a load in smaller loads.
11322 /// Basically a slice is obtained from the following sequence:
11323 /// Origin = load Ty1, Base
11324 /// Shift = srl Ty1 Origin, CstTy Amount
11325 /// Inst = trunc Shift to Ty2
11326 ///
11327 /// Then, it will be rewriten into:
11328 /// Slice = load SliceTy, Base + SliceOffset
11329 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11330 ///
11331 /// SliceTy is deduced from the number of bits that are actually used to
11332 /// build Inst.
11333 struct LoadedSlice {
11334   /// \brief Helper structure used to compute the cost of a slice.
11335   struct Cost {
11336     /// Are we optimizing for code size.
11337     bool ForCodeSize;
11338     /// Various cost.
11339     unsigned Loads;
11340     unsigned Truncates;
11341     unsigned CrossRegisterBanksCopies;
11342     unsigned ZExts;
11343     unsigned Shift;
11344
11345     Cost(bool ForCodeSize = false)
11346         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11347           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11348
11349     /// \brief Get the cost of one isolated slice.
11350     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11351         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11352           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11353       EVT TruncType = LS.Inst->getValueType(0);
11354       EVT LoadedType = LS.getLoadedType();
11355       if (TruncType != LoadedType &&
11356           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11357         ZExts = 1;
11358     }
11359
11360     /// \brief Account for slicing gain in the current cost.
11361     /// Slicing provide a few gains like removing a shift or a
11362     /// truncate. This method allows to grow the cost of the original
11363     /// load with the gain from this slice.
11364     void addSliceGain(const LoadedSlice &LS) {
11365       // Each slice saves a truncate.
11366       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11367       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11368                               LS.Inst->getValueType(0)))
11369         ++Truncates;
11370       // If there is a shift amount, this slice gets rid of it.
11371       if (LS.Shift)
11372         ++Shift;
11373       // If this slice can merge a cross register bank copy, account for it.
11374       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11375         ++CrossRegisterBanksCopies;
11376     }
11377
11378     Cost &operator+=(const Cost &RHS) {
11379       Loads += RHS.Loads;
11380       Truncates += RHS.Truncates;
11381       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11382       ZExts += RHS.ZExts;
11383       Shift += RHS.Shift;
11384       return *this;
11385     }
11386
11387     bool operator==(const Cost &RHS) const {
11388       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11389              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11390              ZExts == RHS.ZExts && Shift == RHS.Shift;
11391     }
11392
11393     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11394
11395     bool operator<(const Cost &RHS) const {
11396       // Assume cross register banks copies are as expensive as loads.
11397       // FIXME: Do we want some more target hooks?
11398       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11399       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11400       // Unless we are optimizing for code size, consider the
11401       // expensive operation first.
11402       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11403         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11404       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11405              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11406     }
11407
11408     bool operator>(const Cost &RHS) const { return RHS < *this; }
11409
11410     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11411
11412     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11413   };
11414   // The last instruction that represent the slice. This should be a
11415   // truncate instruction.
11416   SDNode *Inst;
11417   // The original load instruction.
11418   LoadSDNode *Origin;
11419   // The right shift amount in bits from the original load.
11420   unsigned Shift;
11421   // The DAG from which Origin came from.
11422   // This is used to get some contextual information about legal types, etc.
11423   SelectionDAG *DAG;
11424
11425   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11426               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11427       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11428
11429   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11430   /// \return Result is \p BitWidth and has used bits set to 1 and
11431   ///         not used bits set to 0.
11432   APInt getUsedBits() const {
11433     // Reproduce the trunc(lshr) sequence:
11434     // - Start from the truncated value.
11435     // - Zero extend to the desired bit width.
11436     // - Shift left.
11437     assert(Origin && "No original load to compare against.");
11438     unsigned BitWidth = Origin->getValueSizeInBits(0);
11439     assert(Inst && "This slice is not bound to an instruction");
11440     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11441            "Extracted slice is bigger than the whole type!");
11442     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11443     UsedBits.setAllBits();
11444     UsedBits = UsedBits.zext(BitWidth);
11445     UsedBits <<= Shift;
11446     return UsedBits;
11447   }
11448
11449   /// \brief Get the size of the slice to be loaded in bytes.
11450   unsigned getLoadedSize() const {
11451     unsigned SliceSize = getUsedBits().countPopulation();
11452     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11453     return SliceSize / 8;
11454   }
11455
11456   /// \brief Get the type that will be loaded for this slice.
11457   /// Note: This may not be the final type for the slice.
11458   EVT getLoadedType() const {
11459     assert(DAG && "Missing context");
11460     LLVMContext &Ctxt = *DAG->getContext();
11461     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11462   }
11463
11464   /// \brief Get the alignment of the load used for this slice.
11465   unsigned getAlignment() const {
11466     unsigned Alignment = Origin->getAlignment();
11467     unsigned Offset = getOffsetFromBase();
11468     if (Offset != 0)
11469       Alignment = MinAlign(Alignment, Alignment + Offset);
11470     return Alignment;
11471   }
11472
11473   /// \brief Check if this slice can be rewritten with legal operations.
11474   bool isLegal() const {
11475     // An invalid slice is not legal.
11476     if (!Origin || !Inst || !DAG)
11477       return false;
11478
11479     // Offsets are for indexed load only, we do not handle that.
11480     if (!Origin->getOffset().isUndef())
11481       return false;
11482
11483     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11484
11485     // Check that the type is legal.
11486     EVT SliceType = getLoadedType();
11487     if (!TLI.isTypeLegal(SliceType))
11488       return false;
11489
11490     // Check that the load is legal for this type.
11491     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11492       return false;
11493
11494     // Check that the offset can be computed.
11495     // 1. Check its type.
11496     EVT PtrType = Origin->getBasePtr().getValueType();
11497     if (PtrType == MVT::Untyped || PtrType.isExtended())
11498       return false;
11499
11500     // 2. Check that it fits in the immediate.
11501     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11502       return false;
11503
11504     // 3. Check that the computation is legal.
11505     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11506       return false;
11507
11508     // Check that the zext is legal if it needs one.
11509     EVT TruncateType = Inst->getValueType(0);
11510     if (TruncateType != SliceType &&
11511         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11512       return false;
11513
11514     return true;
11515   }
11516
11517   /// \brief Get the offset in bytes of this slice in the original chunk of
11518   /// bits.
11519   /// \pre DAG != nullptr.
11520   uint64_t getOffsetFromBase() const {
11521     assert(DAG && "Missing context.");
11522     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11523     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11524     uint64_t Offset = Shift / 8;
11525     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11526     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11527            "The size of the original loaded type is not a multiple of a"
11528            " byte.");
11529     // If Offset is bigger than TySizeInBytes, it means we are loading all
11530     // zeros. This should have been optimized before in the process.
11531     assert(TySizeInBytes > Offset &&
11532            "Invalid shift amount for given loaded size");
11533     if (IsBigEndian)
11534       Offset = TySizeInBytes - Offset - getLoadedSize();
11535     return Offset;
11536   }
11537
11538   /// \brief Generate the sequence of instructions to load the slice
11539   /// represented by this object and redirect the uses of this slice to
11540   /// this new sequence of instructions.
11541   /// \pre this->Inst && this->Origin are valid Instructions and this
11542   /// object passed the legal check: LoadedSlice::isLegal returned true.
11543   /// \return The last instruction of the sequence used to load the slice.
11544   SDValue loadSlice() const {
11545     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11546     const SDValue &OldBaseAddr = Origin->getBasePtr();
11547     SDValue BaseAddr = OldBaseAddr;
11548     // Get the offset in that chunk of bytes w.r.t. the endianness.
11549     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11550     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11551     if (Offset) {
11552       // BaseAddr = BaseAddr + Offset.
11553       EVT ArithType = BaseAddr.getValueType();
11554       SDLoc DL(Origin);
11555       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11556                               DAG->getConstant(Offset, DL, ArithType));
11557     }
11558
11559     // Create the type of the loaded slice according to its size.
11560     EVT SliceType = getLoadedType();
11561
11562     // Create the load for the slice.
11563     SDValue LastInst =
11564         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11565                      Origin->getPointerInfo().getWithOffset(Offset),
11566                      getAlignment(), Origin->getMemOperand()->getFlags());
11567     // If the final type is not the same as the loaded type, this means that
11568     // we have to pad with zero. Create a zero extend for that.
11569     EVT FinalType = Inst->getValueType(0);
11570     if (SliceType != FinalType)
11571       LastInst =
11572           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11573     return LastInst;
11574   }
11575
11576   /// \brief Check if this slice can be merged with an expensive cross register
11577   /// bank copy. E.g.,
11578   /// i = load i32
11579   /// f = bitcast i32 i to float
11580   bool canMergeExpensiveCrossRegisterBankCopy() const {
11581     if (!Inst || !Inst->hasOneUse())
11582       return false;
11583     SDNode *Use = *Inst->use_begin();
11584     if (Use->getOpcode() != ISD::BITCAST)
11585       return false;
11586     assert(DAG && "Missing context");
11587     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11588     EVT ResVT = Use->getValueType(0);
11589     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11590     const TargetRegisterClass *ArgRC =
11591         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11592     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11593       return false;
11594
11595     // At this point, we know that we perform a cross-register-bank copy.
11596     // Check if it is expensive.
11597     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11598     // Assume bitcasts are cheap, unless both register classes do not
11599     // explicitly share a common sub class.
11600     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11601       return false;
11602
11603     // Check if it will be merged with the load.
11604     // 1. Check the alignment constraint.
11605     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11606         ResVT.getTypeForEVT(*DAG->getContext()));
11607
11608     if (RequiredAlignment > getAlignment())
11609       return false;
11610
11611     // 2. Check that the load is a legal operation for that type.
11612     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11613       return false;
11614
11615     // 3. Check that we do not have a zext in the way.
11616     if (Inst->getValueType(0) != getLoadedType())
11617       return false;
11618
11619     return true;
11620   }
11621 };
11622 }
11623
11624 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11625 /// \p UsedBits looks like 0..0 1..1 0..0.
11626 static bool areUsedBitsDense(const APInt &UsedBits) {
11627   // If all the bits are one, this is dense!
11628   if (UsedBits.isAllOnesValue())
11629     return true;
11630
11631   // Get rid of the unused bits on the right.
11632   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11633   // Get rid of the unused bits on the left.
11634   if (NarrowedUsedBits.countLeadingZeros())
11635     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11636   // Check that the chunk of bits is completely used.
11637   return NarrowedUsedBits.isAllOnesValue();
11638 }
11639
11640 /// \brief Check whether or not \p First and \p Second are next to each other
11641 /// in memory. This means that there is no hole between the bits loaded
11642 /// by \p First and the bits loaded by \p Second.
11643 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11644                                      const LoadedSlice &Second) {
11645   assert(First.Origin == Second.Origin && First.Origin &&
11646          "Unable to match different memory origins.");
11647   APInt UsedBits = First.getUsedBits();
11648   assert((UsedBits & Second.getUsedBits()) == 0 &&
11649          "Slices are not supposed to overlap.");
11650   UsedBits |= Second.getUsedBits();
11651   return areUsedBitsDense(UsedBits);
11652 }
11653
11654 /// \brief Adjust the \p GlobalLSCost according to the target
11655 /// paring capabilities and the layout of the slices.
11656 /// \pre \p GlobalLSCost should account for at least as many loads as
11657 /// there is in the slices in \p LoadedSlices.
11658 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11659                                  LoadedSlice::Cost &GlobalLSCost) {
11660   unsigned NumberOfSlices = LoadedSlices.size();
11661   // If there is less than 2 elements, no pairing is possible.
11662   if (NumberOfSlices < 2)
11663     return;
11664
11665   // Sort the slices so that elements that are likely to be next to each
11666   // other in memory are next to each other in the list.
11667   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11668             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11669     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11670     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11671   });
11672   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11673   // First (resp. Second) is the first (resp. Second) potentially candidate
11674   // to be placed in a paired load.
11675   const LoadedSlice *First = nullptr;
11676   const LoadedSlice *Second = nullptr;
11677   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11678                 // Set the beginning of the pair.
11679                                                            First = Second) {
11680
11681     Second = &LoadedSlices[CurrSlice];
11682
11683     // If First is NULL, it means we start a new pair.
11684     // Get to the next slice.
11685     if (!First)
11686       continue;
11687
11688     EVT LoadedType = First->getLoadedType();
11689
11690     // If the types of the slices are different, we cannot pair them.
11691     if (LoadedType != Second->getLoadedType())
11692       continue;
11693
11694     // Check if the target supplies paired loads for this type.
11695     unsigned RequiredAlignment = 0;
11696     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11697       // move to the next pair, this type is hopeless.
11698       Second = nullptr;
11699       continue;
11700     }
11701     // Check if we meet the alignment requirement.
11702     if (RequiredAlignment > First->getAlignment())
11703       continue;
11704
11705     // Check that both loads are next to each other in memory.
11706     if (!areSlicesNextToEachOther(*First, *Second))
11707       continue;
11708
11709     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11710     --GlobalLSCost.Loads;
11711     // Move to the next pair.
11712     Second = nullptr;
11713   }
11714 }
11715
11716 /// \brief Check the profitability of all involved LoadedSlice.
11717 /// Currently, it is considered profitable if there is exactly two
11718 /// involved slices (1) which are (2) next to each other in memory, and
11719 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11720 ///
11721 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11722 /// the elements themselves.
11723 ///
11724 /// FIXME: When the cost model will be mature enough, we can relax
11725 /// constraints (1) and (2).
11726 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11727                                 const APInt &UsedBits, bool ForCodeSize) {
11728   unsigned NumberOfSlices = LoadedSlices.size();
11729   if (StressLoadSlicing)
11730     return NumberOfSlices > 1;
11731
11732   // Check (1).
11733   if (NumberOfSlices != 2)
11734     return false;
11735
11736   // Check (2).
11737   if (!areUsedBitsDense(UsedBits))
11738     return false;
11739
11740   // Check (3).
11741   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11742   // The original code has one big load.
11743   OrigCost.Loads = 1;
11744   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11745     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11746     // Accumulate the cost of all the slices.
11747     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11748     GlobalSlicingCost += SliceCost;
11749
11750     // Account as cost in the original configuration the gain obtained
11751     // with the current slices.
11752     OrigCost.addSliceGain(LS);
11753   }
11754
11755   // If the target supports paired load, adjust the cost accordingly.
11756   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11757   return OrigCost > GlobalSlicingCost;
11758 }
11759
11760 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11761 /// operations, split it in the various pieces being extracted.
11762 ///
11763 /// This sort of thing is introduced by SROA.
11764 /// This slicing takes care not to insert overlapping loads.
11765 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11766 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11767   if (Level < AfterLegalizeDAG)
11768     return false;
11769
11770   LoadSDNode *LD = cast<LoadSDNode>(N);
11771   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11772       !LD->getValueType(0).isInteger())
11773     return false;
11774
11775   // Keep track of already used bits to detect overlapping values.
11776   // In that case, we will just abort the transformation.
11777   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11778
11779   SmallVector<LoadedSlice, 4> LoadedSlices;
11780
11781   // Check if this load is used as several smaller chunks of bits.
11782   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11783   // of computation for each trunc.
11784   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11785        UI != UIEnd; ++UI) {
11786     // Skip the uses of the chain.
11787     if (UI.getUse().getResNo() != 0)
11788       continue;
11789
11790     SDNode *User = *UI;
11791     unsigned Shift = 0;
11792
11793     // Check if this is a trunc(lshr).
11794     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11795         isa<ConstantSDNode>(User->getOperand(1))) {
11796       Shift = User->getConstantOperandVal(1);
11797       User = *User->use_begin();
11798     }
11799
11800     // At this point, User is a Truncate, iff we encountered, trunc or
11801     // trunc(lshr).
11802     if (User->getOpcode() != ISD::TRUNCATE)
11803       return false;
11804
11805     // The width of the type must be a power of 2 and greater than 8-bits.
11806     // Otherwise the load cannot be represented in LLVM IR.
11807     // Moreover, if we shifted with a non-8-bits multiple, the slice
11808     // will be across several bytes. We do not support that.
11809     unsigned Width = User->getValueSizeInBits(0);
11810     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11811       return 0;
11812
11813     // Build the slice for this chain of computations.
11814     LoadedSlice LS(User, LD, Shift, &DAG);
11815     APInt CurrentUsedBits = LS.getUsedBits();
11816
11817     // Check if this slice overlaps with another.
11818     if ((CurrentUsedBits & UsedBits) != 0)
11819       return false;
11820     // Update the bits used globally.
11821     UsedBits |= CurrentUsedBits;
11822
11823     // Check if the new slice would be legal.
11824     if (!LS.isLegal())
11825       return false;
11826
11827     // Record the slice.
11828     LoadedSlices.push_back(LS);
11829   }
11830
11831   // Abort slicing if it does not seem to be profitable.
11832   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11833     return false;
11834
11835   ++SlicedLoads;
11836
11837   // Rewrite each chain to use an independent load.
11838   // By construction, each chain can be represented by a unique load.
11839
11840   // Prepare the argument for the new token factor for all the slices.
11841   SmallVector<SDValue, 8> ArgChains;
11842   for (SmallVectorImpl<LoadedSlice>::const_iterator
11843            LSIt = LoadedSlices.begin(),
11844            LSItEnd = LoadedSlices.end();
11845        LSIt != LSItEnd; ++LSIt) {
11846     SDValue SliceInst = LSIt->loadSlice();
11847     CombineTo(LSIt->Inst, SliceInst, true);
11848     if (SliceInst.getOpcode() != ISD::LOAD)
11849       SliceInst = SliceInst.getOperand(0);
11850     assert(SliceInst->getOpcode() == ISD::LOAD &&
11851            "It takes more than a zext to get to the loaded slice!!");
11852     ArgChains.push_back(SliceInst.getValue(1));
11853   }
11854
11855   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11856                               ArgChains);
11857   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11858   AddToWorklist(Chain.getNode());
11859   return true;
11860 }
11861
11862 /// Check to see if V is (and load (ptr), imm), where the load is having
11863 /// specific bytes cleared out.  If so, return the byte size being masked out
11864 /// and the shift amount.
11865 static std::pair<unsigned, unsigned>
11866 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11867   std::pair<unsigned, unsigned> Result(0, 0);
11868
11869   // Check for the structure we're looking for.
11870   if (V->getOpcode() != ISD::AND ||
11871       !isa<ConstantSDNode>(V->getOperand(1)) ||
11872       !ISD::isNormalLoad(V->getOperand(0).getNode()))
11873     return Result;
11874
11875   // Check the chain and pointer.
11876   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11877   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
11878
11879   // The store should be chained directly to the load or be an operand of a
11880   // tokenfactor.
11881   if (LD == Chain.getNode())
11882     ; // ok.
11883   else if (Chain->getOpcode() != ISD::TokenFactor)
11884     return Result; // Fail.
11885   else {
11886     bool isOk = false;
11887     for (const SDValue &ChainOp : Chain->op_values())
11888       if (ChainOp.getNode() == LD) {
11889         isOk = true;
11890         break;
11891       }
11892     if (!isOk) return Result;
11893   }
11894
11895   // This only handles simple types.
11896   if (V.getValueType() != MVT::i16 &&
11897       V.getValueType() != MVT::i32 &&
11898       V.getValueType() != MVT::i64)
11899     return Result;
11900
11901   // Check the constant mask.  Invert it so that the bits being masked out are
11902   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
11903   // follow the sign bit for uniformity.
11904   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11905   unsigned NotMaskLZ = countLeadingZeros(NotMask);
11906   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
11907   unsigned NotMaskTZ = countTrailingZeros(NotMask);
11908   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
11909   if (NotMaskLZ == 64) return Result;  // All zero mask.
11910
11911   // See if we have a continuous run of bits.  If so, we have 0*1+0*
11912   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11913     return Result;
11914
11915   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11916   if (V.getValueType() != MVT::i64 && NotMaskLZ)
11917     NotMaskLZ -= 64-V.getValueSizeInBits();
11918
11919   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11920   switch (MaskedBytes) {
11921   case 1:
11922   case 2:
11923   case 4: break;
11924   default: return Result; // All one mask, or 5-byte mask.
11925   }
11926
11927   // Verify that the first bit starts at a multiple of mask so that the access
11928   // is aligned the same as the access width.
11929   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11930
11931   Result.first = MaskedBytes;
11932   Result.second = NotMaskTZ/8;
11933   return Result;
11934 }
11935
11936
11937 /// Check to see if IVal is something that provides a value as specified by
11938 /// MaskInfo. If so, replace the specified store with a narrower store of
11939 /// truncated IVal.
11940 static SDNode *
11941 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11942                                 SDValue IVal, StoreSDNode *St,
11943                                 DAGCombiner *DC) {
11944   unsigned NumBytes = MaskInfo.first;
11945   unsigned ByteShift = MaskInfo.second;
11946   SelectionDAG &DAG = DC->getDAG();
11947
11948   // Check to see if IVal is all zeros in the part being masked in by the 'or'
11949   // that uses this.  If not, this is not a replacement.
11950   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
11951                                   ByteShift*8, (ByteShift+NumBytes)*8);
11952   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
11953
11954   // Check that it is legal on the target to do this.  It is legal if the new
11955   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
11956   // legalization.
11957   MVT VT = MVT::getIntegerVT(NumBytes*8);
11958   if (!DC->isTypeLegal(VT))
11959     return nullptr;
11960
11961   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
11962   // shifted by ByteShift and truncated down to NumBytes.
11963   if (ByteShift) {
11964     SDLoc DL(IVal);
11965     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
11966                        DAG.getConstant(ByteShift*8, DL,
11967                                     DC->getShiftAmountTy(IVal.getValueType())));
11968   }
11969
11970   // Figure out the offset for the store and the alignment of the access.
11971   unsigned StOffset;
11972   unsigned NewAlign = St->getAlignment();
11973
11974   if (DAG.getDataLayout().isLittleEndian())
11975     StOffset = ByteShift;
11976   else
11977     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11978
11979   SDValue Ptr = St->getBasePtr();
11980   if (StOffset) {
11981     SDLoc DL(IVal);
11982     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11983                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11984     NewAlign = MinAlign(NewAlign, StOffset);
11985   }
11986
11987   // Truncate down to the new size.
11988   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11989
11990   ++OpsNarrowed;
11991   return DAG
11992       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11993                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11994       .getNode();
11995 }
11996
11997
11998 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11999 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12000 /// narrowing the load and store if it would end up being a win for performance
12001 /// or code size.
12002 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12003   StoreSDNode *ST  = cast<StoreSDNode>(N);
12004   if (ST->isVolatile())
12005     return SDValue();
12006
12007   SDValue Chain = ST->getChain();
12008   SDValue Value = ST->getValue();
12009   SDValue Ptr   = ST->getBasePtr();
12010   EVT VT = Value.getValueType();
12011
12012   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12013     return SDValue();
12014
12015   unsigned Opc = Value.getOpcode();
12016
12017   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12018   // is a byte mask indicating a consecutive number of bytes, check to see if
12019   // Y is known to provide just those bytes.  If so, we try to replace the
12020   // load + replace + store sequence with a single (narrower) store, which makes
12021   // the load dead.
12022   if (Opc == ISD::OR) {
12023     std::pair<unsigned, unsigned> MaskedLoad;
12024     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12025     if (MaskedLoad.first)
12026       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12027                                                   Value.getOperand(1), ST,this))
12028         return SDValue(NewST, 0);
12029
12030     // Or is commutative, so try swapping X and Y.
12031     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12032     if (MaskedLoad.first)
12033       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12034                                                   Value.getOperand(0), ST,this))
12035         return SDValue(NewST, 0);
12036   }
12037
12038   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12039       Value.getOperand(1).getOpcode() != ISD::Constant)
12040     return SDValue();
12041
12042   SDValue N0 = Value.getOperand(0);
12043   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12044       Chain == SDValue(N0.getNode(), 1)) {
12045     LoadSDNode *LD = cast<LoadSDNode>(N0);
12046     if (LD->getBasePtr() != Ptr ||
12047         LD->getPointerInfo().getAddrSpace() !=
12048         ST->getPointerInfo().getAddrSpace())
12049       return SDValue();
12050
12051     // Find the type to narrow it the load / op / store to.
12052     SDValue N1 = Value.getOperand(1);
12053     unsigned BitWidth = N1.getValueSizeInBits();
12054     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12055     if (Opc == ISD::AND)
12056       Imm ^= APInt::getAllOnesValue(BitWidth);
12057     if (Imm == 0 || Imm.isAllOnesValue())
12058       return SDValue();
12059     unsigned ShAmt = Imm.countTrailingZeros();
12060     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12061     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12062     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12063     // The narrowing should be profitable, the load/store operation should be
12064     // legal (or custom) and the store size should be equal to the NewVT width.
12065     while (NewBW < BitWidth &&
12066            (NewVT.getStoreSizeInBits() != NewBW ||
12067             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12068             !TLI.isNarrowingProfitable(VT, NewVT))) {
12069       NewBW = NextPowerOf2(NewBW);
12070       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12071     }
12072     if (NewBW >= BitWidth)
12073       return SDValue();
12074
12075     // If the lsb changed does not start at the type bitwidth boundary,
12076     // start at the previous one.
12077     if (ShAmt % NewBW)
12078       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12079     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12080                                    std::min(BitWidth, ShAmt + NewBW));
12081     if ((Imm & Mask) == Imm) {
12082       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12083       if (Opc == ISD::AND)
12084         NewImm ^= APInt::getAllOnesValue(NewBW);
12085       uint64_t PtrOff = ShAmt / 8;
12086       // For big endian targets, we need to adjust the offset to the pointer to
12087       // load the correct bytes.
12088       if (DAG.getDataLayout().isBigEndian())
12089         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12090
12091       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12092       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12093       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12094         return SDValue();
12095
12096       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12097                                    Ptr.getValueType(), Ptr,
12098                                    DAG.getConstant(PtrOff, SDLoc(LD),
12099                                                    Ptr.getValueType()));
12100       SDValue NewLD =
12101           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12102                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12103                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12104       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12105                                    DAG.getConstant(NewImm, SDLoc(Value),
12106                                                    NewVT));
12107       SDValue NewST =
12108           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12109                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12110
12111       AddToWorklist(NewPtr.getNode());
12112       AddToWorklist(NewLD.getNode());
12113       AddToWorklist(NewVal.getNode());
12114       WorklistRemover DeadNodes(*this);
12115       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12116       ++OpsNarrowed;
12117       return NewST;
12118     }
12119   }
12120
12121   return SDValue();
12122 }
12123
12124 /// For a given floating point load / store pair, if the load value isn't used
12125 /// by any other operations, then consider transforming the pair to integer
12126 /// load / store operations if the target deems the transformation profitable.
12127 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12128   StoreSDNode *ST  = cast<StoreSDNode>(N);
12129   SDValue Chain = ST->getChain();
12130   SDValue Value = ST->getValue();
12131   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12132       Value.hasOneUse() &&
12133       Chain == SDValue(Value.getNode(), 1)) {
12134     LoadSDNode *LD = cast<LoadSDNode>(Value);
12135     EVT VT = LD->getMemoryVT();
12136     if (!VT.isFloatingPoint() ||
12137         VT != ST->getMemoryVT() ||
12138         LD->isNonTemporal() ||
12139         ST->isNonTemporal() ||
12140         LD->getPointerInfo().getAddrSpace() != 0 ||
12141         ST->getPointerInfo().getAddrSpace() != 0)
12142       return SDValue();
12143
12144     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12145     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12146         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12147         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12148         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12149       return SDValue();
12150
12151     unsigned LDAlign = LD->getAlignment();
12152     unsigned STAlign = ST->getAlignment();
12153     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12154     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12155     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12156       return SDValue();
12157
12158     SDValue NewLD =
12159         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12160                     LD->getPointerInfo(), LDAlign);
12161
12162     SDValue NewST =
12163         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12164                      ST->getPointerInfo(), STAlign);
12165
12166     AddToWorklist(NewLD.getNode());
12167     AddToWorklist(NewST.getNode());
12168     WorklistRemover DeadNodes(*this);
12169     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12170     ++LdStFP2Int;
12171     return NewST;
12172   }
12173
12174   return SDValue();
12175 }
12176
12177 // This is a helper function for visitMUL to check the profitability
12178 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12179 // MulNode is the original multiply, AddNode is (add x, c1),
12180 // and ConstNode is c2.
12181 //
12182 // If the (add x, c1) has multiple uses, we could increase
12183 // the number of adds if we make this transformation.
12184 // It would only be worth doing this if we can remove a
12185 // multiply in the process. Check for that here.
12186 // To illustrate:
12187 //     (A + c1) * c3
12188 //     (A + c2) * c3
12189 // We're checking for cases where we have common "c3 * A" expressions.
12190 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12191                                               SDValue &AddNode,
12192                                               SDValue &ConstNode) {
12193   APInt Val;
12194
12195   // If the add only has one use, this would be OK to do.
12196   if (AddNode.getNode()->hasOneUse())
12197     return true;
12198
12199   // Walk all the users of the constant with which we're multiplying.
12200   for (SDNode *Use : ConstNode->uses()) {
12201
12202     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12203       continue;
12204
12205     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12206       SDNode *OtherOp;
12207       SDNode *MulVar = AddNode.getOperand(0).getNode();
12208
12209       // OtherOp is what we're multiplying against the constant.
12210       if (Use->getOperand(0) == ConstNode)
12211         OtherOp = Use->getOperand(1).getNode();
12212       else
12213         OtherOp = Use->getOperand(0).getNode();
12214
12215       // Check to see if multiply is with the same operand of our "add".
12216       //
12217       //     ConstNode  = CONST
12218       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12219       //     ...
12220       //     AddNode  = (A + c1)  <-- MulVar is A.
12221       //         = AddNode * ConstNode   <-- current visiting instruction.
12222       //
12223       // If we make this transformation, we will have a common
12224       // multiply (ConstNode * A) that we can save.
12225       if (OtherOp == MulVar)
12226         return true;
12227
12228       // Now check to see if a future expansion will give us a common
12229       // multiply.
12230       //
12231       //     ConstNode  = CONST
12232       //     AddNode    = (A + c1)
12233       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12234       //     ...
12235       //     OtherOp = (A + c2)
12236       //     Use     = OtherOp * ConstNode <-- visiting Use.
12237       //
12238       // If we make this transformation, we will have a common
12239       // multiply (CONST * A) after we also do the same transformation
12240       // to the "t2" instruction.
12241       if (OtherOp->getOpcode() == ISD::ADD &&
12242           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12243           OtherOp->getOperand(0).getNode() == MulVar)
12244         return true;
12245     }
12246   }
12247
12248   // Didn't find a case where this would be profitable.
12249   return false;
12250 }
12251
12252 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12253                                          unsigned NumStores) {
12254   SmallVector<SDValue, 8> Chains;
12255   SmallPtrSet<const SDNode *, 8> Visited;
12256   SDLoc StoreDL(StoreNodes[0].MemNode);
12257
12258   for (unsigned i = 0; i < NumStores; ++i) {
12259     Visited.insert(StoreNodes[i].MemNode);
12260   }
12261
12262   // don't include nodes that are children
12263   for (unsigned i = 0; i < NumStores; ++i) {
12264     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12265       Chains.push_back(StoreNodes[i].MemNode->getChain());
12266   }
12267
12268   assert(Chains.size() > 0 && "Chain should have generated a chain");
12269   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12270 }
12271
12272 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12273                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
12274                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
12275   // Make sure we have something to merge.
12276   if (NumStores < 2)
12277     return false;
12278
12279   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12280
12281   // The latest Node in the DAG.
12282   SDLoc DL(StoreNodes[0].MemNode);
12283
12284   SDValue StoredVal;
12285   if (UseVector) {
12286     bool IsVec = MemVT.isVector();
12287     unsigned Elts = NumStores;
12288     if (IsVec) {
12289       // When merging vector stores, get the total number of elements.
12290       Elts *= MemVT.getVectorNumElements();
12291     }
12292     // Get the type for the merged vector store.
12293     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12294     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12295
12296     if (IsConstantSrc) {
12297       SmallVector<SDValue, 8> BuildVector;
12298       for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12299         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12300         SDValue Val = St->getValue();
12301         if (MemVT.getScalarType().isInteger())
12302           if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12303             Val = DAG.getConstant(
12304                 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12305                 SDLoc(CFP), MemVT);
12306         BuildVector.push_back(Val);
12307       }
12308       StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12309     } else {
12310       SmallVector<SDValue, 8> Ops;
12311       for (unsigned i = 0; i < NumStores; ++i) {
12312         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12313         SDValue Val = St->getValue();
12314         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12315         if (Val.getValueType() != MemVT)
12316           return false;
12317         Ops.push_back(Val);
12318       }
12319
12320       // Build the extracted vector elements back into a vector.
12321       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12322                               DL, Ty, Ops);    }
12323   } else {
12324     // We should always use a vector store when merging extracted vector
12325     // elements, so this path implies a store of constants.
12326     assert(IsConstantSrc && "Merged vector elements should use vector store");
12327
12328     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12329     APInt StoreInt(SizeInBits, 0);
12330
12331     // Construct a single integer constant which is made of the smaller
12332     // constant inputs.
12333     bool IsLE = DAG.getDataLayout().isLittleEndian();
12334     for (unsigned i = 0; i < NumStores; ++i) {
12335       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12336       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12337
12338       SDValue Val = St->getValue();
12339       StoreInt <<= ElementSizeBytes * 8;
12340       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12341         StoreInt |= C->getAPIntValue().zext(SizeInBits);
12342       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12343         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
12344       } else {
12345         llvm_unreachable("Invalid constant element type");
12346       }
12347     }
12348
12349     // Create the new Load and Store operations.
12350     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12351     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12352   }
12353
12354   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12355   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12356   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
12357                                   FirstInChain->getBasePtr(),
12358                                   FirstInChain->getPointerInfo(),
12359                                   FirstInChain->getAlignment());
12360
12361   // Replace all merged stores with the new store.
12362   for (unsigned i = 0; i < NumStores; ++i)
12363     CombineTo(StoreNodes[i].MemNode, NewStore);
12364
12365   AddToWorklist(NewChain.getNode());
12366   return true;
12367 }
12368
12369 void DAGCombiner::getStoreMergeCandidates(
12370     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12371   // This holds the base pointer, index, and the offset in bytes from the base
12372   // pointer.
12373   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12374   EVT MemVT = St->getMemoryVT();
12375
12376   // We must have a base and an offset.
12377   if (!BasePtr.Base.getNode())
12378     return;
12379
12380   // Do not handle stores to undef base pointers.
12381   if (BasePtr.Base.isUndef())
12382     return;
12383
12384   bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12385   bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12386                        isa<ConstantFPSDNode>(St->getValue());
12387   bool IsExtractVecSrc =
12388       (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12389        St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12390   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool {
12391     if (Other->isVolatile() || Other->isIndexed())
12392       return false;
12393     // We can merge constant floats to equivalent integers
12394     if (Other->getMemoryVT() != MemVT)
12395       if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12396             isa<ConstantFPSDNode>(Other->getValue())))
12397         return false;
12398     if (IsLoadSrc)
12399       if (!isa<LoadSDNode>(Other->getValue()))
12400         return false;
12401     if (IsConstantSrc)
12402       if (!(isa<ConstantSDNode>(Other->getValue()) ||
12403             isa<ConstantFPSDNode>(Other->getValue())))
12404         return false;
12405     if (IsExtractVecSrc)
12406       if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12407             Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12408         return false;
12409     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12410     return (Ptr.equalBaseIndex(BasePtr));
12411   };
12412   // We looking for a root node which is an ancestor to all mergable
12413   // stores. We search up through a load, to our root and then down
12414   // through all children. For instance we will find Store{1,2,3} if
12415   // St is Store1, Store2. or Store3 where the root is not a load
12416   // which always true for nonvolatile ops. TODO: Expand
12417   // the search to find all valid candidates through multiple layers of loads.
12418   //
12419   // Root
12420   // |-------|-------|
12421   // Load    Load    Store3
12422   // |       |
12423   // Store1   Store2
12424   //
12425   // FIXME: We should be able to climb and
12426   // descend TokenFactors to find candidates as well.
12427
12428   SDNode *RootNode = (St->getChain()).getNode();
12429
12430   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12431     RootNode = Ldn->getChain().getNode();
12432     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12433       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12434         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12435           if (I2.getOperandNo() == 0)
12436             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12437               BaseIndexOffset Ptr;
12438               if (CandidateMatch(OtherST, Ptr))
12439                 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12440             }
12441   } else
12442     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12443       if (I.getOperandNo() == 0)
12444         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12445           BaseIndexOffset Ptr;
12446           if (CandidateMatch(OtherST, Ptr))
12447             StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12448         }
12449 }
12450
12451 // We need to check that merging these stores does not cause a loop
12452 // in the DAG. Any store candidate may depend on another candidate
12453 // indirectly through its operand (we already consider dependencies
12454 // through the chain). Check in parallel by searching up from
12455 // non-chain operands of candidates.
12456 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12457     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12458   SmallPtrSet<const SDNode *, 16> Visited;
12459   SmallVector<const SDNode *, 8> Worklist;
12460   // search ops of store candidates
12461   for (unsigned i = 0; i < NumStores; ++i) {
12462     SDNode *n = StoreNodes[i].MemNode;
12463     // Potential loops may happen only through non-chain operands
12464     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12465       Worklist.push_back(n->getOperand(j).getNode());
12466   }
12467   // search through DAG. We can stop early if we find a storenode
12468   for (unsigned i = 0; i < NumStores; ++i) {
12469     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12470       return false;
12471   }
12472   return true;
12473 }
12474
12475 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12476   if (OptLevel == CodeGenOpt::None)
12477     return false;
12478
12479   EVT MemVT = St->getMemoryVT();
12480   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12481
12482   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12483     return false;
12484
12485   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12486       Attribute::NoImplicitFloat);
12487
12488   // This function cannot currently deal with non-byte-sized memory sizes.
12489   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12490     return false;
12491
12492   if (!MemVT.isSimple())
12493     return false;
12494
12495   // Perform an early exit check. Do not bother looking at stored values that
12496   // are not constants, loads, or extracted vector elements.
12497   SDValue StoredVal = St->getValue();
12498   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12499   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12500                        isa<ConstantFPSDNode>(StoredVal);
12501   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12502                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12503
12504   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12505     return false;
12506
12507   // Don't merge vectors into wider vectors if the source data comes from loads.
12508   // TODO: This restriction can be lifted by using logic similar to the
12509   // ExtractVecSrc case.
12510   if (MemVT.isVector() && IsLoadSrc)
12511     return false;
12512
12513   SmallVector<MemOpLink, 8> StoreNodes;
12514   // Find potential store merge candidates by searching through chain sub-DAG
12515   getStoreMergeCandidates(St, StoreNodes);
12516
12517   // Check if there is anything to merge.
12518   if (StoreNodes.size() < 2)
12519     return false;
12520
12521   // Sort the memory operands according to their distance from the
12522   // base pointer.
12523   std::sort(StoreNodes.begin(), StoreNodes.end(),
12524             [](MemOpLink LHS, MemOpLink RHS) {
12525               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12526             });
12527
12528   // Store Merge attempts to merge the lowest stores. This generally
12529   // works out as if successful, as the remaining stores are checked
12530   // after the first collection of stores is merged. However, in the
12531   // case that a non-mergeable store is found first, e.g., {p[-2],
12532   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12533   // mergeable cases. To prevent this, we prune such stores from the
12534   // front of StoreNodes here.
12535
12536   unsigned StartIdx = 0;
12537   while ((StartIdx + 1 < StoreNodes.size()) &&
12538          StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12539              StoreNodes[StartIdx + 1].OffsetFromBase)
12540     ++StartIdx;
12541
12542   // Bail if we don't have enough candidates to merge.
12543   if (StartIdx + 1 >= StoreNodes.size())
12544     return false;
12545
12546   if (StartIdx)
12547     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12548
12549   // Scan the memory operations on the chain and find the first non-consecutive
12550   // store memory address.
12551   unsigned NumConsecutiveStores = 0;
12552   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12553
12554   // Check that the addresses are consecutive starting from the second
12555   // element in the list of stores.
12556   for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12557     int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12558     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12559       break;
12560     NumConsecutiveStores = i + 1;
12561   }
12562
12563   if (NumConsecutiveStores < 2)
12564     return false;
12565
12566   // Check that we can merge these candidates without causing a cycle
12567   if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumConsecutiveStores))
12568     return false;
12569
12570
12571   // The node with the lowest store address.
12572   LLVMContext &Context = *DAG.getContext();
12573   const DataLayout &DL = DAG.getDataLayout();
12574
12575   // Store the constants into memory as one consecutive store.
12576   if (IsConstantSrc) {
12577     bool RV = false;
12578     while (NumConsecutiveStores > 1) {
12579       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12580       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12581       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12582       unsigned LastLegalType = 0;
12583       unsigned LastLegalVectorType = 0;
12584       bool NonZero = false;
12585       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12586         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12587         SDValue StoredVal = ST->getValue();
12588
12589         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12590           NonZero |= !C->isNullValue();
12591         } else if (ConstantFPSDNode *C =
12592                        dyn_cast<ConstantFPSDNode>(StoredVal)) {
12593           NonZero |= !C->getConstantFPValue()->isNullValue();
12594         } else {
12595           // Non-constant.
12596           break;
12597         }
12598
12599         // Find a legal type for the constant store.
12600         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12601         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12602         bool IsFast = false;
12603         if (TLI.isTypeLegal(StoreTy) &&
12604             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12605                                    FirstStoreAlign, &IsFast) &&
12606             IsFast) {
12607           LastLegalType = i + 1;
12608           // Or check whether a truncstore is legal.
12609         } else if (TLI.getTypeAction(Context, StoreTy) ==
12610                    TargetLowering::TypePromoteInteger) {
12611           EVT LegalizedStoredValueTy =
12612               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12613           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12614               TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12615                                      FirstStoreAS, FirstStoreAlign, &IsFast) &&
12616               IsFast) {
12617             LastLegalType = i + 1;
12618           }
12619         }
12620
12621         // We only use vectors if the constant is known to be zero or the target
12622         // allows it and the function is not marked with the noimplicitfloat
12623         // attribute.
12624         if ((!NonZero ||
12625              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12626             !NoVectors) {
12627           // Find a legal type for the vector store.
12628           EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12629           if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) &&
12630               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12631                                      FirstStoreAlign, &IsFast) &&
12632               IsFast)
12633             LastLegalVectorType = i + 1;
12634         }
12635       }
12636
12637       // Check if we found a legal integer type that creates a meaningful merge.
12638       if (LastLegalType < 2 && LastLegalVectorType < 2)
12639         break;
12640
12641       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12642       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12643
12644       bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12645                                                     true, UseVector);
12646       if (!Merged)
12647         break;
12648       // Remove merged stores for next iteration.
12649       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12650       RV = true;
12651       NumConsecutiveStores -= NumElem;
12652     }
12653     return RV;
12654   }
12655
12656   // When extracting multiple vector elements, try to store them
12657   // in one vector store rather than a sequence of scalar stores.
12658   if (IsExtractVecSrc) {
12659     bool RV = false;
12660     while (StoreNodes.size() >= 2) {
12661       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12662       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12663       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12664       unsigned NumStoresToMerge = 0;
12665       bool IsVec = MemVT.isVector();
12666       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12667         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12668         unsigned StoreValOpcode = St->getValue().getOpcode();
12669         // This restriction could be loosened.
12670         // Bail out if any stored values are not elements extracted from a
12671         // vector. It should be possible to handle mixed sources, but load
12672         // sources need more careful handling (see the block of code below that
12673         // handles consecutive loads).
12674         if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12675             StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12676           return false;
12677
12678         // Find a legal type for the vector store.
12679         unsigned Elts = i + 1;
12680         if (IsVec) {
12681           // When merging vector stores, get the total number of elements.
12682           Elts *= MemVT.getVectorNumElements();
12683         }
12684         EVT Ty =
12685             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12686         bool IsFast;
12687         if (TLI.isTypeLegal(Ty) &&
12688             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12689                                    FirstStoreAlign, &IsFast) &&
12690             IsFast)
12691           NumStoresToMerge = i + 1;
12692       }
12693
12694       bool Merged = MergeStoresOfConstantsOrVecElts(
12695           StoreNodes, MemVT, NumStoresToMerge, false, true);
12696       if (!Merged)
12697         break;
12698       // Remove merged stores for next iteration.
12699       StoreNodes.erase(StoreNodes.begin(),
12700                        StoreNodes.begin() + NumStoresToMerge);
12701       RV = true;
12702       NumConsecutiveStores -= NumStoresToMerge;
12703     }
12704     return RV;
12705   }
12706
12707   // Below we handle the case of multiple consecutive stores that
12708   // come from multiple consecutive loads. We merge them into a single
12709   // wide load and a single wide store.
12710
12711   // Look for load nodes which are used by the stored values.
12712   SmallVector<MemOpLink, 8> LoadNodes;
12713
12714   // Find acceptable loads. Loads need to have the same chain (token factor),
12715   // must not be zext, volatile, indexed, and they must be consecutive.
12716   BaseIndexOffset LdBasePtr;
12717   for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12718     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
12719     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12720     if (!Ld) break;
12721
12722     // Loads must only have one use.
12723     if (!Ld->hasNUsesOfValue(1, 0))
12724       break;
12725
12726     // The memory operands must not be volatile.
12727     if (Ld->isVolatile() || Ld->isIndexed())
12728       break;
12729
12730     // We do not accept ext loads.
12731     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12732       break;
12733
12734     // The stored memory type must be the same.
12735     if (Ld->getMemoryVT() != MemVT)
12736       break;
12737
12738     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12739     // If this is not the first ptr that we check.
12740     if (LdBasePtr.Base.getNode()) {
12741       // The base ptr must be the same.
12742       if (!LdPtr.equalBaseIndex(LdBasePtr))
12743         break;
12744     } else {
12745       // Check that all other base pointers are the same as this one.
12746       LdBasePtr = LdPtr;
12747     }
12748
12749     // We found a potential memory operand to merge.
12750     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
12751   }
12752
12753   if (LoadNodes.size() < 2)
12754     return false;
12755
12756   // If we have load/store pair instructions and we only have two values,
12757   // don't bother.
12758   unsigned RequiredAlignment;
12759   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12760       St->getAlignment() >= RequiredAlignment)
12761     return false;
12762   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12763   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12764   unsigned FirstStoreAlign = FirstInChain->getAlignment();
12765   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12766   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12767   unsigned FirstLoadAlign = FirstLoad->getAlignment();
12768
12769   // Scan the memory operations on the chain and find the first non-consecutive
12770   // load memory address. These variables hold the index in the store node
12771   // array.
12772   unsigned LastConsecutiveLoad = 0;
12773   // This variable refers to the size and not index in the array.
12774   unsigned LastLegalVectorType = 0;
12775   unsigned LastLegalIntegerType = 0;
12776   StartAddress = LoadNodes[0].OffsetFromBase;
12777   SDValue FirstChain = FirstLoad->getChain();
12778   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12779     // All loads must share the same chain.
12780     if (LoadNodes[i].MemNode->getChain() != FirstChain)
12781       break;
12782
12783     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12784     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12785       break;
12786     LastConsecutiveLoad = i;
12787     // Find a legal type for the vector store.
12788     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
12789     bool IsFastSt, IsFastLd;
12790     if (TLI.isTypeLegal(StoreTy) &&
12791         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12792                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
12793         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12794                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
12795       LastLegalVectorType = i + 1;
12796     }
12797
12798     // Find a legal type for the integer store.
12799     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
12800     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12801     if (TLI.isTypeLegal(StoreTy) &&
12802         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12803                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
12804         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12805                                FirstLoadAlign, &IsFastLd) && IsFastLd)
12806       LastLegalIntegerType = i + 1;
12807     // Or check whether a truncstore and extload is legal.
12808     else if (TLI.getTypeAction(Context, StoreTy) ==
12809              TargetLowering::TypePromoteInteger) {
12810       EVT LegalizedStoredValueTy =
12811         TLI.getTypeToTransformTo(Context, StoreTy);
12812       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12813           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12814           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12815           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12816           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12817                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12818           IsFastSt &&
12819           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12820                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12821           IsFastLd)
12822         LastLegalIntegerType = i+1;
12823     }
12824   }
12825
12826   // Only use vector types if the vector type is larger than the integer type.
12827   // If they are the same, use integers.
12828   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12829   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
12830
12831   // We add +1 here because the LastXXX variables refer to location while
12832   // the NumElem refers to array/index size.
12833   unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12834   NumElem = std::min(LastLegalType, NumElem);
12835
12836   if (NumElem < 2)
12837     return false;
12838
12839   // Find if it is better to use vectors or integers to load and store
12840   // to memory.
12841   EVT JointMemOpVT;
12842   if (UseVectorTy) {
12843     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12844   } else {
12845     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12846     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12847   }
12848
12849   SDLoc LoadDL(LoadNodes[0].MemNode);
12850   SDLoc StoreDL(StoreNodes[0].MemNode);
12851
12852   // The merged loads are required to have the same incoming chain, so
12853   // using the first's chain is acceptable.
12854   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12855                                 FirstLoad->getBasePtr(),
12856                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12857
12858   SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12859
12860   AddToWorklist(NewStoreChain.getNode());
12861
12862   SDValue NewStore =
12863       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12864                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12865
12866   // Transfer chain users from old loads to the new load.
12867   for (unsigned i = 0; i < NumElem; ++i) {
12868     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12869     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12870                                   SDValue(NewLoad.getNode(), 1));
12871   }
12872
12873   // Replace the all stores with the new store.
12874   for (unsigned i = 0; i < NumElem; ++i)
12875     CombineTo(StoreNodes[i].MemNode, NewStore);
12876   return true;
12877 }
12878
12879 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12880   SDLoc SL(ST);
12881   SDValue ReplStore;
12882
12883   // Replace the chain to avoid dependency.
12884   if (ST->isTruncatingStore()) {
12885     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12886                                   ST->getBasePtr(), ST->getMemoryVT(),
12887                                   ST->getMemOperand());
12888   } else {
12889     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12890                              ST->getMemOperand());
12891   }
12892
12893   // Create token to keep both nodes around.
12894   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12895                               MVT::Other, ST->getChain(), ReplStore);
12896
12897   // Make sure the new and old chains are cleaned up.
12898   AddToWorklist(Token.getNode());
12899
12900   // Don't add users to work list.
12901   return CombineTo(ST, Token, false);
12902 }
12903
12904 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12905   SDValue Value = ST->getValue();
12906   if (Value.getOpcode() == ISD::TargetConstantFP)
12907     return SDValue();
12908
12909   SDLoc DL(ST);
12910
12911   SDValue Chain = ST->getChain();
12912   SDValue Ptr = ST->getBasePtr();
12913
12914   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12915
12916   // NOTE: If the original store is volatile, this transform must not increase
12917   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12918   // processor operation but an i64 (which is not legal) requires two.  So the
12919   // transform should not be done in this case.
12920
12921   SDValue Tmp;
12922   switch (CFP->getSimpleValueType(0).SimpleTy) {
12923   default:
12924     llvm_unreachable("Unknown FP type");
12925   case MVT::f16:    // We don't do this for these yet.
12926   case MVT::f80:
12927   case MVT::f128:
12928   case MVT::ppcf128:
12929     return SDValue();
12930   case MVT::f32:
12931     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12932         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12933       ;
12934       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12935                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12936                             MVT::i32);
12937       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12938     }
12939
12940     return SDValue();
12941   case MVT::f64:
12942     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12943          !ST->isVolatile()) ||
12944         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12945       ;
12946       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12947                             getZExtValue(), SDLoc(CFP), MVT::i64);
12948       return DAG.getStore(Chain, DL, Tmp,
12949                           Ptr, ST->getMemOperand());
12950     }
12951
12952     if (!ST->isVolatile() &&
12953         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12954       // Many FP stores are not made apparent until after legalize, e.g. for
12955       // argument passing.  Since this is so common, custom legalize the
12956       // 64-bit integer store into two 32-bit stores.
12957       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12958       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12959       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12960       if (DAG.getDataLayout().isBigEndian())
12961         std::swap(Lo, Hi);
12962
12963       unsigned Alignment = ST->getAlignment();
12964       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12965       AAMDNodes AAInfo = ST->getAAInfo();
12966
12967       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12968                                  ST->getAlignment(), MMOFlags, AAInfo);
12969       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12970                         DAG.getConstant(4, DL, Ptr.getValueType()));
12971       Alignment = MinAlign(Alignment, 4U);
12972       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12973                                  ST->getPointerInfo().getWithOffset(4),
12974                                  Alignment, MMOFlags, AAInfo);
12975       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12976                          St0, St1);
12977     }
12978
12979     return SDValue();
12980   }
12981 }
12982
12983 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12984   StoreSDNode *ST  = cast<StoreSDNode>(N);
12985   SDValue Chain = ST->getChain();
12986   SDValue Value = ST->getValue();
12987   SDValue Ptr   = ST->getBasePtr();
12988
12989   // If this is a store of a bit convert, store the input value if the
12990   // resultant store does not need a higher alignment than the original.
12991   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12992       ST->isUnindexed()) {
12993     EVT SVT = Value.getOperand(0).getValueType();
12994     if (((!LegalOperations && !ST->isVolatile()) ||
12995          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12996         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12997       unsigned OrigAlign = ST->getAlignment();
12998       bool Fast = false;
12999       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13000                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13001           Fast) {
13002         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13003                             ST->getPointerInfo(), OrigAlign,
13004                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13005       }
13006     }
13007   }
13008
13009   // Turn 'store undef, Ptr' -> nothing.
13010   if (Value.isUndef() && ST->isUnindexed())
13011     return Chain;
13012
13013   // Try to infer better alignment information than the store already has.
13014   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13015     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13016       if (Align > ST->getAlignment()) {
13017         SDValue NewStore =
13018             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13019                               ST->getMemoryVT(), Align,
13020                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13021         if (NewStore.getNode() != N)
13022           return CombineTo(ST, NewStore, true);
13023       }
13024     }
13025   }
13026
13027   // Try transforming a pair floating point load / store ops to integer
13028   // load / store ops.
13029   if (SDValue NewST = TransformFPLoadStorePair(N))
13030     return NewST;
13031
13032   if (ST->isUnindexed()) {
13033     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13034     // adjacent stores.
13035     if (findBetterNeighborChains(ST)) {
13036       // replaceStoreChain uses CombineTo, which handled all of the worklist
13037       // manipulation. Return the original node to not do anything else.
13038       return SDValue(ST, 0);
13039     }
13040     Chain = ST->getChain();
13041   }
13042
13043   // Try transforming N to an indexed store.
13044   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13045     return SDValue(N, 0);
13046
13047   // FIXME: is there such a thing as a truncating indexed store?
13048   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13049       Value.getValueType().isInteger()) {
13050     // See if we can simplify the input to this truncstore with knowledge that
13051     // only the low bits are being used.  For example:
13052     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13053     SDValue Shorter = GetDemandedBits(
13054         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13055                                     ST->getMemoryVT().getScalarSizeInBits()));
13056     AddToWorklist(Value.getNode());
13057     if (Shorter.getNode())
13058       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13059                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13060
13061     // Otherwise, see if we can simplify the operation with
13062     // SimplifyDemandedBits, which only works if the value has a single use.
13063     if (SimplifyDemandedBits(
13064             Value,
13065             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13066                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13067       // Re-visit the store if anything changed and the store hasn't been merged
13068       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13069       // node back to the worklist if necessary, but we also need to re-visit
13070       // the Store node itself.
13071       if (N->getOpcode() != ISD::DELETED_NODE)
13072         AddToWorklist(N);
13073       return SDValue(N, 0);
13074     }
13075   }
13076
13077   // If this is a load followed by a store to the same location, then the store
13078   // is dead/noop.
13079   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13080     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13081         ST->isUnindexed() && !ST->isVolatile() &&
13082         // There can't be any side effects between the load and store, such as
13083         // a call or store.
13084         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13085       // The store is dead, remove it.
13086       return Chain;
13087     }
13088   }
13089
13090   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13091     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13092         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13093         ST->getMemoryVT() == ST1->getMemoryVT()) {
13094       // If this is a store followed by a store with the same value to the same
13095       // location, then the store is dead/noop.
13096       if (ST1->getValue() == Value) {
13097         // The store is dead, remove it.
13098         return Chain;
13099       }
13100
13101       // If this is a store who's preceeding store to the same location
13102       // and no one other node is chained to that store we can effectively
13103       // drop the store. Do not remove stores to undef as they may be used as
13104       // data sinks.
13105       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13106           !ST1->getBasePtr().isUndef()) {
13107         // ST1 is fully overwritten and can be elided. Combine with it's chain
13108         // value.
13109         CombineTo(ST1, ST1->getChain());
13110         return SDValue();
13111       }
13112     }
13113   }
13114
13115   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13116   // truncating store.  We can do this even if this is already a truncstore.
13117   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13118       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13119       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13120                             ST->getMemoryVT())) {
13121     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13122                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13123   }
13124
13125   // Only perform this optimization before the types are legal, because we
13126   // don't want to perform this optimization on every DAGCombine invocation.
13127   if (!LegalTypes) {
13128     for (;;) {
13129       // There can be multiple store sequences on the same chain.
13130       // Keep trying to merge store sequences until we are unable to do so
13131       // or until we merge the last store on the chain.
13132       bool Changed = MergeConsecutiveStores(ST);
13133       if (!Changed) break;
13134       // Return N as merge only uses CombineTo and no worklist clean
13135       // up is necessary.
13136       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13137         return SDValue(N, 0);
13138     }
13139   }
13140
13141   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13142   //
13143   // Make sure to do this only after attempting to merge stores in order to
13144   //  avoid changing the types of some subset of stores due to visit order,
13145   //  preventing their merging.
13146   if (isa<ConstantFPSDNode>(ST->getValue())) {
13147     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13148       return NewSt;
13149   }
13150
13151   if (SDValue NewSt = splitMergedValStore(ST))
13152     return NewSt;
13153
13154   return ReduceLoadOpStoreWidth(N);
13155 }
13156
13157 /// For the instruction sequence of store below, F and I values
13158 /// are bundled together as an i64 value before being stored into memory.
13159 /// Sometimes it is more efficent to generate separate stores for F and I,
13160 /// which can remove the bitwise instructions or sink them to colder places.
13161 ///
13162 ///   (store (or (zext (bitcast F to i32) to i64),
13163 ///              (shl (zext I to i64), 32)), addr)  -->
13164 ///   (store F, addr) and (store I, addr+4)
13165 ///
13166 /// Similarly, splitting for other merged store can also be beneficial, like:
13167 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13168 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13169 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13170 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13171 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13172 ///
13173 /// We allow each target to determine specifically which kind of splitting is
13174 /// supported.
13175 ///
13176 /// The store patterns are commonly seen from the simple code snippet below
13177 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13178 ///   void goo(const std::pair<int, float> &);
13179 ///   hoo() {
13180 ///     ...
13181 ///     goo(std::make_pair(tmp, ftmp));
13182 ///     ...
13183 ///   }
13184 ///
13185 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13186   if (OptLevel == CodeGenOpt::None)
13187     return SDValue();
13188
13189   SDValue Val = ST->getValue();
13190   SDLoc DL(ST);
13191
13192   // Match OR operand.
13193   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13194     return SDValue();
13195
13196   // Match SHL operand and get Lower and Higher parts of Val.
13197   SDValue Op1 = Val.getOperand(0);
13198   SDValue Op2 = Val.getOperand(1);
13199   SDValue Lo, Hi;
13200   if (Op1.getOpcode() != ISD::SHL) {
13201     std::swap(Op1, Op2);
13202     if (Op1.getOpcode() != ISD::SHL)
13203       return SDValue();
13204   }
13205   Lo = Op2;
13206   Hi = Op1.getOperand(0);
13207   if (!Op1.hasOneUse())
13208     return SDValue();
13209
13210   // Match shift amount to HalfValBitSize.
13211   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13212   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13213   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13214     return SDValue();
13215
13216   // Lo and Hi are zero-extended from int with size less equal than 32
13217   // to i64.
13218   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13219       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13220       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13221       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13222       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13223       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13224     return SDValue();
13225
13226   // Use the EVT of low and high parts before bitcast as the input
13227   // of target query.
13228   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13229                   ? Lo.getOperand(0).getValueType()
13230                   : Lo.getValueType();
13231   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13232                    ? Hi.getOperand(0).getValueType()
13233                    : Hi.getValueType();
13234   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13235     return SDValue();
13236
13237   // Start to split store.
13238   unsigned Alignment = ST->getAlignment();
13239   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13240   AAMDNodes AAInfo = ST->getAAInfo();
13241
13242   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13243   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13244   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13245   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13246
13247   SDValue Chain = ST->getChain();
13248   SDValue Ptr = ST->getBasePtr();
13249   // Lower value store.
13250   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13251                              ST->getAlignment(), MMOFlags, AAInfo);
13252   Ptr =
13253       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13254                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13255   // Higher value store.
13256   SDValue St1 =
13257       DAG.getStore(St0, DL, Hi, Ptr,
13258                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13259                    Alignment / 2, MMOFlags, AAInfo);
13260   return St1;
13261 }
13262
13263 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13264   SDValue InVec = N->getOperand(0);
13265   SDValue InVal = N->getOperand(1);
13266   SDValue EltNo = N->getOperand(2);
13267   SDLoc DL(N);
13268
13269   // If the inserted element is an UNDEF, just use the input vector.
13270   if (InVal.isUndef())
13271     return InVec;
13272
13273   EVT VT = InVec.getValueType();
13274
13275   // Check that we know which element is being inserted
13276   if (!isa<ConstantSDNode>(EltNo))
13277     return SDValue();
13278   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13279
13280   // Canonicalize insert_vector_elt dag nodes.
13281   // Example:
13282   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13283   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13284   //
13285   // Do this only if the child insert_vector node has one use; also
13286   // do this only if indices are both constants and Idx1 < Idx0.
13287   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13288       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13289     unsigned OtherElt = InVec.getConstantOperandVal(2);
13290     if (Elt < OtherElt) {
13291       // Swap nodes.
13292       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13293                                   InVec.getOperand(0), InVal, EltNo);
13294       AddToWorklist(NewOp.getNode());
13295       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13296                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13297     }
13298   }
13299
13300   // If we can't generate a legal BUILD_VECTOR, exit
13301   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13302     return SDValue();
13303
13304   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13305   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13306   // vector elements.
13307   SmallVector<SDValue, 8> Ops;
13308   // Do not combine these two vectors if the output vector will not replace
13309   // the input vector.
13310   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13311     Ops.append(InVec.getNode()->op_begin(),
13312                InVec.getNode()->op_end());
13313   } else if (InVec.isUndef()) {
13314     unsigned NElts = VT.getVectorNumElements();
13315     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13316   } else {
13317     return SDValue();
13318   }
13319
13320   // Insert the element
13321   if (Elt < Ops.size()) {
13322     // All the operands of BUILD_VECTOR must have the same type;
13323     // we enforce that here.
13324     EVT OpVT = Ops[0].getValueType();
13325     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13326   }
13327
13328   // Return the new vector
13329   return DAG.getBuildVector(VT, DL, Ops);
13330 }
13331
13332 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13333     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13334   assert(!OriginalLoad->isVolatile());
13335
13336   EVT ResultVT = EVE->getValueType(0);
13337   EVT VecEltVT = InVecVT.getVectorElementType();
13338   unsigned Align = OriginalLoad->getAlignment();
13339   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13340       VecEltVT.getTypeForEVT(*DAG.getContext()));
13341
13342   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13343     return SDValue();
13344
13345   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13346     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13347   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13348     return SDValue();
13349
13350   Align = NewAlign;
13351
13352   SDValue NewPtr = OriginalLoad->getBasePtr();
13353   SDValue Offset;
13354   EVT PtrType = NewPtr.getValueType();
13355   MachinePointerInfo MPI;
13356   SDLoc DL(EVE);
13357   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13358     int Elt = ConstEltNo->getZExtValue();
13359     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13360     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13361     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13362   } else {
13363     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13364     Offset = DAG.getNode(
13365         ISD::MUL, DL, PtrType, Offset,
13366         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13367     MPI = OriginalLoad->getPointerInfo();
13368   }
13369   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13370
13371   // The replacement we need to do here is a little tricky: we need to
13372   // replace an extractelement of a load with a load.
13373   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13374   // Note that this replacement assumes that the extractvalue is the only
13375   // use of the load; that's okay because we don't want to perform this
13376   // transformation in other cases anyway.
13377   SDValue Load;
13378   SDValue Chain;
13379   if (ResultVT.bitsGT(VecEltVT)) {
13380     // If the result type of vextract is wider than the load, then issue an
13381     // extending load instead.
13382     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13383                                                   VecEltVT)
13384                                    ? ISD::ZEXTLOAD
13385                                    : ISD::EXTLOAD;
13386     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13387                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13388                           Align, OriginalLoad->getMemOperand()->getFlags(),
13389                           OriginalLoad->getAAInfo());
13390     Chain = Load.getValue(1);
13391   } else {
13392     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13393                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13394                        OriginalLoad->getAAInfo());
13395     Chain = Load.getValue(1);
13396     if (ResultVT.bitsLT(VecEltVT))
13397       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13398     else
13399       Load = DAG.getBitcast(ResultVT, Load);
13400   }
13401   WorklistRemover DeadNodes(*this);
13402   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13403   SDValue To[] = { Load, Chain };
13404   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13405   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13406   // worklist explicitly as well.
13407   AddToWorklist(Load.getNode());
13408   AddUsersToWorklist(Load.getNode()); // Add users too
13409   // Make sure to revisit this node to clean it up; it will usually be dead.
13410   AddToWorklist(EVE);
13411   ++OpsNarrowed;
13412   return SDValue(EVE, 0);
13413 }
13414
13415 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13416   // (vextract (scalar_to_vector val, 0) -> val
13417   SDValue InVec = N->getOperand(0);
13418   EVT VT = InVec.getValueType();
13419   EVT NVT = N->getValueType(0);
13420
13421   if (InVec.isUndef())
13422     return DAG.getUNDEF(NVT);
13423
13424   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13425     // Check if the result type doesn't match the inserted element type. A
13426     // SCALAR_TO_VECTOR may truncate the inserted element and the
13427     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13428     SDValue InOp = InVec.getOperand(0);
13429     if (InOp.getValueType() != NVT) {
13430       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13431       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13432     }
13433     return InOp;
13434   }
13435
13436   SDValue EltNo = N->getOperand(1);
13437   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13438
13439   // extract_vector_elt (build_vector x, y), 1 -> y
13440   if (ConstEltNo &&
13441       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13442       TLI.isTypeLegal(VT) &&
13443       (InVec.hasOneUse() ||
13444        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13445     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13446     EVT InEltVT = Elt.getValueType();
13447
13448     // Sometimes build_vector's scalar input types do not match result type.
13449     if (NVT == InEltVT)
13450       return Elt;
13451
13452     // TODO: It may be useful to truncate if free if the build_vector implicitly
13453     // converts.
13454   }
13455
13456   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13457   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13458       ConstEltNo->isNullValue() && VT.isInteger()) {
13459     SDValue BCSrc = InVec.getOperand(0);
13460     if (BCSrc.getValueType().isScalarInteger())
13461       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13462   }
13463
13464   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13465   //
13466   // This only really matters if the index is non-constant since other combines
13467   // on the constant elements already work.
13468   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13469       EltNo == InVec.getOperand(2)) {
13470     SDValue Elt = InVec.getOperand(1);
13471     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13472   }
13473
13474   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13475   // We only perform this optimization before the op legalization phase because
13476   // we may introduce new vector instructions which are not backed by TD
13477   // patterns. For example on AVX, extracting elements from a wide vector
13478   // without using extract_subvector. However, if we can find an underlying
13479   // scalar value, then we can always use that.
13480   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13481     int NumElem = VT.getVectorNumElements();
13482     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13483     // Find the new index to extract from.
13484     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13485
13486     // Extracting an undef index is undef.
13487     if (OrigElt == -1)
13488       return DAG.getUNDEF(NVT);
13489
13490     // Select the right vector half to extract from.
13491     SDValue SVInVec;
13492     if (OrigElt < NumElem) {
13493       SVInVec = InVec->getOperand(0);
13494     } else {
13495       SVInVec = InVec->getOperand(1);
13496       OrigElt -= NumElem;
13497     }
13498
13499     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13500       SDValue InOp = SVInVec.getOperand(OrigElt);
13501       if (InOp.getValueType() != NVT) {
13502         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13503         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13504       }
13505
13506       return InOp;
13507     }
13508
13509     // FIXME: We should handle recursing on other vector shuffles and
13510     // scalar_to_vector here as well.
13511
13512     if (!LegalOperations) {
13513       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13514       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13515                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13516     }
13517   }
13518
13519   bool BCNumEltsChanged = false;
13520   EVT ExtVT = VT.getVectorElementType();
13521   EVT LVT = ExtVT;
13522
13523   // If the result of load has to be truncated, then it's not necessarily
13524   // profitable.
13525   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13526     return SDValue();
13527
13528   if (InVec.getOpcode() == ISD::BITCAST) {
13529     // Don't duplicate a load with other uses.
13530     if (!InVec.hasOneUse())
13531       return SDValue();
13532
13533     EVT BCVT = InVec.getOperand(0).getValueType();
13534     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13535       return SDValue();
13536     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13537       BCNumEltsChanged = true;
13538     InVec = InVec.getOperand(0);
13539     ExtVT = BCVT.getVectorElementType();
13540   }
13541
13542   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13543   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13544       ISD::isNormalLoad(InVec.getNode()) &&
13545       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13546     SDValue Index = N->getOperand(1);
13547     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13548       if (!OrigLoad->isVolatile()) {
13549         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13550                                                              OrigLoad);
13551       }
13552     }
13553   }
13554
13555   // Perform only after legalization to ensure build_vector / vector_shuffle
13556   // optimizations have already been done.
13557   if (!LegalOperations) return SDValue();
13558
13559   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13560   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13561   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13562
13563   if (ConstEltNo) {
13564     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13565
13566     LoadSDNode *LN0 = nullptr;
13567     const ShuffleVectorSDNode *SVN = nullptr;
13568     if (ISD::isNormalLoad(InVec.getNode())) {
13569       LN0 = cast<LoadSDNode>(InVec);
13570     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13571                InVec.getOperand(0).getValueType() == ExtVT &&
13572                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13573       // Don't duplicate a load with other uses.
13574       if (!InVec.hasOneUse())
13575         return SDValue();
13576
13577       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13578     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13579       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13580       // =>
13581       // (load $addr+1*size)
13582
13583       // Don't duplicate a load with other uses.
13584       if (!InVec.hasOneUse())
13585         return SDValue();
13586
13587       // If the bit convert changed the number of elements, it is unsafe
13588       // to examine the mask.
13589       if (BCNumEltsChanged)
13590         return SDValue();
13591
13592       // Select the input vector, guarding against out of range extract vector.
13593       unsigned NumElems = VT.getVectorNumElements();
13594       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13595       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13596
13597       if (InVec.getOpcode() == ISD::BITCAST) {
13598         // Don't duplicate a load with other uses.
13599         if (!InVec.hasOneUse())
13600           return SDValue();
13601
13602         InVec = InVec.getOperand(0);
13603       }
13604       if (ISD::isNormalLoad(InVec.getNode())) {
13605         LN0 = cast<LoadSDNode>(InVec);
13606         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13607         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13608       }
13609     }
13610
13611     // Make sure we found a non-volatile load and the extractelement is
13612     // the only use.
13613     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13614       return SDValue();
13615
13616     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13617     if (Elt == -1)
13618       return DAG.getUNDEF(LVT);
13619
13620     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13621   }
13622
13623   return SDValue();
13624 }
13625
13626 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13627 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13628   // We perform this optimization post type-legalization because
13629   // the type-legalizer often scalarizes integer-promoted vectors.
13630   // Performing this optimization before may create bit-casts which
13631   // will be type-legalized to complex code sequences.
13632   // We perform this optimization only before the operation legalizer because we
13633   // may introduce illegal operations.
13634   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13635     return SDValue();
13636
13637   unsigned NumInScalars = N->getNumOperands();
13638   SDLoc DL(N);
13639   EVT VT = N->getValueType(0);
13640
13641   // Check to see if this is a BUILD_VECTOR of a bunch of values
13642   // which come from any_extend or zero_extend nodes. If so, we can create
13643   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13644   // optimizations. We do not handle sign-extend because we can't fill the sign
13645   // using shuffles.
13646   EVT SourceType = MVT::Other;
13647   bool AllAnyExt = true;
13648
13649   for (unsigned i = 0; i != NumInScalars; ++i) {
13650     SDValue In = N->getOperand(i);
13651     // Ignore undef inputs.
13652     if (In.isUndef()) continue;
13653
13654     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13655     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13656
13657     // Abort if the element is not an extension.
13658     if (!ZeroExt && !AnyExt) {
13659       SourceType = MVT::Other;
13660       break;
13661     }
13662
13663     // The input is a ZeroExt or AnyExt. Check the original type.
13664     EVT InTy = In.getOperand(0).getValueType();
13665
13666     // Check that all of the widened source types are the same.
13667     if (SourceType == MVT::Other)
13668       // First time.
13669       SourceType = InTy;
13670     else if (InTy != SourceType) {
13671       // Multiple income types. Abort.
13672       SourceType = MVT::Other;
13673       break;
13674     }
13675
13676     // Check if all of the extends are ANY_EXTENDs.
13677     AllAnyExt &= AnyExt;
13678   }
13679
13680   // In order to have valid types, all of the inputs must be extended from the
13681   // same source type and all of the inputs must be any or zero extend.
13682   // Scalar sizes must be a power of two.
13683   EVT OutScalarTy = VT.getScalarType();
13684   bool ValidTypes = SourceType != MVT::Other &&
13685                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13686                  isPowerOf2_32(SourceType.getSizeInBits());
13687
13688   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13689   // turn into a single shuffle instruction.
13690   if (!ValidTypes)
13691     return SDValue();
13692
13693   bool isLE = DAG.getDataLayout().isLittleEndian();
13694   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13695   assert(ElemRatio > 1 && "Invalid element size ratio");
13696   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13697                                DAG.getConstant(0, DL, SourceType);
13698
13699   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13700   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13701
13702   // Populate the new build_vector
13703   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13704     SDValue Cast = N->getOperand(i);
13705     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13706             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13707             Cast.isUndef()) && "Invalid cast opcode");
13708     SDValue In;
13709     if (Cast.isUndef())
13710       In = DAG.getUNDEF(SourceType);
13711     else
13712       In = Cast->getOperand(0);
13713     unsigned Index = isLE ? (i * ElemRatio) :
13714                             (i * ElemRatio + (ElemRatio - 1));
13715
13716     assert(Index < Ops.size() && "Invalid index");
13717     Ops[Index] = In;
13718   }
13719
13720   // The type of the new BUILD_VECTOR node.
13721   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13722   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13723          "Invalid vector size");
13724   // Check if the new vector type is legal.
13725   if (!isTypeLegal(VecVT)) return SDValue();
13726
13727   // Make the new BUILD_VECTOR.
13728   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13729
13730   // The new BUILD_VECTOR node has the potential to be further optimized.
13731   AddToWorklist(BV.getNode());
13732   // Bitcast to the desired type.
13733   return DAG.getBitcast(VT, BV);
13734 }
13735
13736 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13737   EVT VT = N->getValueType(0);
13738
13739   unsigned NumInScalars = N->getNumOperands();
13740   SDLoc DL(N);
13741
13742   EVT SrcVT = MVT::Other;
13743   unsigned Opcode = ISD::DELETED_NODE;
13744   unsigned NumDefs = 0;
13745
13746   for (unsigned i = 0; i != NumInScalars; ++i) {
13747     SDValue In = N->getOperand(i);
13748     unsigned Opc = In.getOpcode();
13749
13750     if (Opc == ISD::UNDEF)
13751       continue;
13752
13753     // If all scalar values are floats and converted from integers.
13754     if (Opcode == ISD::DELETED_NODE &&
13755         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13756       Opcode = Opc;
13757     }
13758
13759     if (Opc != Opcode)
13760       return SDValue();
13761
13762     EVT InVT = In.getOperand(0).getValueType();
13763
13764     // If all scalar values are typed differently, bail out. It's chosen to
13765     // simplify BUILD_VECTOR of integer types.
13766     if (SrcVT == MVT::Other)
13767       SrcVT = InVT;
13768     if (SrcVT != InVT)
13769       return SDValue();
13770     NumDefs++;
13771   }
13772
13773   // If the vector has just one element defined, it's not worth to fold it into
13774   // a vectorized one.
13775   if (NumDefs < 2)
13776     return SDValue();
13777
13778   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13779          && "Should only handle conversion from integer to float.");
13780   assert(SrcVT != MVT::Other && "Cannot determine source type!");
13781
13782   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13783
13784   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13785     return SDValue();
13786
13787   // Just because the floating-point vector type is legal does not necessarily
13788   // mean that the corresponding integer vector type is.
13789   if (!isTypeLegal(NVT))
13790     return SDValue();
13791
13792   SmallVector<SDValue, 8> Opnds;
13793   for (unsigned i = 0; i != NumInScalars; ++i) {
13794     SDValue In = N->getOperand(i);
13795
13796     if (In.isUndef())
13797       Opnds.push_back(DAG.getUNDEF(SrcVT));
13798     else
13799       Opnds.push_back(In.getOperand(0));
13800   }
13801   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13802   AddToWorklist(BV.getNode());
13803
13804   return DAG.getNode(Opcode, DL, VT, BV);
13805 }
13806
13807 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13808                                            ArrayRef<int> VectorMask,
13809                                            SDValue VecIn1, SDValue VecIn2,
13810                                            unsigned LeftIdx) {
13811   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13812   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13813
13814   EVT VT = N->getValueType(0);
13815   EVT InVT1 = VecIn1.getValueType();
13816   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13817
13818   unsigned Vec2Offset = InVT1.getVectorNumElements();
13819   unsigned NumElems = VT.getVectorNumElements();
13820   unsigned ShuffleNumElems = NumElems;
13821
13822   // We can't generate a shuffle node with mismatched input and output types.
13823   // Try to make the types match the type of the output.
13824   if (InVT1 != VT || InVT2 != VT) {
13825     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13826       // If the output vector length is a multiple of both input lengths,
13827       // we can concatenate them and pad the rest with undefs.
13828       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13829       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13830       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13831       ConcatOps[0] = VecIn1;
13832       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13833       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13834       VecIn2 = SDValue();
13835     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13836       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13837         return SDValue();
13838
13839       if (!VecIn2.getNode()) {
13840         // If we only have one input vector, and it's twice the size of the
13841         // output, split it in two.
13842         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13843                              DAG.getConstant(NumElems, DL, IdxTy));
13844         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13845         // Since we now have shorter input vectors, adjust the offset of the
13846         // second vector's start.
13847         Vec2Offset = NumElems;
13848       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13849         // VecIn1 is wider than the output, and we have another, possibly
13850         // smaller input. Pad the smaller input with undefs, shuffle at the
13851         // input vector width, and extract the output.
13852         // The shuffle type is different than VT, so check legality again.
13853         if (LegalOperations &&
13854             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13855           return SDValue();
13856
13857         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
13858         // lower it back into a BUILD_VECTOR. So if the inserted type is
13859         // illegal, don't even try.
13860         if (InVT1 != InVT2) {
13861           if (!TLI.isTypeLegal(InVT2))
13862             return SDValue();
13863           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13864                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13865         }
13866         ShuffleNumElems = NumElems * 2;
13867       } else {
13868         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13869         // than VecIn1. We can't handle this for now - this case will disappear
13870         // when we start sorting the vectors by type.
13871         return SDValue();
13872       }
13873     } else {
13874       // TODO: Support cases where the length mismatch isn't exactly by a
13875       // factor of 2.
13876       // TODO: Move this check upwards, so that if we have bad type
13877       // mismatches, we don't create any DAG nodes.
13878       return SDValue();
13879     }
13880   }
13881
13882   // Initialize mask to undef.
13883   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13884
13885   // Only need to run up to the number of elements actually used, not the
13886   // total number of elements in the shuffle - if we are shuffling a wider
13887   // vector, the high lanes should be set to undef.
13888   for (unsigned i = 0; i != NumElems; ++i) {
13889     if (VectorMask[i] <= 0)
13890       continue;
13891
13892     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13893     if (VectorMask[i] == (int)LeftIdx) {
13894       Mask[i] = ExtIndex;
13895     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13896       Mask[i] = Vec2Offset + ExtIndex;
13897     }
13898   }
13899
13900   // The type the input vectors may have changed above.
13901   InVT1 = VecIn1.getValueType();
13902
13903   // If we already have a VecIn2, it should have the same type as VecIn1.
13904   // If we don't, get an undef/zero vector of the appropriate type.
13905   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13906   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13907
13908   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13909   if (ShuffleNumElems > NumElems)
13910     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13911
13912   return Shuffle;
13913 }
13914
13915 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13916 // operations. If the types of the vectors we're extracting from allow it,
13917 // turn this into a vector_shuffle node.
13918 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13919   SDLoc DL(N);
13920   EVT VT = N->getValueType(0);
13921
13922   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13923   if (!isTypeLegal(VT))
13924     return SDValue();
13925
13926   // May only combine to shuffle after legalize if shuffle is legal.
13927   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13928     return SDValue();
13929
13930   bool UsesZeroVector = false;
13931   unsigned NumElems = N->getNumOperands();
13932
13933   // Record, for each element of the newly built vector, which input vector
13934   // that element comes from. -1 stands for undef, 0 for the zero vector,
13935   // and positive values for the input vectors.
13936   // VectorMask maps each element to its vector number, and VecIn maps vector
13937   // numbers to their initial SDValues.
13938
13939   SmallVector<int, 8> VectorMask(NumElems, -1);
13940   SmallVector<SDValue, 8> VecIn;
13941   VecIn.push_back(SDValue());
13942
13943   for (unsigned i = 0; i != NumElems; ++i) {
13944     SDValue Op = N->getOperand(i);
13945
13946     if (Op.isUndef())
13947       continue;
13948
13949     // See if we can use a blend with a zero vector.
13950     // TODO: Should we generalize this to a blend with an arbitrary constant
13951     // vector?
13952     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13953       UsesZeroVector = true;
13954       VectorMask[i] = 0;
13955       continue;
13956     }
13957
13958     // Not an undef or zero. If the input is something other than an
13959     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13960     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13961         !isa<ConstantSDNode>(Op.getOperand(1)))
13962       return SDValue();
13963
13964     SDValue ExtractedFromVec = Op.getOperand(0);
13965
13966     // All inputs must have the same element type as the output.
13967     if (VT.getVectorElementType() !=
13968         ExtractedFromVec.getValueType().getVectorElementType())
13969       return SDValue();
13970
13971     // Have we seen this input vector before?
13972     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13973     // a map back from SDValues to numbers isn't worth it.
13974     unsigned Idx = std::distance(
13975         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13976     if (Idx == VecIn.size())
13977       VecIn.push_back(ExtractedFromVec);
13978
13979     VectorMask[i] = Idx;
13980   }
13981
13982   // If we didn't find at least one input vector, bail out.
13983   if (VecIn.size() < 2)
13984     return SDValue();
13985
13986   // TODO: We want to sort the vectors by descending length, so that adjacent
13987   // pairs have similar length, and the longer vector is always first in the
13988   // pair.
13989
13990   // TODO: Should this fire if some of the input vectors has illegal type (like
13991   // it does now), or should we let legalization run its course first?
13992
13993   // Shuffle phase:
13994   // Take pairs of vectors, and shuffle them so that the result has elements
13995   // from these vectors in the correct places.
13996   // For example, given:
13997   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13998   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13999   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14000   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14001   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14002   // We will generate:
14003   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14004   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14005   SmallVector<SDValue, 4> Shuffles;
14006   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14007     unsigned LeftIdx = 2 * In + 1;
14008     SDValue VecLeft = VecIn[LeftIdx];
14009     SDValue VecRight =
14010         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14011
14012     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14013                                                 VecRight, LeftIdx))
14014       Shuffles.push_back(Shuffle);
14015     else
14016       return SDValue();
14017   }
14018
14019   // If we need the zero vector as an "ingredient" in the blend tree, add it
14020   // to the list of shuffles.
14021   if (UsesZeroVector)
14022     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14023                                       : DAG.getConstantFP(0.0, DL, VT));
14024
14025   // If we only have one shuffle, we're done.
14026   if (Shuffles.size() == 1)
14027     return Shuffles[0];
14028
14029   // Update the vector mask to point to the post-shuffle vectors.
14030   for (int &Vec : VectorMask)
14031     if (Vec == 0)
14032       Vec = Shuffles.size() - 1;
14033     else
14034       Vec = (Vec - 1) / 2;
14035
14036   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14037   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14038   // generate:
14039   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14040   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14041   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14042   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14043   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14044   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14045   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14046
14047   // Make sure the initial size of the shuffle list is even.
14048   if (Shuffles.size() % 2)
14049     Shuffles.push_back(DAG.getUNDEF(VT));
14050
14051   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14052     if (CurSize % 2) {
14053       Shuffles[CurSize] = DAG.getUNDEF(VT);
14054       CurSize++;
14055     }
14056     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14057       int Left = 2 * In;
14058       int Right = 2 * In + 1;
14059       SmallVector<int, 8> Mask(NumElems, -1);
14060       for (unsigned i = 0; i != NumElems; ++i) {
14061         if (VectorMask[i] == Left) {
14062           Mask[i] = i;
14063           VectorMask[i] = In;
14064         } else if (VectorMask[i] == Right) {
14065           Mask[i] = i + NumElems;
14066           VectorMask[i] = In;
14067         }
14068       }
14069
14070       Shuffles[In] =
14071           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14072     }
14073   }
14074
14075   return Shuffles[0];
14076 }
14077
14078 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14079   EVT VT = N->getValueType(0);
14080
14081   // A vector built entirely of undefs is undef.
14082   if (ISD::allOperandsUndef(N))
14083     return DAG.getUNDEF(VT);
14084
14085   // Check if we can express BUILD VECTOR via subvector extract.
14086   if (!LegalTypes && (N->getNumOperands() > 1)) {
14087     SDValue Op0 = N->getOperand(0);
14088     auto checkElem = [&](SDValue Op) -> uint64_t {
14089       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14090           (Op0.getOperand(0) == Op.getOperand(0)))
14091         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14092           return CNode->getZExtValue();
14093       return -1;
14094     };
14095
14096     int Offset = checkElem(Op0);
14097     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14098       if (Offset + i != checkElem(N->getOperand(i))) {
14099         Offset = -1;
14100         break;
14101       }
14102     }
14103
14104     if ((Offset == 0) &&
14105         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14106       return Op0.getOperand(0);
14107     if ((Offset != -1) &&
14108         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14109          0)) // IDX must be multiple of output size.
14110       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14111                          Op0.getOperand(0), Op0.getOperand(1));
14112   }
14113
14114   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14115     return V;
14116
14117   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14118     return V;
14119
14120   if (SDValue V = reduceBuildVecToShuffle(N))
14121     return V;
14122
14123   return SDValue();
14124 }
14125
14126 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14128   EVT OpVT = N->getOperand(0).getValueType();
14129
14130   // If the operands are legal vectors, leave them alone.
14131   if (TLI.isTypeLegal(OpVT))
14132     return SDValue();
14133
14134   SDLoc DL(N);
14135   EVT VT = N->getValueType(0);
14136   SmallVector<SDValue, 8> Ops;
14137
14138   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14139   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14140
14141   // Keep track of what we encounter.
14142   bool AnyInteger = false;
14143   bool AnyFP = false;
14144   for (const SDValue &Op : N->ops()) {
14145     if (ISD::BITCAST == Op.getOpcode() &&
14146         !Op.getOperand(0).getValueType().isVector())
14147       Ops.push_back(Op.getOperand(0));
14148     else if (ISD::UNDEF == Op.getOpcode())
14149       Ops.push_back(ScalarUndef);
14150     else
14151       return SDValue();
14152
14153     // Note whether we encounter an integer or floating point scalar.
14154     // If it's neither, bail out, it could be something weird like x86mmx.
14155     EVT LastOpVT = Ops.back().getValueType();
14156     if (LastOpVT.isFloatingPoint())
14157       AnyFP = true;
14158     else if (LastOpVT.isInteger())
14159       AnyInteger = true;
14160     else
14161       return SDValue();
14162   }
14163
14164   // If any of the operands is a floating point scalar bitcast to a vector,
14165   // use floating point types throughout, and bitcast everything.
14166   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14167   if (AnyFP) {
14168     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14169     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14170     if (AnyInteger) {
14171       for (SDValue &Op : Ops) {
14172         if (Op.getValueType() == SVT)
14173           continue;
14174         if (Op.isUndef())
14175           Op = ScalarUndef;
14176         else
14177           Op = DAG.getBitcast(SVT, Op);
14178       }
14179     }
14180   }
14181
14182   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14183                                VT.getSizeInBits() / SVT.getSizeInBits());
14184   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14185 }
14186
14187 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14188 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14189 // most two distinct vectors the same size as the result, attempt to turn this
14190 // into a legal shuffle.
14191 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14192   EVT VT = N->getValueType(0);
14193   EVT OpVT = N->getOperand(0).getValueType();
14194   int NumElts = VT.getVectorNumElements();
14195   int NumOpElts = OpVT.getVectorNumElements();
14196
14197   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14198   SmallVector<int, 8> Mask;
14199
14200   for (SDValue Op : N->ops()) {
14201     // Peek through any bitcast.
14202     while (Op.getOpcode() == ISD::BITCAST)
14203       Op = Op.getOperand(0);
14204
14205     // UNDEF nodes convert to UNDEF shuffle mask values.
14206     if (Op.isUndef()) {
14207       Mask.append((unsigned)NumOpElts, -1);
14208       continue;
14209     }
14210
14211     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14212       return SDValue();
14213
14214     // What vector are we extracting the subvector from and at what index?
14215     SDValue ExtVec = Op.getOperand(0);
14216
14217     // We want the EVT of the original extraction to correctly scale the
14218     // extraction index.
14219     EVT ExtVT = ExtVec.getValueType();
14220
14221     // Peek through any bitcast.
14222     while (ExtVec.getOpcode() == ISD::BITCAST)
14223       ExtVec = ExtVec.getOperand(0);
14224
14225     // UNDEF nodes convert to UNDEF shuffle mask values.
14226     if (ExtVec.isUndef()) {
14227       Mask.append((unsigned)NumOpElts, -1);
14228       continue;
14229     }
14230
14231     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14232       return SDValue();
14233     int ExtIdx = Op.getConstantOperandVal(1);
14234
14235     // Ensure that we are extracting a subvector from a vector the same
14236     // size as the result.
14237     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14238       return SDValue();
14239
14240     // Scale the subvector index to account for any bitcast.
14241     int NumExtElts = ExtVT.getVectorNumElements();
14242     if (0 == (NumExtElts % NumElts))
14243       ExtIdx /= (NumExtElts / NumElts);
14244     else if (0 == (NumElts % NumExtElts))
14245       ExtIdx *= (NumElts / NumExtElts);
14246     else
14247       return SDValue();
14248
14249     // At most we can reference 2 inputs in the final shuffle.
14250     if (SV0.isUndef() || SV0 == ExtVec) {
14251       SV0 = ExtVec;
14252       for (int i = 0; i != NumOpElts; ++i)
14253         Mask.push_back(i + ExtIdx);
14254     } else if (SV1.isUndef() || SV1 == ExtVec) {
14255       SV1 = ExtVec;
14256       for (int i = 0; i != NumOpElts; ++i)
14257         Mask.push_back(i + ExtIdx + NumElts);
14258     } else {
14259       return SDValue();
14260     }
14261   }
14262
14263   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14264     return SDValue();
14265
14266   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14267                               DAG.getBitcast(VT, SV1), Mask);
14268 }
14269
14270 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14271   // If we only have one input vector, we don't need to do any concatenation.
14272   if (N->getNumOperands() == 1)
14273     return N->getOperand(0);
14274
14275   // Check if all of the operands are undefs.
14276   EVT VT = N->getValueType(0);
14277   if (ISD::allOperandsUndef(N))
14278     return DAG.getUNDEF(VT);
14279
14280   // Optimize concat_vectors where all but the first of the vectors are undef.
14281   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14282         return Op.isUndef();
14283       })) {
14284     SDValue In = N->getOperand(0);
14285     assert(In.getValueType().isVector() && "Must concat vectors");
14286
14287     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14288     if (In->getOpcode() == ISD::BITCAST &&
14289         !In->getOperand(0)->getValueType(0).isVector()) {
14290       SDValue Scalar = In->getOperand(0);
14291
14292       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14293       // look through the trunc so we can still do the transform:
14294       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14295       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14296           !TLI.isTypeLegal(Scalar.getValueType()) &&
14297           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14298         Scalar = Scalar->getOperand(0);
14299
14300       EVT SclTy = Scalar->getValueType(0);
14301
14302       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14303         return SDValue();
14304
14305       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14306       if (VNTNumElms < 2)
14307         return SDValue();
14308
14309       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14310       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14311         return SDValue();
14312
14313       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14314       return DAG.getBitcast(VT, Res);
14315     }
14316   }
14317
14318   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14319   // We have already tested above for an UNDEF only concatenation.
14320   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14321   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14322   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14323     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14324   };
14325   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14326     SmallVector<SDValue, 8> Opnds;
14327     EVT SVT = VT.getScalarType();
14328
14329     EVT MinVT = SVT;
14330     if (!SVT.isFloatingPoint()) {
14331       // If BUILD_VECTOR are from built from integer, they may have different
14332       // operand types. Get the smallest type and truncate all operands to it.
14333       bool FoundMinVT = false;
14334       for (const SDValue &Op : N->ops())
14335         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14336           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14337           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14338           FoundMinVT = true;
14339         }
14340       assert(FoundMinVT && "Concat vector type mismatch");
14341     }
14342
14343     for (const SDValue &Op : N->ops()) {
14344       EVT OpVT = Op.getValueType();
14345       unsigned NumElts = OpVT.getVectorNumElements();
14346
14347       if (ISD::UNDEF == Op.getOpcode())
14348         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14349
14350       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14351         if (SVT.isFloatingPoint()) {
14352           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14353           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14354         } else {
14355           for (unsigned i = 0; i != NumElts; ++i)
14356             Opnds.push_back(
14357                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14358         }
14359       }
14360     }
14361
14362     assert(VT.getVectorNumElements() == Opnds.size() &&
14363            "Concat vector type mismatch");
14364     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14365   }
14366
14367   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14368   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14369     return V;
14370
14371   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14372   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14373     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14374       return V;
14375
14376   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14377   // nodes often generate nop CONCAT_VECTOR nodes.
14378   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14379   // place the incoming vectors at the exact same location.
14380   SDValue SingleSource = SDValue();
14381   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14382
14383   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14384     SDValue Op = N->getOperand(i);
14385
14386     if (Op.isUndef())
14387       continue;
14388
14389     // Check if this is the identity extract:
14390     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14391       return SDValue();
14392
14393     // Find the single incoming vector for the extract_subvector.
14394     if (SingleSource.getNode()) {
14395       if (Op.getOperand(0) != SingleSource)
14396         return SDValue();
14397     } else {
14398       SingleSource = Op.getOperand(0);
14399
14400       // Check the source type is the same as the type of the result.
14401       // If not, this concat may extend the vector, so we can not
14402       // optimize it away.
14403       if (SingleSource.getValueType() != N->getValueType(0))
14404         return SDValue();
14405     }
14406
14407     unsigned IdentityIndex = i * PartNumElem;
14408     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14409     // The extract index must be constant.
14410     if (!CS)
14411       return SDValue();
14412
14413     // Check that we are reading from the identity index.
14414     if (CS->getZExtValue() != IdentityIndex)
14415       return SDValue();
14416   }
14417
14418   if (SingleSource.getNode())
14419     return SingleSource;
14420
14421   return SDValue();
14422 }
14423
14424 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14425   EVT NVT = N->getValueType(0);
14426   SDValue V = N->getOperand(0);
14427
14428   // Extract from UNDEF is UNDEF.
14429   if (V.isUndef())
14430     return DAG.getUNDEF(NVT);
14431
14432   // Combine:
14433   //    (extract_subvec (concat V1, V2, ...), i)
14434   // Into:
14435   //    Vi if possible
14436   // Only operand 0 is checked as 'concat' assumes all inputs of the same
14437   // type.
14438   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14439       isa<ConstantSDNode>(N->getOperand(1)) &&
14440       V->getOperand(0).getValueType() == NVT) {
14441     unsigned Idx = N->getConstantOperandVal(1);
14442     unsigned NumElems = NVT.getVectorNumElements();
14443     assert((Idx % NumElems) == 0 &&
14444            "IDX in concat is not a multiple of the result vector length.");
14445     return V->getOperand(Idx / NumElems);
14446   }
14447
14448   // Skip bitcasting
14449   if (V->getOpcode() == ISD::BITCAST)
14450     V = V.getOperand(0);
14451
14452   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14453     // Handle only simple case where vector being inserted and vector
14454     // being extracted are of same size.
14455     EVT SmallVT = V->getOperand(1).getValueType();
14456     if (!NVT.bitsEq(SmallVT))
14457       return SDValue();
14458
14459     // Only handle cases where both indexes are constants.
14460     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14461     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14462
14463     if (InsIdx && ExtIdx) {
14464       // Combine:
14465       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14466       // Into:
14467       //    indices are equal or bit offsets are equal => V1
14468       //    otherwise => (extract_subvec V1, ExtIdx)
14469       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14470           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14471         return DAG.getBitcast(NVT, V->getOperand(1));
14472       return DAG.getNode(
14473           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14474           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14475           N->getOperand(1));
14476     }
14477   }
14478
14479   return SDValue();
14480 }
14481
14482 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14483                                                  SDValue V, SelectionDAG &DAG) {
14484   SDLoc DL(V);
14485   EVT VT = V.getValueType();
14486
14487   switch (V.getOpcode()) {
14488   default:
14489     return V;
14490
14491   case ISD::CONCAT_VECTORS: {
14492     EVT OpVT = V->getOperand(0).getValueType();
14493     int OpSize = OpVT.getVectorNumElements();
14494     SmallBitVector OpUsedElements(OpSize, false);
14495     bool FoundSimplification = false;
14496     SmallVector<SDValue, 4> NewOps;
14497     NewOps.reserve(V->getNumOperands());
14498     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14499       SDValue Op = V->getOperand(i);
14500       bool OpUsed = false;
14501       for (int j = 0; j < OpSize; ++j)
14502         if (UsedElements[i * OpSize + j]) {
14503           OpUsedElements[j] = true;
14504           OpUsed = true;
14505         }
14506       NewOps.push_back(
14507           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14508                  : DAG.getUNDEF(OpVT));
14509       FoundSimplification |= Op == NewOps.back();
14510       OpUsedElements.reset();
14511     }
14512     if (FoundSimplification)
14513       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14514     return V;
14515   }
14516
14517   case ISD::INSERT_SUBVECTOR: {
14518     SDValue BaseV = V->getOperand(0);
14519     SDValue SubV = V->getOperand(1);
14520     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14521     if (!IdxN)
14522       return V;
14523
14524     int SubSize = SubV.getValueType().getVectorNumElements();
14525     int Idx = IdxN->getZExtValue();
14526     bool SubVectorUsed = false;
14527     SmallBitVector SubUsedElements(SubSize, false);
14528     for (int i = 0; i < SubSize; ++i)
14529       if (UsedElements[i + Idx]) {
14530         SubVectorUsed = true;
14531         SubUsedElements[i] = true;
14532         UsedElements[i + Idx] = false;
14533       }
14534
14535     // Now recurse on both the base and sub vectors.
14536     SDValue SimplifiedSubV =
14537         SubVectorUsed
14538             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14539             : DAG.getUNDEF(SubV.getValueType());
14540     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14541     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14542       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14543                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14544     return V;
14545   }
14546   }
14547 }
14548
14549 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14550                                        SDValue N1, SelectionDAG &DAG) {
14551   EVT VT = SVN->getValueType(0);
14552   int NumElts = VT.getVectorNumElements();
14553   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14554   for (int M : SVN->getMask())
14555     if (M >= 0 && M < NumElts)
14556       N0UsedElements[M] = true;
14557     else if (M >= NumElts)
14558       N1UsedElements[M - NumElts] = true;
14559
14560   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14561   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14562   if (S0 == N0 && S1 == N1)
14563     return SDValue();
14564
14565   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14566 }
14567
14568 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14569 // or turn a shuffle of a single concat into simpler shuffle then concat.
14570 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14571   EVT VT = N->getValueType(0);
14572   unsigned NumElts = VT.getVectorNumElements();
14573
14574   SDValue N0 = N->getOperand(0);
14575   SDValue N1 = N->getOperand(1);
14576   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14577
14578   SmallVector<SDValue, 4> Ops;
14579   EVT ConcatVT = N0.getOperand(0).getValueType();
14580   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14581   unsigned NumConcats = NumElts / NumElemsPerConcat;
14582
14583   // Special case: shuffle(concat(A,B)) can be more efficiently represented
14584   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14585   // half vector elements.
14586   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14587       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14588                   SVN->getMask().end(), [](int i) { return i == -1; })) {
14589     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14590                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14591     N1 = DAG.getUNDEF(ConcatVT);
14592     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14593   }
14594
14595   // Look at every vector that's inserted. We're looking for exact
14596   // subvector-sized copies from a concatenated vector
14597   for (unsigned I = 0; I != NumConcats; ++I) {
14598     // Make sure we're dealing with a copy.
14599     unsigned Begin = I * NumElemsPerConcat;
14600     bool AllUndef = true, NoUndef = true;
14601     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14602       if (SVN->getMaskElt(J) >= 0)
14603         AllUndef = false;
14604       else
14605         NoUndef = false;
14606     }
14607
14608     if (NoUndef) {
14609       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14610         return SDValue();
14611
14612       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14613         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14614           return SDValue();
14615
14616       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14617       if (FirstElt < N0.getNumOperands())
14618         Ops.push_back(N0.getOperand(FirstElt));
14619       else
14620         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14621
14622     } else if (AllUndef) {
14623       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14624     } else { // Mixed with general masks and undefs, can't do optimization.
14625       return SDValue();
14626     }
14627   }
14628
14629   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14630 }
14631
14632 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14633 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14634 //
14635 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14636 // a simplification in some sense, but it isn't appropriate in general: some
14637 // BUILD_VECTORs are substantially cheaper than others. The general case
14638 // of a BUILD_VECTOR requires inserting each element individually (or
14639 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14640 // all constants is a single constant pool load.  A BUILD_VECTOR where each
14641 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
14642 // are undef lowers to a small number of element insertions.
14643 //
14644 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14645 // We don't fold shuffles where one side is a non-zero constant, and we don't
14646 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14647 // non-constant operands. This seems to work out reasonably well in practice.
14648 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14649                                        SelectionDAG &DAG,
14650                                        const TargetLowering &TLI) {
14651   EVT VT = SVN->getValueType(0);
14652   unsigned NumElts = VT.getVectorNumElements();
14653   SDValue N0 = SVN->getOperand(0);
14654   SDValue N1 = SVN->getOperand(1);
14655
14656   if (!N0->hasOneUse() || !N1->hasOneUse())
14657     return SDValue();
14658   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14659   // discussed above.
14660   if (!N1.isUndef()) {
14661     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14662     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14663     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14664       return SDValue();
14665     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14666       return SDValue();
14667   }
14668
14669   SmallVector<SDValue, 8> Ops;
14670   SmallSet<SDValue, 16> DuplicateOps;
14671   for (int M : SVN->getMask()) {
14672     SDValue Op = DAG.getUNDEF(VT.getScalarType());
14673     if (M >= 0) {
14674       int Idx = M < (int)NumElts ? M : M - NumElts;
14675       SDValue &S = (M < (int)NumElts ? N0 : N1);
14676       if (S.getOpcode() == ISD::BUILD_VECTOR) {
14677         Op = S.getOperand(Idx);
14678       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14679         if (Idx == 0)
14680           Op = S.getOperand(0);
14681       } else {
14682         // Operand can't be combined - bail out.
14683         return SDValue();
14684       }
14685     }
14686
14687     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14688     // fine, but it's likely to generate low-quality code if the target can't
14689     // reconstruct an appropriate shuffle.
14690     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14691       if (!DuplicateOps.insert(Op).second)
14692         return SDValue();
14693
14694     Ops.push_back(Op);
14695   }
14696   // BUILD_VECTOR requires all inputs to be of the same type, find the
14697   // maximum type and extend them all.
14698   EVT SVT = VT.getScalarType();
14699   if (SVT.isInteger())
14700     for (SDValue &Op : Ops)
14701       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14702   if (SVT != VT.getScalarType())
14703     for (SDValue &Op : Ops)
14704       Op = TLI.isZExtFree(Op.getValueType(), SVT)
14705                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14706                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14707   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14708 }
14709
14710 // Match shuffles that can be converted to any_vector_extend_in_reg.
14711 // This is often generated during legalization.
14712 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14713 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
14714 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
14715                                      SelectionDAG &DAG,
14716                                      const TargetLowering &TLI,
14717                                      bool LegalOperations) {
14718   EVT VT = SVN->getValueType(0);
14719   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14720
14721   // TODO Add support for big-endian when we have a test case.
14722   if (!VT.isInteger() || IsBigEndian)
14723     return SDValue();
14724
14725   unsigned NumElts = VT.getVectorNumElements();
14726   unsigned EltSizeInBits = VT.getScalarSizeInBits();
14727   ArrayRef<int> Mask = SVN->getMask();
14728   SDValue N0 = SVN->getOperand(0);
14729
14730   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
14731   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
14732     for (unsigned i = 0; i != NumElts; ++i) {
14733       if (Mask[i] < 0)
14734         continue;
14735       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
14736         continue;
14737       return false;
14738     }
14739     return true;
14740   };
14741
14742   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
14743   // power-of-2 extensions as they are the most likely.
14744   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
14745     if (!isAnyExtend(Scale))
14746       continue;
14747
14748     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
14749     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
14750     if (!LegalOperations ||
14751         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
14752       return DAG.getBitcast(VT,
14753                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
14754   }
14755
14756   return SDValue();
14757 }
14758
14759 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
14760 // each source element of a large type into the lowest elements of a smaller
14761 // destination type. This is often generated during legalization.
14762 // If the source node itself was a '*_extend_vector_inreg' node then we should
14763 // then be able to remove it.
14764 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) {
14765   EVT VT = SVN->getValueType(0);
14766   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14767
14768   // TODO Add support for big-endian when we have a test case.
14769   if (!VT.isInteger() || IsBigEndian)
14770     return SDValue();
14771
14772   SDValue N0 = SVN->getOperand(0);
14773   while (N0.getOpcode() == ISD::BITCAST)
14774     N0 = N0.getOperand(0);
14775
14776   unsigned Opcode = N0.getOpcode();
14777   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
14778       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
14779       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
14780     return SDValue();
14781
14782   SDValue N00 = N0.getOperand(0);
14783   ArrayRef<int> Mask = SVN->getMask();
14784   unsigned NumElts = VT.getVectorNumElements();
14785   unsigned EltSizeInBits = VT.getScalarSizeInBits();
14786   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
14787
14788   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
14789   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
14790   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
14791   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
14792     for (unsigned i = 0; i != NumElts; ++i) {
14793       if (Mask[i] < 0)
14794         continue;
14795       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
14796         continue;
14797       return false;
14798     }
14799     return true;
14800   };
14801
14802   // At the moment we just handle the case where we've truncated back to the
14803   // same size as before the extension.
14804   // TODO: handle more extension/truncation cases as cases arise.
14805   if (EltSizeInBits != ExtSrcSizeInBits)
14806     return SDValue();
14807
14808   // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
14809   // power-of-2 truncations as they are the most likely.
14810   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
14811     if (isTruncate(Scale))
14812       return DAG.getBitcast(VT, N00);
14813
14814   return SDValue();
14815 }
14816
14817 // Combine shuffles of splat-shuffles of the form:
14818 // shuffle (shuffle V, undef, splat-mask), undef, M
14819 // If splat-mask contains undef elements, we need to be careful about
14820 // introducing undef's in the folded mask which are not the result of composing
14821 // the masks of the shuffles.
14822 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
14823                                      ShuffleVectorSDNode *Splat,
14824                                      SelectionDAG &DAG) {
14825   ArrayRef<int> SplatMask = Splat->getMask();
14826   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
14827
14828   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
14829   // every undef mask element in the splat-shuffle has a corresponding undef
14830   // element in the user-shuffle's mask or if the composition of mask elements
14831   // would result in undef.
14832   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
14833   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
14834   //   In this case it is not legal to simplify to the splat-shuffle because we
14835   //   may be exposing the users of the shuffle an undef element at index 1
14836   //   which was not there before the combine.
14837   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
14838   //   In this case the composition of masks yields SplatMask, so it's ok to
14839   //   simplify to the splat-shuffle.
14840   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
14841   //   In this case the composed mask includes all undef elements of SplatMask
14842   //   and in addition sets element zero to undef. It is safe to simplify to
14843   //   the splat-shuffle.
14844   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
14845                                        ArrayRef<int> SplatMask) {
14846     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
14847       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
14848           SplatMask[UserMask[i]] != -1)
14849         return false;
14850     return true;
14851   };
14852   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
14853     return SDValue(Splat, 0);
14854
14855   // Create a new shuffle with a mask that is composed of the two shuffles'
14856   // masks.
14857   SmallVector<int, 32> NewMask;
14858   for (int Idx : UserMask)
14859     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
14860
14861   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
14862                               Splat->getOperand(0), Splat->getOperand(1),
14863                               NewMask);
14864 }
14865
14866 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
14867   EVT VT = N->getValueType(0);
14868   unsigned NumElts = VT.getVectorNumElements();
14869
14870   SDValue N0 = N->getOperand(0);
14871   SDValue N1 = N->getOperand(1);
14872
14873   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
14874
14875   // Canonicalize shuffle undef, undef -> undef
14876   if (N0.isUndef() && N1.isUndef())
14877     return DAG.getUNDEF(VT);
14878
14879   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14880
14881   // Canonicalize shuffle v, v -> v, undef
14882   if (N0 == N1) {
14883     SmallVector<int, 8> NewMask;
14884     for (unsigned i = 0; i != NumElts; ++i) {
14885       int Idx = SVN->getMaskElt(i);
14886       if (Idx >= (int)NumElts) Idx -= NumElts;
14887       NewMask.push_back(Idx);
14888     }
14889     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
14890   }
14891
14892   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
14893   if (N0.isUndef())
14894     return DAG.getCommutedVectorShuffle(*SVN);
14895
14896   // Remove references to rhs if it is undef
14897   if (N1.isUndef()) {
14898     bool Changed = false;
14899     SmallVector<int, 8> NewMask;
14900     for (unsigned i = 0; i != NumElts; ++i) {
14901       int Idx = SVN->getMaskElt(i);
14902       if (Idx >= (int)NumElts) {
14903         Idx = -1;
14904         Changed = true;
14905       }
14906       NewMask.push_back(Idx);
14907     }
14908     if (Changed)
14909       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
14910   }
14911
14912   // A shuffle of a single vector that is a splat can always be folded.
14913   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
14914     if (N1->isUndef() && N0Shuf->isSplat())
14915       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
14916
14917   // If it is a splat, check if the argument vector is another splat or a
14918   // build_vector.
14919   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
14920     SDNode *V = N0.getNode();
14921
14922     // If this is a bit convert that changes the element type of the vector but
14923     // not the number of vector elements, look through it.  Be careful not to
14924     // look though conversions that change things like v4f32 to v2f64.
14925     if (V->getOpcode() == ISD::BITCAST) {
14926       SDValue ConvInput = V->getOperand(0);
14927       if (ConvInput.getValueType().isVector() &&
14928           ConvInput.getValueType().getVectorNumElements() == NumElts)
14929         V = ConvInput.getNode();
14930     }
14931
14932     if (V->getOpcode() == ISD::BUILD_VECTOR) {
14933       assert(V->getNumOperands() == NumElts &&
14934              "BUILD_VECTOR has wrong number of operands");
14935       SDValue Base;
14936       bool AllSame = true;
14937       for (unsigned i = 0; i != NumElts; ++i) {
14938         if (!V->getOperand(i).isUndef()) {
14939           Base = V->getOperand(i);
14940           break;
14941         }
14942       }
14943       // Splat of <u, u, u, u>, return <u, u, u, u>
14944       if (!Base.getNode())
14945         return N0;
14946       for (unsigned i = 0; i != NumElts; ++i) {
14947         if (V->getOperand(i) != Base) {
14948           AllSame = false;
14949           break;
14950         }
14951       }
14952       // Splat of <x, x, x, x>, return <x, x, x, x>
14953       if (AllSame)
14954         return N0;
14955
14956       // Canonicalize any other splat as a build_vector.
14957       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
14958       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
14959       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
14960
14961       // We may have jumped through bitcasts, so the type of the
14962       // BUILD_VECTOR may not match the type of the shuffle.
14963       if (V->getValueType(0) != VT)
14964         NewBV = DAG.getBitcast(VT, NewBV);
14965       return NewBV;
14966     }
14967   }
14968
14969   // There are various patterns used to build up a vector from smaller vectors,
14970   // subvectors, or elements. Scan chains of these and replace unused insertions
14971   // or components with undef.
14972   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
14973     return S;
14974
14975   // Match shuffles that can be converted to any_vector_extend_in_reg.
14976   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
14977     return V;
14978
14979   // Combine "truncate_vector_in_reg" style shuffles.
14980   if (SDValue V = combineTruncationShuffle(SVN, DAG))
14981     return V;
14982
14983   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
14984       Level < AfterLegalizeVectorOps &&
14985       (N1.isUndef() ||
14986       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14987        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
14988     if (SDValue V = partitionShuffleOfConcats(N, DAG))
14989       return V;
14990   }
14991
14992   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14993   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14994   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14995     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
14996       return Res;
14997
14998   // If this shuffle only has a single input that is a bitcasted shuffle,
14999   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15000   // back to their original types.
15001   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15002       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15003       TLI.isTypeLegal(VT)) {
15004
15005     // Peek through the bitcast only if there is one user.
15006     SDValue BC0 = N0;
15007     while (BC0.getOpcode() == ISD::BITCAST) {
15008       if (!BC0.hasOneUse())
15009         break;
15010       BC0 = BC0.getOperand(0);
15011     }
15012
15013     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15014       if (Scale == 1)
15015         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15016
15017       SmallVector<int, 8> NewMask;
15018       for (int M : Mask)
15019         for (int s = 0; s != Scale; ++s)
15020           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15021       return NewMask;
15022     };
15023
15024     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15025       EVT SVT = VT.getScalarType();
15026       EVT InnerVT = BC0->getValueType(0);
15027       EVT InnerSVT = InnerVT.getScalarType();
15028
15029       // Determine which shuffle works with the smaller scalar type.
15030       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15031       EVT ScaleSVT = ScaleVT.getScalarType();
15032
15033       if (TLI.isTypeLegal(ScaleVT) &&
15034           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15035           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15036
15037         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15038         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15039
15040         // Scale the shuffle masks to the smaller scalar type.
15041         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15042         SmallVector<int, 8> InnerMask =
15043             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15044         SmallVector<int, 8> OuterMask =
15045             ScaleShuffleMask(SVN->getMask(), OuterScale);
15046
15047         // Merge the shuffle masks.
15048         SmallVector<int, 8> NewMask;
15049         for (int M : OuterMask)
15050           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15051
15052         // Test for shuffle mask legality over both commutations.
15053         SDValue SV0 = BC0->getOperand(0);
15054         SDValue SV1 = BC0->getOperand(1);
15055         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15056         if (!LegalMask) {
15057           std::swap(SV0, SV1);
15058           ShuffleVectorSDNode::commuteMask(NewMask);
15059           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15060         }
15061
15062         if (LegalMask) {
15063           SV0 = DAG.getBitcast(ScaleVT, SV0);
15064           SV1 = DAG.getBitcast(ScaleVT, SV1);
15065           return DAG.getBitcast(
15066               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15067         }
15068       }
15069     }
15070   }
15071
15072   // Canonicalize shuffles according to rules:
15073   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15074   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15075   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15076   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15077       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15078       TLI.isTypeLegal(VT)) {
15079     // The incoming shuffle must be of the same type as the result of the
15080     // current shuffle.
15081     assert(N1->getOperand(0).getValueType() == VT &&
15082            "Shuffle types don't match");
15083
15084     SDValue SV0 = N1->getOperand(0);
15085     SDValue SV1 = N1->getOperand(1);
15086     bool HasSameOp0 = N0 == SV0;
15087     bool IsSV1Undef = SV1.isUndef();
15088     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15089       // Commute the operands of this shuffle so that next rule
15090       // will trigger.
15091       return DAG.getCommutedVectorShuffle(*SVN);
15092   }
15093
15094   // Try to fold according to rules:
15095   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15096   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15097   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15098   // Don't try to fold shuffles with illegal type.
15099   // Only fold if this shuffle is the only user of the other shuffle.
15100   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15101       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15102     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15103
15104     // Don't try to fold splats; they're likely to simplify somehow, or they
15105     // might be free.
15106     if (OtherSV->isSplat())
15107       return SDValue();
15108
15109     // The incoming shuffle must be of the same type as the result of the
15110     // current shuffle.
15111     assert(OtherSV->getOperand(0).getValueType() == VT &&
15112            "Shuffle types don't match");
15113
15114     SDValue SV0, SV1;
15115     SmallVector<int, 4> Mask;
15116     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15117     // operand, and SV1 as the second operand.
15118     for (unsigned i = 0; i != NumElts; ++i) {
15119       int Idx = SVN->getMaskElt(i);
15120       if (Idx < 0) {
15121         // Propagate Undef.
15122         Mask.push_back(Idx);
15123         continue;
15124       }
15125
15126       SDValue CurrentVec;
15127       if (Idx < (int)NumElts) {
15128         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15129         // shuffle mask to identify which vector is actually referenced.
15130         Idx = OtherSV->getMaskElt(Idx);
15131         if (Idx < 0) {
15132           // Propagate Undef.
15133           Mask.push_back(Idx);
15134           continue;
15135         }
15136
15137         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15138                                            : OtherSV->getOperand(1);
15139       } else {
15140         // This shuffle index references an element within N1.
15141         CurrentVec = N1;
15142       }
15143
15144       // Simple case where 'CurrentVec' is UNDEF.
15145       if (CurrentVec.isUndef()) {
15146         Mask.push_back(-1);
15147         continue;
15148       }
15149
15150       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15151       // will be the first or second operand of the combined shuffle.
15152       Idx = Idx % NumElts;
15153       if (!SV0.getNode() || SV0 == CurrentVec) {
15154         // Ok. CurrentVec is the left hand side.
15155         // Update the mask accordingly.
15156         SV0 = CurrentVec;
15157         Mask.push_back(Idx);
15158         continue;
15159       }
15160
15161       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15162       if (SV1.getNode() && SV1 != CurrentVec)
15163         return SDValue();
15164
15165       // Ok. CurrentVec is the right hand side.
15166       // Update the mask accordingly.
15167       SV1 = CurrentVec;
15168       Mask.push_back(Idx + NumElts);
15169     }
15170
15171     // Check if all indices in Mask are Undef. In case, propagate Undef.
15172     bool isUndefMask = true;
15173     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15174       isUndefMask &= Mask[i] < 0;
15175
15176     if (isUndefMask)
15177       return DAG.getUNDEF(VT);
15178
15179     if (!SV0.getNode())
15180       SV0 = DAG.getUNDEF(VT);
15181     if (!SV1.getNode())
15182       SV1 = DAG.getUNDEF(VT);
15183
15184     // Avoid introducing shuffles with illegal mask.
15185     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15186       ShuffleVectorSDNode::commuteMask(Mask);
15187
15188       if (!TLI.isShuffleMaskLegal(Mask, VT))
15189         return SDValue();
15190
15191       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15192       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15193       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15194       std::swap(SV0, SV1);
15195     }
15196
15197     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15198     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15199     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15200     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15201   }
15202
15203   return SDValue();
15204 }
15205
15206 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15207   SDValue InVal = N->getOperand(0);
15208   EVT VT = N->getValueType(0);
15209
15210   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15211   // with a VECTOR_SHUFFLE.
15212   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15213     SDValue InVec = InVal->getOperand(0);
15214     SDValue EltNo = InVal->getOperand(1);
15215
15216     // FIXME: We could support implicit truncation if the shuffle can be
15217     // scaled to a smaller vector scalar type.
15218     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15219     if (C0 && VT == InVec.getValueType() &&
15220         VT.getScalarType() == InVal.getValueType()) {
15221       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15222       int Elt = C0->getZExtValue();
15223       NewMask[0] = Elt;
15224
15225       if (TLI.isShuffleMaskLegal(NewMask, VT))
15226         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15227                                     NewMask);
15228     }
15229   }
15230
15231   return SDValue();
15232 }
15233
15234 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15235   EVT VT = N->getValueType(0);
15236   SDValue N0 = N->getOperand(0);
15237   SDValue N1 = N->getOperand(1);
15238   SDValue N2 = N->getOperand(2);
15239
15240   // If inserting an UNDEF, just return the original vector.
15241   if (N1.isUndef())
15242     return N0;
15243
15244   // If this is an insert of an extracted vector into an undef vector, we can
15245   // just use the input to the extract.
15246   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15247       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15248     return N1.getOperand(0);
15249
15250   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15251   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15252   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15253   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15254       N0.getOperand(1).getValueType() == N1.getValueType() &&
15255       N0.getOperand(2) == N2)
15256     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15257                        N1, N2);
15258
15259   if (!isa<ConstantSDNode>(N2))
15260     return SDValue();
15261
15262   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15263
15264   // Canonicalize insert_subvector dag nodes.
15265   // Example:
15266   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15267   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15268   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15269       N1.getValueType() == N0.getOperand(1).getValueType() &&
15270       isa<ConstantSDNode>(N0.getOperand(2))) {
15271     unsigned OtherIdx = N0.getConstantOperandVal(2);
15272     if (InsIdx < OtherIdx) {
15273       // Swap nodes.
15274       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15275                                   N0.getOperand(0), N1, N2);
15276       AddToWorklist(NewOp.getNode());
15277       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15278                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15279     }
15280   }
15281
15282   // If the input vector is a concatenation, and the insert replaces
15283   // one of the pieces, we can optimize into a single concat_vectors.
15284   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15285       N0.getOperand(0).getValueType() == N1.getValueType()) {
15286     unsigned Factor = N1.getValueType().getVectorNumElements();
15287
15288     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15289     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15290
15291     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15292   }
15293
15294   return SDValue();
15295 }
15296
15297 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15298   SDValue N0 = N->getOperand(0);
15299
15300   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15301   if (N0->getOpcode() == ISD::FP16_TO_FP)
15302     return N0->getOperand(0);
15303
15304   return SDValue();
15305 }
15306
15307 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15308   SDValue N0 = N->getOperand(0);
15309
15310   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15311   if (N0->getOpcode() == ISD::AND) {
15312     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15313     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15314       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15315                          N0.getOperand(0));
15316     }
15317   }
15318
15319   return SDValue();
15320 }
15321
15322 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15323 /// with the destination vector and a zero vector.
15324 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15325 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
15326 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15327   EVT VT = N->getValueType(0);
15328   SDValue LHS = N->getOperand(0);
15329   SDValue RHS = N->getOperand(1);
15330   SDLoc DL(N);
15331
15332   // Make sure we're not running after operation legalization where it
15333   // may have custom lowered the vector shuffles.
15334   if (LegalOperations)
15335     return SDValue();
15336
15337   if (N->getOpcode() != ISD::AND)
15338     return SDValue();
15339
15340   if (RHS.getOpcode() == ISD::BITCAST)
15341     RHS = RHS.getOperand(0);
15342
15343   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15344     return SDValue();
15345
15346   EVT RVT = RHS.getValueType();
15347   unsigned NumElts = RHS.getNumOperands();
15348
15349   // Attempt to create a valid clear mask, splitting the mask into
15350   // sub elements and checking to see if each is
15351   // all zeros or all ones - suitable for shuffle masking.
15352   auto BuildClearMask = [&](int Split) {
15353     int NumSubElts = NumElts * Split;
15354     int NumSubBits = RVT.getScalarSizeInBits() / Split;
15355
15356     SmallVector<int, 8> Indices;
15357     for (int i = 0; i != NumSubElts; ++i) {
15358       int EltIdx = i / Split;
15359       int SubIdx = i % Split;
15360       SDValue Elt = RHS.getOperand(EltIdx);
15361       if (Elt.isUndef()) {
15362         Indices.push_back(-1);
15363         continue;
15364       }
15365
15366       APInt Bits;
15367       if (isa<ConstantSDNode>(Elt))
15368         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15369       else if (isa<ConstantFPSDNode>(Elt))
15370         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15371       else
15372         return SDValue();
15373
15374       // Extract the sub element from the constant bit mask.
15375       if (DAG.getDataLayout().isBigEndian()) {
15376         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15377       } else {
15378         Bits.lshrInPlace(SubIdx * NumSubBits);
15379       }
15380
15381       if (Split > 1)
15382         Bits = Bits.trunc(NumSubBits);
15383
15384       if (Bits.isAllOnesValue())
15385         Indices.push_back(i);
15386       else if (Bits == 0)
15387         Indices.push_back(i + NumSubElts);
15388       else
15389         return SDValue();
15390     }
15391
15392     // Let's see if the target supports this vector_shuffle.
15393     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15394     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15395     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15396       return SDValue();
15397
15398     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15399     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15400                                                    DAG.getBitcast(ClearVT, LHS),
15401                                                    Zero, Indices));
15402   };
15403
15404   // Determine maximum split level (byte level masking).
15405   int MaxSplit = 1;
15406   if (RVT.getScalarSizeInBits() % 8 == 0)
15407     MaxSplit = RVT.getScalarSizeInBits() / 8;
15408
15409   for (int Split = 1; Split <= MaxSplit; ++Split)
15410     if (RVT.getScalarSizeInBits() % Split == 0)
15411       if (SDValue S = BuildClearMask(Split))
15412         return S;
15413
15414   return SDValue();
15415 }
15416
15417 /// Visit a binary vector operation, like ADD.
15418 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15419   assert(N->getValueType(0).isVector() &&
15420          "SimplifyVBinOp only works on vectors!");
15421
15422   SDValue LHS = N->getOperand(0);
15423   SDValue RHS = N->getOperand(1);
15424   SDValue Ops[] = {LHS, RHS};
15425
15426   // See if we can constant fold the vector operation.
15427   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15428           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15429     return Fold;
15430
15431   // Try to convert a constant mask AND into a shuffle clear mask.
15432   if (SDValue Shuffle = XformToShuffleWithZero(N))
15433     return Shuffle;
15434
15435   // Type legalization might introduce new shuffles in the DAG.
15436   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15437   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
15438   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15439       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15440       LHS.getOperand(1).isUndef() &&
15441       RHS.getOperand(1).isUndef()) {
15442     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15443     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15444
15445     if (SVN0->getMask().equals(SVN1->getMask())) {
15446       EVT VT = N->getValueType(0);
15447       SDValue UndefVector = LHS.getOperand(1);
15448       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15449                                      LHS.getOperand(0), RHS.getOperand(0),
15450                                      N->getFlags());
15451       AddUsersToWorklist(N);
15452       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15453                                   SVN0->getMask());
15454     }
15455   }
15456
15457   return SDValue();
15458 }
15459
15460 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15461                                     SDValue N2) {
15462   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15463
15464   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15465                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
15466
15467   // If we got a simplified select_cc node back from SimplifySelectCC, then
15468   // break it down into a new SETCC node, and a new SELECT node, and then return
15469   // the SELECT node, since we were called with a SELECT node.
15470   if (SCC.getNode()) {
15471     // Check to see if we got a select_cc back (to turn into setcc/select).
15472     // Otherwise, just return whatever node we got back, like fabs.
15473     if (SCC.getOpcode() == ISD::SELECT_CC) {
15474       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15475                                   N0.getValueType(),
15476                                   SCC.getOperand(0), SCC.getOperand(1),
15477                                   SCC.getOperand(4));
15478       AddToWorklist(SETCC.getNode());
15479       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15480                            SCC.getOperand(2), SCC.getOperand(3));
15481     }
15482
15483     return SCC;
15484   }
15485   return SDValue();
15486 }
15487
15488 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15489 /// being selected between, see if we can simplify the select.  Callers of this
15490 /// should assume that TheSelect is deleted if this returns true.  As such, they
15491 /// should return the appropriate thing (e.g. the node) back to the top-level of
15492 /// the DAG combiner loop to avoid it being looked at.
15493 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15494                                     SDValue RHS) {
15495
15496   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15497   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15498   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15499     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15500       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15501       SDValue Sqrt = RHS;
15502       ISD::CondCode CC;
15503       SDValue CmpLHS;
15504       const ConstantFPSDNode *Zero = nullptr;
15505
15506       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15507         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15508         CmpLHS = TheSelect->getOperand(0);
15509         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15510       } else {
15511         // SELECT or VSELECT
15512         SDValue Cmp = TheSelect->getOperand(0);
15513         if (Cmp.getOpcode() == ISD::SETCC) {
15514           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15515           CmpLHS = Cmp.getOperand(0);
15516           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15517         }
15518       }
15519       if (Zero && Zero->isZero() &&
15520           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15521           CC == ISD::SETULT || CC == ISD::SETLT)) {
15522         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15523         CombineTo(TheSelect, Sqrt);
15524         return true;
15525       }
15526     }
15527   }
15528   // Cannot simplify select with vector condition
15529   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15530
15531   // If this is a select from two identical things, try to pull the operation
15532   // through the select.
15533   if (LHS.getOpcode() != RHS.getOpcode() ||
15534       !LHS.hasOneUse() || !RHS.hasOneUse())
15535     return false;
15536
15537   // If this is a load and the token chain is identical, replace the select
15538   // of two loads with a load through a select of the address to load from.
15539   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15540   // constants have been dropped into the constant pool.
15541   if (LHS.getOpcode() == ISD::LOAD) {
15542     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15543     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15544
15545     // Token chains must be identical.
15546     if (LHS.getOperand(0) != RHS.getOperand(0) ||
15547         // Do not let this transformation reduce the number of volatile loads.
15548         LLD->isVolatile() || RLD->isVolatile() ||
15549         // FIXME: If either is a pre/post inc/dec load,
15550         // we'd need to split out the address adjustment.
15551         LLD->isIndexed() || RLD->isIndexed() ||
15552         // If this is an EXTLOAD, the VT's must match.
15553         LLD->getMemoryVT() != RLD->getMemoryVT() ||
15554         // If this is an EXTLOAD, the kind of extension must match.
15555         (LLD->getExtensionType() != RLD->getExtensionType() &&
15556          // The only exception is if one of the extensions is anyext.
15557          LLD->getExtensionType() != ISD::EXTLOAD &&
15558          RLD->getExtensionType() != ISD::EXTLOAD) ||
15559         // FIXME: this discards src value information.  This is
15560         // over-conservative. It would be beneficial to be able to remember
15561         // both potential memory locations.  Since we are discarding
15562         // src value info, don't do the transformation if the memory
15563         // locations are not in the default address space.
15564         LLD->getPointerInfo().getAddrSpace() != 0 ||
15565         RLD->getPointerInfo().getAddrSpace() != 0 ||
15566         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15567                                       LLD->getBasePtr().getValueType()))
15568       return false;
15569
15570     // Check that the select condition doesn't reach either load.  If so,
15571     // folding this will induce a cycle into the DAG.  If not, this is safe to
15572     // xform, so create a select of the addresses.
15573     SDValue Addr;
15574     if (TheSelect->getOpcode() == ISD::SELECT) {
15575       SDNode *CondNode = TheSelect->getOperand(0).getNode();
15576       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15577           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15578         return false;
15579       // The loads must not depend on one another.
15580       if (LLD->isPredecessorOf(RLD) ||
15581           RLD->isPredecessorOf(LLD))
15582         return false;
15583       Addr = DAG.getSelect(SDLoc(TheSelect),
15584                            LLD->getBasePtr().getValueType(),
15585                            TheSelect->getOperand(0), LLD->getBasePtr(),
15586                            RLD->getBasePtr());
15587     } else {  // Otherwise SELECT_CC
15588       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15589       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15590
15591       if ((LLD->hasAnyUseOfValue(1) &&
15592            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15593           (RLD->hasAnyUseOfValue(1) &&
15594            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15595         return false;
15596
15597       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15598                          LLD->getBasePtr().getValueType(),
15599                          TheSelect->getOperand(0),
15600                          TheSelect->getOperand(1),
15601                          LLD->getBasePtr(), RLD->getBasePtr(),
15602                          TheSelect->getOperand(4));
15603     }
15604
15605     SDValue Load;
15606     // It is safe to replace the two loads if they have different alignments,
15607     // but the new load must be the minimum (most restrictive) alignment of the
15608     // inputs.
15609     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15610     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15611     if (!RLD->isInvariant())
15612       MMOFlags &= ~MachineMemOperand::MOInvariant;
15613     if (!RLD->isDereferenceable())
15614       MMOFlags &= ~MachineMemOperand::MODereferenceable;
15615     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15616       // FIXME: Discards pointer and AA info.
15617       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15618                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15619                          MMOFlags);
15620     } else {
15621       // FIXME: Discards pointer and AA info.
15622       Load = DAG.getExtLoad(
15623           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15624                                                   : LLD->getExtensionType(),
15625           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15626           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15627     }
15628
15629     // Users of the select now use the result of the load.
15630     CombineTo(TheSelect, Load);
15631
15632     // Users of the old loads now use the new load's chain.  We know the
15633     // old-load value is dead now.
15634     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15635     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15636     return true;
15637   }
15638
15639   return false;
15640 }
15641
15642 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15643 /// bitwise 'and'.
15644 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15645                                             SDValue N1, SDValue N2, SDValue N3,
15646                                             ISD::CondCode CC) {
15647   // If this is a select where the false operand is zero and the compare is a
15648   // check of the sign bit, see if we can perform the "gzip trick":
15649   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15650   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15651   EVT XType = N0.getValueType();
15652   EVT AType = N2.getValueType();
15653   if (!isNullConstant(N3) || !XType.bitsGE(AType))
15654     return SDValue();
15655
15656   // If the comparison is testing for a positive value, we have to invert
15657   // the sign bit mask, so only do that transform if the target has a bitwise
15658   // 'and not' instruction (the invert is free).
15659   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15660     // (X > -1) ? A : 0
15661     // (X >  0) ? X : 0 <-- This is canonical signed max.
15662     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15663       return SDValue();
15664   } else if (CC == ISD::SETLT) {
15665     // (X <  0) ? A : 0
15666     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
15667     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15668       return SDValue();
15669   } else {
15670     return SDValue();
15671   }
15672
15673   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15674   // constant.
15675   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15676   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15677   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15678     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15679     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15680     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15681     AddToWorklist(Shift.getNode());
15682
15683     if (XType.bitsGT(AType)) {
15684       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15685       AddToWorklist(Shift.getNode());
15686     }
15687
15688     if (CC == ISD::SETGT)
15689       Shift = DAG.getNOT(DL, Shift, AType);
15690
15691     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15692   }
15693
15694   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15695   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15696   AddToWorklist(Shift.getNode());
15697
15698   if (XType.bitsGT(AType)) {
15699     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15700     AddToWorklist(Shift.getNode());
15701   }
15702
15703   if (CC == ISD::SETGT)
15704     Shift = DAG.getNOT(DL, Shift, AType);
15705
15706   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15707 }
15708
15709 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15710 /// where 'cond' is the comparison specified by CC.
15711 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15712                                       SDValue N2, SDValue N3, ISD::CondCode CC,
15713                                       bool NotExtCompare) {
15714   // (x ? y : y) -> y.
15715   if (N2 == N3) return N2;
15716
15717   EVT VT = N2.getValueType();
15718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
15719   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15720
15721   // Determine if the condition we're dealing with is constant
15722   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
15723                               N0, N1, CC, DL, false);
15724   if (SCC.getNode()) AddToWorklist(SCC.getNode());
15725
15726   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
15727     // fold select_cc true, x, y -> x
15728     // fold select_cc false, x, y -> y
15729     return !SCCC->isNullValue() ? N2 : N3;
15730   }
15731
15732   // Check to see if we can simplify the select into an fabs node
15733   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
15734     // Allow either -0.0 or 0.0
15735     if (CFP->isZero()) {
15736       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
15737       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
15738           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
15739           N2 == N3.getOperand(0))
15740         return DAG.getNode(ISD::FABS, DL, VT, N0);
15741
15742       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
15743       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
15744           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
15745           N2.getOperand(0) == N3)
15746         return DAG.getNode(ISD::FABS, DL, VT, N3);
15747     }
15748   }
15749
15750   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
15751   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
15752   // in it.  This is a win when the constant is not otherwise available because
15753   // it replaces two constant pool loads with one.  We only do this if the FP
15754   // type is known to be legal, because if it isn't, then we are before legalize
15755   // types an we want the other legalization to happen first (e.g. to avoid
15756   // messing with soft float) and if the ConstantFP is not legal, because if
15757   // it is legal, we may not need to store the FP constant in a constant pool.
15758   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
15759     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
15760       if (TLI.isTypeLegal(N2.getValueType()) &&
15761           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
15762                TargetLowering::Legal &&
15763            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
15764            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
15765           // If both constants have multiple uses, then we won't need to do an
15766           // extra load, they are likely around in registers for other users.
15767           (TV->hasOneUse() || FV->hasOneUse())) {
15768         Constant *Elts[] = {
15769           const_cast<ConstantFP*>(FV->getConstantFPValue()),
15770           const_cast<ConstantFP*>(TV->getConstantFPValue())
15771         };
15772         Type *FPTy = Elts[0]->getType();
15773         const DataLayout &TD = DAG.getDataLayout();
15774
15775         // Create a ConstantArray of the two constants.
15776         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
15777         SDValue CPIdx =
15778             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
15779                                 TD.getPrefTypeAlignment(FPTy));
15780         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
15781
15782         // Get the offsets to the 0 and 1 element of the array so that we can
15783         // select between them.
15784         SDValue Zero = DAG.getIntPtrConstant(0, DL);
15785         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
15786         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
15787
15788         SDValue Cond = DAG.getSetCC(DL,
15789                                     getSetCCResultType(N0.getValueType()),
15790                                     N0, N1, CC);
15791         AddToWorklist(Cond.getNode());
15792         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
15793                                           Cond, One, Zero);
15794         AddToWorklist(CstOffset.getNode());
15795         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
15796                             CstOffset);
15797         AddToWorklist(CPIdx.getNode());
15798         return DAG.getLoad(
15799             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
15800             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
15801             Alignment);
15802       }
15803     }
15804
15805   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
15806     return V;
15807
15808   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
15809   // where y is has a single bit set.
15810   // A plaintext description would be, we can turn the SELECT_CC into an AND
15811   // when the condition can be materialized as an all-ones register.  Any
15812   // single bit-test can be materialized as an all-ones register with
15813   // shift-left and shift-right-arith.
15814   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
15815       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
15816     SDValue AndLHS = N0->getOperand(0);
15817     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15818     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
15819       // Shift the tested bit over the sign bit.
15820       const APInt &AndMask = ConstAndRHS->getAPIntValue();
15821       SDValue ShlAmt =
15822         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
15823                         getShiftAmountTy(AndLHS.getValueType()));
15824       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
15825
15826       // Now arithmetic right shift it all the way over, so the result is either
15827       // all-ones, or zero.
15828       SDValue ShrAmt =
15829         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
15830                         getShiftAmountTy(Shl.getValueType()));
15831       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
15832
15833       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
15834     }
15835   }
15836
15837   // fold select C, 16, 0 -> shl C, 4
15838   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
15839       TLI.getBooleanContents(N0.getValueType()) ==
15840           TargetLowering::ZeroOrOneBooleanContent) {
15841
15842     // If the caller doesn't want us to simplify this into a zext of a compare,
15843     // don't do it.
15844     if (NotExtCompare && N2C->isOne())
15845       return SDValue();
15846
15847     // Get a SetCC of the condition
15848     // NOTE: Don't create a SETCC if it's not legal on this target.
15849     if (!LegalOperations ||
15850         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
15851       SDValue Temp, SCC;
15852       // cast from setcc result type to select result type
15853       if (LegalTypes) {
15854         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
15855                             N0, N1, CC);
15856         if (N2.getValueType().bitsLT(SCC.getValueType()))
15857           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
15858                                         N2.getValueType());
15859         else
15860           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15861                              N2.getValueType(), SCC);
15862       } else {
15863         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
15864         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15865                            N2.getValueType(), SCC);
15866       }
15867
15868       AddToWorklist(SCC.getNode());
15869       AddToWorklist(Temp.getNode());
15870
15871       if (N2C->isOne())
15872         return Temp;
15873
15874       // shl setcc result by log2 n2c
15875       return DAG.getNode(
15876           ISD::SHL, DL, N2.getValueType(), Temp,
15877           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
15878                           getShiftAmountTy(Temp.getValueType())));
15879     }
15880   }
15881
15882   // Check to see if this is an integer abs.
15883   // select_cc setg[te] X,  0,  X, -X ->
15884   // select_cc setgt    X, -1,  X, -X ->
15885   // select_cc setl[te] X,  0, -X,  X ->
15886   // select_cc setlt    X,  1, -X,  X ->
15887   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
15888   if (N1C) {
15889     ConstantSDNode *SubC = nullptr;
15890     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
15891          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
15892         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
15893       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
15894     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
15895               (N1C->isOne() && CC == ISD::SETLT)) &&
15896              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
15897       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
15898
15899     EVT XType = N0.getValueType();
15900     if (SubC && SubC->isNullValue() && XType.isInteger()) {
15901       SDLoc DL(N0);
15902       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
15903                                   N0,
15904                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
15905                                          getShiftAmountTy(N0.getValueType())));
15906       SDValue Add = DAG.getNode(ISD::ADD, DL,
15907                                 XType, N0, Shift);
15908       AddToWorklist(Shift.getNode());
15909       AddToWorklist(Add.getNode());
15910       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
15911     }
15912   }
15913
15914   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
15915   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
15916   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
15917   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
15918   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
15919   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
15920   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
15921   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
15922   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15923     SDValue ValueOnZero = N2;
15924     SDValue Count = N3;
15925     // If the condition is NE instead of E, swap the operands.
15926     if (CC == ISD::SETNE)
15927       std::swap(ValueOnZero, Count);
15928     // Check if the value on zero is a constant equal to the bits in the type.
15929     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
15930       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
15931         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
15932         // legal, combine to just cttz.
15933         if ((Count.getOpcode() == ISD::CTTZ ||
15934              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
15935             N0 == Count.getOperand(0) &&
15936             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
15937           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
15938         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
15939         // legal, combine to just ctlz.
15940         if ((Count.getOpcode() == ISD::CTLZ ||
15941              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
15942             N0 == Count.getOperand(0) &&
15943             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
15944           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
15945       }
15946     }
15947   }
15948
15949   return SDValue();
15950 }
15951
15952 /// This is a stub for TargetLowering::SimplifySetCC.
15953 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
15954                                    ISD::CondCode Cond, const SDLoc &DL,
15955                                    bool foldBooleans) {
15956   TargetLowering::DAGCombinerInfo
15957     DagCombineInfo(DAG, Level, false, this);
15958   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
15959 }
15960
15961 /// Given an ISD::SDIV node expressing a divide by constant, return
15962 /// a DAG expression to select that will generate the same value by multiplying
15963 /// by a magic number.
15964 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15965 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
15966   // when optimising for minimum size, we don't want to expand a div to a mul
15967   // and a shift.
15968   if (DAG.getMachineFunction().getFunction()->optForMinSize())
15969     return SDValue();
15970
15971   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15972   if (!C)
15973     return SDValue();
15974
15975   // Avoid division by zero.
15976   if (C->isNullValue())
15977     return SDValue();
15978
15979   std::vector<SDNode*> Built;
15980   SDValue S =
15981       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15982
15983   for (SDNode *N : Built)
15984     AddToWorklist(N);
15985   return S;
15986 }
15987
15988 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
15989 /// DAG expression that will generate the same value by right shifting.
15990 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
15991   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15992   if (!C)
15993     return SDValue();
15994
15995   // Avoid division by zero.
15996   if (C->isNullValue())
15997     return SDValue();
15998
15999   std::vector<SDNode *> Built;
16000   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16001
16002   for (SDNode *N : Built)
16003     AddToWorklist(N);
16004   return S;
16005 }
16006
16007 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16008 /// expression that will generate the same value by multiplying by a magic
16009 /// number.
16010 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16011 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16012   // when optimising for minimum size, we don't want to expand a div to a mul
16013   // and a shift.
16014   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16015     return SDValue();
16016
16017   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16018   if (!C)
16019     return SDValue();
16020
16021   // Avoid division by zero.
16022   if (C->isNullValue())
16023     return SDValue();
16024
16025   std::vector<SDNode*> Built;
16026   SDValue S =
16027       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16028
16029   for (SDNode *N : Built)
16030     AddToWorklist(N);
16031   return S;
16032 }
16033
16034 /// Determines the LogBase2 value for a non-null input value using the
16035 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16036 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16037   EVT VT = V.getValueType();
16038   unsigned EltBits = VT.getScalarSizeInBits();
16039   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16040   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16041   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16042   return LogBase2;
16043 }
16044
16045 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16046 /// For the reciprocal, we need to find the zero of the function:
16047 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16048 ///     =>
16049 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16050 ///     does not require additional intermediate precision]
16051 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16052   if (Level >= AfterLegalizeDAG)
16053     return SDValue();
16054
16055   // TODO: Handle half and/or extended types?
16056   EVT VT = Op.getValueType();
16057   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16058     return SDValue();
16059
16060   // If estimates are explicitly disabled for this function, we're done.
16061   MachineFunction &MF = DAG.getMachineFunction();
16062   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16063   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16064     return SDValue();
16065
16066   // Estimates may be explicitly enabled for this type with a custom number of
16067   // refinement steps.
16068   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16069   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16070     AddToWorklist(Est.getNode());
16071
16072     if (Iterations) {
16073       EVT VT = Op.getValueType();
16074       SDLoc DL(Op);
16075       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16076
16077       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16078       for (int i = 0; i < Iterations; ++i) {
16079         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16080         AddToWorklist(NewEst.getNode());
16081
16082         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16083         AddToWorklist(NewEst.getNode());
16084
16085         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16086         AddToWorklist(NewEst.getNode());
16087
16088         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16089         AddToWorklist(Est.getNode());
16090       }
16091     }
16092     return Est;
16093   }
16094
16095   return SDValue();
16096 }
16097
16098 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16099 /// For the reciprocal sqrt, we need to find the zero of the function:
16100 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16101 ///     =>
16102 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16103 /// As a result, we precompute A/2 prior to the iteration loop.
16104 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16105                                          unsigned Iterations,
16106                                          SDNodeFlags Flags, bool Reciprocal) {
16107   EVT VT = Arg.getValueType();
16108   SDLoc DL(Arg);
16109   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16110
16111   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16112   // this entire sequence requires only one FP constant.
16113   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16114   AddToWorklist(HalfArg.getNode());
16115
16116   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16117   AddToWorklist(HalfArg.getNode());
16118
16119   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16120   for (unsigned i = 0; i < Iterations; ++i) {
16121     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16122     AddToWorklist(NewEst.getNode());
16123
16124     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16125     AddToWorklist(NewEst.getNode());
16126
16127     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16128     AddToWorklist(NewEst.getNode());
16129
16130     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16131     AddToWorklist(Est.getNode());
16132   }
16133
16134   // If non-reciprocal square root is requested, multiply the result by Arg.
16135   if (!Reciprocal) {
16136     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16137     AddToWorklist(Est.getNode());
16138   }
16139
16140   return Est;
16141 }
16142
16143 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16144 /// For the reciprocal sqrt, we need to find the zero of the function:
16145 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16146 ///     =>
16147 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16148 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16149                                          unsigned Iterations,
16150                                          SDNodeFlags Flags, bool Reciprocal) {
16151   EVT VT = Arg.getValueType();
16152   SDLoc DL(Arg);
16153   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16154   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16155
16156   // This routine must enter the loop below to work correctly
16157   // when (Reciprocal == false).
16158   assert(Iterations > 0);
16159
16160   // Newton iterations for reciprocal square root:
16161   // E = (E * -0.5) * ((A * E) * E + -3.0)
16162   for (unsigned i = 0; i < Iterations; ++i) {
16163     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16164     AddToWorklist(AE.getNode());
16165
16166     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16167     AddToWorklist(AEE.getNode());
16168
16169     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16170     AddToWorklist(RHS.getNode());
16171
16172     // When calculating a square root at the last iteration build:
16173     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16174     // (notice a common subexpression)
16175     SDValue LHS;
16176     if (Reciprocal || (i + 1) < Iterations) {
16177       // RSQRT: LHS = (E * -0.5)
16178       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16179     } else {
16180       // SQRT: LHS = (A * E) * -0.5
16181       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16182     }
16183     AddToWorklist(LHS.getNode());
16184
16185     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16186     AddToWorklist(Est.getNode());
16187   }
16188
16189   return Est;
16190 }
16191
16192 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16193 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16194 /// Op can be zero.
16195 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16196                                            bool Reciprocal) {
16197   if (Level >= AfterLegalizeDAG)
16198     return SDValue();
16199
16200   // TODO: Handle half and/or extended types?
16201   EVT VT = Op.getValueType();
16202   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16203     return SDValue();
16204
16205   // If estimates are explicitly disabled for this function, we're done.
16206   MachineFunction &MF = DAG.getMachineFunction();
16207   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16208   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16209     return SDValue();
16210
16211   // Estimates may be explicitly enabled for this type with a custom number of
16212   // refinement steps.
16213   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16214
16215   bool UseOneConstNR = false;
16216   if (SDValue Est =
16217       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16218                           Reciprocal)) {
16219     AddToWorklist(Est.getNode());
16220
16221     if (Iterations) {
16222       Est = UseOneConstNR
16223             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16224             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16225
16226       if (!Reciprocal) {
16227         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16228         // Select out this case and force the answer to 0.0.
16229         EVT VT = Op.getValueType();
16230         SDLoc DL(Op);
16231
16232         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16233         EVT CCVT = getSetCCResultType(VT);
16234         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16235         AddToWorklist(ZeroCmp.getNode());
16236
16237         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16238                           ZeroCmp, FPZero, Est);
16239         AddToWorklist(Est.getNode());
16240       }
16241     }
16242     return Est;
16243   }
16244
16245   return SDValue();
16246 }
16247
16248 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16249   return buildSqrtEstimateImpl(Op, Flags, true);
16250 }
16251
16252 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16253   return buildSqrtEstimateImpl(Op, Flags, false);
16254 }
16255
16256 /// Return true if base is a frame index, which is known not to alias with
16257 /// anything but itself.  Provides base object and offset as results.
16258 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16259                            const GlobalValue *&GV, const void *&CV) {
16260   // Assume it is a primitive operation.
16261   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16262
16263   // If it's an adding a simple constant then integrate the offset.
16264   if (Base.getOpcode() == ISD::ADD) {
16265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16266       Base = Base.getOperand(0);
16267       Offset += C->getSExtValue();
16268     }
16269   }
16270
16271   // Return the underlying GlobalValue, and update the Offset.  Return false
16272   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16273   // by multiple nodes with different offsets.
16274   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16275     GV = G->getGlobal();
16276     Offset += G->getOffset();
16277     return false;
16278   }
16279
16280   // Return the underlying Constant value, and update the Offset.  Return false
16281   // for ConstantSDNodes since the same constant pool entry may be represented
16282   // by multiple nodes with different offsets.
16283   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16284     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16285                                          : (const void *)C->getConstVal();
16286     Offset += C->getOffset();
16287     return false;
16288   }
16289   // If it's any of the following then it can't alias with anything but itself.
16290   return isa<FrameIndexSDNode>(Base);
16291 }
16292
16293 /// Return true if there is any possibility that the two addresses overlap.
16294 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16295   // If they are the same then they must be aliases.
16296   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16297
16298   // If they are both volatile then they cannot be reordered.
16299   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16300
16301   // If one operation reads from invariant memory, and the other may store, they
16302   // cannot alias. These should really be checking the equivalent of mayWrite,
16303   // but it only matters for memory nodes other than load /store.
16304   if (Op0->isInvariant() && Op1->writeMem())
16305     return false;
16306
16307   if (Op1->isInvariant() && Op0->writeMem())
16308     return false;
16309
16310   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16311   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16312
16313   // Check for BaseIndexOffset matching.
16314   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16315   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16316   if (BasePtr0.equalBaseIndex(BasePtr1))
16317     return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) ||
16318              (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset));
16319
16320   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16321   // modified to use BaseIndexOffset.
16322
16323   // Gather base node and offset information.
16324   SDValue Base0, Base1;
16325   int64_t Offset0, Offset1;
16326   const GlobalValue *GV0, *GV1;
16327   const void *CV0, *CV1;
16328   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16329                                       Base0, Offset0, GV0, CV0);
16330   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16331                                       Base1, Offset1, GV1, CV1);
16332
16333   // If they have the same base address, then check to see if they overlap.
16334   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16335     return !((Offset0 + NumBytes0) <= Offset1 ||
16336              (Offset1 + NumBytes1) <= Offset0);
16337
16338   // It is possible for different frame indices to alias each other, mostly
16339   // when tail call optimization reuses return address slots for arguments.
16340   // To catch this case, look up the actual index of frame indices to compute
16341   // the real alias relationship.
16342   if (IsFrameIndex0 && IsFrameIndex1) {
16343     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16344     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16345     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16346     return !((Offset0 + NumBytes0) <= Offset1 ||
16347              (Offset1 + NumBytes1) <= Offset0);
16348   }
16349
16350   // Otherwise, if we know what the bases are, and they aren't identical, then
16351   // we know they cannot alias.
16352   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16353     return false;
16354
16355   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16356   // compared to the size and offset of the access, we may be able to prove they
16357   // do not alias. This check is conservative for now to catch cases created by
16358   // splitting vector types.
16359   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16360   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16361   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16362   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16363   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16364       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16365     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16366     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16367
16368     // There is no overlap between these relatively aligned accesses of similar
16369     // size. Return no alias.
16370     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16371         (OffAlign1 + NumBytes1) <= OffAlign0)
16372       return false;
16373   }
16374
16375   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16376                    ? CombinerGlobalAA
16377                    : DAG.getSubtarget().useAA();
16378 #ifndef NDEBUG
16379   if (CombinerAAOnlyFunc.getNumOccurrences() &&
16380       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16381     UseAA = false;
16382 #endif
16383
16384   if (UseAA && AA &&
16385       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16386     // Use alias analysis information.
16387     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16388     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16389     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16390     AliasResult AAResult =
16391         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16392                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16393                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16394                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
16395     if (AAResult == NoAlias)
16396       return false;
16397   }
16398
16399   // Otherwise we have to assume they alias.
16400   return true;
16401 }
16402
16403 /// Walk up chain skipping non-aliasing memory nodes,
16404 /// looking for aliasing nodes and adding them to the Aliases vector.
16405 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16406                                    SmallVectorImpl<SDValue> &Aliases) {
16407   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
16408   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
16409
16410   // Get alias information for node.
16411   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16412
16413   // Starting off.
16414   Chains.push_back(OriginalChain);
16415   unsigned Depth = 0;
16416
16417   // Look at each chain and determine if it is an alias.  If so, add it to the
16418   // aliases list.  If not, then continue up the chain looking for the next
16419   // candidate.
16420   while (!Chains.empty()) {
16421     SDValue Chain = Chains.pop_back_val();
16422
16423     // For TokenFactor nodes, look at each operand and only continue up the
16424     // chain until we reach the depth limit.
16425     //
16426     // FIXME: The depth check could be made to return the last non-aliasing
16427     // chain we found before we hit a tokenfactor rather than the original
16428     // chain.
16429     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16430       Aliases.clear();
16431       Aliases.push_back(OriginalChain);
16432       return;
16433     }
16434
16435     // Don't bother if we've been before.
16436     if (!Visited.insert(Chain.getNode()).second)
16437       continue;
16438
16439     switch (Chain.getOpcode()) {
16440     case ISD::EntryToken:
16441       // Entry token is ideal chain operand, but handled in FindBetterChain.
16442       break;
16443
16444     case ISD::LOAD:
16445     case ISD::STORE: {
16446       // Get alias information for Chain.
16447       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16448           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16449
16450       // If chain is alias then stop here.
16451       if (!(IsLoad && IsOpLoad) &&
16452           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16453         Aliases.push_back(Chain);
16454       } else {
16455         // Look further up the chain.
16456         Chains.push_back(Chain.getOperand(0));
16457         ++Depth;
16458       }
16459       break;
16460     }
16461
16462     case ISD::TokenFactor:
16463       // We have to check each of the operands of the token factor for "small"
16464       // token factors, so we queue them up.  Adding the operands to the queue
16465       // (stack) in reverse order maintains the original order and increases the
16466       // likelihood that getNode will find a matching token factor (CSE.)
16467       if (Chain.getNumOperands() > 16) {
16468         Aliases.push_back(Chain);
16469         break;
16470       }
16471       for (unsigned n = Chain.getNumOperands(); n;)
16472         Chains.push_back(Chain.getOperand(--n));
16473       ++Depth;
16474       break;
16475
16476     case ISD::CopyFromReg:
16477       // Forward past CopyFromReg.
16478       Chains.push_back(Chain.getOperand(0));
16479       ++Depth;
16480       break;
16481
16482     default:
16483       // For all other instructions we will just have to take what we can get.
16484       Aliases.push_back(Chain);
16485       break;
16486     }
16487   }
16488 }
16489
16490 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16491 /// (aliasing node.)
16492 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16493   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
16494
16495   // Accumulate all the aliases to this node.
16496   GatherAllAliases(N, OldChain, Aliases);
16497
16498   // If no operands then chain to entry token.
16499   if (Aliases.size() == 0)
16500     return DAG.getEntryNode();
16501
16502   // If a single operand then chain to it.  We don't need to revisit it.
16503   if (Aliases.size() == 1)
16504     return Aliases[0];
16505
16506   // Construct a custom tailored token factor.
16507   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16508 }
16509
16510 // This function tries to collect a bunch of potentially interesting
16511 // nodes to improve the chains of, all at once. This might seem
16512 // redundant, as this function gets called when visiting every store
16513 // node, so why not let the work be done on each store as it's visited?
16514 //
16515 // I believe this is mainly important because MergeConsecutiveStores
16516 // is unable to deal with merging stores of different sizes, so unless
16517 // we improve the chains of all the potential candidates up-front
16518 // before running MergeConsecutiveStores, it might only see some of
16519 // the nodes that will eventually be candidates, and then not be able
16520 // to go from a partially-merged state to the desired final
16521 // fully-merged state.
16522 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16523   // This holds the base pointer, index, and the offset in bytes from the base
16524   // pointer.
16525   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16526
16527   // We must have a base and an offset.
16528   if (!BasePtr.Base.getNode())
16529     return false;
16530
16531   // Do not handle stores to undef base pointers.
16532   if (BasePtr.Base.isUndef())
16533     return false;
16534
16535   SmallVector<StoreSDNode *, 8> ChainedStores;
16536   ChainedStores.push_back(St);
16537
16538   // Walk up the chain and look for nodes with offsets from the same
16539   // base pointer. Stop when reaching an instruction with a different kind
16540   // or instruction which has a different base pointer.
16541   StoreSDNode *Index = St;
16542   while (Index) {
16543     // If the chain has more than one use, then we can't reorder the mem ops.
16544     if (Index != St && !SDValue(Index, 0)->hasOneUse())
16545       break;
16546
16547     if (Index->isVolatile() || Index->isIndexed())
16548       break;
16549
16550     // Find the base pointer and offset for this memory node.
16551     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16552
16553     // Check that the base pointer is the same as the original one.
16554     if (!Ptr.equalBaseIndex(BasePtr))
16555       break;
16556
16557     // Walk up the chain to find the next store node, ignoring any
16558     // intermediate loads. Any other kind of node will halt the loop.
16559     SDNode *NextInChain = Index->getChain().getNode();
16560     while (true) {
16561       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16562         // We found a store node. Use it for the next iteration.
16563         if (STn->isVolatile() || STn->isIndexed()) {
16564           Index = nullptr;
16565           break;
16566         }
16567         ChainedStores.push_back(STn);
16568         Index = STn;
16569         break;
16570       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16571         NextInChain = Ldn->getChain().getNode();
16572         continue;
16573       } else {
16574         Index = nullptr;
16575         break;
16576       }
16577     } // end while
16578   }
16579
16580   // At this point, ChainedStores lists all of the Store nodes
16581   // reachable by iterating up through chain nodes matching the above
16582   // conditions.  For each such store identified, try to find an
16583   // earlier chain to attach the store to which won't violate the
16584   // required ordering.
16585   bool MadeChangeToSt = false;
16586   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16587
16588   for (StoreSDNode *ChainedStore : ChainedStores) {
16589     SDValue Chain = ChainedStore->getChain();
16590     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16591
16592     if (Chain != BetterChain) {
16593       if (ChainedStore == St)
16594         MadeChangeToSt = true;
16595       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16596     }
16597   }
16598
16599   // Do all replacements after finding the replacements to make to avoid making
16600   // the chains more complicated by introducing new TokenFactors.
16601   for (auto Replacement : BetterChains)
16602     replaceStoreChain(Replacement.first, Replacement.second);
16603
16604   return MadeChangeToSt;
16605 }
16606
16607 /// This is the entry point for the file.
16608 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
16609                            CodeGenOpt::Level OptLevel) {
16610   /// This is the main entry point to this class.
16611   DAGCombiner(*this, AA, OptLevel).Run(Level);
16612 }