a1edb29e4860ba3605791d7bacf5429f857a2ca8
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     /// Replaces all uses of the results of one DAG node with new values.
160     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
161                       bool AddTo = true);
162
163     /// Replaces all uses of the results of one DAG node with new values.
164     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165       return CombineTo(N, &Res, 1, AddTo);
166     }
167
168     /// Replaces all uses of the results of one DAG node with new values.
169     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
170                       bool AddTo = true) {
171       SDValue To[] = { Res0, Res1 };
172       return CombineTo(N, To, 2, AddTo);
173     }
174
175     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176
177   private:
178
179     /// Check the specified integer node value to see if it can be simplified or
180     /// if things it uses can be simplified by bit propagation.
181     /// If so, return true.
182     bool SimplifyDemandedBits(SDValue Op) {
183       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184       APInt Demanded = APInt::getAllOnesValue(BitWidth);
185       return SimplifyDemandedBits(Op, Demanded);
186     }
187
188     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
189
190     bool CombineToPreIndexedLoadStore(SDNode *N);
191     bool CombineToPostIndexedLoadStore(SDNode *N);
192     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193     bool SliceUpLoad(SDNode *N);
194
195     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
196     ///   load.
197     ///
198     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200     /// \param EltNo index of the vector element to load.
201     /// \param OriginalLoad load that EVE came from to be replaced.
202     /// \returns EVE on success SDValue() on failure.
203     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue PromoteIntBinOp(SDValue Op);
210     SDValue PromoteIntShiftOp(SDValue Op);
211     SDValue PromoteExtend(SDValue Op);
212     bool PromoteLoad(SDValue Op);
213
214     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216                          ISD::NodeType ExtType);
217
218     /// Call the node-specific routine that knows how to fold each
219     /// particular type of node. If that doesn't do anything, try the
220     /// target-specific DAG combines.
221     SDValue combine(SDNode *N);
222
223     // Visitation implementation - Implement dag node combining for different
224     // node types.  The semantics are as follows:
225     // Return Value:
226     //   SDValue.getNode() == 0 - No change was made
227     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
228     //   otherwise              - N should be replaced by the returned Operand.
229     //
230     SDValue visitTokenFactor(SDNode *N);
231     SDValue visitMERGE_VALUES(SDNode *N);
232     SDValue visitADD(SDNode *N);
233     SDValue visitSUB(SDNode *N);
234     SDValue visitADDC(SDNode *N);
235     SDValue visitSUBC(SDNode *N);
236     SDValue visitADDE(SDNode *N);
237     SDValue visitSUBE(SDNode *N);
238     SDValue visitMUL(SDNode *N);
239     SDValue useDivRem(SDNode *N);
240     SDValue visitSDIV(SDNode *N);
241     SDValue visitUDIV(SDNode *N);
242     SDValue visitREM(SDNode *N);
243     SDValue visitMULHU(SDNode *N);
244     SDValue visitMULHS(SDNode *N);
245     SDValue visitSMUL_LOHI(SDNode *N);
246     SDValue visitUMUL_LOHI(SDNode *N);
247     SDValue visitSMULO(SDNode *N);
248     SDValue visitUMULO(SDNode *N);
249     SDValue visitIMINMAX(SDNode *N);
250     SDValue visitAND(SDNode *N);
251     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitOR(SDNode *N);
253     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254     SDValue visitXOR(SDNode *N);
255     SDValue SimplifyVBinOp(SDNode *N);
256     SDValue visitSHL(SDNode *N);
257     SDValue visitSRA(SDNode *N);
258     SDValue visitSRL(SDNode *N);
259     SDValue visitRotate(SDNode *N);
260     SDValue visitBSWAP(SDNode *N);
261     SDValue visitCTLZ(SDNode *N);
262     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTTZ(SDNode *N);
264     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTPOP(SDNode *N);
266     SDValue visitSELECT(SDNode *N);
267     SDValue visitVSELECT(SDNode *N);
268     SDValue visitSELECT_CC(SDNode *N);
269     SDValue visitSETCC(SDNode *N);
270     SDValue visitSIGN_EXTEND(SDNode *N);
271     SDValue visitZERO_EXTEND(SDNode *N);
272     SDValue visitANY_EXTEND(SDNode *N);
273     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
274     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
275     SDValue visitTRUNCATE(SDNode *N);
276     SDValue visitBITCAST(SDNode *N);
277     SDValue visitBUILD_PAIR(SDNode *N);
278     SDValue visitFADD(SDNode *N);
279     SDValue visitFSUB(SDNode *N);
280     SDValue visitFMUL(SDNode *N);
281     SDValue visitFMA(SDNode *N);
282     SDValue visitFDIV(SDNode *N);
283     SDValue visitFREM(SDNode *N);
284     SDValue visitFSQRT(SDNode *N);
285     SDValue visitFCOPYSIGN(SDNode *N);
286     SDValue visitSINT_TO_FP(SDNode *N);
287     SDValue visitUINT_TO_FP(SDNode *N);
288     SDValue visitFP_TO_SINT(SDNode *N);
289     SDValue visitFP_TO_UINT(SDNode *N);
290     SDValue visitFP_ROUND(SDNode *N);
291     SDValue visitFP_ROUND_INREG(SDNode *N);
292     SDValue visitFP_EXTEND(SDNode *N);
293     SDValue visitFNEG(SDNode *N);
294     SDValue visitFABS(SDNode *N);
295     SDValue visitFCEIL(SDNode *N);
296     SDValue visitFTRUNC(SDNode *N);
297     SDValue visitFFLOOR(SDNode *N);
298     SDValue visitFMINNUM(SDNode *N);
299     SDValue visitFMAXNUM(SDNode *N);
300     SDValue visitBRCOND(SDNode *N);
301     SDValue visitBR_CC(SDNode *N);
302     SDValue visitLOAD(SDNode *N);
303
304     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
305     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
306
307     SDValue visitSTORE(SDNode *N);
308     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
309     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
310     SDValue visitBUILD_VECTOR(SDNode *N);
311     SDValue visitCONCAT_VECTORS(SDNode *N);
312     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
313     SDValue visitVECTOR_SHUFFLE(SDNode *N);
314     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
315     SDValue visitINSERT_SUBVECTOR(SDNode *N);
316     SDValue visitMLOAD(SDNode *N);
317     SDValue visitMSTORE(SDNode *N);
318     SDValue visitMGATHER(SDNode *N);
319     SDValue visitMSCATTER(SDNode *N);
320     SDValue visitFP_TO_FP16(SDNode *N);
321     SDValue visitFP16_TO_FP(SDNode *N);
322
323     SDValue visitFADDForFMACombine(SDNode *N);
324     SDValue visitFSUBForFMACombine(SDNode *N);
325     SDValue visitFMULForFMACombine(SDNode *N);
326
327     SDValue XformToShuffleWithZero(SDNode *N);
328     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
329
330     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
331
332     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
333     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
334     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
335     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
336                              SDValue N3, ISD::CondCode CC,
337                              bool NotExtCompare = false);
338     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
339                           SDLoc DL, bool foldBooleans = true);
340
341     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
342                            SDValue &CC) const;
343     bool isOneUseSetCC(SDValue N) const;
344
345     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
346                                          unsigned HiOp);
347     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
348     SDValue CombineExtLoad(SDNode *N);
349     SDValue combineRepeatedFPDivisors(SDNode *N);
350     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
351     SDValue BuildSDIV(SDNode *N);
352     SDValue BuildSDIVPow2(SDNode *N);
353     SDValue BuildUDIV(SDNode *N);
354     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
355     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
356     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
357                                  SDNodeFlags *Flags);
358     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
359                                  SDNodeFlags *Flags);
360     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
361                                bool DemandHighBits = true);
362     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
363     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
364                               SDValue InnerPos, SDValue InnerNeg,
365                               unsigned PosOpcode, unsigned NegOpcode,
366                               SDLoc DL);
367     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
368     SDValue ReduceLoadWidth(SDNode *N);
369     SDValue ReduceLoadOpStoreWidth(SDNode *N);
370     SDValue TransformFPLoadStorePair(SDNode *N);
371     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
372     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
373
374     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
375
376     /// Walk up chain skipping non-aliasing memory nodes,
377     /// looking for aliasing nodes and adding them to the Aliases vector.
378     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
379                           SmallVectorImpl<SDValue> &Aliases);
380
381     /// Return true if there is any possibility that the two addresses overlap.
382     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
383
384     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
385     /// chain (aliasing node.)
386     SDValue FindBetterChain(SDNode *N, SDValue Chain);
387
388     /// Do FindBetterChain for a store and any possibly adjacent stores on
389     /// consecutive chains.
390     bool findBetterNeighborChains(StoreSDNode *St);
391
392     /// Holds a pointer to an LSBaseSDNode as well as information on where it
393     /// is located in a sequence of memory operations connected by a chain.
394     struct MemOpLink {
395       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
396       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
397       // Ptr to the mem node.
398       LSBaseSDNode *MemNode;
399       // Offset from the base ptr.
400       int64_t OffsetFromBase;
401       // What is the sequence number of this mem node.
402       // Lowest mem operand in the DAG starts at zero.
403       unsigned SequenceNum;
404     };
405
406     /// This is a helper function for visitMUL to check the profitability
407     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
408     /// MulNode is the original multiply, AddNode is (add x, c1),
409     /// and ConstNode is c2.
410     bool isMulAddWithConstProfitable(SDNode *MulNode,
411                                      SDValue &AddNode,
412                                      SDValue &ConstNode);
413
414     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
415     /// constant build_vector of the stored constant values in Stores.
416     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
417                                          SDLoc SL,
418                                          ArrayRef<MemOpLink> Stores,
419                                          SmallVectorImpl<SDValue> &Chains,
420                                          EVT Ty) const;
421
422     /// This is a helper function for MergeConsecutiveStores. When the source
423     /// elements of the consecutive stores are all constants or all extracted
424     /// vector elements, try to merge them into one larger store.
425     /// \return True if a merged store was created.
426     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
427                                          EVT MemVT, unsigned NumStores,
428                                          bool IsConstantSrc, bool UseVector);
429
430     /// This is a helper function for MergeConsecutiveStores.
431     /// Stores that may be merged are placed in StoreNodes.
432     /// Loads that may alias with those stores are placed in AliasLoadNodes.
433     void getStoreMergeAndAliasCandidates(
434         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
435         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
436
437     /// Merge consecutive store operations into a wide store.
438     /// This optimization uses wide integers or vectors when possible.
439     /// \return True if some memory operations were changed.
440     bool MergeConsecutiveStores(StoreSDNode *N);
441
442     /// \brief Try to transform a truncation where C is a constant:
443     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
444     ///
445     /// \p N needs to be a truncation and its first operand an AND. Other
446     /// requirements are checked by the function (e.g. that trunc is
447     /// single-use) and if missed an empty SDValue is returned.
448     SDValue distributeTruncateThroughAnd(SDNode *N);
449
450   public:
451     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
452         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
453           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
454       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
455     }
456
457     /// Runs the dag combiner on all nodes in the work list
458     void Run(CombineLevel AtLevel);
459
460     SelectionDAG &getDAG() const { return DAG; }
461
462     /// Returns a type large enough to hold any valid shift amount - before type
463     /// legalization these can be huge.
464     EVT getShiftAmountTy(EVT LHSTy) {
465       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
466       if (LHSTy.isVector())
467         return LHSTy;
468       auto &DL = DAG.getDataLayout();
469       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
470                         : TLI.getPointerTy(DL);
471     }
472
473     /// This method returns true if we are running before type legalization or
474     /// if the specified VT is legal.
475     bool isTypeLegal(const EVT &VT) {
476       if (!LegalTypes) return true;
477       return TLI.isTypeLegal(VT);
478     }
479
480     /// Convenience wrapper around TargetLowering::getSetCCResultType
481     EVT getSetCCResultType(EVT VT) const {
482       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
483     }
484   };
485 }
486
487
488 namespace {
489 /// This class is a DAGUpdateListener that removes any deleted
490 /// nodes from the worklist.
491 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
492   DAGCombiner &DC;
493 public:
494   explicit WorklistRemover(DAGCombiner &dc)
495     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
496
497   void NodeDeleted(SDNode *N, SDNode *E) override {
498     DC.removeFromWorklist(N);
499   }
500 };
501 }
502
503 //===----------------------------------------------------------------------===//
504 //  TargetLowering::DAGCombinerInfo implementation
505 //===----------------------------------------------------------------------===//
506
507 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
508   ((DAGCombiner*)DC)->AddToWorklist(N);
509 }
510
511 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
512   ((DAGCombiner*)DC)->removeFromWorklist(N);
513 }
514
515 SDValue TargetLowering::DAGCombinerInfo::
516 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
517   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
518 }
519
520 SDValue TargetLowering::DAGCombinerInfo::
521 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
522   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
523 }
524
525
526 SDValue TargetLowering::DAGCombinerInfo::
527 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
528   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
529 }
530
531 void TargetLowering::DAGCombinerInfo::
532 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
533   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
534 }
535
536 //===----------------------------------------------------------------------===//
537 // Helper Functions
538 //===----------------------------------------------------------------------===//
539
540 void DAGCombiner::deleteAndRecombine(SDNode *N) {
541   removeFromWorklist(N);
542
543   // If the operands of this node are only used by the node, they will now be
544   // dead. Make sure to re-visit them and recursively delete dead nodes.
545   for (const SDValue &Op : N->ops())
546     // For an operand generating multiple values, one of the values may
547     // become dead allowing further simplification (e.g. split index
548     // arithmetic from an indexed load).
549     if (Op->hasOneUse() || Op->getNumValues() > 1)
550       AddToWorklist(Op.getNode());
551
552   DAG.DeleteNode(N);
553 }
554
555 /// Return 1 if we can compute the negated form of the specified expression for
556 /// the same cost as the expression itself, or 2 if we can compute the negated
557 /// form more cheaply than the expression itself.
558 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
559                                const TargetLowering &TLI,
560                                const TargetOptions *Options,
561                                unsigned Depth = 0) {
562   // fneg is removable even if it has multiple uses.
563   if (Op.getOpcode() == ISD::FNEG) return 2;
564
565   // Don't allow anything with multiple uses.
566   if (!Op.hasOneUse()) return 0;
567
568   // Don't recurse exponentially.
569   if (Depth > 6) return 0;
570
571   switch (Op.getOpcode()) {
572   default: return false;
573   case ISD::ConstantFP:
574     // Don't invert constant FP values after legalize.  The negated constant
575     // isn't necessarily legal.
576     return LegalOperations ? 0 : 1;
577   case ISD::FADD:
578     // FIXME: determine better conditions for this xform.
579     if (!Options->UnsafeFPMath) return 0;
580
581     // After operation legalization, it might not be legal to create new FSUBs.
582     if (LegalOperations &&
583         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
584       return 0;
585
586     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
587     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
588                                     Options, Depth + 1))
589       return V;
590     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
591     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
592                               Depth + 1);
593   case ISD::FSUB:
594     // We can't turn -(A-B) into B-A when we honor signed zeros.
595     if (!Options->UnsafeFPMath) return 0;
596
597     // fold (fneg (fsub A, B)) -> (fsub B, A)
598     return 1;
599
600   case ISD::FMUL:
601   case ISD::FDIV:
602     if (Options->HonorSignDependentRoundingFPMath()) return 0;
603
604     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
605     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
606                                     Options, Depth + 1))
607       return V;
608
609     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
610                               Depth + 1);
611
612   case ISD::FP_EXTEND:
613   case ISD::FP_ROUND:
614   case ISD::FSIN:
615     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
616                               Depth + 1);
617   }
618 }
619
620 /// If isNegatibleForFree returns true, return the newly negated expression.
621 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
622                                     bool LegalOperations, unsigned Depth = 0) {
623   const TargetOptions &Options = DAG.getTarget().Options;
624   // fneg is removable even if it has multiple uses.
625   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
626
627   // Don't allow anything with multiple uses.
628   assert(Op.hasOneUse() && "Unknown reuse!");
629
630   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
631
632   const SDNodeFlags *Flags = Op.getNode()->getFlags();
633
634   switch (Op.getOpcode()) {
635   default: llvm_unreachable("Unknown code");
636   case ISD::ConstantFP: {
637     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
638     V.changeSign();
639     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
640   }
641   case ISD::FADD:
642     // FIXME: determine better conditions for this xform.
643     assert(Options.UnsafeFPMath);
644
645     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
646     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
647                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
648       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
649                          GetNegatedExpression(Op.getOperand(0), DAG,
650                                               LegalOperations, Depth+1),
651                          Op.getOperand(1), Flags);
652     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
653     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
654                        GetNegatedExpression(Op.getOperand(1), DAG,
655                                             LegalOperations, Depth+1),
656                        Op.getOperand(0), Flags);
657   case ISD::FSUB:
658     // We can't turn -(A-B) into B-A when we honor signed zeros.
659     assert(Options.UnsafeFPMath);
660
661     // fold (fneg (fsub 0, B)) -> B
662     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
663       if (N0CFP->isZero())
664         return Op.getOperand(1);
665
666     // fold (fneg (fsub A, B)) -> (fsub B, A)
667     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
668                        Op.getOperand(1), Op.getOperand(0), Flags);
669
670   case ISD::FMUL:
671   case ISD::FDIV:
672     assert(!Options.HonorSignDependentRoundingFPMath());
673
674     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
675     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
676                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
677       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
678                          GetNegatedExpression(Op.getOperand(0), DAG,
679                                               LegalOperations, Depth+1),
680                          Op.getOperand(1), Flags);
681
682     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
683     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
684                        Op.getOperand(0),
685                        GetNegatedExpression(Op.getOperand(1), DAG,
686                                             LegalOperations, Depth+1), Flags);
687
688   case ISD::FP_EXTEND:
689   case ISD::FSIN:
690     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
691                        GetNegatedExpression(Op.getOperand(0), DAG,
692                                             LegalOperations, Depth+1));
693   case ISD::FP_ROUND:
694       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
695                          GetNegatedExpression(Op.getOperand(0), DAG,
696                                               LegalOperations, Depth+1),
697                          Op.getOperand(1));
698   }
699 }
700
701 // Return true if this node is a setcc, or is a select_cc
702 // that selects between the target values used for true and false, making it
703 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
704 // the appropriate nodes based on the type of node we are checking. This
705 // simplifies life a bit for the callers.
706 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
707                                     SDValue &CC) const {
708   if (N.getOpcode() == ISD::SETCC) {
709     LHS = N.getOperand(0);
710     RHS = N.getOperand(1);
711     CC  = N.getOperand(2);
712     return true;
713   }
714
715   if (N.getOpcode() != ISD::SELECT_CC ||
716       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
717       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
718     return false;
719
720   if (TLI.getBooleanContents(N.getValueType()) ==
721       TargetLowering::UndefinedBooleanContent)
722     return false;
723
724   LHS = N.getOperand(0);
725   RHS = N.getOperand(1);
726   CC  = N.getOperand(4);
727   return true;
728 }
729
730 /// Return true if this is a SetCC-equivalent operation with only one use.
731 /// If this is true, it allows the users to invert the operation for free when
732 /// it is profitable to do so.
733 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
734   SDValue N0, N1, N2;
735   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
736     return true;
737   return false;
738 }
739
740 /// Returns true if N is a BUILD_VECTOR node whose
741 /// elements are all the same constant or undefined.
742 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
743   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
744   if (!C)
745     return false;
746
747   APInt SplatUndef;
748   unsigned SplatBitSize;
749   bool HasAnyUndefs;
750   EVT EltVT = N->getValueType(0).getVectorElementType();
751   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
752                              HasAnyUndefs) &&
753           EltVT.getSizeInBits() >= SplatBitSize);
754 }
755
756 // \brief Returns the SDNode if it is a constant integer BuildVector
757 // or constant integer.
758 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
759   if (isa<ConstantSDNode>(N))
760     return N.getNode();
761   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
762     return N.getNode();
763   return nullptr;
764 }
765
766 // \brief Returns the SDNode if it is a constant float BuildVector
767 // or constant float.
768 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
769   if (isa<ConstantFPSDNode>(N))
770     return N.getNode();
771   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
772     return N.getNode();
773   return nullptr;
774 }
775
776 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
777 // int.
778 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
779   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
780     return CN;
781
782   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
783     BitVector UndefElements;
784     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
785
786     // BuildVectors can truncate their operands. Ignore that case here.
787     // FIXME: We blindly ignore splats which include undef which is overly
788     // pessimistic.
789     if (CN && UndefElements.none() &&
790         CN->getValueType(0) == N.getValueType().getScalarType())
791       return CN;
792   }
793
794   return nullptr;
795 }
796
797 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
798 // float.
799 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
800   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
801     return CN;
802
803   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
804     BitVector UndefElements;
805     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
806
807     if (CN && UndefElements.none())
808       return CN;
809   }
810
811   return nullptr;
812 }
813
814 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
815                                     SDValue N0, SDValue N1) {
816   EVT VT = N0.getValueType();
817   if (N0.getOpcode() == Opc) {
818     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
819       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
820         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
821         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
822           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
823         return SDValue();
824       }
825       if (N0.hasOneUse()) {
826         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
827         // use
828         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
829         if (!OpNode.getNode())
830           return SDValue();
831         AddToWorklist(OpNode.getNode());
832         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
833       }
834     }
835   }
836
837   if (N1.getOpcode() == Opc) {
838     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
839       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
840         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
841         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
842           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
843         return SDValue();
844       }
845       if (N1.hasOneUse()) {
846         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
847         // use
848         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
849         if (!OpNode.getNode())
850           return SDValue();
851         AddToWorklist(OpNode.getNode());
852         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
853       }
854     }
855   }
856
857   return SDValue();
858 }
859
860 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
861                                bool AddTo) {
862   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
863   ++NodesCombined;
864   DEBUG(dbgs() << "\nReplacing.1 ";
865         N->dump(&DAG);
866         dbgs() << "\nWith: ";
867         To[0].getNode()->dump(&DAG);
868         dbgs() << " and " << NumTo-1 << " other values\n");
869   for (unsigned i = 0, e = NumTo; i != e; ++i)
870     assert((!To[i].getNode() ||
871             N->getValueType(i) == To[i].getValueType()) &&
872            "Cannot combine value to value of different type!");
873
874   WorklistRemover DeadNodes(*this);
875   DAG.ReplaceAllUsesWith(N, To);
876   if (AddTo) {
877     // Push the new nodes and any users onto the worklist
878     for (unsigned i = 0, e = NumTo; i != e; ++i) {
879       if (To[i].getNode()) {
880         AddToWorklist(To[i].getNode());
881         AddUsersToWorklist(To[i].getNode());
882       }
883     }
884   }
885
886   // Finally, if the node is now dead, remove it from the graph.  The node
887   // may not be dead if the replacement process recursively simplified to
888   // something else needing this node.
889   if (N->use_empty())
890     deleteAndRecombine(N);
891   return SDValue(N, 0);
892 }
893
894 void DAGCombiner::
895 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
896   // Replace all uses.  If any nodes become isomorphic to other nodes and
897   // are deleted, make sure to remove them from our worklist.
898   WorklistRemover DeadNodes(*this);
899   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
900
901   // Push the new node and any (possibly new) users onto the worklist.
902   AddToWorklist(TLO.New.getNode());
903   AddUsersToWorklist(TLO.New.getNode());
904
905   // Finally, if the node is now dead, remove it from the graph.  The node
906   // may not be dead if the replacement process recursively simplified to
907   // something else needing this node.
908   if (TLO.Old.getNode()->use_empty())
909     deleteAndRecombine(TLO.Old.getNode());
910 }
911
912 /// Check the specified integer node value to see if it can be simplified or if
913 /// things it uses can be simplified by bit propagation. If so, return true.
914 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
915   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
916   APInt KnownZero, KnownOne;
917   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
918     return false;
919
920   // Revisit the node.
921   AddToWorklist(Op.getNode());
922
923   // Replace the old value with the new one.
924   ++NodesCombined;
925   DEBUG(dbgs() << "\nReplacing.2 ";
926         TLO.Old.getNode()->dump(&DAG);
927         dbgs() << "\nWith: ";
928         TLO.New.getNode()->dump(&DAG);
929         dbgs() << '\n');
930
931   CommitTargetLoweringOpt(TLO);
932   return true;
933 }
934
935 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
936   SDLoc dl(Load);
937   EVT VT = Load->getValueType(0);
938   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
939
940   DEBUG(dbgs() << "\nReplacing.9 ";
941         Load->dump(&DAG);
942         dbgs() << "\nWith: ";
943         Trunc.getNode()->dump(&DAG);
944         dbgs() << '\n');
945   WorklistRemover DeadNodes(*this);
946   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
947   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
948   deleteAndRecombine(Load);
949   AddToWorklist(Trunc.getNode());
950 }
951
952 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
953   Replace = false;
954   SDLoc dl(Op);
955   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
956     EVT MemVT = LD->getMemoryVT();
957     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
958       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
959                                                        : ISD::EXTLOAD)
960       : LD->getExtensionType();
961     Replace = true;
962     return DAG.getExtLoad(ExtType, dl, PVT,
963                           LD->getChain(), LD->getBasePtr(),
964                           MemVT, LD->getMemOperand());
965   }
966
967   unsigned Opc = Op.getOpcode();
968   switch (Opc) {
969   default: break;
970   case ISD::AssertSext:
971     return DAG.getNode(ISD::AssertSext, dl, PVT,
972                        SExtPromoteOperand(Op.getOperand(0), PVT),
973                        Op.getOperand(1));
974   case ISD::AssertZext:
975     return DAG.getNode(ISD::AssertZext, dl, PVT,
976                        ZExtPromoteOperand(Op.getOperand(0), PVT),
977                        Op.getOperand(1));
978   case ISD::Constant: {
979     unsigned ExtOpc =
980       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
981     return DAG.getNode(ExtOpc, dl, PVT, Op);
982   }
983   }
984
985   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
986     return SDValue();
987   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
988 }
989
990 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
991   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
992     return SDValue();
993   EVT OldVT = Op.getValueType();
994   SDLoc dl(Op);
995   bool Replace = false;
996   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
997   if (!NewOp.getNode())
998     return SDValue();
999   AddToWorklist(NewOp.getNode());
1000
1001   if (Replace)
1002     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1003   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1004                      DAG.getValueType(OldVT));
1005 }
1006
1007 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1008   EVT OldVT = Op.getValueType();
1009   SDLoc dl(Op);
1010   bool Replace = false;
1011   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1012   if (!NewOp.getNode())
1013     return SDValue();
1014   AddToWorklist(NewOp.getNode());
1015
1016   if (Replace)
1017     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1018   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1019 }
1020
1021 /// Promote the specified integer binary operation if the target indicates it is
1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1023 /// i32 since i16 instructions are longer.
1024 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1025   if (!LegalOperations)
1026     return SDValue();
1027
1028   EVT VT = Op.getValueType();
1029   if (VT.isVector() || !VT.isInteger())
1030     return SDValue();
1031
1032   // If operation type is 'undesirable', e.g. i16 on x86, consider
1033   // promoting it.
1034   unsigned Opc = Op.getOpcode();
1035   if (TLI.isTypeDesirableForOp(Opc, VT))
1036     return SDValue();
1037
1038   EVT PVT = VT;
1039   // Consult target whether it is a good idea to promote this operation and
1040   // what's the right type to promote it to.
1041   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1042     assert(PVT != VT && "Don't know what type to promote to!");
1043
1044     bool Replace0 = false;
1045     SDValue N0 = Op.getOperand(0);
1046     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1047     if (!NN0.getNode())
1048       return SDValue();
1049
1050     bool Replace1 = false;
1051     SDValue N1 = Op.getOperand(1);
1052     SDValue NN1;
1053     if (N0 == N1)
1054       NN1 = NN0;
1055     else {
1056       NN1 = PromoteOperand(N1, PVT, Replace1);
1057       if (!NN1.getNode())
1058         return SDValue();
1059     }
1060
1061     AddToWorklist(NN0.getNode());
1062     if (NN1.getNode())
1063       AddToWorklist(NN1.getNode());
1064
1065     if (Replace0)
1066       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1067     if (Replace1)
1068       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1069
1070     DEBUG(dbgs() << "\nPromoting ";
1071           Op.getNode()->dump(&DAG));
1072     SDLoc dl(Op);
1073     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1074                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1075   }
1076   return SDValue();
1077 }
1078
1079 /// Promote the specified integer shift operation if the target indicates it is
1080 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1081 /// i32 since i16 instructions are longer.
1082 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1083   if (!LegalOperations)
1084     return SDValue();
1085
1086   EVT VT = Op.getValueType();
1087   if (VT.isVector() || !VT.isInteger())
1088     return SDValue();
1089
1090   // If operation type is 'undesirable', e.g. i16 on x86, consider
1091   // promoting it.
1092   unsigned Opc = Op.getOpcode();
1093   if (TLI.isTypeDesirableForOp(Opc, VT))
1094     return SDValue();
1095
1096   EVT PVT = VT;
1097   // Consult target whether it is a good idea to promote this operation and
1098   // what's the right type to promote it to.
1099   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100     assert(PVT != VT && "Don't know what type to promote to!");
1101
1102     bool Replace = false;
1103     SDValue N0 = Op.getOperand(0);
1104     if (Opc == ISD::SRA)
1105       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1106     else if (Opc == ISD::SRL)
1107       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1108     else
1109       N0 = PromoteOperand(N0, PVT, Replace);
1110     if (!N0.getNode())
1111       return SDValue();
1112
1113     AddToWorklist(N0.getNode());
1114     if (Replace)
1115       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1116
1117     DEBUG(dbgs() << "\nPromoting ";
1118           Op.getNode()->dump(&DAG));
1119     SDLoc dl(Op);
1120     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1121                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1122   }
1123   return SDValue();
1124 }
1125
1126 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1127   if (!LegalOperations)
1128     return SDValue();
1129
1130   EVT VT = Op.getValueType();
1131   if (VT.isVector() || !VT.isInteger())
1132     return SDValue();
1133
1134   // If operation type is 'undesirable', e.g. i16 on x86, consider
1135   // promoting it.
1136   unsigned Opc = Op.getOpcode();
1137   if (TLI.isTypeDesirableForOp(Opc, VT))
1138     return SDValue();
1139
1140   EVT PVT = VT;
1141   // Consult target whether it is a good idea to promote this operation and
1142   // what's the right type to promote it to.
1143   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1144     assert(PVT != VT && "Don't know what type to promote to!");
1145     // fold (aext (aext x)) -> (aext x)
1146     // fold (aext (zext x)) -> (zext x)
1147     // fold (aext (sext x)) -> (sext x)
1148     DEBUG(dbgs() << "\nPromoting ";
1149           Op.getNode()->dump(&DAG));
1150     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1151   }
1152   return SDValue();
1153 }
1154
1155 bool DAGCombiner::PromoteLoad(SDValue Op) {
1156   if (!LegalOperations)
1157     return false;
1158
1159   EVT VT = Op.getValueType();
1160   if (VT.isVector() || !VT.isInteger())
1161     return false;
1162
1163   // If operation type is 'undesirable', e.g. i16 on x86, consider
1164   // promoting it.
1165   unsigned Opc = Op.getOpcode();
1166   if (TLI.isTypeDesirableForOp(Opc, VT))
1167     return false;
1168
1169   EVT PVT = VT;
1170   // Consult target whether it is a good idea to promote this operation and
1171   // what's the right type to promote it to.
1172   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1173     assert(PVT != VT && "Don't know what type to promote to!");
1174
1175     SDLoc dl(Op);
1176     SDNode *N = Op.getNode();
1177     LoadSDNode *LD = cast<LoadSDNode>(N);
1178     EVT MemVT = LD->getMemoryVT();
1179     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1180       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1181                                                        : ISD::EXTLOAD)
1182       : LD->getExtensionType();
1183     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1184                                    LD->getChain(), LD->getBasePtr(),
1185                                    MemVT, LD->getMemOperand());
1186     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1187
1188     DEBUG(dbgs() << "\nPromoting ";
1189           N->dump(&DAG);
1190           dbgs() << "\nTo: ";
1191           Result.getNode()->dump(&DAG);
1192           dbgs() << '\n');
1193     WorklistRemover DeadNodes(*this);
1194     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1195     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1196     deleteAndRecombine(N);
1197     AddToWorklist(Result.getNode());
1198     return true;
1199   }
1200   return false;
1201 }
1202
1203 /// \brief Recursively delete a node which has no uses and any operands for
1204 /// which it is the only use.
1205 ///
1206 /// Note that this both deletes the nodes and removes them from the worklist.
1207 /// It also adds any nodes who have had a user deleted to the worklist as they
1208 /// may now have only one use and subject to other combines.
1209 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1210   if (!N->use_empty())
1211     return false;
1212
1213   SmallSetVector<SDNode *, 16> Nodes;
1214   Nodes.insert(N);
1215   do {
1216     N = Nodes.pop_back_val();
1217     if (!N)
1218       continue;
1219
1220     if (N->use_empty()) {
1221       for (const SDValue &ChildN : N->op_values())
1222         Nodes.insert(ChildN.getNode());
1223
1224       removeFromWorklist(N);
1225       DAG.DeleteNode(N);
1226     } else {
1227       AddToWorklist(N);
1228     }
1229   } while (!Nodes.empty());
1230   return true;
1231 }
1232
1233 //===----------------------------------------------------------------------===//
1234 //  Main DAG Combiner implementation
1235 //===----------------------------------------------------------------------===//
1236
1237 void DAGCombiner::Run(CombineLevel AtLevel) {
1238   // set the instance variables, so that the various visit routines may use it.
1239   Level = AtLevel;
1240   LegalOperations = Level >= AfterLegalizeVectorOps;
1241   LegalTypes = Level >= AfterLegalizeTypes;
1242
1243   // Add all the dag nodes to the worklist.
1244   for (SDNode &Node : DAG.allnodes())
1245     AddToWorklist(&Node);
1246
1247   // Create a dummy node (which is not added to allnodes), that adds a reference
1248   // to the root node, preventing it from being deleted, and tracking any
1249   // changes of the root.
1250   HandleSDNode Dummy(DAG.getRoot());
1251
1252   // while the worklist isn't empty, find a node and
1253   // try and combine it.
1254   while (!WorklistMap.empty()) {
1255     SDNode *N;
1256     // The Worklist holds the SDNodes in order, but it may contain null entries.
1257     do {
1258       N = Worklist.pop_back_val();
1259     } while (!N);
1260
1261     bool GoodWorklistEntry = WorklistMap.erase(N);
1262     (void)GoodWorklistEntry;
1263     assert(GoodWorklistEntry &&
1264            "Found a worklist entry without a corresponding map entry!");
1265
1266     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1267     // N is deleted from the DAG, since they too may now be dead or may have a
1268     // reduced number of uses, allowing other xforms.
1269     if (recursivelyDeleteUnusedNodes(N))
1270       continue;
1271
1272     WorklistRemover DeadNodes(*this);
1273
1274     // If this combine is running after legalizing the DAG, re-legalize any
1275     // nodes pulled off the worklist.
1276     if (Level == AfterLegalizeDAG) {
1277       SmallSetVector<SDNode *, 16> UpdatedNodes;
1278       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1279
1280       for (SDNode *LN : UpdatedNodes) {
1281         AddToWorklist(LN);
1282         AddUsersToWorklist(LN);
1283       }
1284       if (!NIsValid)
1285         continue;
1286     }
1287
1288     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1289
1290     // Add any operands of the new node which have not yet been combined to the
1291     // worklist as well. Because the worklist uniques things already, this
1292     // won't repeatedly process the same operand.
1293     CombinedNodes.insert(N);
1294     for (const SDValue &ChildN : N->op_values())
1295       if (!CombinedNodes.count(ChildN.getNode()))
1296         AddToWorklist(ChildN.getNode());
1297
1298     SDValue RV = combine(N);
1299
1300     if (!RV.getNode())
1301       continue;
1302
1303     ++NodesCombined;
1304
1305     // If we get back the same node we passed in, rather than a new node or
1306     // zero, we know that the node must have defined multiple values and
1307     // CombineTo was used.  Since CombineTo takes care of the worklist
1308     // mechanics for us, we have no work to do in this case.
1309     if (RV.getNode() == N)
1310       continue;
1311
1312     assert(N->getOpcode() != ISD::DELETED_NODE &&
1313            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1314            "Node was deleted but visit returned new node!");
1315
1316     DEBUG(dbgs() << " ... into: ";
1317           RV.getNode()->dump(&DAG));
1318
1319     // Transfer debug value.
1320     DAG.TransferDbgValues(SDValue(N, 0), RV);
1321     if (N->getNumValues() == RV.getNode()->getNumValues())
1322       DAG.ReplaceAllUsesWith(N, RV.getNode());
1323     else {
1324       assert(N->getValueType(0) == RV.getValueType() &&
1325              N->getNumValues() == 1 && "Type mismatch");
1326       SDValue OpV = RV;
1327       DAG.ReplaceAllUsesWith(N, &OpV);
1328     }
1329
1330     // Push the new node and any users onto the worklist
1331     AddToWorklist(RV.getNode());
1332     AddUsersToWorklist(RV.getNode());
1333
1334     // Finally, if the node is now dead, remove it from the graph.  The node
1335     // may not be dead if the replacement process recursively simplified to
1336     // something else needing this node. This will also take care of adding any
1337     // operands which have lost a user to the worklist.
1338     recursivelyDeleteUnusedNodes(N);
1339   }
1340
1341   // If the root changed (e.g. it was a dead load, update the root).
1342   DAG.setRoot(Dummy.getValue());
1343   DAG.RemoveDeadNodes();
1344 }
1345
1346 SDValue DAGCombiner::visit(SDNode *N) {
1347   switch (N->getOpcode()) {
1348   default: break;
1349   case ISD::TokenFactor:        return visitTokenFactor(N);
1350   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1351   case ISD::ADD:                return visitADD(N);
1352   case ISD::SUB:                return visitSUB(N);
1353   case ISD::ADDC:               return visitADDC(N);
1354   case ISD::SUBC:               return visitSUBC(N);
1355   case ISD::ADDE:               return visitADDE(N);
1356   case ISD::SUBE:               return visitSUBE(N);
1357   case ISD::MUL:                return visitMUL(N);
1358   case ISD::SDIV:               return visitSDIV(N);
1359   case ISD::UDIV:               return visitUDIV(N);
1360   case ISD::SREM:
1361   case ISD::UREM:               return visitREM(N);
1362   case ISD::MULHU:              return visitMULHU(N);
1363   case ISD::MULHS:              return visitMULHS(N);
1364   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1365   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1366   case ISD::SMULO:              return visitSMULO(N);
1367   case ISD::UMULO:              return visitUMULO(N);
1368   case ISD::SMIN:
1369   case ISD::SMAX:
1370   case ISD::UMIN:
1371   case ISD::UMAX:               return visitIMINMAX(N);
1372   case ISD::AND:                return visitAND(N);
1373   case ISD::OR:                 return visitOR(N);
1374   case ISD::XOR:                return visitXOR(N);
1375   case ISD::SHL:                return visitSHL(N);
1376   case ISD::SRA:                return visitSRA(N);
1377   case ISD::SRL:                return visitSRL(N);
1378   case ISD::ROTR:
1379   case ISD::ROTL:               return visitRotate(N);
1380   case ISD::BSWAP:              return visitBSWAP(N);
1381   case ISD::CTLZ:               return visitCTLZ(N);
1382   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1383   case ISD::CTTZ:               return visitCTTZ(N);
1384   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1385   case ISD::CTPOP:              return visitCTPOP(N);
1386   case ISD::SELECT:             return visitSELECT(N);
1387   case ISD::VSELECT:            return visitVSELECT(N);
1388   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1389   case ISD::SETCC:              return visitSETCC(N);
1390   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1391   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1392   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1393   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1394   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1395   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1396   case ISD::BITCAST:            return visitBITCAST(N);
1397   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1398   case ISD::FADD:               return visitFADD(N);
1399   case ISD::FSUB:               return visitFSUB(N);
1400   case ISD::FMUL:               return visitFMUL(N);
1401   case ISD::FMA:                return visitFMA(N);
1402   case ISD::FDIV:               return visitFDIV(N);
1403   case ISD::FREM:               return visitFREM(N);
1404   case ISD::FSQRT:              return visitFSQRT(N);
1405   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1406   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1407   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1408   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1409   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1410   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1411   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1412   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1413   case ISD::FNEG:               return visitFNEG(N);
1414   case ISD::FABS:               return visitFABS(N);
1415   case ISD::FFLOOR:             return visitFFLOOR(N);
1416   case ISD::FMINNUM:            return visitFMINNUM(N);
1417   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1418   case ISD::FCEIL:              return visitFCEIL(N);
1419   case ISD::FTRUNC:             return visitFTRUNC(N);
1420   case ISD::BRCOND:             return visitBRCOND(N);
1421   case ISD::BR_CC:              return visitBR_CC(N);
1422   case ISD::LOAD:               return visitLOAD(N);
1423   case ISD::STORE:              return visitSTORE(N);
1424   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1425   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1426   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1427   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1428   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1429   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1430   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1431   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1432   case ISD::MGATHER:            return visitMGATHER(N);
1433   case ISD::MLOAD:              return visitMLOAD(N);
1434   case ISD::MSCATTER:           return visitMSCATTER(N);
1435   case ISD::MSTORE:             return visitMSTORE(N);
1436   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1437   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1438   }
1439   return SDValue();
1440 }
1441
1442 SDValue DAGCombiner::combine(SDNode *N) {
1443   SDValue RV = visit(N);
1444
1445   // If nothing happened, try a target-specific DAG combine.
1446   if (!RV.getNode()) {
1447     assert(N->getOpcode() != ISD::DELETED_NODE &&
1448            "Node was deleted but visit returned NULL!");
1449
1450     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1451         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1452
1453       // Expose the DAG combiner to the target combiner impls.
1454       TargetLowering::DAGCombinerInfo
1455         DagCombineInfo(DAG, Level, false, this);
1456
1457       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1458     }
1459   }
1460
1461   // If nothing happened still, try promoting the operation.
1462   if (!RV.getNode()) {
1463     switch (N->getOpcode()) {
1464     default: break;
1465     case ISD::ADD:
1466     case ISD::SUB:
1467     case ISD::MUL:
1468     case ISD::AND:
1469     case ISD::OR:
1470     case ISD::XOR:
1471       RV = PromoteIntBinOp(SDValue(N, 0));
1472       break;
1473     case ISD::SHL:
1474     case ISD::SRA:
1475     case ISD::SRL:
1476       RV = PromoteIntShiftOp(SDValue(N, 0));
1477       break;
1478     case ISD::SIGN_EXTEND:
1479     case ISD::ZERO_EXTEND:
1480     case ISD::ANY_EXTEND:
1481       RV = PromoteExtend(SDValue(N, 0));
1482       break;
1483     case ISD::LOAD:
1484       if (PromoteLoad(SDValue(N, 0)))
1485         RV = SDValue(N, 0);
1486       break;
1487     }
1488   }
1489
1490   // If N is a commutative binary node, try commuting it to enable more
1491   // sdisel CSE.
1492   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1493       N->getNumValues() == 1) {
1494     SDValue N0 = N->getOperand(0);
1495     SDValue N1 = N->getOperand(1);
1496
1497     // Constant operands are canonicalized to RHS.
1498     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1499       SDValue Ops[] = {N1, N0};
1500       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1501                                             N->getFlags());
1502       if (CSENode)
1503         return SDValue(CSENode, 0);
1504     }
1505   }
1506
1507   return RV;
1508 }
1509
1510 /// Given a node, return its input chain if it has one, otherwise return a null
1511 /// sd operand.
1512 static SDValue getInputChainForNode(SDNode *N) {
1513   if (unsigned NumOps = N->getNumOperands()) {
1514     if (N->getOperand(0).getValueType() == MVT::Other)
1515       return N->getOperand(0);
1516     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1517       return N->getOperand(NumOps-1);
1518     for (unsigned i = 1; i < NumOps-1; ++i)
1519       if (N->getOperand(i).getValueType() == MVT::Other)
1520         return N->getOperand(i);
1521   }
1522   return SDValue();
1523 }
1524
1525 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1526   // If N has two operands, where one has an input chain equal to the other,
1527   // the 'other' chain is redundant.
1528   if (N->getNumOperands() == 2) {
1529     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1530       return N->getOperand(0);
1531     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1532       return N->getOperand(1);
1533   }
1534
1535   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1536   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1537   SmallPtrSet<SDNode*, 16> SeenOps;
1538   bool Changed = false;             // If we should replace this token factor.
1539
1540   // Start out with this token factor.
1541   TFs.push_back(N);
1542
1543   // Iterate through token factors.  The TFs grows when new token factors are
1544   // encountered.
1545   for (unsigned i = 0; i < TFs.size(); ++i) {
1546     SDNode *TF = TFs[i];
1547
1548     // Check each of the operands.
1549     for (const SDValue &Op : TF->op_values()) {
1550
1551       switch (Op.getOpcode()) {
1552       case ISD::EntryToken:
1553         // Entry tokens don't need to be added to the list. They are
1554         // redundant.
1555         Changed = true;
1556         break;
1557
1558       case ISD::TokenFactor:
1559         if (Op.hasOneUse() &&
1560             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1561           // Queue up for processing.
1562           TFs.push_back(Op.getNode());
1563           // Clean up in case the token factor is removed.
1564           AddToWorklist(Op.getNode());
1565           Changed = true;
1566           break;
1567         }
1568         // Fall thru
1569
1570       default:
1571         // Only add if it isn't already in the list.
1572         if (SeenOps.insert(Op.getNode()).second)
1573           Ops.push_back(Op);
1574         else
1575           Changed = true;
1576         break;
1577       }
1578     }
1579   }
1580
1581   SDValue Result;
1582
1583   // If we've changed things around then replace token factor.
1584   if (Changed) {
1585     if (Ops.empty()) {
1586       // The entry token is the only possible outcome.
1587       Result = DAG.getEntryNode();
1588     } else {
1589       // New and improved token factor.
1590       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1591     }
1592
1593     // Add users to worklist if AA is enabled, since it may introduce
1594     // a lot of new chained token factors while removing memory deps.
1595     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1596       : DAG.getSubtarget().useAA();
1597     return CombineTo(N, Result, UseAA /*add to worklist*/);
1598   }
1599
1600   return Result;
1601 }
1602
1603 /// MERGE_VALUES can always be eliminated.
1604 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1605   WorklistRemover DeadNodes(*this);
1606   // Replacing results may cause a different MERGE_VALUES to suddenly
1607   // be CSE'd with N, and carry its uses with it. Iterate until no
1608   // uses remain, to ensure that the node can be safely deleted.
1609   // First add the users of this node to the work list so that they
1610   // can be tried again once they have new operands.
1611   AddUsersToWorklist(N);
1612   do {
1613     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1614       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1615   } while (!N->use_empty());
1616   deleteAndRecombine(N);
1617   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1618 }
1619
1620 static bool isNullConstant(SDValue V) {
1621   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622   return Const != nullptr && Const->isNullValue();
1623 }
1624
1625 static bool isNullFPConstant(SDValue V) {
1626   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1627   return Const != nullptr && Const->isZero() && !Const->isNegative();
1628 }
1629
1630 static bool isAllOnesConstant(SDValue V) {
1631   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1632   return Const != nullptr && Const->isAllOnesValue();
1633 }
1634
1635 static bool isOneConstant(SDValue V) {
1636   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1637   return Const != nullptr && Const->isOne();
1638 }
1639
1640 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1641 /// ContantSDNode pointer else nullptr.
1642 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1643   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1644   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1645 }
1646
1647 SDValue DAGCombiner::visitADD(SDNode *N) {
1648   SDValue N0 = N->getOperand(0);
1649   SDValue N1 = N->getOperand(1);
1650   EVT VT = N0.getValueType();
1651
1652   // fold vector ops
1653   if (VT.isVector()) {
1654     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1655       return FoldedVOp;
1656
1657     // fold (add x, 0) -> x, vector edition
1658     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1659       return N0;
1660     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1661       return N1;
1662   }
1663
1664   // fold (add x, undef) -> undef
1665   if (N0.getOpcode() == ISD::UNDEF)
1666     return N0;
1667   if (N1.getOpcode() == ISD::UNDEF)
1668     return N1;
1669   // fold (add c1, c2) -> c1+c2
1670   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1671   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1672   if (N0C && N1C)
1673     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1674   // canonicalize constant to RHS
1675   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1676      !isConstantIntBuildVectorOrConstantInt(N1))
1677     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1678   // fold (add x, 0) -> x
1679   if (isNullConstant(N1))
1680     return N0;
1681   // fold (add Sym, c) -> Sym+c
1682   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1683     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1684         GA->getOpcode() == ISD::GlobalAddress)
1685       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1686                                   GA->getOffset() +
1687                                     (uint64_t)N1C->getSExtValue());
1688   // fold ((c1-A)+c2) -> (c1+c2)-A
1689   if (N1C && N0.getOpcode() == ISD::SUB)
1690     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1691       SDLoc DL(N);
1692       return DAG.getNode(ISD::SUB, DL, VT,
1693                          DAG.getConstant(N1C->getAPIntValue()+
1694                                          N0C->getAPIntValue(), DL, VT),
1695                          N0.getOperand(1));
1696     }
1697   // reassociate add
1698   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1699     return RADD;
1700   // fold ((0-A) + B) -> B-A
1701   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1702     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1703   // fold (A + (0-B)) -> A-B
1704   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1705     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1706   // fold (A+(B-A)) -> B
1707   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1708     return N1.getOperand(0);
1709   // fold ((B-A)+A) -> B
1710   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1711     return N0.getOperand(0);
1712   // fold (A+(B-(A+C))) to (B-C)
1713   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1714       N0 == N1.getOperand(1).getOperand(0))
1715     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1716                        N1.getOperand(1).getOperand(1));
1717   // fold (A+(B-(C+A))) to (B-C)
1718   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1719       N0 == N1.getOperand(1).getOperand(1))
1720     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1721                        N1.getOperand(1).getOperand(0));
1722   // fold (A+((B-A)+or-C)) to (B+or-C)
1723   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1724       N1.getOperand(0).getOpcode() == ISD::SUB &&
1725       N0 == N1.getOperand(0).getOperand(1))
1726     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1727                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1728
1729   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1730   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1731     SDValue N00 = N0.getOperand(0);
1732     SDValue N01 = N0.getOperand(1);
1733     SDValue N10 = N1.getOperand(0);
1734     SDValue N11 = N1.getOperand(1);
1735
1736     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1737       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1738                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1739                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1740   }
1741
1742   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1743     return SDValue(N, 0);
1744
1745   // fold (a+b) -> (a|b) iff a and b share no bits.
1746   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1747       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1748     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1749
1750   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1751   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1752       isNullConstant(N1.getOperand(0).getOperand(0)))
1753     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1754                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1755                                    N1.getOperand(0).getOperand(1),
1756                                    N1.getOperand(1)));
1757   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1758       isNullConstant(N0.getOperand(0).getOperand(0)))
1759     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1760                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1761                                    N0.getOperand(0).getOperand(1),
1762                                    N0.getOperand(1)));
1763
1764   if (N1.getOpcode() == ISD::AND) {
1765     SDValue AndOp0 = N1.getOperand(0);
1766     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1767     unsigned DestBits = VT.getScalarType().getSizeInBits();
1768
1769     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1770     // and similar xforms where the inner op is either ~0 or 0.
1771     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1772       SDLoc DL(N);
1773       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1774     }
1775   }
1776
1777   // add (sext i1), X -> sub X, (zext i1)
1778   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1779       N0.getOperand(0).getValueType() == MVT::i1 &&
1780       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1781     SDLoc DL(N);
1782     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1783     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1784   }
1785
1786   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1787   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1788     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1789     if (TN->getVT() == MVT::i1) {
1790       SDLoc DL(N);
1791       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1792                                  DAG.getConstant(1, DL, VT));
1793       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1794     }
1795   }
1796
1797   return SDValue();
1798 }
1799
1800 SDValue DAGCombiner::visitADDC(SDNode *N) {
1801   SDValue N0 = N->getOperand(0);
1802   SDValue N1 = N->getOperand(1);
1803   EVT VT = N0.getValueType();
1804
1805   // If the flag result is dead, turn this into an ADD.
1806   if (!N->hasAnyUseOfValue(1))
1807     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1808                      DAG.getNode(ISD::CARRY_FALSE,
1809                                  SDLoc(N), MVT::Glue));
1810
1811   // canonicalize constant to RHS.
1812   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1813   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1814   if (N0C && !N1C)
1815     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1816
1817   // fold (addc x, 0) -> x + no carry out
1818   if (isNullConstant(N1))
1819     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1820                                         SDLoc(N), MVT::Glue));
1821
1822   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1823   APInt LHSZero, LHSOne;
1824   APInt RHSZero, RHSOne;
1825   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1826
1827   if (LHSZero.getBoolValue()) {
1828     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1829
1830     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1831     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1832     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1833       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1834                        DAG.getNode(ISD::CARRY_FALSE,
1835                                    SDLoc(N), MVT::Glue));
1836   }
1837
1838   return SDValue();
1839 }
1840
1841 SDValue DAGCombiner::visitADDE(SDNode *N) {
1842   SDValue N0 = N->getOperand(0);
1843   SDValue N1 = N->getOperand(1);
1844   SDValue CarryIn = N->getOperand(2);
1845
1846   // canonicalize constant to RHS
1847   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1848   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1849   if (N0C && !N1C)
1850     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1851                        N1, N0, CarryIn);
1852
1853   // fold (adde x, y, false) -> (addc x, y)
1854   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1855     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1856
1857   return SDValue();
1858 }
1859
1860 // Since it may not be valid to emit a fold to zero for vector initializers
1861 // check if we can before folding.
1862 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1863                              SelectionDAG &DAG,
1864                              bool LegalOperations, bool LegalTypes) {
1865   if (!VT.isVector())
1866     return DAG.getConstant(0, DL, VT);
1867   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1868     return DAG.getConstant(0, DL, VT);
1869   return SDValue();
1870 }
1871
1872 SDValue DAGCombiner::visitSUB(SDNode *N) {
1873   SDValue N0 = N->getOperand(0);
1874   SDValue N1 = N->getOperand(1);
1875   EVT VT = N0.getValueType();
1876
1877   // fold vector ops
1878   if (VT.isVector()) {
1879     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1880       return FoldedVOp;
1881
1882     // fold (sub x, 0) -> x, vector edition
1883     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1884       return N0;
1885   }
1886
1887   // fold (sub x, x) -> 0
1888   // FIXME: Refactor this and xor and other similar operations together.
1889   if (N0 == N1)
1890     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1891   // fold (sub c1, c2) -> c1-c2
1892   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1893   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1894   if (N0C && N1C)
1895     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1896   // fold (sub x, c) -> (add x, -c)
1897   if (N1C) {
1898     SDLoc DL(N);
1899     return DAG.getNode(ISD::ADD, DL, VT, N0,
1900                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1901   }
1902   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1903   if (isAllOnesConstant(N0))
1904     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1905   // fold A-(A-B) -> B
1906   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1907     return N1.getOperand(1);
1908   // fold (A+B)-A -> B
1909   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1910     return N0.getOperand(1);
1911   // fold (A+B)-B -> A
1912   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1913     return N0.getOperand(0);
1914   // fold C2-(A+C1) -> (C2-C1)-A
1915   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1916     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1917   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1918     SDLoc DL(N);
1919     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1920                                    DL, VT);
1921     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1922                        N1.getOperand(0));
1923   }
1924   // fold ((A+(B+or-C))-B) -> A+or-C
1925   if (N0.getOpcode() == ISD::ADD &&
1926       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1927        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1928       N0.getOperand(1).getOperand(0) == N1)
1929     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1930                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1931   // fold ((A+(C+B))-B) -> A+C
1932   if (N0.getOpcode() == ISD::ADD &&
1933       N0.getOperand(1).getOpcode() == ISD::ADD &&
1934       N0.getOperand(1).getOperand(1) == N1)
1935     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1936                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1937   // fold ((A-(B-C))-C) -> A-B
1938   if (N0.getOpcode() == ISD::SUB &&
1939       N0.getOperand(1).getOpcode() == ISD::SUB &&
1940       N0.getOperand(1).getOperand(1) == N1)
1941     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1942                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1943
1944   // If either operand of a sub is undef, the result is undef
1945   if (N0.getOpcode() == ISD::UNDEF)
1946     return N0;
1947   if (N1.getOpcode() == ISD::UNDEF)
1948     return N1;
1949
1950   // If the relocation model supports it, consider symbol offsets.
1951   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1952     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1953       // fold (sub Sym, c) -> Sym-c
1954       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1955         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1956                                     GA->getOffset() -
1957                                       (uint64_t)N1C->getSExtValue());
1958       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1959       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1960         if (GA->getGlobal() == GB->getGlobal())
1961           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1962                                  SDLoc(N), VT);
1963     }
1964
1965   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1966   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1967     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1968     if (TN->getVT() == MVT::i1) {
1969       SDLoc DL(N);
1970       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1971                                  DAG.getConstant(1, DL, VT));
1972       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1973     }
1974   }
1975
1976   return SDValue();
1977 }
1978
1979 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1980   SDValue N0 = N->getOperand(0);
1981   SDValue N1 = N->getOperand(1);
1982   EVT VT = N0.getValueType();
1983   SDLoc DL(N);
1984
1985   // If the flag result is dead, turn this into an SUB.
1986   if (!N->hasAnyUseOfValue(1))
1987     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1988                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1989
1990   // fold (subc x, x) -> 0 + no borrow
1991   if (N0 == N1)
1992     return CombineTo(N, DAG.getConstant(0, DL, VT),
1993                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1994
1995   // fold (subc x, 0) -> x + no borrow
1996   if (isNullConstant(N1))
1997     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1998
1999   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2000   if (isAllOnesConstant(N0))
2001     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2002                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2003
2004   return SDValue();
2005 }
2006
2007 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2008   SDValue N0 = N->getOperand(0);
2009   SDValue N1 = N->getOperand(1);
2010   SDValue CarryIn = N->getOperand(2);
2011
2012   // fold (sube x, y, false) -> (subc x, y)
2013   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2014     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2015
2016   return SDValue();
2017 }
2018
2019 SDValue DAGCombiner::visitMUL(SDNode *N) {
2020   SDValue N0 = N->getOperand(0);
2021   SDValue N1 = N->getOperand(1);
2022   EVT VT = N0.getValueType();
2023
2024   // fold (mul x, undef) -> 0
2025   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2026     return DAG.getConstant(0, SDLoc(N), VT);
2027
2028   bool N0IsConst = false;
2029   bool N1IsConst = false;
2030   bool N1IsOpaqueConst = false;
2031   bool N0IsOpaqueConst = false;
2032   APInt ConstValue0, ConstValue1;
2033   // fold vector ops
2034   if (VT.isVector()) {
2035     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2036       return FoldedVOp;
2037
2038     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2039     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2040   } else {
2041     N0IsConst = isa<ConstantSDNode>(N0);
2042     if (N0IsConst) {
2043       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2044       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2045     }
2046     N1IsConst = isa<ConstantSDNode>(N1);
2047     if (N1IsConst) {
2048       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2049       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2050     }
2051   }
2052
2053   // fold (mul c1, c2) -> c1*c2
2054   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2055     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2056                                       N0.getNode(), N1.getNode());
2057
2058   // canonicalize constant to RHS (vector doesn't have to splat)
2059   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2060      !isConstantIntBuildVectorOrConstantInt(N1))
2061     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2062   // fold (mul x, 0) -> 0
2063   if (N1IsConst && ConstValue1 == 0)
2064     return N1;
2065   // We require a splat of the entire scalar bit width for non-contiguous
2066   // bit patterns.
2067   bool IsFullSplat =
2068     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2069   // fold (mul x, 1) -> x
2070   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2071     return N0;
2072   // fold (mul x, -1) -> 0-x
2073   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2074     SDLoc DL(N);
2075     return DAG.getNode(ISD::SUB, DL, VT,
2076                        DAG.getConstant(0, DL, VT), N0);
2077   }
2078   // fold (mul x, (1 << c)) -> x << c
2079   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2080       IsFullSplat) {
2081     SDLoc DL(N);
2082     return DAG.getNode(ISD::SHL, DL, VT, N0,
2083                        DAG.getConstant(ConstValue1.logBase2(), DL,
2084                                        getShiftAmountTy(N0.getValueType())));
2085   }
2086   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2087   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2088       IsFullSplat) {
2089     unsigned Log2Val = (-ConstValue1).logBase2();
2090     SDLoc DL(N);
2091     // FIXME: If the input is something that is easily negated (e.g. a
2092     // single-use add), we should put the negate there.
2093     return DAG.getNode(ISD::SUB, DL, VT,
2094                        DAG.getConstant(0, DL, VT),
2095                        DAG.getNode(ISD::SHL, DL, VT, N0,
2096                             DAG.getConstant(Log2Val, DL,
2097                                       getShiftAmountTy(N0.getValueType()))));
2098   }
2099
2100   APInt Val;
2101   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2102   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2103       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2104                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2105     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2106                              N1, N0.getOperand(1));
2107     AddToWorklist(C3.getNode());
2108     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2109                        N0.getOperand(0), C3);
2110   }
2111
2112   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2113   // use.
2114   {
2115     SDValue Sh(nullptr,0), Y(nullptr,0);
2116     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2117     if (N0.getOpcode() == ISD::SHL &&
2118         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2119                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2120         N0.getNode()->hasOneUse()) {
2121       Sh = N0; Y = N1;
2122     } else if (N1.getOpcode() == ISD::SHL &&
2123                isa<ConstantSDNode>(N1.getOperand(1)) &&
2124                N1.getNode()->hasOneUse()) {
2125       Sh = N1; Y = N0;
2126     }
2127
2128     if (Sh.getNode()) {
2129       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2130                                 Sh.getOperand(0), Y);
2131       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2132                          Mul, Sh.getOperand(1));
2133     }
2134   }
2135
2136   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2137   if (isConstantIntBuildVectorOrConstantInt(N1) &&
2138       N0.getOpcode() == ISD::ADD &&
2139       isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2140       isMulAddWithConstProfitable(N, N0, N1))
2141       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2142                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2143                                      N0.getOperand(0), N1),
2144                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2145                                      N0.getOperand(1), N1));
2146
2147   // reassociate mul
2148   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2149     return RMUL;
2150
2151   return SDValue();
2152 }
2153
2154 /// Return true if divmod libcall is available.
2155 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2156                                      const TargetLowering &TLI) {
2157   RTLIB::Libcall LC;
2158   switch (Node->getSimpleValueType(0).SimpleTy) {
2159   default: return false; // No libcall for vector types.
2160   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2161   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2162   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2163   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2164   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2165   }
2166
2167   return TLI.getLibcallName(LC) != nullptr;
2168 }
2169
2170 /// Issue divrem if both quotient and remainder are needed.
2171 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2172   if (Node->use_empty())
2173     return SDValue(); // This is a dead node, leave it alone.
2174
2175   EVT VT = Node->getValueType(0);
2176   if (!TLI.isTypeLegal(VT))
2177     return SDValue();
2178
2179   unsigned Opcode = Node->getOpcode();
2180   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2181
2182   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2183   // If DIVREM is going to get expanded into a libcall,
2184   // but there is no libcall available, then don't combine.
2185   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2186       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2187     return SDValue();
2188
2189   // If div is legal, it's better to do the normal expansion
2190   unsigned OtherOpcode = 0;
2191   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2192     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2193     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2194       return SDValue();
2195   } else {
2196     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2197     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2198       return SDValue();
2199   }
2200
2201   SDValue Op0 = Node->getOperand(0);
2202   SDValue Op1 = Node->getOperand(1);
2203   SDValue combined;
2204   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2205          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2206     SDNode *User = *UI;
2207     if (User == Node || User->use_empty())
2208       continue;
2209     // Convert the other matching node(s), too;
2210     // otherwise, the DIVREM may get target-legalized into something
2211     // target-specific that we won't be able to recognize.
2212     unsigned UserOpc = User->getOpcode();
2213     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2214         User->getOperand(0) == Op0 &&
2215         User->getOperand(1) == Op1) {
2216       if (!combined) {
2217         if (UserOpc == OtherOpcode) {
2218           SDVTList VTs = DAG.getVTList(VT, VT);
2219           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2220         } else if (UserOpc == DivRemOpc) {
2221           combined = SDValue(User, 0);
2222         } else {
2223           assert(UserOpc == Opcode);
2224           continue;
2225         }
2226       }
2227       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2228         CombineTo(User, combined);
2229       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2230         CombineTo(User, combined.getValue(1));
2231     }
2232   }
2233   return combined;
2234 }
2235
2236 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2237   SDValue N0 = N->getOperand(0);
2238   SDValue N1 = N->getOperand(1);
2239   EVT VT = N->getValueType(0);
2240
2241   // fold vector ops
2242   if (VT.isVector())
2243     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2244       return FoldedVOp;
2245
2246   SDLoc DL(N);
2247
2248   // fold (sdiv c1, c2) -> c1/c2
2249   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2250   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2251   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2252     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2253   // fold (sdiv X, 1) -> X
2254   if (N1C && N1C->isOne())
2255     return N0;
2256   // fold (sdiv X, -1) -> 0-X
2257   if (N1C && N1C->isAllOnesValue())
2258     return DAG.getNode(ISD::SUB, DL, VT,
2259                        DAG.getConstant(0, DL, VT), N0);
2260
2261   // If we know the sign bits of both operands are zero, strength reduce to a
2262   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2263   if (!VT.isVector()) {
2264     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2265       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2266   }
2267
2268   // fold (sdiv X, pow2) -> simple ops after legalize
2269   // FIXME: We check for the exact bit here because the generic lowering gives
2270   // better results in that case. The target-specific lowering should learn how
2271   // to handle exact sdivs efficiently.
2272   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2273       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2274       (N1C->getAPIntValue().isPowerOf2() ||
2275        (-N1C->getAPIntValue()).isPowerOf2())) {
2276     // Target-specific implementation of sdiv x, pow2.
2277     if (SDValue Res = BuildSDIVPow2(N))
2278       return Res;
2279
2280     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2281
2282     // Splat the sign bit into the register
2283     SDValue SGN =
2284         DAG.getNode(ISD::SRA, DL, VT, N0,
2285                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2286                                     getShiftAmountTy(N0.getValueType())));
2287     AddToWorklist(SGN.getNode());
2288
2289     // Add (N0 < 0) ? abs2 - 1 : 0;
2290     SDValue SRL =
2291         DAG.getNode(ISD::SRL, DL, VT, SGN,
2292                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2293                                     getShiftAmountTy(SGN.getValueType())));
2294     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2295     AddToWorklist(SRL.getNode());
2296     AddToWorklist(ADD.getNode());    // Divide by pow2
2297     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2298                   DAG.getConstant(lg2, DL,
2299                                   getShiftAmountTy(ADD.getValueType())));
2300
2301     // If we're dividing by a positive value, we're done.  Otherwise, we must
2302     // negate the result.
2303     if (N1C->getAPIntValue().isNonNegative())
2304       return SRA;
2305
2306     AddToWorklist(SRA.getNode());
2307     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2308   }
2309
2310   // If integer divide is expensive and we satisfy the requirements, emit an
2311   // alternate sequence.  Targets may check function attributes for size/speed
2312   // trade-offs.
2313   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2314   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2315     if (SDValue Op = BuildSDIV(N))
2316       return Op;
2317
2318   // sdiv, srem -> sdivrem
2319   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2320   // Otherwise, we break the simplification logic in visitREM().
2321   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2322     if (SDValue DivRem = useDivRem(N))
2323         return DivRem;
2324
2325   // undef / X -> 0
2326   if (N0.getOpcode() == ISD::UNDEF)
2327     return DAG.getConstant(0, DL, VT);
2328   // X / undef -> undef
2329   if (N1.getOpcode() == ISD::UNDEF)
2330     return N1;
2331
2332   return SDValue();
2333 }
2334
2335 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2336   SDValue N0 = N->getOperand(0);
2337   SDValue N1 = N->getOperand(1);
2338   EVT VT = N->getValueType(0);
2339
2340   // fold vector ops
2341   if (VT.isVector())
2342     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2343       return FoldedVOp;
2344
2345   SDLoc DL(N);
2346
2347   // fold (udiv c1, c2) -> c1/c2
2348   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2349   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2350   if (N0C && N1C)
2351     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2352                                                     N0C, N1C))
2353       return Folded;
2354   // fold (udiv x, (1 << c)) -> x >>u c
2355   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2356     return DAG.getNode(ISD::SRL, DL, VT, N0,
2357                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2358                                        getShiftAmountTy(N0.getValueType())));
2359
2360   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2361   if (N1.getOpcode() == ISD::SHL) {
2362     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2363       if (SHC->getAPIntValue().isPowerOf2()) {
2364         EVT ADDVT = N1.getOperand(1).getValueType();
2365         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2366                                   N1.getOperand(1),
2367                                   DAG.getConstant(SHC->getAPIntValue()
2368                                                                   .logBase2(),
2369                                                   DL, ADDVT));
2370         AddToWorklist(Add.getNode());
2371         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2372       }
2373     }
2374   }
2375
2376   // fold (udiv x, c) -> alternate
2377   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2378   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2379     if (SDValue Op = BuildUDIV(N))
2380       return Op;
2381
2382   // sdiv, srem -> sdivrem
2383   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2384   // Otherwise, we break the simplification logic in visitREM().
2385   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2386     if (SDValue DivRem = useDivRem(N))
2387         return DivRem;
2388
2389   // undef / X -> 0
2390   if (N0.getOpcode() == ISD::UNDEF)
2391     return DAG.getConstant(0, DL, VT);
2392   // X / undef -> undef
2393   if (N1.getOpcode() == ISD::UNDEF)
2394     return N1;
2395
2396   return SDValue();
2397 }
2398
2399 // handles ISD::SREM and ISD::UREM
2400 SDValue DAGCombiner::visitREM(SDNode *N) {
2401   unsigned Opcode = N->getOpcode();
2402   SDValue N0 = N->getOperand(0);
2403   SDValue N1 = N->getOperand(1);
2404   EVT VT = N->getValueType(0);
2405   bool isSigned = (Opcode == ISD::SREM);
2406   SDLoc DL(N);
2407
2408   // fold (rem c1, c2) -> c1%c2
2409   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2410   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2411   if (N0C && N1C)
2412     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2413       return Folded;
2414
2415   if (isSigned) {
2416     // If we know the sign bits of both operands are zero, strength reduce to a
2417     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2418     if (!VT.isVector()) {
2419       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2420         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2421     }
2422   } else {
2423     // fold (urem x, pow2) -> (and x, pow2-1)
2424     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2425         N1C->getAPIntValue().isPowerOf2()) {
2426       return DAG.getNode(ISD::AND, DL, VT, N0,
2427                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2428     }
2429     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2430     if (N1.getOpcode() == ISD::SHL) {
2431       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2432         if (SHC->getAPIntValue().isPowerOf2()) {
2433           SDValue Add =
2434             DAG.getNode(ISD::ADD, DL, VT, N1,
2435                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2436                                  VT));
2437           AddToWorklist(Add.getNode());
2438           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2439         }
2440       }
2441     }
2442   }
2443
2444   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2445
2446   // If X/C can be simplified by the division-by-constant logic, lower
2447   // X%C to the equivalent of X-X/C*C.
2448   // To avoid mangling nodes, this simplification requires that the combine()
2449   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2450   // against this by skipping the simplification if isIntDivCheap().  When
2451   // div is not cheap, combine will not return a DIVREM.  Regardless,
2452   // checking cheapness here makes sense since the simplification results in
2453   // fatter code.
2454   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2455     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2456     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2457     AddToWorklist(Div.getNode());
2458     SDValue OptimizedDiv = combine(Div.getNode());
2459     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2460       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2461              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2462       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2463       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2464       AddToWorklist(Mul.getNode());
2465       return Sub;
2466     }
2467   }
2468
2469   // sdiv, srem -> sdivrem
2470   if (SDValue DivRem = useDivRem(N))
2471     return DivRem.getValue(1);
2472
2473   // undef % X -> 0
2474   if (N0.getOpcode() == ISD::UNDEF)
2475     return DAG.getConstant(0, DL, VT);
2476   // X % undef -> undef
2477   if (N1.getOpcode() == ISD::UNDEF)
2478     return N1;
2479
2480   return SDValue();
2481 }
2482
2483 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2484   SDValue N0 = N->getOperand(0);
2485   SDValue N1 = N->getOperand(1);
2486   EVT VT = N->getValueType(0);
2487   SDLoc DL(N);
2488
2489   // fold (mulhs x, 0) -> 0
2490   if (isNullConstant(N1))
2491     return N1;
2492   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2493   if (isOneConstant(N1)) {
2494     SDLoc DL(N);
2495     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2496                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2497                                        DL,
2498                                        getShiftAmountTy(N0.getValueType())));
2499   }
2500   // fold (mulhs x, undef) -> 0
2501   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2502     return DAG.getConstant(0, SDLoc(N), VT);
2503
2504   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2505   // plus a shift.
2506   if (VT.isSimple() && !VT.isVector()) {
2507     MVT Simple = VT.getSimpleVT();
2508     unsigned SimpleSize = Simple.getSizeInBits();
2509     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2510     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2511       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2512       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2513       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2514       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2515             DAG.getConstant(SimpleSize, DL,
2516                             getShiftAmountTy(N1.getValueType())));
2517       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2518     }
2519   }
2520
2521   return SDValue();
2522 }
2523
2524 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2525   SDValue N0 = N->getOperand(0);
2526   SDValue N1 = N->getOperand(1);
2527   EVT VT = N->getValueType(0);
2528   SDLoc DL(N);
2529
2530   // fold (mulhu x, 0) -> 0
2531   if (isNullConstant(N1))
2532     return N1;
2533   // fold (mulhu x, 1) -> 0
2534   if (isOneConstant(N1))
2535     return DAG.getConstant(0, DL, N0.getValueType());
2536   // fold (mulhu x, undef) -> 0
2537   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2538     return DAG.getConstant(0, DL, VT);
2539
2540   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2541   // plus a shift.
2542   if (VT.isSimple() && !VT.isVector()) {
2543     MVT Simple = VT.getSimpleVT();
2544     unsigned SimpleSize = Simple.getSizeInBits();
2545     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2546     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2547       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2548       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2549       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2550       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2551             DAG.getConstant(SimpleSize, DL,
2552                             getShiftAmountTy(N1.getValueType())));
2553       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2554     }
2555   }
2556
2557   return SDValue();
2558 }
2559
2560 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2561 /// give the opcodes for the two computations that are being performed. Return
2562 /// true if a simplification was made.
2563 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2564                                                 unsigned HiOp) {
2565   // If the high half is not needed, just compute the low half.
2566   bool HiExists = N->hasAnyUseOfValue(1);
2567   if (!HiExists &&
2568       (!LegalOperations ||
2569        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2570     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2571     return CombineTo(N, Res, Res);
2572   }
2573
2574   // If the low half is not needed, just compute the high half.
2575   bool LoExists = N->hasAnyUseOfValue(0);
2576   if (!LoExists &&
2577       (!LegalOperations ||
2578        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2579     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2580     return CombineTo(N, Res, Res);
2581   }
2582
2583   // If both halves are used, return as it is.
2584   if (LoExists && HiExists)
2585     return SDValue();
2586
2587   // If the two computed results can be simplified separately, separate them.
2588   if (LoExists) {
2589     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2590     AddToWorklist(Lo.getNode());
2591     SDValue LoOpt = combine(Lo.getNode());
2592     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2593         (!LegalOperations ||
2594          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2595       return CombineTo(N, LoOpt, LoOpt);
2596   }
2597
2598   if (HiExists) {
2599     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2600     AddToWorklist(Hi.getNode());
2601     SDValue HiOpt = combine(Hi.getNode());
2602     if (HiOpt.getNode() && HiOpt != Hi &&
2603         (!LegalOperations ||
2604          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2605       return CombineTo(N, HiOpt, HiOpt);
2606   }
2607
2608   return SDValue();
2609 }
2610
2611 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2612   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2613     return Res;
2614
2615   EVT VT = N->getValueType(0);
2616   SDLoc DL(N);
2617
2618   // If the type is twice as wide is legal, transform the mulhu to a wider
2619   // multiply plus a shift.
2620   if (VT.isSimple() && !VT.isVector()) {
2621     MVT Simple = VT.getSimpleVT();
2622     unsigned SimpleSize = Simple.getSizeInBits();
2623     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2624     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2625       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2626       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2627       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2628       // Compute the high part as N1.
2629       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2630             DAG.getConstant(SimpleSize, DL,
2631                             getShiftAmountTy(Lo.getValueType())));
2632       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2633       // Compute the low part as N0.
2634       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2635       return CombineTo(N, Lo, Hi);
2636     }
2637   }
2638
2639   return SDValue();
2640 }
2641
2642 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2643   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2644     return Res;
2645
2646   EVT VT = N->getValueType(0);
2647   SDLoc DL(N);
2648
2649   // If the type is twice as wide is legal, transform the mulhu to a wider
2650   // multiply plus a shift.
2651   if (VT.isSimple() && !VT.isVector()) {
2652     MVT Simple = VT.getSimpleVT();
2653     unsigned SimpleSize = Simple.getSizeInBits();
2654     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2655     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2656       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2657       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2658       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2659       // Compute the high part as N1.
2660       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2661             DAG.getConstant(SimpleSize, DL,
2662                             getShiftAmountTy(Lo.getValueType())));
2663       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2664       // Compute the low part as N0.
2665       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2666       return CombineTo(N, Lo, Hi);
2667     }
2668   }
2669
2670   return SDValue();
2671 }
2672
2673 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2674   // (smulo x, 2) -> (saddo x, x)
2675   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2676     if (C2->getAPIntValue() == 2)
2677       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2678                          N->getOperand(0), N->getOperand(0));
2679
2680   return SDValue();
2681 }
2682
2683 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2684   // (umulo x, 2) -> (uaddo x, x)
2685   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2686     if (C2->getAPIntValue() == 2)
2687       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2688                          N->getOperand(0), N->getOperand(0));
2689
2690   return SDValue();
2691 }
2692
2693 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2694   SDValue N0 = N->getOperand(0);
2695   SDValue N1 = N->getOperand(1);
2696   EVT VT = N0.getValueType();
2697
2698   // fold vector ops
2699   if (VT.isVector())
2700     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2701       return FoldedVOp;
2702
2703   // fold (add c1, c2) -> c1+c2
2704   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2705   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2706   if (N0C && N1C)
2707     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2708
2709   // canonicalize constant to RHS
2710   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2711      !isConstantIntBuildVectorOrConstantInt(N1))
2712     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2713
2714   return SDValue();
2715 }
2716
2717 /// If this is a binary operator with two operands of the same opcode, try to
2718 /// simplify it.
2719 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2720   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2721   EVT VT = N0.getValueType();
2722   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2723
2724   // Bail early if none of these transforms apply.
2725   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2726
2727   // For each of OP in AND/OR/XOR:
2728   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2729   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2730   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2731   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2732   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2733   //
2734   // do not sink logical op inside of a vector extend, since it may combine
2735   // into a vsetcc.
2736   EVT Op0VT = N0.getOperand(0).getValueType();
2737   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2738        N0.getOpcode() == ISD::SIGN_EXTEND ||
2739        N0.getOpcode() == ISD::BSWAP ||
2740        // Avoid infinite looping with PromoteIntBinOp.
2741        (N0.getOpcode() == ISD::ANY_EXTEND &&
2742         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2743        (N0.getOpcode() == ISD::TRUNCATE &&
2744         (!TLI.isZExtFree(VT, Op0VT) ||
2745          !TLI.isTruncateFree(Op0VT, VT)) &&
2746         TLI.isTypeLegal(Op0VT))) &&
2747       !VT.isVector() &&
2748       Op0VT == N1.getOperand(0).getValueType() &&
2749       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2750     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2751                                  N0.getOperand(0).getValueType(),
2752                                  N0.getOperand(0), N1.getOperand(0));
2753     AddToWorklist(ORNode.getNode());
2754     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2755   }
2756
2757   // For each of OP in SHL/SRL/SRA/AND...
2758   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2759   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2760   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2761   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2762        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2763       N0.getOperand(1) == N1.getOperand(1)) {
2764     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2765                                  N0.getOperand(0).getValueType(),
2766                                  N0.getOperand(0), N1.getOperand(0));
2767     AddToWorklist(ORNode.getNode());
2768     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2769                        ORNode, N0.getOperand(1));
2770   }
2771
2772   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2773   // Only perform this optimization after type legalization and before
2774   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2775   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2776   // we don't want to undo this promotion.
2777   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2778   // on scalars.
2779   if ((N0.getOpcode() == ISD::BITCAST ||
2780        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2781       Level == AfterLegalizeTypes) {
2782     SDValue In0 = N0.getOperand(0);
2783     SDValue In1 = N1.getOperand(0);
2784     EVT In0Ty = In0.getValueType();
2785     EVT In1Ty = In1.getValueType();
2786     SDLoc DL(N);
2787     // If both incoming values are integers, and the original types are the
2788     // same.
2789     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2790       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2791       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2792       AddToWorklist(Op.getNode());
2793       return BC;
2794     }
2795   }
2796
2797   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2798   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2799   // If both shuffles use the same mask, and both shuffle within a single
2800   // vector, then it is worthwhile to move the swizzle after the operation.
2801   // The type-legalizer generates this pattern when loading illegal
2802   // vector types from memory. In many cases this allows additional shuffle
2803   // optimizations.
2804   // There are other cases where moving the shuffle after the xor/and/or
2805   // is profitable even if shuffles don't perform a swizzle.
2806   // If both shuffles use the same mask, and both shuffles have the same first
2807   // or second operand, then it might still be profitable to move the shuffle
2808   // after the xor/and/or operation.
2809   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2810     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2811     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2812
2813     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2814            "Inputs to shuffles are not the same type");
2815
2816     // Check that both shuffles use the same mask. The masks are known to be of
2817     // the same length because the result vector type is the same.
2818     // Check also that shuffles have only one use to avoid introducing extra
2819     // instructions.
2820     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2821         SVN0->getMask().equals(SVN1->getMask())) {
2822       SDValue ShOp = N0->getOperand(1);
2823
2824       // Don't try to fold this node if it requires introducing a
2825       // build vector of all zeros that might be illegal at this stage.
2826       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2827         if (!LegalTypes)
2828           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2829         else
2830           ShOp = SDValue();
2831       }
2832
2833       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2834       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2835       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2836       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2837         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2838                                       N0->getOperand(0), N1->getOperand(0));
2839         AddToWorklist(NewNode.getNode());
2840         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2841                                     &SVN0->getMask()[0]);
2842       }
2843
2844       // Don't try to fold this node if it requires introducing a
2845       // build vector of all zeros that might be illegal at this stage.
2846       ShOp = N0->getOperand(0);
2847       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2848         if (!LegalTypes)
2849           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2850         else
2851           ShOp = SDValue();
2852       }
2853
2854       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2855       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2856       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2857       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2858         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2859                                       N0->getOperand(1), N1->getOperand(1));
2860         AddToWorklist(NewNode.getNode());
2861         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2862                                     &SVN0->getMask()[0]);
2863       }
2864     }
2865   }
2866
2867   return SDValue();
2868 }
2869
2870 /// This contains all DAGCombine rules which reduce two values combined by
2871 /// an And operation to a single value. This makes them reusable in the context
2872 /// of visitSELECT(). Rules involving constants are not included as
2873 /// visitSELECT() already handles those cases.
2874 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2875                                   SDNode *LocReference) {
2876   EVT VT = N1.getValueType();
2877
2878   // fold (and x, undef) -> 0
2879   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2880     return DAG.getConstant(0, SDLoc(LocReference), VT);
2881   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2882   SDValue LL, LR, RL, RR, CC0, CC1;
2883   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2884     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2885     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2886
2887     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2888         LL.getValueType().isInteger()) {
2889       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2890       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2891         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2892                                      LR.getValueType(), LL, RL);
2893         AddToWorklist(ORNode.getNode());
2894         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2895       }
2896       if (isAllOnesConstant(LR)) {
2897         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2898         if (Op1 == ISD::SETEQ) {
2899           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2900                                         LR.getValueType(), LL, RL);
2901           AddToWorklist(ANDNode.getNode());
2902           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2903         }
2904         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2905         if (Op1 == ISD::SETGT) {
2906           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2907                                        LR.getValueType(), LL, RL);
2908           AddToWorklist(ORNode.getNode());
2909           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2910         }
2911       }
2912     }
2913     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2914     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2915         Op0 == Op1 && LL.getValueType().isInteger() &&
2916       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2917                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2918       SDLoc DL(N0);
2919       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2920                                     LL, DAG.getConstant(1, DL,
2921                                                         LL.getValueType()));
2922       AddToWorklist(ADDNode.getNode());
2923       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2924                           DAG.getConstant(2, DL, LL.getValueType()),
2925                           ISD::SETUGE);
2926     }
2927     // canonicalize equivalent to ll == rl
2928     if (LL == RR && LR == RL) {
2929       Op1 = ISD::getSetCCSwappedOperands(Op1);
2930       std::swap(RL, RR);
2931     }
2932     if (LL == RL && LR == RR) {
2933       bool isInteger = LL.getValueType().isInteger();
2934       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2935       if (Result != ISD::SETCC_INVALID &&
2936           (!LegalOperations ||
2937            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2938             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2939         EVT CCVT = getSetCCResultType(LL.getValueType());
2940         if (N0.getValueType() == CCVT ||
2941             (!LegalOperations && N0.getValueType() == MVT::i1))
2942           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2943                               LL, LR, Result);
2944       }
2945     }
2946   }
2947
2948   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2949       VT.getSizeInBits() <= 64) {
2950     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2951       APInt ADDC = ADDI->getAPIntValue();
2952       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2953         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2954         // immediate for an add, but it is legal if its top c2 bits are set,
2955         // transform the ADD so the immediate doesn't need to be materialized
2956         // in a register.
2957         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2958           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2959                                              SRLI->getZExtValue());
2960           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2961             ADDC |= Mask;
2962             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2963               SDLoc DL(N0);
2964               SDValue NewAdd =
2965                 DAG.getNode(ISD::ADD, DL, VT,
2966                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2967               CombineTo(N0.getNode(), NewAdd);
2968               // Return N so it doesn't get rechecked!
2969               return SDValue(LocReference, 0);
2970             }
2971           }
2972         }
2973       }
2974     }
2975   }
2976
2977   return SDValue();
2978 }
2979
2980 SDValue DAGCombiner::visitAND(SDNode *N) {
2981   SDValue N0 = N->getOperand(0);
2982   SDValue N1 = N->getOperand(1);
2983   EVT VT = N1.getValueType();
2984
2985   // fold vector ops
2986   if (VT.isVector()) {
2987     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2988       return FoldedVOp;
2989
2990     // fold (and x, 0) -> 0, vector edition
2991     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2992       // do not return N0, because undef node may exist in N0
2993       return DAG.getConstant(
2994           APInt::getNullValue(
2995               N0.getValueType().getScalarType().getSizeInBits()),
2996           SDLoc(N), N0.getValueType());
2997     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2998       // do not return N1, because undef node may exist in N1
2999       return DAG.getConstant(
3000           APInt::getNullValue(
3001               N1.getValueType().getScalarType().getSizeInBits()),
3002           SDLoc(N), N1.getValueType());
3003
3004     // fold (and x, -1) -> x, vector edition
3005     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3006       return N1;
3007     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3008       return N0;
3009   }
3010
3011   // fold (and c1, c2) -> c1&c2
3012   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3013   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3014   if (N0C && N1C && !N1C->isOpaque())
3015     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3016   // canonicalize constant to RHS
3017   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3018      !isConstantIntBuildVectorOrConstantInt(N1))
3019     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3020   // fold (and x, -1) -> x
3021   if (isAllOnesConstant(N1))
3022     return N0;
3023   // if (and x, c) is known to be zero, return 0
3024   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3025   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3026                                    APInt::getAllOnesValue(BitWidth)))
3027     return DAG.getConstant(0, SDLoc(N), VT);
3028   // reassociate and
3029   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3030     return RAND;
3031   // fold (and (or x, C), D) -> D if (C & D) == D
3032   if (N1C && N0.getOpcode() == ISD::OR)
3033     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3034       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3035         return N1;
3036   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3037   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3038     SDValue N0Op0 = N0.getOperand(0);
3039     APInt Mask = ~N1C->getAPIntValue();
3040     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3041     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3042       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3043                                  N0.getValueType(), N0Op0);
3044
3045       // Replace uses of the AND with uses of the Zero extend node.
3046       CombineTo(N, Zext);
3047
3048       // We actually want to replace all uses of the any_extend with the
3049       // zero_extend, to avoid duplicating things.  This will later cause this
3050       // AND to be folded.
3051       CombineTo(N0.getNode(), Zext);
3052       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3053     }
3054   }
3055   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3056   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3057   // already be zero by virtue of the width of the base type of the load.
3058   //
3059   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3060   // more cases.
3061   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3062        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3063       N0.getOpcode() == ISD::LOAD) {
3064     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3065                                          N0 : N0.getOperand(0) );
3066
3067     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3068     // This can be a pure constant or a vector splat, in which case we treat the
3069     // vector as a scalar and use the splat value.
3070     APInt Constant = APInt::getNullValue(1);
3071     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3072       Constant = C->getAPIntValue();
3073     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3074       APInt SplatValue, SplatUndef;
3075       unsigned SplatBitSize;
3076       bool HasAnyUndefs;
3077       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3078                                              SplatBitSize, HasAnyUndefs);
3079       if (IsSplat) {
3080         // Undef bits can contribute to a possible optimisation if set, so
3081         // set them.
3082         SplatValue |= SplatUndef;
3083
3084         // The splat value may be something like "0x00FFFFFF", which means 0 for
3085         // the first vector value and FF for the rest, repeating. We need a mask
3086         // that will apply equally to all members of the vector, so AND all the
3087         // lanes of the constant together.
3088         EVT VT = Vector->getValueType(0);
3089         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3090
3091         // If the splat value has been compressed to a bitlength lower
3092         // than the size of the vector lane, we need to re-expand it to
3093         // the lane size.
3094         if (BitWidth > SplatBitSize)
3095           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3096                SplatBitSize < BitWidth;
3097                SplatBitSize = SplatBitSize * 2)
3098             SplatValue |= SplatValue.shl(SplatBitSize);
3099
3100         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3101         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3102         if (SplatBitSize % BitWidth == 0) {
3103           Constant = APInt::getAllOnesValue(BitWidth);
3104           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3105             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3106         }
3107       }
3108     }
3109
3110     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3111     // actually legal and isn't going to get expanded, else this is a false
3112     // optimisation.
3113     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3114                                                     Load->getValueType(0),
3115                                                     Load->getMemoryVT());
3116
3117     // Resize the constant to the same size as the original memory access before
3118     // extension. If it is still the AllOnesValue then this AND is completely
3119     // unneeded.
3120     Constant =
3121       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3122
3123     bool B;
3124     switch (Load->getExtensionType()) {
3125     default: B = false; break;
3126     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3127     case ISD::ZEXTLOAD:
3128     case ISD::NON_EXTLOAD: B = true; break;
3129     }
3130
3131     if (B && Constant.isAllOnesValue()) {
3132       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3133       // preserve semantics once we get rid of the AND.
3134       SDValue NewLoad(Load, 0);
3135       if (Load->getExtensionType() == ISD::EXTLOAD) {
3136         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3137                               Load->getValueType(0), SDLoc(Load),
3138                               Load->getChain(), Load->getBasePtr(),
3139                               Load->getOffset(), Load->getMemoryVT(),
3140                               Load->getMemOperand());
3141         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3142         if (Load->getNumValues() == 3) {
3143           // PRE/POST_INC loads have 3 values.
3144           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3145                            NewLoad.getValue(2) };
3146           CombineTo(Load, To, 3, true);
3147         } else {
3148           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3149         }
3150       }
3151
3152       // Fold the AND away, taking care not to fold to the old load node if we
3153       // replaced it.
3154       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3155
3156       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3157     }
3158   }
3159
3160   // fold (and (load x), 255) -> (zextload x, i8)
3161   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3162   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3163   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3164               (N0.getOpcode() == ISD::ANY_EXTEND &&
3165                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3166     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3167     LoadSDNode *LN0 = HasAnyExt
3168       ? cast<LoadSDNode>(N0.getOperand(0))
3169       : cast<LoadSDNode>(N0);
3170     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3171         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3172       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3173       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3174         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3175         EVT LoadedVT = LN0->getMemoryVT();
3176         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3177
3178         if (ExtVT == LoadedVT &&
3179             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3180                                                     ExtVT))) {
3181
3182           SDValue NewLoad =
3183             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3184                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3185                            LN0->getMemOperand());
3186           AddToWorklist(N);
3187           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3188           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3189         }
3190
3191         // Do not change the width of a volatile load.
3192         // Do not generate loads of non-round integer types since these can
3193         // be expensive (and would be wrong if the type is not byte sized).
3194         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3195             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3196                                                     ExtVT)) &&
3197             TLI.shouldReduceLoadWidth(LN0, ISD::ZEXTLOAD, ExtVT)) {
3198           EVT PtrType = LN0->getOperand(1).getValueType();
3199
3200           unsigned Alignment = LN0->getAlignment();
3201           SDValue NewPtr = LN0->getBasePtr();
3202
3203           // For big endian targets, we need to add an offset to the pointer
3204           // to load the correct bytes.  For little endian systems, we merely
3205           // need to read fewer bytes from the same pointer.
3206           if (DAG.getDataLayout().isBigEndian()) {
3207             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3208             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3209             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3210             SDLoc DL(LN0);
3211             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3212                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3213             Alignment = MinAlign(Alignment, PtrOff);
3214           }
3215
3216           AddToWorklist(NewPtr.getNode());
3217
3218           SDValue Load =
3219             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3220                            LN0->getChain(), NewPtr,
3221                            LN0->getPointerInfo(),
3222                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3223                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3224           AddToWorklist(N);
3225           CombineTo(LN0, Load, Load.getValue(1));
3226           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3227         }
3228       }
3229     }
3230   }
3231
3232   if (SDValue Combined = visitANDLike(N0, N1, N))
3233     return Combined;
3234
3235   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3236   if (N0.getOpcode() == N1.getOpcode())
3237     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3238       return Tmp;
3239
3240   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3241   // fold (and (sra)) -> (and (srl)) when possible.
3242   if (!VT.isVector() &&
3243       SimplifyDemandedBits(SDValue(N, 0)))
3244     return SDValue(N, 0);
3245
3246   // fold (zext_inreg (extload x)) -> (zextload x)
3247   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3248     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3249     EVT MemVT = LN0->getMemoryVT();
3250     // If we zero all the possible extended bits, then we can turn this into
3251     // a zextload if we are running before legalize or the operation is legal.
3252     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3253     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3254                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3255         ((!LegalOperations && !LN0->isVolatile()) ||
3256          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3257       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3258                                        LN0->getChain(), LN0->getBasePtr(),
3259                                        MemVT, LN0->getMemOperand());
3260       AddToWorklist(N);
3261       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3262       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3263     }
3264   }
3265   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3266   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3267       N0.hasOneUse()) {
3268     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3269     EVT MemVT = LN0->getMemoryVT();
3270     // If we zero all the possible extended bits, then we can turn this into
3271     // a zextload if we are running before legalize or the operation is legal.
3272     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3273     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3274                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3275         ((!LegalOperations && !LN0->isVolatile()) ||
3276          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3277       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3278                                        LN0->getChain(), LN0->getBasePtr(),
3279                                        MemVT, LN0->getMemOperand());
3280       AddToWorklist(N);
3281       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3282       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3283     }
3284   }
3285   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3286   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3287     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3288                                        N0.getOperand(1), false);
3289     if (BSwap.getNode())
3290       return BSwap;
3291   }
3292
3293   return SDValue();
3294 }
3295
3296 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3297 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3298                                         bool DemandHighBits) {
3299   if (!LegalOperations)
3300     return SDValue();
3301
3302   EVT VT = N->getValueType(0);
3303   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3304     return SDValue();
3305   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3306     return SDValue();
3307
3308   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3309   bool LookPassAnd0 = false;
3310   bool LookPassAnd1 = false;
3311   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3312       std::swap(N0, N1);
3313   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3314       std::swap(N0, N1);
3315   if (N0.getOpcode() == ISD::AND) {
3316     if (!N0.getNode()->hasOneUse())
3317       return SDValue();
3318     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3319     if (!N01C || N01C->getZExtValue() != 0xFF00)
3320       return SDValue();
3321     N0 = N0.getOperand(0);
3322     LookPassAnd0 = true;
3323   }
3324
3325   if (N1.getOpcode() == ISD::AND) {
3326     if (!N1.getNode()->hasOneUse())
3327       return SDValue();
3328     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3329     if (!N11C || N11C->getZExtValue() != 0xFF)
3330       return SDValue();
3331     N1 = N1.getOperand(0);
3332     LookPassAnd1 = true;
3333   }
3334
3335   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3336     std::swap(N0, N1);
3337   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3338     return SDValue();
3339   if (!N0.getNode()->hasOneUse() ||
3340       !N1.getNode()->hasOneUse())
3341     return SDValue();
3342
3343   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3344   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3345   if (!N01C || !N11C)
3346     return SDValue();
3347   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3348     return SDValue();
3349
3350   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3351   SDValue N00 = N0->getOperand(0);
3352   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3353     if (!N00.getNode()->hasOneUse())
3354       return SDValue();
3355     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3356     if (!N001C || N001C->getZExtValue() != 0xFF)
3357       return SDValue();
3358     N00 = N00.getOperand(0);
3359     LookPassAnd0 = true;
3360   }
3361
3362   SDValue N10 = N1->getOperand(0);
3363   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3364     if (!N10.getNode()->hasOneUse())
3365       return SDValue();
3366     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3367     if (!N101C || N101C->getZExtValue() != 0xFF00)
3368       return SDValue();
3369     N10 = N10.getOperand(0);
3370     LookPassAnd1 = true;
3371   }
3372
3373   if (N00 != N10)
3374     return SDValue();
3375
3376   // Make sure everything beyond the low halfword gets set to zero since the SRL
3377   // 16 will clear the top bits.
3378   unsigned OpSizeInBits = VT.getSizeInBits();
3379   if (DemandHighBits && OpSizeInBits > 16) {
3380     // If the left-shift isn't masked out then the only way this is a bswap is
3381     // if all bits beyond the low 8 are 0. In that case the entire pattern
3382     // reduces to a left shift anyway: leave it for other parts of the combiner.
3383     if (!LookPassAnd0)
3384       return SDValue();
3385
3386     // However, if the right shift isn't masked out then it might be because
3387     // it's not needed. See if we can spot that too.
3388     if (!LookPassAnd1 &&
3389         !DAG.MaskedValueIsZero(
3390             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3391       return SDValue();
3392   }
3393
3394   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3395   if (OpSizeInBits > 16) {
3396     SDLoc DL(N);
3397     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3398                       DAG.getConstant(OpSizeInBits - 16, DL,
3399                                       getShiftAmountTy(VT)));
3400   }
3401   return Res;
3402 }
3403
3404 /// Return true if the specified node is an element that makes up a 32-bit
3405 /// packed halfword byteswap.
3406 /// ((x & 0x000000ff) << 8) |
3407 /// ((x & 0x0000ff00) >> 8) |
3408 /// ((x & 0x00ff0000) << 8) |
3409 /// ((x & 0xff000000) >> 8)
3410 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3411   if (!N.getNode()->hasOneUse())
3412     return false;
3413
3414   unsigned Opc = N.getOpcode();
3415   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3416     return false;
3417
3418   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3419   if (!N1C)
3420     return false;
3421
3422   unsigned Num;
3423   switch (N1C->getZExtValue()) {
3424   default:
3425     return false;
3426   case 0xFF:       Num = 0; break;
3427   case 0xFF00:     Num = 1; break;
3428   case 0xFF0000:   Num = 2; break;
3429   case 0xFF000000: Num = 3; break;
3430   }
3431
3432   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3433   SDValue N0 = N.getOperand(0);
3434   if (Opc == ISD::AND) {
3435     if (Num == 0 || Num == 2) {
3436       // (x >> 8) & 0xff
3437       // (x >> 8) & 0xff0000
3438       if (N0.getOpcode() != ISD::SRL)
3439         return false;
3440       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3441       if (!C || C->getZExtValue() != 8)
3442         return false;
3443     } else {
3444       // (x << 8) & 0xff00
3445       // (x << 8) & 0xff000000
3446       if (N0.getOpcode() != ISD::SHL)
3447         return false;
3448       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3449       if (!C || C->getZExtValue() != 8)
3450         return false;
3451     }
3452   } else if (Opc == ISD::SHL) {
3453     // (x & 0xff) << 8
3454     // (x & 0xff0000) << 8
3455     if (Num != 0 && Num != 2)
3456       return false;
3457     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3458     if (!C || C->getZExtValue() != 8)
3459       return false;
3460   } else { // Opc == ISD::SRL
3461     // (x & 0xff00) >> 8
3462     // (x & 0xff000000) >> 8
3463     if (Num != 1 && Num != 3)
3464       return false;
3465     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3466     if (!C || C->getZExtValue() != 8)
3467       return false;
3468   }
3469
3470   if (Parts[Num])
3471     return false;
3472
3473   Parts[Num] = N0.getOperand(0).getNode();
3474   return true;
3475 }
3476
3477 /// Match a 32-bit packed halfword bswap. That is
3478 /// ((x & 0x000000ff) << 8) |
3479 /// ((x & 0x0000ff00) >> 8) |
3480 /// ((x & 0x00ff0000) << 8) |
3481 /// ((x & 0xff000000) >> 8)
3482 /// => (rotl (bswap x), 16)
3483 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3484   if (!LegalOperations)
3485     return SDValue();
3486
3487   EVT VT = N->getValueType(0);
3488   if (VT != MVT::i32)
3489     return SDValue();
3490   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3491     return SDValue();
3492
3493   // Look for either
3494   // (or (or (and), (and)), (or (and), (and)))
3495   // (or (or (or (and), (and)), (and)), (and))
3496   if (N0.getOpcode() != ISD::OR)
3497     return SDValue();
3498   SDValue N00 = N0.getOperand(0);
3499   SDValue N01 = N0.getOperand(1);
3500   SDNode *Parts[4] = {};
3501
3502   if (N1.getOpcode() == ISD::OR &&
3503       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3504     // (or (or (and), (and)), (or (and), (and)))
3505     SDValue N000 = N00.getOperand(0);
3506     if (!isBSwapHWordElement(N000, Parts))
3507       return SDValue();
3508
3509     SDValue N001 = N00.getOperand(1);
3510     if (!isBSwapHWordElement(N001, Parts))
3511       return SDValue();
3512     SDValue N010 = N01.getOperand(0);
3513     if (!isBSwapHWordElement(N010, Parts))
3514       return SDValue();
3515     SDValue N011 = N01.getOperand(1);
3516     if (!isBSwapHWordElement(N011, Parts))
3517       return SDValue();
3518   } else {
3519     // (or (or (or (and), (and)), (and)), (and))
3520     if (!isBSwapHWordElement(N1, Parts))
3521       return SDValue();
3522     if (!isBSwapHWordElement(N01, Parts))
3523       return SDValue();
3524     if (N00.getOpcode() != ISD::OR)
3525       return SDValue();
3526     SDValue N000 = N00.getOperand(0);
3527     if (!isBSwapHWordElement(N000, Parts))
3528       return SDValue();
3529     SDValue N001 = N00.getOperand(1);
3530     if (!isBSwapHWordElement(N001, Parts))
3531       return SDValue();
3532   }
3533
3534   // Make sure the parts are all coming from the same node.
3535   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3536     return SDValue();
3537
3538   SDLoc DL(N);
3539   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3540                               SDValue(Parts[0], 0));
3541
3542   // Result of the bswap should be rotated by 16. If it's not legal, then
3543   // do  (x << 16) | (x >> 16).
3544   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3545   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3546     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3547   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3548     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3549   return DAG.getNode(ISD::OR, DL, VT,
3550                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3551                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3552 }
3553
3554 /// This contains all DAGCombine rules which reduce two values combined by
3555 /// an Or operation to a single value \see visitANDLike().
3556 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3557   EVT VT = N1.getValueType();
3558   // fold (or x, undef) -> -1
3559   if (!LegalOperations &&
3560       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3561     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3562     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3563                            SDLoc(LocReference), VT);
3564   }
3565   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3566   SDValue LL, LR, RL, RR, CC0, CC1;
3567   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3568     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3569     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3570
3571     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3572       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3573       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3574       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3575         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3576                                      LR.getValueType(), LL, RL);
3577         AddToWorklist(ORNode.getNode());
3578         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3579       }
3580       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3581       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3582       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3583         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3584                                       LR.getValueType(), LL, RL);
3585         AddToWorklist(ANDNode.getNode());
3586         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3587       }
3588     }
3589     // canonicalize equivalent to ll == rl
3590     if (LL == RR && LR == RL) {
3591       Op1 = ISD::getSetCCSwappedOperands(Op1);
3592       std::swap(RL, RR);
3593     }
3594     if (LL == RL && LR == RR) {
3595       bool isInteger = LL.getValueType().isInteger();
3596       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3597       if (Result != ISD::SETCC_INVALID &&
3598           (!LegalOperations ||
3599            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3600             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3601         EVT CCVT = getSetCCResultType(LL.getValueType());
3602         if (N0.getValueType() == CCVT ||
3603             (!LegalOperations && N0.getValueType() == MVT::i1))
3604           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3605                               LL, LR, Result);
3606       }
3607     }
3608   }
3609
3610   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3611   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3612       // Don't increase # computations.
3613       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3614     // We can only do this xform if we know that bits from X that are set in C2
3615     // but not in C1 are already zero.  Likewise for Y.
3616     if (const ConstantSDNode *N0O1C =
3617         getAsNonOpaqueConstant(N0.getOperand(1))) {
3618       if (const ConstantSDNode *N1O1C =
3619           getAsNonOpaqueConstant(N1.getOperand(1))) {
3620         // We can only do this xform if we know that bits from X that are set in
3621         // C2 but not in C1 are already zero.  Likewise for Y.
3622         const APInt &LHSMask = N0O1C->getAPIntValue();
3623         const APInt &RHSMask = N1O1C->getAPIntValue();
3624
3625         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3626             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3627           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3628                                   N0.getOperand(0), N1.getOperand(0));
3629           SDLoc DL(LocReference);
3630           return DAG.getNode(ISD::AND, DL, VT, X,
3631                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3632         }
3633       }
3634     }
3635   }
3636
3637   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3638   if (N0.getOpcode() == ISD::AND &&
3639       N1.getOpcode() == ISD::AND &&
3640       N0.getOperand(0) == N1.getOperand(0) &&
3641       // Don't increase # computations.
3642       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3643     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3644                             N0.getOperand(1), N1.getOperand(1));
3645     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3646   }
3647
3648   return SDValue();
3649 }
3650
3651 SDValue DAGCombiner::visitOR(SDNode *N) {
3652   SDValue N0 = N->getOperand(0);
3653   SDValue N1 = N->getOperand(1);
3654   EVT VT = N1.getValueType();
3655
3656   // fold vector ops
3657   if (VT.isVector()) {
3658     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3659       return FoldedVOp;
3660
3661     // fold (or x, 0) -> x, vector edition
3662     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3663       return N1;
3664     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3665       return N0;
3666
3667     // fold (or x, -1) -> -1, vector edition
3668     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3669       // do not return N0, because undef node may exist in N0
3670       return DAG.getConstant(
3671           APInt::getAllOnesValue(
3672               N0.getValueType().getScalarType().getSizeInBits()),
3673           SDLoc(N), N0.getValueType());
3674     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3675       // do not return N1, because undef node may exist in N1
3676       return DAG.getConstant(
3677           APInt::getAllOnesValue(
3678               N1.getValueType().getScalarType().getSizeInBits()),
3679           SDLoc(N), N1.getValueType());
3680
3681     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3682     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3683     // Do this only if the resulting shuffle is legal.
3684     if (isa<ShuffleVectorSDNode>(N0) &&
3685         isa<ShuffleVectorSDNode>(N1) &&
3686         // Avoid folding a node with illegal type.
3687         TLI.isTypeLegal(VT) &&
3688         N0->getOperand(1) == N1->getOperand(1) &&
3689         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3690       bool CanFold = true;
3691       unsigned NumElts = VT.getVectorNumElements();
3692       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3693       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3694       // We construct two shuffle masks:
3695       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3696       // and N1 as the second operand.
3697       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3698       // and N0 as the second operand.
3699       // We do this because OR is commutable and therefore there might be
3700       // two ways to fold this node into a shuffle.
3701       SmallVector<int,4> Mask1;
3702       SmallVector<int,4> Mask2;
3703
3704       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3705         int M0 = SV0->getMaskElt(i);
3706         int M1 = SV1->getMaskElt(i);
3707
3708         // Both shuffle indexes are undef. Propagate Undef.
3709         if (M0 < 0 && M1 < 0) {
3710           Mask1.push_back(M0);
3711           Mask2.push_back(M0);
3712           continue;
3713         }
3714
3715         if (M0 < 0 || M1 < 0 ||
3716             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3717             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3718           CanFold = false;
3719           break;
3720         }
3721
3722         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3723         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3724       }
3725
3726       if (CanFold) {
3727         // Fold this sequence only if the resulting shuffle is 'legal'.
3728         if (TLI.isShuffleMaskLegal(Mask1, VT))
3729           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3730                                       N1->getOperand(0), &Mask1[0]);
3731         if (TLI.isShuffleMaskLegal(Mask2, VT))
3732           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3733                                       N0->getOperand(0), &Mask2[0]);
3734       }
3735     }
3736   }
3737
3738   // fold (or c1, c2) -> c1|c2
3739   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3740   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3741   if (N0C && N1C && !N1C->isOpaque())
3742     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3743   // canonicalize constant to RHS
3744   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3745      !isConstantIntBuildVectorOrConstantInt(N1))
3746     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3747   // fold (or x, 0) -> x
3748   if (isNullConstant(N1))
3749     return N0;
3750   // fold (or x, -1) -> -1
3751   if (isAllOnesConstant(N1))
3752     return N1;
3753   // fold (or x, c) -> c iff (x & ~c) == 0
3754   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3755     return N1;
3756
3757   if (SDValue Combined = visitORLike(N0, N1, N))
3758     return Combined;
3759
3760   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3761   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3762     return BSwap;
3763   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3764     return BSwap;
3765
3766   // reassociate or
3767   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3768     return ROR;
3769   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3770   // iff (c1 & c2) == 0.
3771   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3772              isa<ConstantSDNode>(N0.getOperand(1))) {
3773     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3774     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3775       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3776                                                    N1C, C1))
3777         return DAG.getNode(
3778             ISD::AND, SDLoc(N), VT,
3779             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3780       return SDValue();
3781     }
3782   }
3783   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3784   if (N0.getOpcode() == N1.getOpcode())
3785     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3786       return Tmp;
3787
3788   // See if this is some rotate idiom.
3789   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3790     return SDValue(Rot, 0);
3791
3792   // Simplify the operands using demanded-bits information.
3793   if (!VT.isVector() &&
3794       SimplifyDemandedBits(SDValue(N, 0)))
3795     return SDValue(N, 0);
3796
3797   return SDValue();
3798 }
3799
3800 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3801 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3802   if (Op.getOpcode() == ISD::AND) {
3803     if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3804       Mask = Op.getOperand(1);
3805       Op = Op.getOperand(0);
3806     } else {
3807       return false;
3808     }
3809   }
3810
3811   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3812     Shift = Op;
3813     return true;
3814   }
3815
3816   return false;
3817 }
3818
3819 // Return true if we can prove that, whenever Neg and Pos are both in the
3820 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3821 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3822 //
3823 //     (or (shift1 X, Neg), (shift2 X, Pos))
3824 //
3825 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3826 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3827 // to consider shift amounts with defined behavior.
3828 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3829   // If EltSize is a power of 2 then:
3830   //
3831   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3832   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3833   //
3834   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3835   // for the stronger condition:
3836   //
3837   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3838   //
3839   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3840   // we can just replace Neg with Neg' for the rest of the function.
3841   //
3842   // In other cases we check for the even stronger condition:
3843   //
3844   //     Neg == EltSize - Pos                                    [B]
3845   //
3846   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3847   // behavior if Pos == 0 (and consequently Neg == EltSize).
3848   //
3849   // We could actually use [A] whenever EltSize is a power of 2, but the
3850   // only extra cases that it would match are those uninteresting ones
3851   // where Neg and Pos are never in range at the same time.  E.g. for
3852   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3853   // as well as (sub 32, Pos), but:
3854   //
3855   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3856   //
3857   // always invokes undefined behavior for 32-bit X.
3858   //
3859   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3860   unsigned MaskLoBits = 0;
3861   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3862     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3863       if (NegC->getAPIntValue() == EltSize - 1) {
3864         Neg = Neg.getOperand(0);
3865         MaskLoBits = Log2_64(EltSize);
3866       }
3867     }
3868   }
3869
3870   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3871   if (Neg.getOpcode() != ISD::SUB)
3872     return 0;
3873   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3874   if (!NegC)
3875     return 0;
3876   SDValue NegOp1 = Neg.getOperand(1);
3877
3878   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3879   // Pos'.  The truncation is redundant for the purpose of the equality.
3880   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3881     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3882       if (PosC->getAPIntValue() == EltSize - 1)
3883         Pos = Pos.getOperand(0);
3884
3885   // The condition we need is now:
3886   //
3887   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3888   //
3889   // If NegOp1 == Pos then we need:
3890   //
3891   //              EltSize & Mask == NegC & Mask
3892   //
3893   // (because "x & Mask" is a truncation and distributes through subtraction).
3894   APInt Width;
3895   if (Pos == NegOp1)
3896     Width = NegC->getAPIntValue();
3897
3898   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3899   // Then the condition we want to prove becomes:
3900   //
3901   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3902   //
3903   // which, again because "x & Mask" is a truncation, becomes:
3904   //
3905   //                NegC & Mask == (EltSize - PosC) & Mask
3906   //             EltSize & Mask == (NegC + PosC) & Mask
3907   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3908     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3909       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3910     else
3911       return false;
3912   } else
3913     return false;
3914
3915   // Now we just need to check that EltSize & Mask == Width & Mask.
3916   if (MaskLoBits)
3917     // EltSize & Mask is 0 since Mask is EltSize - 1.
3918     return Width.getLoBits(MaskLoBits) == 0;
3919   return Width == EltSize;
3920 }
3921
3922 // A subroutine of MatchRotate used once we have found an OR of two opposite
3923 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3924 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3925 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3926 // Neg with outer conversions stripped away.
3927 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3928                                        SDValue Neg, SDValue InnerPos,
3929                                        SDValue InnerNeg, unsigned PosOpcode,
3930                                        unsigned NegOpcode, SDLoc DL) {
3931   // fold (or (shl x, (*ext y)),
3932   //          (srl x, (*ext (sub 32, y)))) ->
3933   //   (rotl x, y) or (rotr x, (sub 32, y))
3934   //
3935   // fold (or (shl x, (*ext (sub 32, y))),
3936   //          (srl x, (*ext y))) ->
3937   //   (rotr x, y) or (rotl x, (sub 32, y))
3938   EVT VT = Shifted.getValueType();
3939   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3940     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3941     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3942                        HasPos ? Pos : Neg).getNode();
3943   }
3944
3945   return nullptr;
3946 }
3947
3948 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3949 // idioms for rotate, and if the target supports rotation instructions, generate
3950 // a rot[lr].
3951 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3952   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3953   EVT VT = LHS.getValueType();
3954   if (!TLI.isTypeLegal(VT)) return nullptr;
3955
3956   // The target must have at least one rotate flavor.
3957   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3958   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3959   if (!HasROTL && !HasROTR) return nullptr;
3960
3961   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3962   SDValue LHSShift;   // The shift.
3963   SDValue LHSMask;    // AND value if any.
3964   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3965     return nullptr; // Not part of a rotate.
3966
3967   SDValue RHSShift;   // The shift.
3968   SDValue RHSMask;    // AND value if any.
3969   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3970     return nullptr; // Not part of a rotate.
3971
3972   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3973     return nullptr;   // Not shifting the same value.
3974
3975   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3976     return nullptr;   // Shifts must disagree.
3977
3978   // Canonicalize shl to left side in a shl/srl pair.
3979   if (RHSShift.getOpcode() == ISD::SHL) {
3980     std::swap(LHS, RHS);
3981     std::swap(LHSShift, RHSShift);
3982     std::swap(LHSMask, RHSMask);
3983   }
3984
3985   unsigned EltSizeInBits = VT.getScalarSizeInBits();
3986   SDValue LHSShiftArg = LHSShift.getOperand(0);
3987   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3988   SDValue RHSShiftArg = RHSShift.getOperand(0);
3989   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3990
3991   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3992   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3993   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
3994     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
3995     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
3996     if ((LShVal + RShVal) != EltSizeInBits)
3997       return nullptr;
3998
3999     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4000                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4001
4002     // If there is an AND of either shifted operand, apply it to the result.
4003     if (LHSMask.getNode() || RHSMask.getNode()) {
4004       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4005       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4006
4007       if (LHSMask.getNode()) {
4008         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4009         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4010                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4011                                        DAG.getConstant(RHSBits, DL, VT)));
4012       }
4013       if (RHSMask.getNode()) {
4014         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4015         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4016                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4017                                        DAG.getConstant(LHSBits, DL, VT)));
4018       }
4019
4020       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4021     }
4022
4023     return Rot.getNode();
4024   }
4025
4026   // If there is a mask here, and we have a variable shift, we can't be sure
4027   // that we're masking out the right stuff.
4028   if (LHSMask.getNode() || RHSMask.getNode())
4029     return nullptr;
4030
4031   // If the shift amount is sign/zext/any-extended just peel it off.
4032   SDValue LExtOp0 = LHSShiftAmt;
4033   SDValue RExtOp0 = RHSShiftAmt;
4034   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4035        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4036        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4037        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4038       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4039        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4040        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4041        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4042     LExtOp0 = LHSShiftAmt.getOperand(0);
4043     RExtOp0 = RHSShiftAmt.getOperand(0);
4044   }
4045
4046   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4047                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4048   if (TryL)
4049     return TryL;
4050
4051   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4052                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4053   if (TryR)
4054     return TryR;
4055
4056   return nullptr;
4057 }
4058
4059 SDValue DAGCombiner::visitXOR(SDNode *N) {
4060   SDValue N0 = N->getOperand(0);
4061   SDValue N1 = N->getOperand(1);
4062   EVT VT = N0.getValueType();
4063
4064   // fold vector ops
4065   if (VT.isVector()) {
4066     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4067       return FoldedVOp;
4068
4069     // fold (xor x, 0) -> x, vector edition
4070     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4071       return N1;
4072     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4073       return N0;
4074   }
4075
4076   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4077   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4078     return DAG.getConstant(0, SDLoc(N), VT);
4079   // fold (xor x, undef) -> undef
4080   if (N0.getOpcode() == ISD::UNDEF)
4081     return N0;
4082   if (N1.getOpcode() == ISD::UNDEF)
4083     return N1;
4084   // fold (xor c1, c2) -> c1^c2
4085   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4086   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4087   if (N0C && N1C)
4088     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4089   // canonicalize constant to RHS
4090   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4091      !isConstantIntBuildVectorOrConstantInt(N1))
4092     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4093   // fold (xor x, 0) -> x
4094   if (isNullConstant(N1))
4095     return N0;
4096   // reassociate xor
4097   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4098     return RXOR;
4099
4100   // fold !(x cc y) -> (x !cc y)
4101   SDValue LHS, RHS, CC;
4102   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4103     bool isInt = LHS.getValueType().isInteger();
4104     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4105                                                isInt);
4106
4107     if (!LegalOperations ||
4108         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4109       switch (N0.getOpcode()) {
4110       default:
4111         llvm_unreachable("Unhandled SetCC Equivalent!");
4112       case ISD::SETCC:
4113         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4114       case ISD::SELECT_CC:
4115         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4116                                N0.getOperand(3), NotCC);
4117       }
4118     }
4119   }
4120
4121   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4122   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4123       N0.getNode()->hasOneUse() &&
4124       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4125     SDValue V = N0.getOperand(0);
4126     SDLoc DL(N0);
4127     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4128                     DAG.getConstant(1, DL, V.getValueType()));
4129     AddToWorklist(V.getNode());
4130     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4131   }
4132
4133   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4134   if (isOneConstant(N1) && VT == MVT::i1 &&
4135       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4136     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4137     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4138       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4139       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4140       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4141       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4142       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4143     }
4144   }
4145   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4146   if (isAllOnesConstant(N1) &&
4147       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4148     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4149     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4150       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4151       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4152       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4153       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4154       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4155     }
4156   }
4157   // fold (xor (and x, y), y) -> (and (not x), y)
4158   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4159       N0->getOperand(1) == N1) {
4160     SDValue X = N0->getOperand(0);
4161     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4162     AddToWorklist(NotX.getNode());
4163     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4164   }
4165   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4166   if (N1C && N0.getOpcode() == ISD::XOR) {
4167     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4168       SDLoc DL(N);
4169       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4170                          DAG.getConstant(N1C->getAPIntValue() ^
4171                                          N00C->getAPIntValue(), DL, VT));
4172     }
4173     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4174       SDLoc DL(N);
4175       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4176                          DAG.getConstant(N1C->getAPIntValue() ^
4177                                          N01C->getAPIntValue(), DL, VT));
4178     }
4179   }
4180   // fold (xor x, x) -> 0
4181   if (N0 == N1)
4182     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4183
4184   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4185   // Here is a concrete example of this equivalence:
4186   // i16   x ==  14
4187   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4188   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4189   //
4190   // =>
4191   //
4192   // i16     ~1      == 0b1111111111111110
4193   // i16 rol(~1, 14) == 0b1011111111111111
4194   //
4195   // Some additional tips to help conceptualize this transform:
4196   // - Try to see the operation as placing a single zero in a value of all ones.
4197   // - There exists no value for x which would allow the result to contain zero.
4198   // - Values of x larger than the bitwidth are undefined and do not require a
4199   //   consistent result.
4200   // - Pushing the zero left requires shifting one bits in from the right.
4201   // A rotate left of ~1 is a nice way of achieving the desired result.
4202   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4203       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4204     SDLoc DL(N);
4205     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4206                        N0.getOperand(1));
4207   }
4208
4209   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4210   if (N0.getOpcode() == N1.getOpcode())
4211     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4212       return Tmp;
4213
4214   // Simplify the expression using non-local knowledge.
4215   if (!VT.isVector() &&
4216       SimplifyDemandedBits(SDValue(N, 0)))
4217     return SDValue(N, 0);
4218
4219   return SDValue();
4220 }
4221
4222 /// Handle transforms common to the three shifts, when the shift amount is a
4223 /// constant.
4224 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4225   SDNode *LHS = N->getOperand(0).getNode();
4226   if (!LHS->hasOneUse()) return SDValue();
4227
4228   // We want to pull some binops through shifts, so that we have (and (shift))
4229   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4230   // thing happens with address calculations, so it's important to canonicalize
4231   // it.
4232   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4233
4234   switch (LHS->getOpcode()) {
4235   default: return SDValue();
4236   case ISD::OR:
4237   case ISD::XOR:
4238     HighBitSet = false; // We can only transform sra if the high bit is clear.
4239     break;
4240   case ISD::AND:
4241     HighBitSet = true;  // We can only transform sra if the high bit is set.
4242     break;
4243   case ISD::ADD:
4244     if (N->getOpcode() != ISD::SHL)
4245       return SDValue(); // only shl(add) not sr[al](add).
4246     HighBitSet = false; // We can only transform sra if the high bit is clear.
4247     break;
4248   }
4249
4250   // We require the RHS of the binop to be a constant and not opaque as well.
4251   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4252   if (!BinOpCst) return SDValue();
4253
4254   // FIXME: disable this unless the input to the binop is a shift by a constant.
4255   // If it is not a shift, it pessimizes some common cases like:
4256   //
4257   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4258   //    int bar(int *X, int i) { return X[i & 255]; }
4259   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4260   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4261        BinOpLHSVal->getOpcode() != ISD::SRA &&
4262        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4263       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4264     return SDValue();
4265
4266   EVT VT = N->getValueType(0);
4267
4268   // If this is a signed shift right, and the high bit is modified by the
4269   // logical operation, do not perform the transformation. The highBitSet
4270   // boolean indicates the value of the high bit of the constant which would
4271   // cause it to be modified for this operation.
4272   if (N->getOpcode() == ISD::SRA) {
4273     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4274     if (BinOpRHSSignSet != HighBitSet)
4275       return SDValue();
4276   }
4277
4278   if (!TLI.isDesirableToCommuteWithShift(LHS))
4279     return SDValue();
4280
4281   // Fold the constants, shifting the binop RHS by the shift amount.
4282   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4283                                N->getValueType(0),
4284                                LHS->getOperand(1), N->getOperand(1));
4285   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4286
4287   // Create the new shift.
4288   SDValue NewShift = DAG.getNode(N->getOpcode(),
4289                                  SDLoc(LHS->getOperand(0)),
4290                                  VT, LHS->getOperand(0), N->getOperand(1));
4291
4292   // Create the new binop.
4293   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4294 }
4295
4296 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4297   assert(N->getOpcode() == ISD::TRUNCATE);
4298   assert(N->getOperand(0).getOpcode() == ISD::AND);
4299
4300   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4301   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4302     SDValue N01 = N->getOperand(0).getOperand(1);
4303
4304     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4305       if (!N01C->isOpaque()) {
4306         EVT TruncVT = N->getValueType(0);
4307         SDValue N00 = N->getOperand(0).getOperand(0);
4308         APInt TruncC = N01C->getAPIntValue();
4309         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4310         SDLoc DL(N);
4311
4312         return DAG.getNode(ISD::AND, DL, TruncVT,
4313                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4314                            DAG.getConstant(TruncC, DL, TruncVT));
4315       }
4316     }
4317   }
4318
4319   return SDValue();
4320 }
4321
4322 SDValue DAGCombiner::visitRotate(SDNode *N) {
4323   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4324   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4325       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4326     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4327     if (NewOp1.getNode())
4328       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4329                          N->getOperand(0), NewOp1);
4330   }
4331   return SDValue();
4332 }
4333
4334 SDValue DAGCombiner::visitSHL(SDNode *N) {
4335   SDValue N0 = N->getOperand(0);
4336   SDValue N1 = N->getOperand(1);
4337   EVT VT = N0.getValueType();
4338   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4339
4340   // fold vector ops
4341   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4342   if (VT.isVector()) {
4343     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4344       return FoldedVOp;
4345
4346     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4347     // If setcc produces all-one true value then:
4348     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4349     if (N1CV && N1CV->isConstant()) {
4350       if (N0.getOpcode() == ISD::AND) {
4351         SDValue N00 = N0->getOperand(0);
4352         SDValue N01 = N0->getOperand(1);
4353         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4354
4355         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4356             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4357                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4358           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4359                                                      N01CV, N1CV))
4360             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4361         }
4362       } else {
4363         N1C = isConstOrConstSplat(N1);
4364       }
4365     }
4366   }
4367
4368   // fold (shl c1, c2) -> c1<<c2
4369   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4370   if (N0C && N1C && !N1C->isOpaque())
4371     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4372   // fold (shl 0, x) -> 0
4373   if (isNullConstant(N0))
4374     return N0;
4375   // fold (shl x, c >= size(x)) -> undef
4376   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4377     return DAG.getUNDEF(VT);
4378   // fold (shl x, 0) -> x
4379   if (N1C && N1C->isNullValue())
4380     return N0;
4381   // fold (shl undef, x) -> 0
4382   if (N0.getOpcode() == ISD::UNDEF)
4383     return DAG.getConstant(0, SDLoc(N), VT);
4384   // if (shl x, c) is known to be zero, return 0
4385   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4386                             APInt::getAllOnesValue(OpSizeInBits)))
4387     return DAG.getConstant(0, SDLoc(N), VT);
4388   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4389   if (N1.getOpcode() == ISD::TRUNCATE &&
4390       N1.getOperand(0).getOpcode() == ISD::AND) {
4391     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4392     if (NewOp1.getNode())
4393       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4394   }
4395
4396   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4397     return SDValue(N, 0);
4398
4399   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4400   if (N1C && N0.getOpcode() == ISD::SHL) {
4401     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4402       uint64_t c1 = N0C1->getZExtValue();
4403       uint64_t c2 = N1C->getZExtValue();
4404       SDLoc DL(N);
4405       if (c1 + c2 >= OpSizeInBits)
4406         return DAG.getConstant(0, DL, VT);
4407       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4408                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4409     }
4410   }
4411
4412   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4413   // For this to be valid, the second form must not preserve any of the bits
4414   // that are shifted out by the inner shift in the first form.  This means
4415   // the outer shift size must be >= the number of bits added by the ext.
4416   // As a corollary, we don't care what kind of ext it is.
4417   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4418               N0.getOpcode() == ISD::ANY_EXTEND ||
4419               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4420       N0.getOperand(0).getOpcode() == ISD::SHL) {
4421     SDValue N0Op0 = N0.getOperand(0);
4422     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4423       uint64_t c1 = N0Op0C1->getZExtValue();
4424       uint64_t c2 = N1C->getZExtValue();
4425       EVT InnerShiftVT = N0Op0.getValueType();
4426       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4427       if (c2 >= OpSizeInBits - InnerShiftSize) {
4428         SDLoc DL(N0);
4429         if (c1 + c2 >= OpSizeInBits)
4430           return DAG.getConstant(0, DL, VT);
4431         return DAG.getNode(ISD::SHL, DL, VT,
4432                            DAG.getNode(N0.getOpcode(), DL, VT,
4433                                        N0Op0->getOperand(0)),
4434                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4435       }
4436     }
4437   }
4438
4439   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4440   // Only fold this if the inner zext has no other uses to avoid increasing
4441   // the total number of instructions.
4442   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4443       N0.getOperand(0).getOpcode() == ISD::SRL) {
4444     SDValue N0Op0 = N0.getOperand(0);
4445     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4446       uint64_t c1 = N0Op0C1->getZExtValue();
4447       if (c1 < VT.getScalarSizeInBits()) {
4448         uint64_t c2 = N1C->getZExtValue();
4449         if (c1 == c2) {
4450           SDValue NewOp0 = N0.getOperand(0);
4451           EVT CountVT = NewOp0.getOperand(1).getValueType();
4452           SDLoc DL(N);
4453           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4454                                        NewOp0,
4455                                        DAG.getConstant(c2, DL, CountVT));
4456           AddToWorklist(NewSHL.getNode());
4457           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4458         }
4459       }
4460     }
4461   }
4462
4463   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4464   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4465   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4466       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4467     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4468       uint64_t C1 = N0C1->getZExtValue();
4469       uint64_t C2 = N1C->getZExtValue();
4470       SDLoc DL(N);
4471       if (C1 <= C2)
4472         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4473                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4474       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4475                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4476     }
4477   }
4478
4479   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4480   //                               (and (srl x, (sub c1, c2), MASK)
4481   // Only fold this if the inner shift has no other uses -- if it does, folding
4482   // this will increase the total number of instructions.
4483   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4484     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4485       uint64_t c1 = N0C1->getZExtValue();
4486       if (c1 < OpSizeInBits) {
4487         uint64_t c2 = N1C->getZExtValue();
4488         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4489         SDValue Shift;
4490         if (c2 > c1) {
4491           Mask = Mask.shl(c2 - c1);
4492           SDLoc DL(N);
4493           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4494                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4495         } else {
4496           Mask = Mask.lshr(c1 - c2);
4497           SDLoc DL(N);
4498           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4499                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4500         }
4501         SDLoc DL(N0);
4502         return DAG.getNode(ISD::AND, DL, VT, Shift,
4503                            DAG.getConstant(Mask, DL, VT));
4504       }
4505     }
4506   }
4507   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4508   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4509     unsigned BitSize = VT.getScalarSizeInBits();
4510     SDLoc DL(N);
4511     SDValue HiBitsMask =
4512       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4513                                             BitSize - N1C->getZExtValue()),
4514                       DL, VT);
4515     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4516                        HiBitsMask);
4517   }
4518
4519   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4520   // Variant of version done on multiply, except mul by a power of 2 is turned
4521   // into a shift.
4522   APInt Val;
4523   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4524       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4525        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4526     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4527     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4528     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4529   }
4530
4531   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4532   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4533     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4534       if (SDValue Folded =
4535               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4536         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4537     }
4538   }
4539
4540   if (N1C && !N1C->isOpaque())
4541     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4542       return NewSHL;
4543
4544   return SDValue();
4545 }
4546
4547 SDValue DAGCombiner::visitSRA(SDNode *N) {
4548   SDValue N0 = N->getOperand(0);
4549   SDValue N1 = N->getOperand(1);
4550   EVT VT = N0.getValueType();
4551   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4552
4553   // fold vector ops
4554   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4555   if (VT.isVector()) {
4556     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4557       return FoldedVOp;
4558
4559     N1C = isConstOrConstSplat(N1);
4560   }
4561
4562   // fold (sra c1, c2) -> (sra c1, c2)
4563   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4564   if (N0C && N1C && !N1C->isOpaque())
4565     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4566   // fold (sra 0, x) -> 0
4567   if (isNullConstant(N0))
4568     return N0;
4569   // fold (sra -1, x) -> -1
4570   if (isAllOnesConstant(N0))
4571     return N0;
4572   // fold (sra x, (setge c, size(x))) -> undef
4573   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4574     return DAG.getUNDEF(VT);
4575   // fold (sra x, 0) -> x
4576   if (N1C && N1C->isNullValue())
4577     return N0;
4578   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4579   // sext_inreg.
4580   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4581     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4582     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4583     if (VT.isVector())
4584       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4585                                ExtVT, VT.getVectorNumElements());
4586     if ((!LegalOperations ||
4587          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4588       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4589                          N0.getOperand(0), DAG.getValueType(ExtVT));
4590   }
4591
4592   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4593   if (N1C && N0.getOpcode() == ISD::SRA) {
4594     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4595       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4596       if (Sum >= OpSizeInBits)
4597         Sum = OpSizeInBits - 1;
4598       SDLoc DL(N);
4599       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4600                          DAG.getConstant(Sum, DL, N1.getValueType()));
4601     }
4602   }
4603
4604   // fold (sra (shl X, m), (sub result_size, n))
4605   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4606   // result_size - n != m.
4607   // If truncate is free for the target sext(shl) is likely to result in better
4608   // code.
4609   if (N0.getOpcode() == ISD::SHL && N1C) {
4610     // Get the two constanst of the shifts, CN0 = m, CN = n.
4611     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4612     if (N01C) {
4613       LLVMContext &Ctx = *DAG.getContext();
4614       // Determine what the truncate's result bitsize and type would be.
4615       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4616
4617       if (VT.isVector())
4618         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4619
4620       // Determine the residual right-shift amount.
4621       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4622
4623       // If the shift is not a no-op (in which case this should be just a sign
4624       // extend already), the truncated to type is legal, sign_extend is legal
4625       // on that type, and the truncate to that type is both legal and free,
4626       // perform the transform.
4627       if ((ShiftAmt > 0) &&
4628           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4629           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4630           TLI.isTruncateFree(VT, TruncVT)) {
4631
4632         SDLoc DL(N);
4633         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4634             getShiftAmountTy(N0.getOperand(0).getValueType()));
4635         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4636                                     N0.getOperand(0), Amt);
4637         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4638                                     Shift);
4639         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4640                            N->getValueType(0), Trunc);
4641       }
4642     }
4643   }
4644
4645   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4646   if (N1.getOpcode() == ISD::TRUNCATE &&
4647       N1.getOperand(0).getOpcode() == ISD::AND) {
4648     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4649     if (NewOp1.getNode())
4650       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4651   }
4652
4653   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4654   //      if c1 is equal to the number of bits the trunc removes
4655   if (N0.getOpcode() == ISD::TRUNCATE &&
4656       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4657        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4658       N0.getOperand(0).hasOneUse() &&
4659       N0.getOperand(0).getOperand(1).hasOneUse() &&
4660       N1C) {
4661     SDValue N0Op0 = N0.getOperand(0);
4662     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4663       unsigned LargeShiftVal = LargeShift->getZExtValue();
4664       EVT LargeVT = N0Op0.getValueType();
4665
4666       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4667         SDLoc DL(N);
4668         SDValue Amt =
4669           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4670                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4671         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4672                                   N0Op0.getOperand(0), Amt);
4673         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4674       }
4675     }
4676   }
4677
4678   // Simplify, based on bits shifted out of the LHS.
4679   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4680     return SDValue(N, 0);
4681
4682
4683   // If the sign bit is known to be zero, switch this to a SRL.
4684   if (DAG.SignBitIsZero(N0))
4685     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4686
4687   if (N1C && !N1C->isOpaque())
4688     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4689       return NewSRA;
4690
4691   return SDValue();
4692 }
4693
4694 SDValue DAGCombiner::visitSRL(SDNode *N) {
4695   SDValue N0 = N->getOperand(0);
4696   SDValue N1 = N->getOperand(1);
4697   EVT VT = N0.getValueType();
4698   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4699
4700   // fold vector ops
4701   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4702   if (VT.isVector()) {
4703     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4704       return FoldedVOp;
4705
4706     N1C = isConstOrConstSplat(N1);
4707   }
4708
4709   // fold (srl c1, c2) -> c1 >>u c2
4710   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4711   if (N0C && N1C && !N1C->isOpaque())
4712     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4713   // fold (srl 0, x) -> 0
4714   if (isNullConstant(N0))
4715     return N0;
4716   // fold (srl x, c >= size(x)) -> undef
4717   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4718     return DAG.getUNDEF(VT);
4719   // fold (srl x, 0) -> x
4720   if (N1C && N1C->isNullValue())
4721     return N0;
4722   // if (srl x, c) is known to be zero, return 0
4723   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4724                                    APInt::getAllOnesValue(OpSizeInBits)))
4725     return DAG.getConstant(0, SDLoc(N), VT);
4726
4727   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4728   if (N1C && N0.getOpcode() == ISD::SRL) {
4729     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4730       uint64_t c1 = N01C->getZExtValue();
4731       uint64_t c2 = N1C->getZExtValue();
4732       SDLoc DL(N);
4733       if (c1 + c2 >= OpSizeInBits)
4734         return DAG.getConstant(0, DL, VT);
4735       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4736                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4737     }
4738   }
4739
4740   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4741   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4742       N0.getOperand(0).getOpcode() == ISD::SRL &&
4743       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4744     uint64_t c1 =
4745       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4746     uint64_t c2 = N1C->getZExtValue();
4747     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4748     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4749     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4750     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4751     if (c1 + OpSizeInBits == InnerShiftSize) {
4752       SDLoc DL(N0);
4753       if (c1 + c2 >= InnerShiftSize)
4754         return DAG.getConstant(0, DL, VT);
4755       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4756                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4757                                      N0.getOperand(0)->getOperand(0),
4758                                      DAG.getConstant(c1 + c2, DL,
4759                                                      ShiftCountVT)));
4760     }
4761   }
4762
4763   // fold (srl (shl x, c), c) -> (and x, cst2)
4764   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4765     unsigned BitSize = N0.getScalarValueSizeInBits();
4766     if (BitSize <= 64) {
4767       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4768       SDLoc DL(N);
4769       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4770                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4771     }
4772   }
4773
4774   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4775   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4776     // Shifting in all undef bits?
4777     EVT SmallVT = N0.getOperand(0).getValueType();
4778     unsigned BitSize = SmallVT.getScalarSizeInBits();
4779     if (N1C->getZExtValue() >= BitSize)
4780       return DAG.getUNDEF(VT);
4781
4782     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4783       uint64_t ShiftAmt = N1C->getZExtValue();
4784       SDLoc DL0(N0);
4785       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4786                                        N0.getOperand(0),
4787                           DAG.getConstant(ShiftAmt, DL0,
4788                                           getShiftAmountTy(SmallVT)));
4789       AddToWorklist(SmallShift.getNode());
4790       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4791       SDLoc DL(N);
4792       return DAG.getNode(ISD::AND, DL, VT,
4793                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4794                          DAG.getConstant(Mask, DL, VT));
4795     }
4796   }
4797
4798   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4799   // bit, which is unmodified by sra.
4800   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4801     if (N0.getOpcode() == ISD::SRA)
4802       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4803   }
4804
4805   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4806   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4807       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4808     APInt KnownZero, KnownOne;
4809     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4810
4811     // If any of the input bits are KnownOne, then the input couldn't be all
4812     // zeros, thus the result of the srl will always be zero.
4813     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4814
4815     // If all of the bits input the to ctlz node are known to be zero, then
4816     // the result of the ctlz is "32" and the result of the shift is one.
4817     APInt UnknownBits = ~KnownZero;
4818     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4819
4820     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4821     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4822       // Okay, we know that only that the single bit specified by UnknownBits
4823       // could be set on input to the CTLZ node. If this bit is set, the SRL
4824       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4825       // to an SRL/XOR pair, which is likely to simplify more.
4826       unsigned ShAmt = UnknownBits.countTrailingZeros();
4827       SDValue Op = N0.getOperand(0);
4828
4829       if (ShAmt) {
4830         SDLoc DL(N0);
4831         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4832                   DAG.getConstant(ShAmt, DL,
4833                                   getShiftAmountTy(Op.getValueType())));
4834         AddToWorklist(Op.getNode());
4835       }
4836
4837       SDLoc DL(N);
4838       return DAG.getNode(ISD::XOR, DL, VT,
4839                          Op, DAG.getConstant(1, DL, VT));
4840     }
4841   }
4842
4843   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4844   if (N1.getOpcode() == ISD::TRUNCATE &&
4845       N1.getOperand(0).getOpcode() == ISD::AND) {
4846     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4847       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4848   }
4849
4850   // fold operands of srl based on knowledge that the low bits are not
4851   // demanded.
4852   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4853     return SDValue(N, 0);
4854
4855   if (N1C && !N1C->isOpaque())
4856     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4857       return NewSRL;
4858
4859   // Attempt to convert a srl of a load into a narrower zero-extending load.
4860   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4861     return NarrowLoad;
4862
4863   // Here is a common situation. We want to optimize:
4864   //
4865   //   %a = ...
4866   //   %b = and i32 %a, 2
4867   //   %c = srl i32 %b, 1
4868   //   brcond i32 %c ...
4869   //
4870   // into
4871   //
4872   //   %a = ...
4873   //   %b = and %a, 2
4874   //   %c = setcc eq %b, 0
4875   //   brcond %c ...
4876   //
4877   // However when after the source operand of SRL is optimized into AND, the SRL
4878   // itself may not be optimized further. Look for it and add the BRCOND into
4879   // the worklist.
4880   if (N->hasOneUse()) {
4881     SDNode *Use = *N->use_begin();
4882     if (Use->getOpcode() == ISD::BRCOND)
4883       AddToWorklist(Use);
4884     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4885       // Also look pass the truncate.
4886       Use = *Use->use_begin();
4887       if (Use->getOpcode() == ISD::BRCOND)
4888         AddToWorklist(Use);
4889     }
4890   }
4891
4892   return SDValue();
4893 }
4894
4895 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4896   SDValue N0 = N->getOperand(0);
4897   EVT VT = N->getValueType(0);
4898
4899   // fold (bswap c1) -> c2
4900   if (isConstantIntBuildVectorOrConstantInt(N0))
4901     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4902   // fold (bswap (bswap x)) -> x
4903   if (N0.getOpcode() == ISD::BSWAP)
4904     return N0->getOperand(0);
4905   return SDValue();
4906 }
4907
4908 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4909   SDValue N0 = N->getOperand(0);
4910   EVT VT = N->getValueType(0);
4911
4912   // fold (ctlz c1) -> c2
4913   if (isConstantIntBuildVectorOrConstantInt(N0))
4914     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4915   return SDValue();
4916 }
4917
4918 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4919   SDValue N0 = N->getOperand(0);
4920   EVT VT = N->getValueType(0);
4921
4922   // fold (ctlz_zero_undef c1) -> c2
4923   if (isConstantIntBuildVectorOrConstantInt(N0))
4924     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4925   return SDValue();
4926 }
4927
4928 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4929   SDValue N0 = N->getOperand(0);
4930   EVT VT = N->getValueType(0);
4931
4932   // fold (cttz c1) -> c2
4933   if (isConstantIntBuildVectorOrConstantInt(N0))
4934     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4935   return SDValue();
4936 }
4937
4938 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4939   SDValue N0 = N->getOperand(0);
4940   EVT VT = N->getValueType(0);
4941
4942   // fold (cttz_zero_undef c1) -> c2
4943   if (isConstantIntBuildVectorOrConstantInt(N0))
4944     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4945   return SDValue();
4946 }
4947
4948 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4949   SDValue N0 = N->getOperand(0);
4950   EVT VT = N->getValueType(0);
4951
4952   // fold (ctpop c1) -> c2
4953   if (isConstantIntBuildVectorOrConstantInt(N0))
4954     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4955   return SDValue();
4956 }
4957
4958
4959 /// \brief Generate Min/Max node
4960 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4961                                    SDValue True, SDValue False,
4962                                    ISD::CondCode CC, const TargetLowering &TLI,
4963                                    SelectionDAG &DAG) {
4964   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4965     return SDValue();
4966
4967   switch (CC) {
4968   case ISD::SETOLT:
4969   case ISD::SETOLE:
4970   case ISD::SETLT:
4971   case ISD::SETLE:
4972   case ISD::SETULT:
4973   case ISD::SETULE: {
4974     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4975     if (TLI.isOperationLegal(Opcode, VT))
4976       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4977     return SDValue();
4978   }
4979   case ISD::SETOGT:
4980   case ISD::SETOGE:
4981   case ISD::SETGT:
4982   case ISD::SETGE:
4983   case ISD::SETUGT:
4984   case ISD::SETUGE: {
4985     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4986     if (TLI.isOperationLegal(Opcode, VT))
4987       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4988     return SDValue();
4989   }
4990   default:
4991     return SDValue();
4992   }
4993 }
4994
4995 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4996   SDValue N0 = N->getOperand(0);
4997   SDValue N1 = N->getOperand(1);
4998   SDValue N2 = N->getOperand(2);
4999   EVT VT = N->getValueType(0);
5000   EVT VT0 = N0.getValueType();
5001
5002   // fold (select C, X, X) -> X
5003   if (N1 == N2)
5004     return N1;
5005   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5006     // fold (select true, X, Y) -> X
5007     // fold (select false, X, Y) -> Y
5008     return !N0C->isNullValue() ? N1 : N2;
5009   }
5010   // fold (select C, 1, X) -> (or C, X)
5011   if (VT == MVT::i1 && isOneConstant(N1))
5012     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5013   // fold (select C, 0, 1) -> (xor C, 1)
5014   // We can't do this reliably if integer based booleans have different contents
5015   // to floating point based booleans. This is because we can't tell whether we
5016   // have an integer-based boolean or a floating-point-based boolean unless we
5017   // can find the SETCC that produced it and inspect its operands. This is
5018   // fairly easy if C is the SETCC node, but it can potentially be
5019   // undiscoverable (or not reasonably discoverable). For example, it could be
5020   // in another basic block or it could require searching a complicated
5021   // expression.
5022   if (VT.isInteger() &&
5023       (VT0 == MVT::i1 || (VT0.isInteger() &&
5024                           TLI.getBooleanContents(false, false) ==
5025                               TLI.getBooleanContents(false, true) &&
5026                           TLI.getBooleanContents(false, false) ==
5027                               TargetLowering::ZeroOrOneBooleanContent)) &&
5028       isNullConstant(N1) && isOneConstant(N2)) {
5029     SDValue XORNode;
5030     if (VT == VT0) {
5031       SDLoc DL(N);
5032       return DAG.getNode(ISD::XOR, DL, VT0,
5033                          N0, DAG.getConstant(1, DL, VT0));
5034     }
5035     SDLoc DL0(N0);
5036     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5037                           N0, DAG.getConstant(1, DL0, VT0));
5038     AddToWorklist(XORNode.getNode());
5039     if (VT.bitsGT(VT0))
5040       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5041     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5042   }
5043   // fold (select C, 0, X) -> (and (not C), X)
5044   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5045     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5046     AddToWorklist(NOTNode.getNode());
5047     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5048   }
5049   // fold (select C, X, 1) -> (or (not C), X)
5050   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5051     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5052     AddToWorklist(NOTNode.getNode());
5053     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5054   }
5055   // fold (select C, X, 0) -> (and C, X)
5056   if (VT == MVT::i1 && isNullConstant(N2))
5057     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5058   // fold (select X, X, Y) -> (or X, Y)
5059   // fold (select X, 1, Y) -> (or X, Y)
5060   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5061     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5062   // fold (select X, Y, X) -> (and X, Y)
5063   // fold (select X, Y, 0) -> (and X, Y)
5064   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5065     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5066
5067   // If we can fold this based on the true/false value, do so.
5068   if (SimplifySelectOps(N, N1, N2))
5069     return SDValue(N, 0);  // Don't revisit N.
5070
5071   if (VT0 == MVT::i1) {
5072     // The code in this block deals with the following 2 equivalences:
5073     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5074     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5075     // The target can specify its prefered form with the
5076     // shouldNormalizeToSelectSequence() callback. However we always transform
5077     // to the right anyway if we find the inner select exists in the DAG anyway
5078     // and we always transform to the left side if we know that we can further
5079     // optimize the combination of the conditions.
5080     bool normalizeToSequence
5081       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5082     // select (and Cond0, Cond1), X, Y
5083     //   -> select Cond0, (select Cond1, X, Y), Y
5084     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5085       SDValue Cond0 = N0->getOperand(0);
5086       SDValue Cond1 = N0->getOperand(1);
5087       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5088                                         N1.getValueType(), Cond1, N1, N2);
5089       if (normalizeToSequence || !InnerSelect.use_empty())
5090         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5091                            InnerSelect, N2);
5092     }
5093     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5094     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5095       SDValue Cond0 = N0->getOperand(0);
5096       SDValue Cond1 = N0->getOperand(1);
5097       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5098                                         N1.getValueType(), Cond1, N1, N2);
5099       if (normalizeToSequence || !InnerSelect.use_empty())
5100         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5101                            InnerSelect);
5102     }
5103
5104     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5105     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5106       SDValue N1_0 = N1->getOperand(0);
5107       SDValue N1_1 = N1->getOperand(1);
5108       SDValue N1_2 = N1->getOperand(2);
5109       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5110         // Create the actual and node if we can generate good code for it.
5111         if (!normalizeToSequence) {
5112           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5113                                     N0, N1_0);
5114           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5115                              N1_1, N2);
5116         }
5117         // Otherwise see if we can optimize the "and" to a better pattern.
5118         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5119           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5120                              N1_1, N2);
5121       }
5122     }
5123     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5124     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5125       SDValue N2_0 = N2->getOperand(0);
5126       SDValue N2_1 = N2->getOperand(1);
5127       SDValue N2_2 = N2->getOperand(2);
5128       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5129         // Create the actual or node if we can generate good code for it.
5130         if (!normalizeToSequence) {
5131           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5132                                    N0, N2_0);
5133           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5134                              N1, N2_2);
5135         }
5136         // Otherwise see if we can optimize to a better pattern.
5137         if (SDValue Combined = visitORLike(N0, N2_0, N))
5138           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5139                              N1, N2_2);
5140       }
5141     }
5142   }
5143
5144   // fold selects based on a setcc into other things, such as min/max/abs
5145   if (N0.getOpcode() == ISD::SETCC) {
5146     // select x, y (fcmp lt x, y) -> fminnum x, y
5147     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5148     //
5149     // This is OK if we don't care about what happens if either operand is a
5150     // NaN.
5151     //
5152
5153     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5154     // no signed zeros as well as no nans.
5155     const TargetOptions &Options = DAG.getTarget().Options;
5156     if (Options.UnsafeFPMath &&
5157         VT.isFloatingPoint() && N0.hasOneUse() &&
5158         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5159       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5160
5161       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5162                                                 N0.getOperand(1), N1, N2, CC,
5163                                                 TLI, DAG))
5164         return FMinMax;
5165     }
5166
5167     if ((!LegalOperations &&
5168          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5169         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5170       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5171                          N0.getOperand(0), N0.getOperand(1),
5172                          N1, N2, N0.getOperand(2));
5173     return SimplifySelect(SDLoc(N), N0, N1, N2);
5174   }
5175
5176   return SDValue();
5177 }
5178
5179 static
5180 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5181   SDLoc DL(N);
5182   EVT LoVT, HiVT;
5183   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5184
5185   // Split the inputs.
5186   SDValue Lo, Hi, LL, LH, RL, RH;
5187   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5188   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5189
5190   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5191   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5192
5193   return std::make_pair(Lo, Hi);
5194 }
5195
5196 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5197 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5198 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5199   SDLoc dl(N);
5200   SDValue Cond = N->getOperand(0);
5201   SDValue LHS = N->getOperand(1);
5202   SDValue RHS = N->getOperand(2);
5203   EVT VT = N->getValueType(0);
5204   int NumElems = VT.getVectorNumElements();
5205   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5206          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5207          Cond.getOpcode() == ISD::BUILD_VECTOR);
5208
5209   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5210   // binary ones here.
5211   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5212     return SDValue();
5213
5214   // We're sure we have an even number of elements due to the
5215   // concat_vectors we have as arguments to vselect.
5216   // Skip BV elements until we find one that's not an UNDEF
5217   // After we find an UNDEF element, keep looping until we get to half the
5218   // length of the BV and see if all the non-undef nodes are the same.
5219   ConstantSDNode *BottomHalf = nullptr;
5220   for (int i = 0; i < NumElems / 2; ++i) {
5221     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5222       continue;
5223
5224     if (BottomHalf == nullptr)
5225       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5226     else if (Cond->getOperand(i).getNode() != BottomHalf)
5227       return SDValue();
5228   }
5229
5230   // Do the same for the second half of the BuildVector
5231   ConstantSDNode *TopHalf = nullptr;
5232   for (int i = NumElems / 2; i < NumElems; ++i) {
5233     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5234       continue;
5235
5236     if (TopHalf == nullptr)
5237       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5238     else if (Cond->getOperand(i).getNode() != TopHalf)
5239       return SDValue();
5240   }
5241
5242   assert(TopHalf && BottomHalf &&
5243          "One half of the selector was all UNDEFs and the other was all the "
5244          "same value. This should have been addressed before this function.");
5245   return DAG.getNode(
5246       ISD::CONCAT_VECTORS, dl, VT,
5247       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5248       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5249 }
5250
5251 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5252
5253   if (Level >= AfterLegalizeTypes)
5254     return SDValue();
5255
5256   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5257   SDValue Mask = MSC->getMask();
5258   SDValue Data  = MSC->getValue();
5259   SDLoc DL(N);
5260
5261   // If the MSCATTER data type requires splitting and the mask is provided by a
5262   // SETCC, then split both nodes and its operands before legalization. This
5263   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5264   // and enables future optimizations (e.g. min/max pattern matching on X86).
5265   if (Mask.getOpcode() != ISD::SETCC)
5266     return SDValue();
5267
5268   // Check if any splitting is required.
5269   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5270       TargetLowering::TypeSplitVector)
5271     return SDValue();
5272   SDValue MaskLo, MaskHi, Lo, Hi;
5273   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5274
5275   EVT LoVT, HiVT;
5276   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5277
5278   SDValue Chain = MSC->getChain();
5279
5280   EVT MemoryVT = MSC->getMemoryVT();
5281   unsigned Alignment = MSC->getOriginalAlignment();
5282
5283   EVT LoMemVT, HiMemVT;
5284   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5285
5286   SDValue DataLo, DataHi;
5287   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5288
5289   SDValue BasePtr = MSC->getBasePtr();
5290   SDValue IndexLo, IndexHi;
5291   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5292
5293   MachineMemOperand *MMO = DAG.getMachineFunction().
5294     getMachineMemOperand(MSC->getPointerInfo(),
5295                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5296                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5297
5298   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5299   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5300                             DL, OpsLo, MMO);
5301
5302   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5303   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5304                             DL, OpsHi, MMO);
5305
5306   AddToWorklist(Lo.getNode());
5307   AddToWorklist(Hi.getNode());
5308
5309   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5310 }
5311
5312 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5313
5314   if (Level >= AfterLegalizeTypes)
5315     return SDValue();
5316
5317   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5318   SDValue Mask = MST->getMask();
5319   SDValue Data  = MST->getValue();
5320   SDLoc DL(N);
5321
5322   // If the MSTORE data type requires splitting and the mask is provided by a
5323   // SETCC, then split both nodes and its operands before legalization. This
5324   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5325   // and enables future optimizations (e.g. min/max pattern matching on X86).
5326   if (Mask.getOpcode() == ISD::SETCC) {
5327
5328     // Check if any splitting is required.
5329     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5330         TargetLowering::TypeSplitVector)
5331       return SDValue();
5332
5333     SDValue MaskLo, MaskHi, Lo, Hi;
5334     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5335
5336     EVT LoVT, HiVT;
5337     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5338
5339     SDValue Chain = MST->getChain();
5340     SDValue Ptr   = MST->getBasePtr();
5341
5342     EVT MemoryVT = MST->getMemoryVT();
5343     unsigned Alignment = MST->getOriginalAlignment();
5344
5345     // if Alignment is equal to the vector size,
5346     // take the half of it for the second part
5347     unsigned SecondHalfAlignment =
5348       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5349          Alignment/2 : Alignment;
5350
5351     EVT LoMemVT, HiMemVT;
5352     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5353
5354     SDValue DataLo, DataHi;
5355     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5356
5357     MachineMemOperand *MMO = DAG.getMachineFunction().
5358       getMachineMemOperand(MST->getPointerInfo(),
5359                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5360                            Alignment, MST->getAAInfo(), MST->getRanges());
5361
5362     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5363                             MST->isTruncatingStore());
5364
5365     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5366     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5367                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5368
5369     MMO = DAG.getMachineFunction().
5370       getMachineMemOperand(MST->getPointerInfo(),
5371                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5372                            SecondHalfAlignment, MST->getAAInfo(),
5373                            MST->getRanges());
5374
5375     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5376                             MST->isTruncatingStore());
5377
5378     AddToWorklist(Lo.getNode());
5379     AddToWorklist(Hi.getNode());
5380
5381     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5382   }
5383   return SDValue();
5384 }
5385
5386 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5387
5388   if (Level >= AfterLegalizeTypes)
5389     return SDValue();
5390
5391   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5392   SDValue Mask = MGT->getMask();
5393   SDLoc DL(N);
5394
5395   // If the MGATHER result requires splitting and the mask is provided by a
5396   // SETCC, then split both nodes and its operands before legalization. This
5397   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5398   // and enables future optimizations (e.g. min/max pattern matching on X86).
5399
5400   if (Mask.getOpcode() != ISD::SETCC)
5401     return SDValue();
5402
5403   EVT VT = N->getValueType(0);
5404
5405   // Check if any splitting is required.
5406   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5407       TargetLowering::TypeSplitVector)
5408     return SDValue();
5409
5410   SDValue MaskLo, MaskHi, Lo, Hi;
5411   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5412
5413   SDValue Src0 = MGT->getValue();
5414   SDValue Src0Lo, Src0Hi;
5415   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5416
5417   EVT LoVT, HiVT;
5418   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5419
5420   SDValue Chain = MGT->getChain();
5421   EVT MemoryVT = MGT->getMemoryVT();
5422   unsigned Alignment = MGT->getOriginalAlignment();
5423
5424   EVT LoMemVT, HiMemVT;
5425   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5426
5427   SDValue BasePtr = MGT->getBasePtr();
5428   SDValue Index = MGT->getIndex();
5429   SDValue IndexLo, IndexHi;
5430   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5431
5432   MachineMemOperand *MMO = DAG.getMachineFunction().
5433     getMachineMemOperand(MGT->getPointerInfo(),
5434                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5435                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5436
5437   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5438   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5439                             MMO);
5440
5441   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5442   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5443                             MMO);
5444
5445   AddToWorklist(Lo.getNode());
5446   AddToWorklist(Hi.getNode());
5447
5448   // Build a factor node to remember that this load is independent of the
5449   // other one.
5450   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5451                       Hi.getValue(1));
5452
5453   // Legalized the chain result - switch anything that used the old chain to
5454   // use the new one.
5455   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5456
5457   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5458
5459   SDValue RetOps[] = { GatherRes, Chain };
5460   return DAG.getMergeValues(RetOps, DL);
5461 }
5462
5463 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5464
5465   if (Level >= AfterLegalizeTypes)
5466     return SDValue();
5467
5468   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5469   SDValue Mask = MLD->getMask();
5470   SDLoc DL(N);
5471
5472   // If the MLOAD result requires splitting and the mask is provided by a
5473   // SETCC, then split both nodes and its operands before legalization. This
5474   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5475   // and enables future optimizations (e.g. min/max pattern matching on X86).
5476
5477   if (Mask.getOpcode() == ISD::SETCC) {
5478     EVT VT = N->getValueType(0);
5479
5480     // Check if any splitting is required.
5481     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5482         TargetLowering::TypeSplitVector)
5483       return SDValue();
5484
5485     SDValue MaskLo, MaskHi, Lo, Hi;
5486     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5487
5488     SDValue Src0 = MLD->getSrc0();
5489     SDValue Src0Lo, Src0Hi;
5490     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5491
5492     EVT LoVT, HiVT;
5493     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5494
5495     SDValue Chain = MLD->getChain();
5496     SDValue Ptr   = MLD->getBasePtr();
5497     EVT MemoryVT = MLD->getMemoryVT();
5498     unsigned Alignment = MLD->getOriginalAlignment();
5499
5500     // if Alignment is equal to the vector size,
5501     // take the half of it for the second part
5502     unsigned SecondHalfAlignment =
5503       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5504          Alignment/2 : Alignment;
5505
5506     EVT LoMemVT, HiMemVT;
5507     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5508
5509     MachineMemOperand *MMO = DAG.getMachineFunction().
5510     getMachineMemOperand(MLD->getPointerInfo(),
5511                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5512                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5513
5514     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5515                            ISD::NON_EXTLOAD);
5516
5517     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5518     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5519                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5520
5521     MMO = DAG.getMachineFunction().
5522     getMachineMemOperand(MLD->getPointerInfo(),
5523                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5524                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5525
5526     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5527                            ISD::NON_EXTLOAD);
5528
5529     AddToWorklist(Lo.getNode());
5530     AddToWorklist(Hi.getNode());
5531
5532     // Build a factor node to remember that this load is independent of the
5533     // other one.
5534     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5535                         Hi.getValue(1));
5536
5537     // Legalized the chain result - switch anything that used the old chain to
5538     // use the new one.
5539     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5540
5541     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5542
5543     SDValue RetOps[] = { LoadRes, Chain };
5544     return DAG.getMergeValues(RetOps, DL);
5545   }
5546   return SDValue();
5547 }
5548
5549 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5550   SDValue N0 = N->getOperand(0);
5551   SDValue N1 = N->getOperand(1);
5552   SDValue N2 = N->getOperand(2);
5553   SDLoc DL(N);
5554
5555   // Canonicalize integer abs.
5556   // vselect (setg[te] X,  0),  X, -X ->
5557   // vselect (setgt    X, -1),  X, -X ->
5558   // vselect (setl[te] X,  0), -X,  X ->
5559   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5560   if (N0.getOpcode() == ISD::SETCC) {
5561     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5562     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5563     bool isAbs = false;
5564     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5565
5566     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5567          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5568         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5569       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5570     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5571              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5572       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5573
5574     if (isAbs) {
5575       EVT VT = LHS.getValueType();
5576       SDValue Shift = DAG.getNode(
5577           ISD::SRA, DL, VT, LHS,
5578           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5579       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5580       AddToWorklist(Shift.getNode());
5581       AddToWorklist(Add.getNode());
5582       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5583     }
5584   }
5585
5586   if (SimplifySelectOps(N, N1, N2))
5587     return SDValue(N, 0);  // Don't revisit N.
5588
5589   // If the VSELECT result requires splitting and the mask is provided by a
5590   // SETCC, then split both nodes and its operands before legalization. This
5591   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5592   // and enables future optimizations (e.g. min/max pattern matching on X86).
5593   if (N0.getOpcode() == ISD::SETCC) {
5594     EVT VT = N->getValueType(0);
5595
5596     // Check if any splitting is required.
5597     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5598         TargetLowering::TypeSplitVector)
5599       return SDValue();
5600
5601     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5602     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5603     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5604     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5605
5606     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5607     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5608
5609     // Add the new VSELECT nodes to the work list in case they need to be split
5610     // again.
5611     AddToWorklist(Lo.getNode());
5612     AddToWorklist(Hi.getNode());
5613
5614     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5615   }
5616
5617   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5618   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5619     return N1;
5620   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5621   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5622     return N2;
5623
5624   // The ConvertSelectToConcatVector function is assuming both the above
5625   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5626   // and addressed.
5627   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5628       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5629       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5630     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5631       return CV;
5632   }
5633
5634   return SDValue();
5635 }
5636
5637 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5638   SDValue N0 = N->getOperand(0);
5639   SDValue N1 = N->getOperand(1);
5640   SDValue N2 = N->getOperand(2);
5641   SDValue N3 = N->getOperand(3);
5642   SDValue N4 = N->getOperand(4);
5643   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5644
5645   // fold select_cc lhs, rhs, x, x, cc -> x
5646   if (N2 == N3)
5647     return N2;
5648
5649   // Determine if the condition we're dealing with is constant
5650   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5651                               N0, N1, CC, SDLoc(N), false);
5652   if (SCC.getNode()) {
5653     AddToWorklist(SCC.getNode());
5654
5655     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5656       if (!SCCC->isNullValue())
5657         return N2;    // cond always true -> true val
5658       else
5659         return N3;    // cond always false -> false val
5660     } else if (SCC->getOpcode() == ISD::UNDEF) {
5661       // When the condition is UNDEF, just return the first operand. This is
5662       // coherent the DAG creation, no setcc node is created in this case
5663       return N2;
5664     } else if (SCC.getOpcode() == ISD::SETCC) {
5665       // Fold to a simpler select_cc
5666       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5667                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5668                          SCC.getOperand(2));
5669     }
5670   }
5671
5672   // If we can fold this based on the true/false value, do so.
5673   if (SimplifySelectOps(N, N2, N3))
5674     return SDValue(N, 0);  // Don't revisit N.
5675
5676   // fold select_cc into other things, such as min/max/abs
5677   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5678 }
5679
5680 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5681   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5682                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5683                        SDLoc(N));
5684 }
5685
5686 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5687 /// a build_vector of constants.
5688 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5689 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5690 /// Vector extends are not folded if operations are legal; this is to
5691 /// avoid introducing illegal build_vector dag nodes.
5692 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5693                                          SelectionDAG &DAG, bool LegalTypes,
5694                                          bool LegalOperations) {
5695   unsigned Opcode = N->getOpcode();
5696   SDValue N0 = N->getOperand(0);
5697   EVT VT = N->getValueType(0);
5698
5699   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5700          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5701          && "Expected EXTEND dag node in input!");
5702
5703   // fold (sext c1) -> c1
5704   // fold (zext c1) -> c1
5705   // fold (aext c1) -> c1
5706   if (isa<ConstantSDNode>(N0))
5707     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5708
5709   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5710   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5711   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5712   EVT SVT = VT.getScalarType();
5713   if (!(VT.isVector() &&
5714       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5715       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5716     return nullptr;
5717
5718   // We can fold this node into a build_vector.
5719   unsigned VTBits = SVT.getSizeInBits();
5720   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5721   SmallVector<SDValue, 8> Elts;
5722   unsigned NumElts = VT.getVectorNumElements();
5723   SDLoc DL(N);
5724
5725   for (unsigned i=0; i != NumElts; ++i) {
5726     SDValue Op = N0->getOperand(i);
5727     if (Op->getOpcode() == ISD::UNDEF) {
5728       Elts.push_back(DAG.getUNDEF(SVT));
5729       continue;
5730     }
5731
5732     SDLoc DL(Op);
5733     // Get the constant value and if needed trunc it to the size of the type.
5734     // Nodes like build_vector might have constants wider than the scalar type.
5735     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5736     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5737       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5738     else
5739       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5740   }
5741
5742   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5743 }
5744
5745 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5746 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5747 // transformation. Returns true if extension are possible and the above
5748 // mentioned transformation is profitable.
5749 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5750                                     unsigned ExtOpc,
5751                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5752                                     const TargetLowering &TLI) {
5753   bool HasCopyToRegUses = false;
5754   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5755   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5756                             UE = N0.getNode()->use_end();
5757        UI != UE; ++UI) {
5758     SDNode *User = *UI;
5759     if (User == N)
5760       continue;
5761     if (UI.getUse().getResNo() != N0.getResNo())
5762       continue;
5763     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5764     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5765       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5766       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5767         // Sign bits will be lost after a zext.
5768         return false;
5769       bool Add = false;
5770       for (unsigned i = 0; i != 2; ++i) {
5771         SDValue UseOp = User->getOperand(i);
5772         if (UseOp == N0)
5773           continue;
5774         if (!isa<ConstantSDNode>(UseOp))
5775           return false;
5776         Add = true;
5777       }
5778       if (Add)
5779         ExtendNodes.push_back(User);
5780       continue;
5781     }
5782     // If truncates aren't free and there are users we can't
5783     // extend, it isn't worthwhile.
5784     if (!isTruncFree)
5785       return false;
5786     // Remember if this value is live-out.
5787     if (User->getOpcode() == ISD::CopyToReg)
5788       HasCopyToRegUses = true;
5789   }
5790
5791   if (HasCopyToRegUses) {
5792     bool BothLiveOut = false;
5793     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5794          UI != UE; ++UI) {
5795       SDUse &Use = UI.getUse();
5796       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5797         BothLiveOut = true;
5798         break;
5799       }
5800     }
5801     if (BothLiveOut)
5802       // Both unextended and extended values are live out. There had better be
5803       // a good reason for the transformation.
5804       return ExtendNodes.size();
5805   }
5806   return true;
5807 }
5808
5809 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5810                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5811                                   ISD::NodeType ExtType) {
5812   // Extend SetCC uses if necessary.
5813   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5814     SDNode *SetCC = SetCCs[i];
5815     SmallVector<SDValue, 4> Ops;
5816
5817     for (unsigned j = 0; j != 2; ++j) {
5818       SDValue SOp = SetCC->getOperand(j);
5819       if (SOp == Trunc)
5820         Ops.push_back(ExtLoad);
5821       else
5822         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5823     }
5824
5825     Ops.push_back(SetCC->getOperand(2));
5826     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5827   }
5828 }
5829
5830 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5831 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5832   SDValue N0 = N->getOperand(0);
5833   EVT DstVT = N->getValueType(0);
5834   EVT SrcVT = N0.getValueType();
5835
5836   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5837           N->getOpcode() == ISD::ZERO_EXTEND) &&
5838          "Unexpected node type (not an extend)!");
5839
5840   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5841   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5842   //   (v8i32 (sext (v8i16 (load x))))
5843   // into:
5844   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5845   //                          (v4i32 (sextload (x + 16)))))
5846   // Where uses of the original load, i.e.:
5847   //   (v8i16 (load x))
5848   // are replaced with:
5849   //   (v8i16 (truncate
5850   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5851   //                            (v4i32 (sextload (x + 16)))))))
5852   //
5853   // This combine is only applicable to illegal, but splittable, vectors.
5854   // All legal types, and illegal non-vector types, are handled elsewhere.
5855   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5856   //
5857   if (N0->getOpcode() != ISD::LOAD)
5858     return SDValue();
5859
5860   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5861
5862   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5863       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5864       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5865     return SDValue();
5866
5867   SmallVector<SDNode *, 4> SetCCs;
5868   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5869     return SDValue();
5870
5871   ISD::LoadExtType ExtType =
5872       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5873
5874   // Try to split the vector types to get down to legal types.
5875   EVT SplitSrcVT = SrcVT;
5876   EVT SplitDstVT = DstVT;
5877   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5878          SplitSrcVT.getVectorNumElements() > 1) {
5879     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5880     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5881   }
5882
5883   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5884     return SDValue();
5885
5886   SDLoc DL(N);
5887   const unsigned NumSplits =
5888       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5889   const unsigned Stride = SplitSrcVT.getStoreSize();
5890   SmallVector<SDValue, 4> Loads;
5891   SmallVector<SDValue, 4> Chains;
5892
5893   SDValue BasePtr = LN0->getBasePtr();
5894   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5895     const unsigned Offset = Idx * Stride;
5896     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5897
5898     SDValue SplitLoad = DAG.getExtLoad(
5899         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5900         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5901         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5902         Align, LN0->getAAInfo());
5903
5904     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5905                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5906
5907     Loads.push_back(SplitLoad.getValue(0));
5908     Chains.push_back(SplitLoad.getValue(1));
5909   }
5910
5911   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5912   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5913
5914   CombineTo(N, NewValue);
5915
5916   // Replace uses of the original load (before extension)
5917   // with a truncate of the concatenated sextloaded vectors.
5918   SDValue Trunc =
5919       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5920   CombineTo(N0.getNode(), Trunc, NewChain);
5921   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5922                   (ISD::NodeType)N->getOpcode());
5923   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5924 }
5925
5926 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5927   SDValue N0 = N->getOperand(0);
5928   EVT VT = N->getValueType(0);
5929
5930   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5931                                               LegalOperations))
5932     return SDValue(Res, 0);
5933
5934   // fold (sext (sext x)) -> (sext x)
5935   // fold (sext (aext x)) -> (sext x)
5936   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5937     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5938                        N0.getOperand(0));
5939
5940   if (N0.getOpcode() == ISD::TRUNCATE) {
5941     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5942     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5943     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5944       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5945       if (NarrowLoad.getNode() != N0.getNode()) {
5946         CombineTo(N0.getNode(), NarrowLoad);
5947         // CombineTo deleted the truncate, if needed, but not what's under it.
5948         AddToWorklist(oye);
5949       }
5950       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5951     }
5952
5953     // See if the value being truncated is already sign extended.  If so, just
5954     // eliminate the trunc/sext pair.
5955     SDValue Op = N0.getOperand(0);
5956     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5957     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5958     unsigned DestBits = VT.getScalarType().getSizeInBits();
5959     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5960
5961     if (OpBits == DestBits) {
5962       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5963       // bits, it is already ready.
5964       if (NumSignBits > DestBits-MidBits)
5965         return Op;
5966     } else if (OpBits < DestBits) {
5967       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5968       // bits, just sext from i32.
5969       if (NumSignBits > OpBits-MidBits)
5970         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5971     } else {
5972       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5973       // bits, just truncate to i32.
5974       if (NumSignBits > OpBits-MidBits)
5975         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5976     }
5977
5978     // fold (sext (truncate x)) -> (sextinreg x).
5979     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5980                                                  N0.getValueType())) {
5981       if (OpBits < DestBits)
5982         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5983       else if (OpBits > DestBits)
5984         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5985       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5986                          DAG.getValueType(N0.getValueType()));
5987     }
5988   }
5989
5990   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5991   // Only generate vector extloads when 1) they're legal, and 2) they are
5992   // deemed desirable by the target.
5993   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5994       ((!LegalOperations && !VT.isVector() &&
5995         !cast<LoadSDNode>(N0)->isVolatile()) ||
5996        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5997     bool DoXform = true;
5998     SmallVector<SDNode*, 4> SetCCs;
5999     if (!N0.hasOneUse())
6000       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6001     if (VT.isVector())
6002       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6003     if (DoXform) {
6004       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6005       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6006                                        LN0->getChain(),
6007                                        LN0->getBasePtr(), N0.getValueType(),
6008                                        LN0->getMemOperand());
6009       CombineTo(N, ExtLoad);
6010       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6011                                   N0.getValueType(), ExtLoad);
6012       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6013       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6014                       ISD::SIGN_EXTEND);
6015       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6016     }
6017   }
6018
6019   // fold (sext (load x)) to multiple smaller sextloads.
6020   // Only on illegal but splittable vectors.
6021   if (SDValue ExtLoad = CombineExtLoad(N))
6022     return ExtLoad;
6023
6024   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6025   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6026   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6027       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6028     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6029     EVT MemVT = LN0->getMemoryVT();
6030     if ((!LegalOperations && !LN0->isVolatile()) ||
6031         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6032       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6033                                        LN0->getChain(),
6034                                        LN0->getBasePtr(), MemVT,
6035                                        LN0->getMemOperand());
6036       CombineTo(N, ExtLoad);
6037       CombineTo(N0.getNode(),
6038                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6039                             N0.getValueType(), ExtLoad),
6040                 ExtLoad.getValue(1));
6041       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6042     }
6043   }
6044
6045   // fold (sext (and/or/xor (load x), cst)) ->
6046   //      (and/or/xor (sextload x), (sext cst))
6047   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6048        N0.getOpcode() == ISD::XOR) &&
6049       isa<LoadSDNode>(N0.getOperand(0)) &&
6050       N0.getOperand(1).getOpcode() == ISD::Constant &&
6051       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6052       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6053     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6054     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6055       bool DoXform = true;
6056       SmallVector<SDNode*, 4> SetCCs;
6057       if (!N0.hasOneUse())
6058         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6059                                           SetCCs, TLI);
6060       if (DoXform) {
6061         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6062                                          LN0->getChain(), LN0->getBasePtr(),
6063                                          LN0->getMemoryVT(),
6064                                          LN0->getMemOperand());
6065         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6066         Mask = Mask.sext(VT.getSizeInBits());
6067         SDLoc DL(N);
6068         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6069                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6070         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6071                                     SDLoc(N0.getOperand(0)),
6072                                     N0.getOperand(0).getValueType(), ExtLoad);
6073         CombineTo(N, And);
6074         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6075         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6076                         ISD::SIGN_EXTEND);
6077         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6078       }
6079     }
6080   }
6081
6082   if (N0.getOpcode() == ISD::SETCC) {
6083     EVT N0VT = N0.getOperand(0).getValueType();
6084     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6085     // Only do this before legalize for now.
6086     if (VT.isVector() && !LegalOperations &&
6087         TLI.getBooleanContents(N0VT) ==
6088             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6089       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6090       // of the same size as the compared operands. Only optimize sext(setcc())
6091       // if this is the case.
6092       EVT SVT = getSetCCResultType(N0VT);
6093
6094       // We know that the # elements of the results is the same as the
6095       // # elements of the compare (and the # elements of the compare result
6096       // for that matter).  Check to see that they are the same size.  If so,
6097       // we know that the element size of the sext'd result matches the
6098       // element size of the compare operands.
6099       if (VT.getSizeInBits() == SVT.getSizeInBits())
6100         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6101                              N0.getOperand(1),
6102                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6103
6104       // If the desired elements are smaller or larger than the source
6105       // elements we can use a matching integer vector type and then
6106       // truncate/sign extend
6107       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6108       if (SVT == MatchingVectorType) {
6109         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6110                                N0.getOperand(0), N0.getOperand(1),
6111                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6112         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6113       }
6114     }
6115
6116     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6117     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6118     SDLoc DL(N);
6119     SDValue NegOne =
6120       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6121     SDValue SCC =
6122       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6123                        NegOne, DAG.getConstant(0, DL, VT),
6124                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6125     if (SCC.getNode()) return SCC;
6126
6127     if (!VT.isVector()) {
6128       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6129       if (!LegalOperations ||
6130           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6131         SDLoc DL(N);
6132         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6133         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6134                                      N0.getOperand(0), N0.getOperand(1), CC);
6135         return DAG.getSelect(DL, VT, SetCC,
6136                              NegOne, DAG.getConstant(0, DL, VT));
6137       }
6138     }
6139   }
6140
6141   // fold (sext x) -> (zext x) if the sign bit is known zero.
6142   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6143       DAG.SignBitIsZero(N0))
6144     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6145
6146   return SDValue();
6147 }
6148
6149 // isTruncateOf - If N is a truncate of some other value, return true, record
6150 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6151 // This function computes KnownZero to avoid a duplicated call to
6152 // computeKnownBits in the caller.
6153 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6154                          APInt &KnownZero) {
6155   APInt KnownOne;
6156   if (N->getOpcode() == ISD::TRUNCATE) {
6157     Op = N->getOperand(0);
6158     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6159     return true;
6160   }
6161
6162   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6163       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6164     return false;
6165
6166   SDValue Op0 = N->getOperand(0);
6167   SDValue Op1 = N->getOperand(1);
6168   assert(Op0.getValueType() == Op1.getValueType());
6169
6170   if (isNullConstant(Op0))
6171     Op = Op1;
6172   else if (isNullConstant(Op1))
6173     Op = Op0;
6174   else
6175     return false;
6176
6177   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6178
6179   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6180     return false;
6181
6182   return true;
6183 }
6184
6185 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6186   SDValue N0 = N->getOperand(0);
6187   EVT VT = N->getValueType(0);
6188
6189   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6190                                               LegalOperations))
6191     return SDValue(Res, 0);
6192
6193   // fold (zext (zext x)) -> (zext x)
6194   // fold (zext (aext x)) -> (zext x)
6195   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6196     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6197                        N0.getOperand(0));
6198
6199   // fold (zext (truncate x)) -> (zext x) or
6200   //      (zext (truncate x)) -> (truncate x)
6201   // This is valid when the truncated bits of x are already zero.
6202   // FIXME: We should extend this to work for vectors too.
6203   SDValue Op;
6204   APInt KnownZero;
6205   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6206     APInt TruncatedBits =
6207       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6208       APInt(Op.getValueSizeInBits(), 0) :
6209       APInt::getBitsSet(Op.getValueSizeInBits(),
6210                         N0.getValueSizeInBits(),
6211                         std::min(Op.getValueSizeInBits(),
6212                                  VT.getSizeInBits()));
6213     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6214       if (VT.bitsGT(Op.getValueType()))
6215         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6216       if (VT.bitsLT(Op.getValueType()))
6217         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6218
6219       return Op;
6220     }
6221   }
6222
6223   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6224   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6225   if (N0.getOpcode() == ISD::TRUNCATE) {
6226     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6227       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6228       if (NarrowLoad.getNode() != N0.getNode()) {
6229         CombineTo(N0.getNode(), NarrowLoad);
6230         // CombineTo deleted the truncate, if needed, but not what's under it.
6231         AddToWorklist(oye);
6232       }
6233       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6234     }
6235   }
6236
6237   // fold (zext (truncate x)) -> (and x, mask)
6238   if (N0.getOpcode() == ISD::TRUNCATE) {
6239     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6240     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6241     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6242       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6243       if (NarrowLoad.getNode() != N0.getNode()) {
6244         CombineTo(N0.getNode(), NarrowLoad);
6245         // CombineTo deleted the truncate, if needed, but not what's under it.
6246         AddToWorklist(oye);
6247       }
6248       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6249     }
6250
6251     EVT SrcVT = N0.getOperand(0).getValueType();
6252     EVT MinVT = N0.getValueType();
6253
6254     // Try to mask before the extension to avoid having to generate a larger mask,
6255     // possibly over several sub-vectors.
6256     if (SrcVT.bitsLT(VT)) {
6257       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6258                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6259         SDValue Op = N0.getOperand(0);
6260         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6261         AddToWorklist(Op.getNode());
6262         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6263       }
6264     }
6265
6266     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6267       SDValue Op = N0.getOperand(0);
6268       if (SrcVT.bitsLT(VT)) {
6269         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6270         AddToWorklist(Op.getNode());
6271       } else if (SrcVT.bitsGT(VT)) {
6272         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6273         AddToWorklist(Op.getNode());
6274       }
6275       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6276     }
6277   }
6278
6279   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6280   // if either of the casts is not free.
6281   if (N0.getOpcode() == ISD::AND &&
6282       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6283       N0.getOperand(1).getOpcode() == ISD::Constant &&
6284       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6285                            N0.getValueType()) ||
6286        !TLI.isZExtFree(N0.getValueType(), VT))) {
6287     SDValue X = N0.getOperand(0).getOperand(0);
6288     if (X.getValueType().bitsLT(VT)) {
6289       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6290     } else if (X.getValueType().bitsGT(VT)) {
6291       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6292     }
6293     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6294     Mask = Mask.zext(VT.getSizeInBits());
6295     SDLoc DL(N);
6296     return DAG.getNode(ISD::AND, DL, VT,
6297                        X, DAG.getConstant(Mask, DL, VT));
6298   }
6299
6300   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6301   // Only generate vector extloads when 1) they're legal, and 2) they are
6302   // deemed desirable by the target.
6303   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6304       ((!LegalOperations && !VT.isVector() &&
6305         !cast<LoadSDNode>(N0)->isVolatile()) ||
6306        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6307     bool DoXform = true;
6308     SmallVector<SDNode*, 4> SetCCs;
6309     if (!N0.hasOneUse())
6310       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6311     if (VT.isVector())
6312       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6313     if (DoXform) {
6314       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6315       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6316                                        LN0->getChain(),
6317                                        LN0->getBasePtr(), N0.getValueType(),
6318                                        LN0->getMemOperand());
6319       CombineTo(N, ExtLoad);
6320       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6321                                   N0.getValueType(), ExtLoad);
6322       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6323
6324       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6325                       ISD::ZERO_EXTEND);
6326       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6327     }
6328   }
6329
6330   // fold (zext (load x)) to multiple smaller zextloads.
6331   // Only on illegal but splittable vectors.
6332   if (SDValue ExtLoad = CombineExtLoad(N))
6333     return ExtLoad;
6334
6335   // fold (zext (and/or/xor (load x), cst)) ->
6336   //      (and/or/xor (zextload x), (zext cst))
6337   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6338        N0.getOpcode() == ISD::XOR) &&
6339       isa<LoadSDNode>(N0.getOperand(0)) &&
6340       N0.getOperand(1).getOpcode() == ISD::Constant &&
6341       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6342       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6343     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6344     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6345       bool DoXform = true;
6346       SmallVector<SDNode*, 4> SetCCs;
6347       if (!N0.hasOneUse())
6348         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6349                                           SetCCs, TLI);
6350       if (DoXform) {
6351         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6352                                          LN0->getChain(), LN0->getBasePtr(),
6353                                          LN0->getMemoryVT(),
6354                                          LN0->getMemOperand());
6355         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6356         Mask = Mask.zext(VT.getSizeInBits());
6357         SDLoc DL(N);
6358         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6359                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6360         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6361                                     SDLoc(N0.getOperand(0)),
6362                                     N0.getOperand(0).getValueType(), ExtLoad);
6363         CombineTo(N, And);
6364         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6365         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6366                         ISD::ZERO_EXTEND);
6367         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6368       }
6369     }
6370   }
6371
6372   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6373   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6374   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6375       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6376     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6377     EVT MemVT = LN0->getMemoryVT();
6378     if ((!LegalOperations && !LN0->isVolatile()) ||
6379         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6380       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6381                                        LN0->getChain(),
6382                                        LN0->getBasePtr(), MemVT,
6383                                        LN0->getMemOperand());
6384       CombineTo(N, ExtLoad);
6385       CombineTo(N0.getNode(),
6386                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6387                             ExtLoad),
6388                 ExtLoad.getValue(1));
6389       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6390     }
6391   }
6392
6393   if (N0.getOpcode() == ISD::SETCC) {
6394     if (!LegalOperations && VT.isVector() &&
6395         N0.getValueType().getVectorElementType() == MVT::i1) {
6396       EVT N0VT = N0.getOperand(0).getValueType();
6397       if (getSetCCResultType(N0VT) == N0.getValueType())
6398         return SDValue();
6399
6400       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6401       // Only do this before legalize for now.
6402       EVT EltVT = VT.getVectorElementType();
6403       SDLoc DL(N);
6404       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6405                                     DAG.getConstant(1, DL, EltVT));
6406       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6407         // We know that the # elements of the results is the same as the
6408         // # elements of the compare (and the # elements of the compare result
6409         // for that matter).  Check to see that they are the same size.  If so,
6410         // we know that the element size of the sext'd result matches the
6411         // element size of the compare operands.
6412         return DAG.getNode(ISD::AND, DL, VT,
6413                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6414                                          N0.getOperand(1),
6415                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6416                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6417                                        OneOps));
6418
6419       // If the desired elements are smaller or larger than the source
6420       // elements we can use a matching integer vector type and then
6421       // truncate/sign extend
6422       EVT MatchingElementType =
6423         EVT::getIntegerVT(*DAG.getContext(),
6424                           N0VT.getScalarType().getSizeInBits());
6425       EVT MatchingVectorType =
6426         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6427                          N0VT.getVectorNumElements());
6428       SDValue VsetCC =
6429         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6430                       N0.getOperand(1),
6431                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6432       return DAG.getNode(ISD::AND, DL, VT,
6433                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6434                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6435     }
6436
6437     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6438     SDLoc DL(N);
6439     SDValue SCC =
6440       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6441                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6442                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6443     if (SCC.getNode()) return SCC;
6444   }
6445
6446   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6447   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6448       isa<ConstantSDNode>(N0.getOperand(1)) &&
6449       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6450       N0.hasOneUse()) {
6451     SDValue ShAmt = N0.getOperand(1);
6452     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6453     if (N0.getOpcode() == ISD::SHL) {
6454       SDValue InnerZExt = N0.getOperand(0);
6455       // If the original shl may be shifting out bits, do not perform this
6456       // transformation.
6457       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6458         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6459       if (ShAmtVal > KnownZeroBits)
6460         return SDValue();
6461     }
6462
6463     SDLoc DL(N);
6464
6465     // Ensure that the shift amount is wide enough for the shifted value.
6466     if (VT.getSizeInBits() >= 256)
6467       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6468
6469     return DAG.getNode(N0.getOpcode(), DL, VT,
6470                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6471                        ShAmt);
6472   }
6473
6474   return SDValue();
6475 }
6476
6477 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6478   SDValue N0 = N->getOperand(0);
6479   EVT VT = N->getValueType(0);
6480
6481   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6482                                               LegalOperations))
6483     return SDValue(Res, 0);
6484
6485   // fold (aext (aext x)) -> (aext x)
6486   // fold (aext (zext x)) -> (zext x)
6487   // fold (aext (sext x)) -> (sext x)
6488   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6489       N0.getOpcode() == ISD::ZERO_EXTEND ||
6490       N0.getOpcode() == ISD::SIGN_EXTEND)
6491     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6492
6493   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6494   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6495   if (N0.getOpcode() == ISD::TRUNCATE) {
6496     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6497       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6498       if (NarrowLoad.getNode() != N0.getNode()) {
6499         CombineTo(N0.getNode(), NarrowLoad);
6500         // CombineTo deleted the truncate, if needed, but not what's under it.
6501         AddToWorklist(oye);
6502       }
6503       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6504     }
6505   }
6506
6507   // fold (aext (truncate x))
6508   if (N0.getOpcode() == ISD::TRUNCATE) {
6509     SDValue TruncOp = N0.getOperand(0);
6510     if (TruncOp.getValueType() == VT)
6511       return TruncOp; // x iff x size == zext size.
6512     if (TruncOp.getValueType().bitsGT(VT))
6513       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6514     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6515   }
6516
6517   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6518   // if the trunc is not free.
6519   if (N0.getOpcode() == ISD::AND &&
6520       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6521       N0.getOperand(1).getOpcode() == ISD::Constant &&
6522       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6523                           N0.getValueType())) {
6524     SDValue X = N0.getOperand(0).getOperand(0);
6525     if (X.getValueType().bitsLT(VT)) {
6526       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6527     } else if (X.getValueType().bitsGT(VT)) {
6528       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6529     }
6530     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6531     Mask = Mask.zext(VT.getSizeInBits());
6532     SDLoc DL(N);
6533     return DAG.getNode(ISD::AND, DL, VT,
6534                        X, DAG.getConstant(Mask, DL, VT));
6535   }
6536
6537   // fold (aext (load x)) -> (aext (truncate (extload x)))
6538   // None of the supported targets knows how to perform load and any_ext
6539   // on vectors in one instruction.  We only perform this transformation on
6540   // scalars.
6541   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6542       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6543       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6544     bool DoXform = true;
6545     SmallVector<SDNode*, 4> SetCCs;
6546     if (!N0.hasOneUse())
6547       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6548     if (DoXform) {
6549       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6550       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6551                                        LN0->getChain(),
6552                                        LN0->getBasePtr(), N0.getValueType(),
6553                                        LN0->getMemOperand());
6554       CombineTo(N, ExtLoad);
6555       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6556                                   N0.getValueType(), ExtLoad);
6557       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6558       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6559                       ISD::ANY_EXTEND);
6560       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6561     }
6562   }
6563
6564   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6565   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6566   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6567   if (N0.getOpcode() == ISD::LOAD &&
6568       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6569       N0.hasOneUse()) {
6570     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6571     ISD::LoadExtType ExtType = LN0->getExtensionType();
6572     EVT MemVT = LN0->getMemoryVT();
6573     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6574       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6575                                        VT, LN0->getChain(), LN0->getBasePtr(),
6576                                        MemVT, LN0->getMemOperand());
6577       CombineTo(N, ExtLoad);
6578       CombineTo(N0.getNode(),
6579                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6580                             N0.getValueType(), ExtLoad),
6581                 ExtLoad.getValue(1));
6582       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6583     }
6584   }
6585
6586   if (N0.getOpcode() == ISD::SETCC) {
6587     // For vectors:
6588     // aext(setcc) -> vsetcc
6589     // aext(setcc) -> truncate(vsetcc)
6590     // aext(setcc) -> aext(vsetcc)
6591     // Only do this before legalize for now.
6592     if (VT.isVector() && !LegalOperations) {
6593       EVT N0VT = N0.getOperand(0).getValueType();
6594         // We know that the # elements of the results is the same as the
6595         // # elements of the compare (and the # elements of the compare result
6596         // for that matter).  Check to see that they are the same size.  If so,
6597         // we know that the element size of the sext'd result matches the
6598         // element size of the compare operands.
6599       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6600         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6601                              N0.getOperand(1),
6602                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6603       // If the desired elements are smaller or larger than the source
6604       // elements we can use a matching integer vector type and then
6605       // truncate/any extend
6606       else {
6607         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6608         SDValue VsetCC =
6609           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6610                         N0.getOperand(1),
6611                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6612         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6613       }
6614     }
6615
6616     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6617     SDLoc DL(N);
6618     SDValue SCC =
6619       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6620                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6621                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6622     if (SCC.getNode())
6623       return SCC;
6624   }
6625
6626   return SDValue();
6627 }
6628
6629 /// See if the specified operand can be simplified with the knowledge that only
6630 /// the bits specified by Mask are used.  If so, return the simpler operand,
6631 /// otherwise return a null SDValue.
6632 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6633   switch (V.getOpcode()) {
6634   default: break;
6635   case ISD::Constant: {
6636     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6637     assert(CV && "Const value should be ConstSDNode.");
6638     const APInt &CVal = CV->getAPIntValue();
6639     APInt NewVal = CVal & Mask;
6640     if (NewVal != CVal)
6641       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6642     break;
6643   }
6644   case ISD::OR:
6645   case ISD::XOR:
6646     // If the LHS or RHS don't contribute bits to the or, drop them.
6647     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6648       return V.getOperand(1);
6649     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6650       return V.getOperand(0);
6651     break;
6652   case ISD::SRL:
6653     // Only look at single-use SRLs.
6654     if (!V.getNode()->hasOneUse())
6655       break;
6656     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6657       // See if we can recursively simplify the LHS.
6658       unsigned Amt = RHSC->getZExtValue();
6659
6660       // Watch out for shift count overflow though.
6661       if (Amt >= Mask.getBitWidth()) break;
6662       APInt NewMask = Mask << Amt;
6663       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6664         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6665                            SimplifyLHS, V.getOperand(1));
6666     }
6667   }
6668   return SDValue();
6669 }
6670
6671 /// If the result of a wider load is shifted to right of N  bits and then
6672 /// truncated to a narrower type and where N is a multiple of number of bits of
6673 /// the narrower type, transform it to a narrower load from address + N / num of
6674 /// bits of new type. If the result is to be extended, also fold the extension
6675 /// to form a extending load.
6676 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6677   unsigned Opc = N->getOpcode();
6678
6679   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6680   SDValue N0 = N->getOperand(0);
6681   EVT VT = N->getValueType(0);
6682   EVT ExtVT = VT;
6683
6684   // This transformation isn't valid for vector loads.
6685   if (VT.isVector())
6686     return SDValue();
6687
6688   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6689   // extended to VT.
6690   if (Opc == ISD::SIGN_EXTEND_INREG) {
6691     ExtType = ISD::SEXTLOAD;
6692     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6693   } else if (Opc == ISD::SRL) {
6694     // Another special-case: SRL is basically zero-extending a narrower value.
6695     ExtType = ISD::ZEXTLOAD;
6696     N0 = SDValue(N, 0);
6697     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6698     if (!N01) return SDValue();
6699     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6700                               VT.getSizeInBits() - N01->getZExtValue());
6701   }
6702   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6703     return SDValue();
6704
6705   unsigned EVTBits = ExtVT.getSizeInBits();
6706
6707   // Do not generate loads of non-round integer types since these can
6708   // be expensive (and would be wrong if the type is not byte sized).
6709   if (!ExtVT.isRound())
6710     return SDValue();
6711
6712   unsigned ShAmt = 0;
6713   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6714     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6715       ShAmt = N01->getZExtValue();
6716       // Is the shift amount a multiple of size of VT?
6717       if ((ShAmt & (EVTBits-1)) == 0) {
6718         N0 = N0.getOperand(0);
6719         // Is the load width a multiple of size of VT?
6720         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6721           return SDValue();
6722       }
6723
6724       // At this point, we must have a load or else we can't do the transform.
6725       if (!isa<LoadSDNode>(N0)) return SDValue();
6726
6727       // Because a SRL must be assumed to *need* to zero-extend the high bits
6728       // (as opposed to anyext the high bits), we can't combine the zextload
6729       // lowering of SRL and an sextload.
6730       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6731         return SDValue();
6732
6733       // If the shift amount is larger than the input type then we're not
6734       // accessing any of the loaded bytes.  If the load was a zextload/extload
6735       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6736       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6737         return SDValue();
6738     }
6739   }
6740
6741   // If the load is shifted left (and the result isn't shifted back right),
6742   // we can fold the truncate through the shift.
6743   unsigned ShLeftAmt = 0;
6744   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6745       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6746     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6747       ShLeftAmt = N01->getZExtValue();
6748       N0 = N0.getOperand(0);
6749     }
6750   }
6751
6752   // If we haven't found a load, we can't narrow it.  Don't transform one with
6753   // multiple uses, this would require adding a new load.
6754   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6755     return SDValue();
6756
6757   // Don't change the width of a volatile load.
6758   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6759   if (LN0->isVolatile())
6760     return SDValue();
6761
6762   // Verify that we are actually reducing a load width here.
6763   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6764     return SDValue();
6765
6766   // For the transform to be legal, the load must produce only two values
6767   // (the value loaded and the chain).  Don't transform a pre-increment
6768   // load, for example, which produces an extra value.  Otherwise the
6769   // transformation is not equivalent, and the downstream logic to replace
6770   // uses gets things wrong.
6771   if (LN0->getNumValues() > 2)
6772     return SDValue();
6773
6774   // If the load that we're shrinking is an extload and we're not just
6775   // discarding the extension we can't simply shrink the load. Bail.
6776   // TODO: It would be possible to merge the extensions in some cases.
6777   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6778       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6779     return SDValue();
6780
6781   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6782     return SDValue();
6783
6784   EVT PtrType = N0.getOperand(1).getValueType();
6785
6786   if (PtrType == MVT::Untyped || PtrType.isExtended())
6787     // It's not possible to generate a constant of extended or untyped type.
6788     return SDValue();
6789
6790   // For big endian targets, we need to adjust the offset to the pointer to
6791   // load the correct bytes.
6792   if (DAG.getDataLayout().isBigEndian()) {
6793     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6794     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6795     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6796   }
6797
6798   uint64_t PtrOff = ShAmt / 8;
6799   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6800   SDLoc DL(LN0);
6801   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6802                                PtrType, LN0->getBasePtr(),
6803                                DAG.getConstant(PtrOff, DL, PtrType));
6804   AddToWorklist(NewPtr.getNode());
6805
6806   SDValue Load;
6807   if (ExtType == ISD::NON_EXTLOAD)
6808     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6809                         LN0->getPointerInfo().getWithOffset(PtrOff),
6810                         LN0->isVolatile(), LN0->isNonTemporal(),
6811                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6812   else
6813     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6814                           LN0->getPointerInfo().getWithOffset(PtrOff),
6815                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6816                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6817
6818   // Replace the old load's chain with the new load's chain.
6819   WorklistRemover DeadNodes(*this);
6820   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6821
6822   // Shift the result left, if we've swallowed a left shift.
6823   SDValue Result = Load;
6824   if (ShLeftAmt != 0) {
6825     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6826     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6827       ShImmTy = VT;
6828     // If the shift amount is as large as the result size (but, presumably,
6829     // no larger than the source) then the useful bits of the result are
6830     // zero; we can't simply return the shortened shift, because the result
6831     // of that operation is undefined.
6832     SDLoc DL(N0);
6833     if (ShLeftAmt >= VT.getSizeInBits())
6834       Result = DAG.getConstant(0, DL, VT);
6835     else
6836       Result = DAG.getNode(ISD::SHL, DL, VT,
6837                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6838   }
6839
6840   // Return the new loaded value.
6841   return Result;
6842 }
6843
6844 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6845   SDValue N0 = N->getOperand(0);
6846   SDValue N1 = N->getOperand(1);
6847   EVT VT = N->getValueType(0);
6848   EVT EVT = cast<VTSDNode>(N1)->getVT();
6849   unsigned VTBits = VT.getScalarType().getSizeInBits();
6850   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6851
6852   if (N0.isUndef())
6853     return DAG.getUNDEF(VT);
6854
6855   // fold (sext_in_reg c1) -> c1
6856   if (isConstantIntBuildVectorOrConstantInt(N0))
6857     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6858
6859   // If the input is already sign extended, just drop the extension.
6860   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6861     return N0;
6862
6863   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6864   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6865       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6866     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6867                        N0.getOperand(0), N1);
6868
6869   // fold (sext_in_reg (sext x)) -> (sext x)
6870   // fold (sext_in_reg (aext x)) -> (sext x)
6871   // if x is small enough.
6872   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6873     SDValue N00 = N0.getOperand(0);
6874     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6875         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6876       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6877   }
6878
6879   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6880   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6881     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6882
6883   // fold operands of sext_in_reg based on knowledge that the top bits are not
6884   // demanded.
6885   if (SimplifyDemandedBits(SDValue(N, 0)))
6886     return SDValue(N, 0);
6887
6888   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6889   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6890   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6891     return NarrowLoad;
6892
6893   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6894   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6895   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6896   if (N0.getOpcode() == ISD::SRL) {
6897     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6898       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6899         // We can turn this into an SRA iff the input to the SRL is already sign
6900         // extended enough.
6901         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6902         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6903           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6904                              N0.getOperand(0), N0.getOperand(1));
6905       }
6906   }
6907
6908   // fold (sext_inreg (extload x)) -> (sextload x)
6909   if (ISD::isEXTLoad(N0.getNode()) &&
6910       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6911       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6912       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6913        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6914     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6915     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6916                                      LN0->getChain(),
6917                                      LN0->getBasePtr(), EVT,
6918                                      LN0->getMemOperand());
6919     CombineTo(N, ExtLoad);
6920     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6921     AddToWorklist(ExtLoad.getNode());
6922     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6923   }
6924   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6925   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6926       N0.hasOneUse() &&
6927       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6928       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6929        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6930     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6931     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6932                                      LN0->getChain(),
6933                                      LN0->getBasePtr(), EVT,
6934                                      LN0->getMemOperand());
6935     CombineTo(N, ExtLoad);
6936     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6937     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6938   }
6939
6940   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6941   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6942     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6943                                        N0.getOperand(1), false);
6944     if (BSwap.getNode())
6945       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6946                          BSwap, N1);
6947   }
6948
6949   return SDValue();
6950 }
6951
6952 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6953   SDValue N0 = N->getOperand(0);
6954   EVT VT = N->getValueType(0);
6955
6956   if (N0.getOpcode() == ISD::UNDEF)
6957     return DAG.getUNDEF(VT);
6958
6959   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6960                                               LegalOperations))
6961     return SDValue(Res, 0);
6962
6963   return SDValue();
6964 }
6965
6966 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6967   SDValue N0 = N->getOperand(0);
6968   EVT VT = N->getValueType(0);
6969   bool isLE = DAG.getDataLayout().isLittleEndian();
6970
6971   // noop truncate
6972   if (N0.getValueType() == N->getValueType(0))
6973     return N0;
6974   // fold (truncate c1) -> c1
6975   if (isConstantIntBuildVectorOrConstantInt(N0))
6976     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6977   // fold (truncate (truncate x)) -> (truncate x)
6978   if (N0.getOpcode() == ISD::TRUNCATE)
6979     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6980   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6981   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6982       N0.getOpcode() == ISD::SIGN_EXTEND ||
6983       N0.getOpcode() == ISD::ANY_EXTEND) {
6984     if (N0.getOperand(0).getValueType().bitsLT(VT))
6985       // if the source is smaller than the dest, we still need an extend
6986       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6987                          N0.getOperand(0));
6988     if (N0.getOperand(0).getValueType().bitsGT(VT))
6989       // if the source is larger than the dest, than we just need the truncate
6990       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6991     // if the source and dest are the same type, we can drop both the extend
6992     // and the truncate.
6993     return N0.getOperand(0);
6994   }
6995
6996   // Fold extract-and-trunc into a narrow extract. For example:
6997   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6998   //   i32 y = TRUNCATE(i64 x)
6999   //        -- becomes --
7000   //   v16i8 b = BITCAST (v2i64 val)
7001   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7002   //
7003   // Note: We only run this optimization after type legalization (which often
7004   // creates this pattern) and before operation legalization after which
7005   // we need to be more careful about the vector instructions that we generate.
7006   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7007       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7008
7009     EVT VecTy = N0.getOperand(0).getValueType();
7010     EVT ExTy = N0.getValueType();
7011     EVT TrTy = N->getValueType(0);
7012
7013     unsigned NumElem = VecTy.getVectorNumElements();
7014     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7015
7016     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7017     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7018
7019     SDValue EltNo = N0->getOperand(1);
7020     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7021       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7022       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7023       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7024
7025       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7026                               NVT, N0.getOperand(0));
7027
7028       SDLoc DL(N);
7029       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7030                          DL, TrTy, V,
7031                          DAG.getConstant(Index, DL, IndexTy));
7032     }
7033   }
7034
7035   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7036   if (N0.getOpcode() == ISD::SELECT) {
7037     EVT SrcVT = N0.getValueType();
7038     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7039         TLI.isTruncateFree(SrcVT, VT)) {
7040       SDLoc SL(N0);
7041       SDValue Cond = N0.getOperand(0);
7042       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7043       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7044       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7045     }
7046   }
7047
7048   // Fold a series of buildvector, bitcast, and truncate if possible.
7049   // For example fold
7050   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7051   //   (2xi32 (buildvector x, y)).
7052   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7053       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7054       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7055       N0.getOperand(0).hasOneUse()) {
7056
7057     SDValue BuildVect = N0.getOperand(0);
7058     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7059     EVT TruncVecEltTy = VT.getVectorElementType();
7060
7061     // Check that the element types match.
7062     if (BuildVectEltTy == TruncVecEltTy) {
7063       // Now we only need to compute the offset of the truncated elements.
7064       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7065       unsigned TruncVecNumElts = VT.getVectorNumElements();
7066       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7067
7068       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7069              "Invalid number of elements");
7070
7071       SmallVector<SDValue, 8> Opnds;
7072       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7073         Opnds.push_back(BuildVect.getOperand(i));
7074
7075       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7076     }
7077   }
7078
7079   // See if we can simplify the input to this truncate through knowledge that
7080   // only the low bits are being used.
7081   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7082   // Currently we only perform this optimization on scalars because vectors
7083   // may have different active low bits.
7084   if (!VT.isVector()) {
7085     SDValue Shorter =
7086       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7087                                                VT.getSizeInBits()));
7088     if (Shorter.getNode())
7089       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7090   }
7091   // fold (truncate (load x)) -> (smaller load x)
7092   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7093   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7094     if (SDValue Reduced = ReduceLoadWidth(N))
7095       return Reduced;
7096
7097     // Handle the case where the load remains an extending load even
7098     // after truncation.
7099     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7100       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7101       if (!LN0->isVolatile() &&
7102           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7103         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7104                                          VT, LN0->getChain(), LN0->getBasePtr(),
7105                                          LN0->getMemoryVT(),
7106                                          LN0->getMemOperand());
7107         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7108         return NewLoad;
7109       }
7110     }
7111   }
7112   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7113   // where ... are all 'undef'.
7114   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7115     SmallVector<EVT, 8> VTs;
7116     SDValue V;
7117     unsigned Idx = 0;
7118     unsigned NumDefs = 0;
7119
7120     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7121       SDValue X = N0.getOperand(i);
7122       if (X.getOpcode() != ISD::UNDEF) {
7123         V = X;
7124         Idx = i;
7125         NumDefs++;
7126       }
7127       // Stop if more than one members are non-undef.
7128       if (NumDefs > 1)
7129         break;
7130       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7131                                      VT.getVectorElementType(),
7132                                      X.getValueType().getVectorNumElements()));
7133     }
7134
7135     if (NumDefs == 0)
7136       return DAG.getUNDEF(VT);
7137
7138     if (NumDefs == 1) {
7139       assert(V.getNode() && "The single defined operand is empty!");
7140       SmallVector<SDValue, 8> Opnds;
7141       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7142         if (i != Idx) {
7143           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7144           continue;
7145         }
7146         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7147         AddToWorklist(NV.getNode());
7148         Opnds.push_back(NV);
7149       }
7150       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7151     }
7152   }
7153
7154   // Simplify the operands using demanded-bits information.
7155   if (!VT.isVector() &&
7156       SimplifyDemandedBits(SDValue(N, 0)))
7157     return SDValue(N, 0);
7158
7159   return SDValue();
7160 }
7161
7162 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7163   SDValue Elt = N->getOperand(i);
7164   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7165     return Elt.getNode();
7166   return Elt.getOperand(Elt.getResNo()).getNode();
7167 }
7168
7169 /// build_pair (load, load) -> load
7170 /// if load locations are consecutive.
7171 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7172   assert(N->getOpcode() == ISD::BUILD_PAIR);
7173
7174   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7175   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7176   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7177       LD1->getAddressSpace() != LD2->getAddressSpace())
7178     return SDValue();
7179   EVT LD1VT = LD1->getValueType(0);
7180
7181   if (ISD::isNON_EXTLoad(LD2) &&
7182       LD2->hasOneUse() &&
7183       // If both are volatile this would reduce the number of volatile loads.
7184       // If one is volatile it might be ok, but play conservative and bail out.
7185       !LD1->isVolatile() &&
7186       !LD2->isVolatile() &&
7187       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7188     unsigned Align = LD1->getAlignment();
7189     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7190         VT.getTypeForEVT(*DAG.getContext()));
7191
7192     if (NewAlign <= Align &&
7193         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7194       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7195                          LD1->getBasePtr(), LD1->getPointerInfo(),
7196                          false, false, false, Align);
7197   }
7198
7199   return SDValue();
7200 }
7201
7202 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7203   SDValue N0 = N->getOperand(0);
7204   EVT VT = N->getValueType(0);
7205
7206   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7207   // Only do this before legalize, since afterward the target may be depending
7208   // on the bitconvert.
7209   // First check to see if this is all constant.
7210   if (!LegalTypes &&
7211       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7212       VT.isVector()) {
7213     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7214
7215     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7216     assert(!DestEltVT.isVector() &&
7217            "Element type of vector ValueType must not be vector!");
7218     if (isSimple)
7219       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7220   }
7221
7222   // If the input is a constant, let getNode fold it.
7223   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7224     // If we can't allow illegal operations, we need to check that this is just
7225     // a fp -> int or int -> conversion and that the resulting operation will
7226     // be legal.
7227     if (!LegalOperations ||
7228         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7229          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7230         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7231          TLI.isOperationLegal(ISD::Constant, VT)))
7232       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7233   }
7234
7235   // (conv (conv x, t1), t2) -> (conv x, t2)
7236   if (N0.getOpcode() == ISD::BITCAST)
7237     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7238                        N0.getOperand(0));
7239
7240   // fold (conv (load x)) -> (load (conv*)x)
7241   // If the resultant load doesn't need a higher alignment than the original!
7242   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7243       // Do not change the width of a volatile load.
7244       !cast<LoadSDNode>(N0)->isVolatile() &&
7245       // Do not remove the cast if the types differ in endian layout.
7246       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7247           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7248       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7249       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7250     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7251     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7252         VT.getTypeForEVT(*DAG.getContext()));
7253     unsigned OrigAlign = LN0->getAlignment();
7254
7255     if (Align <= OrigAlign) {
7256       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7257                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7258                                  LN0->isVolatile(), LN0->isNonTemporal(),
7259                                  LN0->isInvariant(), OrigAlign,
7260                                  LN0->getAAInfo());
7261       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7262       return Load;
7263     }
7264   }
7265
7266   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7267   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7268   // This often reduces constant pool loads.
7269   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7270        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7271       N0.getNode()->hasOneUse() && VT.isInteger() &&
7272       !VT.isVector() && !N0.getValueType().isVector()) {
7273     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7274                                   N0.getOperand(0));
7275     AddToWorklist(NewConv.getNode());
7276
7277     SDLoc DL(N);
7278     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7279     if (N0.getOpcode() == ISD::FNEG)
7280       return DAG.getNode(ISD::XOR, DL, VT,
7281                          NewConv, DAG.getConstant(SignBit, DL, VT));
7282     assert(N0.getOpcode() == ISD::FABS);
7283     return DAG.getNode(ISD::AND, DL, VT,
7284                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7285   }
7286
7287   // fold (bitconvert (fcopysign cst, x)) ->
7288   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7289   // Note that we don't handle (copysign x, cst) because this can always be
7290   // folded to an fneg or fabs.
7291   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7292       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7293       VT.isInteger() && !VT.isVector()) {
7294     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7295     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7296     if (isTypeLegal(IntXVT)) {
7297       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7298                               IntXVT, N0.getOperand(1));
7299       AddToWorklist(X.getNode());
7300
7301       // If X has a different width than the result/lhs, sext it or truncate it.
7302       unsigned VTWidth = VT.getSizeInBits();
7303       if (OrigXWidth < VTWidth) {
7304         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7305         AddToWorklist(X.getNode());
7306       } else if (OrigXWidth > VTWidth) {
7307         // To get the sign bit in the right place, we have to shift it right
7308         // before truncating.
7309         SDLoc DL(X);
7310         X = DAG.getNode(ISD::SRL, DL,
7311                         X.getValueType(), X,
7312                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7313                                         X.getValueType()));
7314         AddToWorklist(X.getNode());
7315         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7316         AddToWorklist(X.getNode());
7317       }
7318
7319       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7320       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7321                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7322       AddToWorklist(X.getNode());
7323
7324       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7325                                 VT, N0.getOperand(0));
7326       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7327                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7328       AddToWorklist(Cst.getNode());
7329
7330       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7331     }
7332   }
7333
7334   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7335   if (N0.getOpcode() == ISD::BUILD_PAIR)
7336     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7337       return CombineLD;
7338
7339   // Remove double bitcasts from shuffles - this is often a legacy of
7340   // XformToShuffleWithZero being used to combine bitmaskings (of
7341   // float vectors bitcast to integer vectors) into shuffles.
7342   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7343   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7344       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7345       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7346       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7347     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7348
7349     // If operands are a bitcast, peek through if it casts the original VT.
7350     // If operands are a constant, just bitcast back to original VT.
7351     auto PeekThroughBitcast = [&](SDValue Op) {
7352       if (Op.getOpcode() == ISD::BITCAST &&
7353           Op.getOperand(0).getValueType() == VT)
7354         return SDValue(Op.getOperand(0));
7355       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7356           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7357         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7358       return SDValue();
7359     };
7360
7361     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7362     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7363     if (!(SV0 && SV1))
7364       return SDValue();
7365
7366     int MaskScale =
7367         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7368     SmallVector<int, 8> NewMask;
7369     for (int M : SVN->getMask())
7370       for (int i = 0; i != MaskScale; ++i)
7371         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7372
7373     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7374     if (!LegalMask) {
7375       std::swap(SV0, SV1);
7376       ShuffleVectorSDNode::commuteMask(NewMask);
7377       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7378     }
7379
7380     if (LegalMask)
7381       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7382   }
7383
7384   return SDValue();
7385 }
7386
7387 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7388   EVT VT = N->getValueType(0);
7389   return CombineConsecutiveLoads(N, VT);
7390 }
7391
7392 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7393 /// operands. DstEltVT indicates the destination element value type.
7394 SDValue DAGCombiner::
7395 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7396   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7397
7398   // If this is already the right type, we're done.
7399   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7400
7401   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7402   unsigned DstBitSize = DstEltVT.getSizeInBits();
7403
7404   // If this is a conversion of N elements of one type to N elements of another
7405   // type, convert each element.  This handles FP<->INT cases.
7406   if (SrcBitSize == DstBitSize) {
7407     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7408                               BV->getValueType(0).getVectorNumElements());
7409
7410     // Due to the FP element handling below calling this routine recursively,
7411     // we can end up with a scalar-to-vector node here.
7412     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7413       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7414                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7415                                      DstEltVT, BV->getOperand(0)));
7416
7417     SmallVector<SDValue, 8> Ops;
7418     for (SDValue Op : BV->op_values()) {
7419       // If the vector element type is not legal, the BUILD_VECTOR operands
7420       // are promoted and implicitly truncated.  Make that explicit here.
7421       if (Op.getValueType() != SrcEltVT)
7422         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7423       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7424                                 DstEltVT, Op));
7425       AddToWorklist(Ops.back().getNode());
7426     }
7427     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7428   }
7429
7430   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7431   // handle annoying details of growing/shrinking FP values, we convert them to
7432   // int first.
7433   if (SrcEltVT.isFloatingPoint()) {
7434     // Convert the input float vector to a int vector where the elements are the
7435     // same sizes.
7436     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7437     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7438     SrcEltVT = IntVT;
7439   }
7440
7441   // Now we know the input is an integer vector.  If the output is a FP type,
7442   // convert to integer first, then to FP of the right size.
7443   if (DstEltVT.isFloatingPoint()) {
7444     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7445     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7446
7447     // Next, convert to FP elements of the same size.
7448     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7449   }
7450
7451   SDLoc DL(BV);
7452
7453   // Okay, we know the src/dst types are both integers of differing types.
7454   // Handling growing first.
7455   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7456   if (SrcBitSize < DstBitSize) {
7457     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7458
7459     SmallVector<SDValue, 8> Ops;
7460     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7461          i += NumInputsPerOutput) {
7462       bool isLE = DAG.getDataLayout().isLittleEndian();
7463       APInt NewBits = APInt(DstBitSize, 0);
7464       bool EltIsUndef = true;
7465       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7466         // Shift the previously computed bits over.
7467         NewBits <<= SrcBitSize;
7468         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7469         if (Op.getOpcode() == ISD::UNDEF) continue;
7470         EltIsUndef = false;
7471
7472         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7473                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7474       }
7475
7476       if (EltIsUndef)
7477         Ops.push_back(DAG.getUNDEF(DstEltVT));
7478       else
7479         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7480     }
7481
7482     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7483     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7484   }
7485
7486   // Finally, this must be the case where we are shrinking elements: each input
7487   // turns into multiple outputs.
7488   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7489   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7490                             NumOutputsPerInput*BV->getNumOperands());
7491   SmallVector<SDValue, 8> Ops;
7492
7493   for (const SDValue &Op : BV->op_values()) {
7494     if (Op.getOpcode() == ISD::UNDEF) {
7495       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7496       continue;
7497     }
7498
7499     APInt OpVal = cast<ConstantSDNode>(Op)->
7500                   getAPIntValue().zextOrTrunc(SrcBitSize);
7501
7502     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7503       APInt ThisVal = OpVal.trunc(DstBitSize);
7504       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7505       OpVal = OpVal.lshr(DstBitSize);
7506     }
7507
7508     // For big endian targets, swap the order of the pieces of each element.
7509     if (DAG.getDataLayout().isBigEndian())
7510       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7511   }
7512
7513   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7514 }
7515
7516 /// Try to perform FMA combining on a given FADD node.
7517 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7518   SDValue N0 = N->getOperand(0);
7519   SDValue N1 = N->getOperand(1);
7520   EVT VT = N->getValueType(0);
7521   SDLoc SL(N);
7522
7523   const TargetOptions &Options = DAG.getTarget().Options;
7524   bool AllowFusion =
7525       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7526
7527   // Floating-point multiply-add with intermediate rounding.
7528   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7529
7530   // Floating-point multiply-add without intermediate rounding.
7531   bool HasFMA =
7532       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7533       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7534
7535   // No valid opcode, do not combine.
7536   if (!HasFMAD && !HasFMA)
7537     return SDValue();
7538
7539   // Always prefer FMAD to FMA for precision.
7540   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7541   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7542   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7543
7544   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7545   // prefer to fold the multiply with fewer uses.
7546   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7547       N1.getOpcode() == ISD::FMUL) {
7548     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7549       std::swap(N0, N1);
7550   }
7551
7552   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7553   if (N0.getOpcode() == ISD::FMUL &&
7554       (Aggressive || N0->hasOneUse())) {
7555     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7556                        N0.getOperand(0), N0.getOperand(1), N1);
7557   }
7558
7559   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7560   // Note: Commutes FADD operands.
7561   if (N1.getOpcode() == ISD::FMUL &&
7562       (Aggressive || N1->hasOneUse())) {
7563     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7564                        N1.getOperand(0), N1.getOperand(1), N0);
7565   }
7566
7567   // Look through FP_EXTEND nodes to do more combining.
7568   if (AllowFusion && LookThroughFPExt) {
7569     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7570     if (N0.getOpcode() == ISD::FP_EXTEND) {
7571       SDValue N00 = N0.getOperand(0);
7572       if (N00.getOpcode() == ISD::FMUL)
7573         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7574                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7575                                        N00.getOperand(0)),
7576                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7577                                        N00.getOperand(1)), N1);
7578     }
7579
7580     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7581     // Note: Commutes FADD operands.
7582     if (N1.getOpcode() == ISD::FP_EXTEND) {
7583       SDValue N10 = N1.getOperand(0);
7584       if (N10.getOpcode() == ISD::FMUL)
7585         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7586                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7587                                        N10.getOperand(0)),
7588                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7589                                        N10.getOperand(1)), N0);
7590     }
7591   }
7592
7593   // More folding opportunities when target permits.
7594   if ((AllowFusion || HasFMAD)  && Aggressive) {
7595     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7596     if (N0.getOpcode() == PreferredFusedOpcode &&
7597         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7598       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7599                          N0.getOperand(0), N0.getOperand(1),
7600                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7601                                      N0.getOperand(2).getOperand(0),
7602                                      N0.getOperand(2).getOperand(1),
7603                                      N1));
7604     }
7605
7606     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7607     if (N1->getOpcode() == PreferredFusedOpcode &&
7608         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7609       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7610                          N1.getOperand(0), N1.getOperand(1),
7611                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7612                                      N1.getOperand(2).getOperand(0),
7613                                      N1.getOperand(2).getOperand(1),
7614                                      N0));
7615     }
7616
7617     if (AllowFusion && LookThroughFPExt) {
7618       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7619       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7620       auto FoldFAddFMAFPExtFMul = [&] (
7621           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7622         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7623                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7624                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7625                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7626                                        Z));
7627       };
7628       if (N0.getOpcode() == PreferredFusedOpcode) {
7629         SDValue N02 = N0.getOperand(2);
7630         if (N02.getOpcode() == ISD::FP_EXTEND) {
7631           SDValue N020 = N02.getOperand(0);
7632           if (N020.getOpcode() == ISD::FMUL)
7633             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7634                                         N020.getOperand(0), N020.getOperand(1),
7635                                         N1);
7636         }
7637       }
7638
7639       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7640       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7641       // FIXME: This turns two single-precision and one double-precision
7642       // operation into two double-precision operations, which might not be
7643       // interesting for all targets, especially GPUs.
7644       auto FoldFAddFPExtFMAFMul = [&] (
7645           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7646         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7647                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7648                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7649                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7650                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7651                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7652                                        Z));
7653       };
7654       if (N0.getOpcode() == ISD::FP_EXTEND) {
7655         SDValue N00 = N0.getOperand(0);
7656         if (N00.getOpcode() == PreferredFusedOpcode) {
7657           SDValue N002 = N00.getOperand(2);
7658           if (N002.getOpcode() == ISD::FMUL)
7659             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7660                                         N002.getOperand(0), N002.getOperand(1),
7661                                         N1);
7662         }
7663       }
7664
7665       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7666       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7667       if (N1.getOpcode() == PreferredFusedOpcode) {
7668         SDValue N12 = N1.getOperand(2);
7669         if (N12.getOpcode() == ISD::FP_EXTEND) {
7670           SDValue N120 = N12.getOperand(0);
7671           if (N120.getOpcode() == ISD::FMUL)
7672             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7673                                         N120.getOperand(0), N120.getOperand(1),
7674                                         N0);
7675         }
7676       }
7677
7678       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7679       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7680       // FIXME: This turns two single-precision and one double-precision
7681       // operation into two double-precision operations, which might not be
7682       // interesting for all targets, especially GPUs.
7683       if (N1.getOpcode() == ISD::FP_EXTEND) {
7684         SDValue N10 = N1.getOperand(0);
7685         if (N10.getOpcode() == PreferredFusedOpcode) {
7686           SDValue N102 = N10.getOperand(2);
7687           if (N102.getOpcode() == ISD::FMUL)
7688             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7689                                         N102.getOperand(0), N102.getOperand(1),
7690                                         N0);
7691         }
7692       }
7693     }
7694   }
7695
7696   return SDValue();
7697 }
7698
7699 /// Try to perform FMA combining on a given FSUB node.
7700 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7701   SDValue N0 = N->getOperand(0);
7702   SDValue N1 = N->getOperand(1);
7703   EVT VT = N->getValueType(0);
7704   SDLoc SL(N);
7705
7706   const TargetOptions &Options = DAG.getTarget().Options;
7707   bool AllowFusion =
7708       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7709
7710   // Floating-point multiply-add with intermediate rounding.
7711   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7712
7713   // Floating-point multiply-add without intermediate rounding.
7714   bool HasFMA =
7715       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7716       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7717
7718   // No valid opcode, do not combine.
7719   if (!HasFMAD && !HasFMA)
7720     return SDValue();
7721
7722   // Always prefer FMAD to FMA for precision.
7723   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7724   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7725   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7726
7727   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7728   if (N0.getOpcode() == ISD::FMUL &&
7729       (Aggressive || N0->hasOneUse())) {
7730     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7731                        N0.getOperand(0), N0.getOperand(1),
7732                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7733   }
7734
7735   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7736   // Note: Commutes FSUB operands.
7737   if (N1.getOpcode() == ISD::FMUL &&
7738       (Aggressive || N1->hasOneUse()))
7739     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7740                        DAG.getNode(ISD::FNEG, SL, VT,
7741                                    N1.getOperand(0)),
7742                        N1.getOperand(1), N0);
7743
7744   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7745   if (N0.getOpcode() == ISD::FNEG &&
7746       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7747       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7748     SDValue N00 = N0.getOperand(0).getOperand(0);
7749     SDValue N01 = N0.getOperand(0).getOperand(1);
7750     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7751                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7752                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7753   }
7754
7755   // Look through FP_EXTEND nodes to do more combining.
7756   if (AllowFusion && LookThroughFPExt) {
7757     // fold (fsub (fpext (fmul x, y)), z)
7758     //   -> (fma (fpext x), (fpext y), (fneg z))
7759     if (N0.getOpcode() == ISD::FP_EXTEND) {
7760       SDValue N00 = N0.getOperand(0);
7761       if (N00.getOpcode() == ISD::FMUL)
7762         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7763                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7764                                        N00.getOperand(0)),
7765                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7766                                        N00.getOperand(1)),
7767                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7768     }
7769
7770     // fold (fsub x, (fpext (fmul y, z)))
7771     //   -> (fma (fneg (fpext y)), (fpext z), x)
7772     // Note: Commutes FSUB operands.
7773     if (N1.getOpcode() == ISD::FP_EXTEND) {
7774       SDValue N10 = N1.getOperand(0);
7775       if (N10.getOpcode() == ISD::FMUL)
7776         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7777                            DAG.getNode(ISD::FNEG, SL, VT,
7778                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779                                                    N10.getOperand(0))),
7780                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7781                                        N10.getOperand(1)),
7782                            N0);
7783     }
7784
7785     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7786     //   -> (fneg (fma (fpext x), (fpext y), z))
7787     // Note: This could be removed with appropriate canonicalization of the
7788     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7789     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7790     // from implementing the canonicalization in visitFSUB.
7791     if (N0.getOpcode() == ISD::FP_EXTEND) {
7792       SDValue N00 = N0.getOperand(0);
7793       if (N00.getOpcode() == ISD::FNEG) {
7794         SDValue N000 = N00.getOperand(0);
7795         if (N000.getOpcode() == ISD::FMUL) {
7796           return DAG.getNode(ISD::FNEG, SL, VT,
7797                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7798                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7799                                                      N000.getOperand(0)),
7800                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7801                                                      N000.getOperand(1)),
7802                                          N1));
7803         }
7804       }
7805     }
7806
7807     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7808     //   -> (fneg (fma (fpext x)), (fpext y), z)
7809     // Note: This could be removed with appropriate canonicalization of the
7810     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7811     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7812     // from implementing the canonicalization in visitFSUB.
7813     if (N0.getOpcode() == ISD::FNEG) {
7814       SDValue N00 = N0.getOperand(0);
7815       if (N00.getOpcode() == ISD::FP_EXTEND) {
7816         SDValue N000 = N00.getOperand(0);
7817         if (N000.getOpcode() == ISD::FMUL) {
7818           return DAG.getNode(ISD::FNEG, SL, VT,
7819                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7820                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7821                                                      N000.getOperand(0)),
7822                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7823                                                      N000.getOperand(1)),
7824                                          N1));
7825         }
7826       }
7827     }
7828
7829   }
7830
7831   // More folding opportunities when target permits.
7832   if ((AllowFusion || HasFMAD) && Aggressive) {
7833     // fold (fsub (fma x, y, (fmul u, v)), z)
7834     //   -> (fma x, y (fma u, v, (fneg z)))
7835     if (N0.getOpcode() == PreferredFusedOpcode &&
7836         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7837       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7838                          N0.getOperand(0), N0.getOperand(1),
7839                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7840                                      N0.getOperand(2).getOperand(0),
7841                                      N0.getOperand(2).getOperand(1),
7842                                      DAG.getNode(ISD::FNEG, SL, VT,
7843                                                  N1)));
7844     }
7845
7846     // fold (fsub x, (fma y, z, (fmul u, v)))
7847     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7848     if (N1.getOpcode() == PreferredFusedOpcode &&
7849         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7850       SDValue N20 = N1.getOperand(2).getOperand(0);
7851       SDValue N21 = N1.getOperand(2).getOperand(1);
7852       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7853                          DAG.getNode(ISD::FNEG, SL, VT,
7854                                      N1.getOperand(0)),
7855                          N1.getOperand(1),
7856                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7857                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7858
7859                                      N21, N0));
7860     }
7861
7862     if (AllowFusion && LookThroughFPExt) {
7863       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7864       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7865       if (N0.getOpcode() == PreferredFusedOpcode) {
7866         SDValue N02 = N0.getOperand(2);
7867         if (N02.getOpcode() == ISD::FP_EXTEND) {
7868           SDValue N020 = N02.getOperand(0);
7869           if (N020.getOpcode() == ISD::FMUL)
7870             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7871                                N0.getOperand(0), N0.getOperand(1),
7872                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7873                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7874                                                        N020.getOperand(0)),
7875                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7876                                                        N020.getOperand(1)),
7877                                            DAG.getNode(ISD::FNEG, SL, VT,
7878                                                        N1)));
7879         }
7880       }
7881
7882       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7883       //   -> (fma (fpext x), (fpext y),
7884       //           (fma (fpext u), (fpext v), (fneg z)))
7885       // FIXME: This turns two single-precision and one double-precision
7886       // operation into two double-precision operations, which might not be
7887       // interesting for all targets, especially GPUs.
7888       if (N0.getOpcode() == ISD::FP_EXTEND) {
7889         SDValue N00 = N0.getOperand(0);
7890         if (N00.getOpcode() == PreferredFusedOpcode) {
7891           SDValue N002 = N00.getOperand(2);
7892           if (N002.getOpcode() == ISD::FMUL)
7893             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7894                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7895                                            N00.getOperand(0)),
7896                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7897                                            N00.getOperand(1)),
7898                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7899                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7900                                                        N002.getOperand(0)),
7901                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7902                                                        N002.getOperand(1)),
7903                                            DAG.getNode(ISD::FNEG, SL, VT,
7904                                                        N1)));
7905         }
7906       }
7907
7908       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7909       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7910       if (N1.getOpcode() == PreferredFusedOpcode &&
7911         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7912         SDValue N120 = N1.getOperand(2).getOperand(0);
7913         if (N120.getOpcode() == ISD::FMUL) {
7914           SDValue N1200 = N120.getOperand(0);
7915           SDValue N1201 = N120.getOperand(1);
7916           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7917                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7918                              N1.getOperand(1),
7919                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7920                                          DAG.getNode(ISD::FNEG, SL, VT,
7921                                              DAG.getNode(ISD::FP_EXTEND, SL,
7922                                                          VT, N1200)),
7923                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7924                                                      N1201),
7925                                          N0));
7926         }
7927       }
7928
7929       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7930       //   -> (fma (fneg (fpext y)), (fpext z),
7931       //           (fma (fneg (fpext u)), (fpext v), x))
7932       // FIXME: This turns two single-precision and one double-precision
7933       // operation into two double-precision operations, which might not be
7934       // interesting for all targets, especially GPUs.
7935       if (N1.getOpcode() == ISD::FP_EXTEND &&
7936         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7937         SDValue N100 = N1.getOperand(0).getOperand(0);
7938         SDValue N101 = N1.getOperand(0).getOperand(1);
7939         SDValue N102 = N1.getOperand(0).getOperand(2);
7940         if (N102.getOpcode() == ISD::FMUL) {
7941           SDValue N1020 = N102.getOperand(0);
7942           SDValue N1021 = N102.getOperand(1);
7943           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7944                              DAG.getNode(ISD::FNEG, SL, VT,
7945                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7946                                                      N100)),
7947                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7948                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7949                                          DAG.getNode(ISD::FNEG, SL, VT,
7950                                              DAG.getNode(ISD::FP_EXTEND, SL,
7951                                                          VT, N1020)),
7952                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7953                                                      N1021),
7954                                          N0));
7955         }
7956       }
7957     }
7958   }
7959
7960   return SDValue();
7961 }
7962
7963 /// Try to perform FMA combining on a given FMUL node.
7964 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7965   SDValue N0 = N->getOperand(0);
7966   SDValue N1 = N->getOperand(1);
7967   EVT VT = N->getValueType(0);
7968   SDLoc SL(N);
7969
7970   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7971
7972   const TargetOptions &Options = DAG.getTarget().Options;
7973   bool AllowFusion =
7974       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7975
7976   // Floating-point multiply-add with intermediate rounding.
7977   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7978
7979   // Floating-point multiply-add without intermediate rounding.
7980   bool HasFMA =
7981       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7982       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7983
7984   // No valid opcode, do not combine.
7985   if (!HasFMAD && !HasFMA)
7986     return SDValue();
7987
7988   // Always prefer FMAD to FMA for precision.
7989   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7990   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7991
7992   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7993   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7994   auto FuseFADD = [&](SDValue X, SDValue Y) {
7995     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7996       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7997       if (XC1 && XC1->isExactlyValue(+1.0))
7998         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7999       if (XC1 && XC1->isExactlyValue(-1.0))
8000         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8001                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8002     }
8003     return SDValue();
8004   };
8005
8006   if (SDValue FMA = FuseFADD(N0, N1))
8007     return FMA;
8008   if (SDValue FMA = FuseFADD(N1, N0))
8009     return FMA;
8010
8011   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8012   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8013   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8014   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8015   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8016     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8017       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8018       if (XC0 && XC0->isExactlyValue(+1.0))
8019         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8020                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8021                            Y);
8022       if (XC0 && XC0->isExactlyValue(-1.0))
8023         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8024                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8025                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8026
8027       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8028       if (XC1 && XC1->isExactlyValue(+1.0))
8029         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8030                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8031       if (XC1 && XC1->isExactlyValue(-1.0))
8032         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8033     }
8034     return SDValue();
8035   };
8036
8037   if (SDValue FMA = FuseFSUB(N0, N1))
8038     return FMA;
8039   if (SDValue FMA = FuseFSUB(N1, N0))
8040     return FMA;
8041
8042   return SDValue();
8043 }
8044
8045 SDValue DAGCombiner::visitFADD(SDNode *N) {
8046   SDValue N0 = N->getOperand(0);
8047   SDValue N1 = N->getOperand(1);
8048   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8049   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8050   EVT VT = N->getValueType(0);
8051   SDLoc DL(N);
8052   const TargetOptions &Options = DAG.getTarget().Options;
8053   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8054
8055   // fold vector ops
8056   if (VT.isVector())
8057     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8058       return FoldedVOp;
8059
8060   // fold (fadd c1, c2) -> c1 + c2
8061   if (N0CFP && N1CFP)
8062     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8063
8064   // canonicalize constant to RHS
8065   if (N0CFP && !N1CFP)
8066     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8067
8068   // fold (fadd A, (fneg B)) -> (fsub A, B)
8069   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8070       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8071     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8072                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8073
8074   // fold (fadd (fneg A), B) -> (fsub B, A)
8075   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8076       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8077     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8078                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8079
8080   // If 'unsafe math' is enabled, fold lots of things.
8081   if (Options.UnsafeFPMath) {
8082     // No FP constant should be created after legalization as Instruction
8083     // Selection pass has a hard time dealing with FP constants.
8084     bool AllowNewConst = (Level < AfterLegalizeDAG);
8085
8086     // fold (fadd A, 0) -> A
8087     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8088       if (N1C->isZero())
8089         return N0;
8090
8091     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8092     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8093         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8094       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8095                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8096                                      Flags),
8097                          Flags);
8098
8099     // If allowed, fold (fadd (fneg x), x) -> 0.0
8100     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8101       return DAG.getConstantFP(0.0, DL, VT);
8102
8103     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8104     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8105       return DAG.getConstantFP(0.0, DL, VT);
8106
8107     // We can fold chains of FADD's of the same value into multiplications.
8108     // This transform is not safe in general because we are reducing the number
8109     // of rounding steps.
8110     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8111       if (N0.getOpcode() == ISD::FMUL) {
8112         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8113         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8114
8115         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8116         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8117           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8118                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8119           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8120         }
8121
8122         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8123         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8124             N1.getOperand(0) == N1.getOperand(1) &&
8125             N0.getOperand(0) == N1.getOperand(0)) {
8126           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8127                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8128           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8129         }
8130       }
8131
8132       if (N1.getOpcode() == ISD::FMUL) {
8133         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8134         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8135
8136         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8137         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8138           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8139                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8140           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8141         }
8142
8143         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8144         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8145             N0.getOperand(0) == N0.getOperand(1) &&
8146             N1.getOperand(0) == N0.getOperand(0)) {
8147           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8148                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8149           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8150         }
8151       }
8152
8153       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8154         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8155         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8156         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8157             (N0.getOperand(0) == N1)) {
8158           return DAG.getNode(ISD::FMUL, DL, VT,
8159                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8160         }
8161       }
8162
8163       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8164         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8165         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8166         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8167             N1.getOperand(0) == N0) {
8168           return DAG.getNode(ISD::FMUL, DL, VT,
8169                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8170         }
8171       }
8172
8173       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8174       if (AllowNewConst &&
8175           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8176           N0.getOperand(0) == N0.getOperand(1) &&
8177           N1.getOperand(0) == N1.getOperand(1) &&
8178           N0.getOperand(0) == N1.getOperand(0)) {
8179         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8180                            DAG.getConstantFP(4.0, DL, VT), Flags);
8181       }
8182     }
8183   } // enable-unsafe-fp-math
8184
8185   // FADD -> FMA combines:
8186   if (SDValue Fused = visitFADDForFMACombine(N)) {
8187     AddToWorklist(Fused.getNode());
8188     return Fused;
8189   }
8190
8191   return SDValue();
8192 }
8193
8194 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8195   SDValue N0 = N->getOperand(0);
8196   SDValue N1 = N->getOperand(1);
8197   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8198   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8199   EVT VT = N->getValueType(0);
8200   SDLoc dl(N);
8201   const TargetOptions &Options = DAG.getTarget().Options;
8202   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8203
8204   // fold vector ops
8205   if (VT.isVector())
8206     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8207       return FoldedVOp;
8208
8209   // fold (fsub c1, c2) -> c1-c2
8210   if (N0CFP && N1CFP)
8211     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8212
8213   // fold (fsub A, (fneg B)) -> (fadd A, B)
8214   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8215     return DAG.getNode(ISD::FADD, dl, VT, N0,
8216                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8217
8218   // If 'unsafe math' is enabled, fold lots of things.
8219   if (Options.UnsafeFPMath) {
8220     // (fsub A, 0) -> A
8221     if (N1CFP && N1CFP->isZero())
8222       return N0;
8223
8224     // (fsub 0, B) -> -B
8225     if (N0CFP && N0CFP->isZero()) {
8226       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8227         return GetNegatedExpression(N1, DAG, LegalOperations);
8228       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8229         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8230     }
8231
8232     // (fsub x, x) -> 0.0
8233     if (N0 == N1)
8234       return DAG.getConstantFP(0.0f, dl, VT);
8235
8236     // (fsub x, (fadd x, y)) -> (fneg y)
8237     // (fsub x, (fadd y, x)) -> (fneg y)
8238     if (N1.getOpcode() == ISD::FADD) {
8239       SDValue N10 = N1->getOperand(0);
8240       SDValue N11 = N1->getOperand(1);
8241
8242       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8243         return GetNegatedExpression(N11, DAG, LegalOperations);
8244
8245       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8246         return GetNegatedExpression(N10, DAG, LegalOperations);
8247     }
8248   }
8249
8250   // FSUB -> FMA combines:
8251   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8252     AddToWorklist(Fused.getNode());
8253     return Fused;
8254   }
8255
8256   return SDValue();
8257 }
8258
8259 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8260   SDValue N0 = N->getOperand(0);
8261   SDValue N1 = N->getOperand(1);
8262   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8263   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8264   EVT VT = N->getValueType(0);
8265   SDLoc DL(N);
8266   const TargetOptions &Options = DAG.getTarget().Options;
8267   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8268
8269   // fold vector ops
8270   if (VT.isVector()) {
8271     // This just handles C1 * C2 for vectors. Other vector folds are below.
8272     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8273       return FoldedVOp;
8274   }
8275
8276   // fold (fmul c1, c2) -> c1*c2
8277   if (N0CFP && N1CFP)
8278     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8279
8280   // canonicalize constant to RHS
8281   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8282      !isConstantFPBuildVectorOrConstantFP(N1))
8283     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8284
8285   // fold (fmul A, 1.0) -> A
8286   if (N1CFP && N1CFP->isExactlyValue(1.0))
8287     return N0;
8288
8289   if (Options.UnsafeFPMath) {
8290     // fold (fmul A, 0) -> 0
8291     if (N1CFP && N1CFP->isZero())
8292       return N1;
8293
8294     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8295     if (N0.getOpcode() == ISD::FMUL) {
8296       // Fold scalars or any vector constants (not just splats).
8297       // This fold is done in general by InstCombine, but extra fmul insts
8298       // may have been generated during lowering.
8299       SDValue N00 = N0.getOperand(0);
8300       SDValue N01 = N0.getOperand(1);
8301       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8302       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8303       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8304
8305       // Check 1: Make sure that the first operand of the inner multiply is NOT
8306       // a constant. Otherwise, we may induce infinite looping.
8307       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8308         // Check 2: Make sure that the second operand of the inner multiply and
8309         // the second operand of the outer multiply are constants.
8310         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8311             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8312           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8313           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8314         }
8315       }
8316     }
8317
8318     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8319     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8320     // during an early run of DAGCombiner can prevent folding with fmuls
8321     // inserted during lowering.
8322     if (N0.getOpcode() == ISD::FADD &&
8323         (N0.getOperand(0) == N0.getOperand(1)) &&
8324         N0.hasOneUse()) {
8325       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8326       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8327       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8328     }
8329   }
8330
8331   // fold (fmul X, 2.0) -> (fadd X, X)
8332   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8333     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8334
8335   // fold (fmul X, -1.0) -> (fneg X)
8336   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8337     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8338       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8339
8340   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8341   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8342     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8343       // Both can be negated for free, check to see if at least one is cheaper
8344       // negated.
8345       if (LHSNeg == 2 || RHSNeg == 2)
8346         return DAG.getNode(ISD::FMUL, DL, VT,
8347                            GetNegatedExpression(N0, DAG, LegalOperations),
8348                            GetNegatedExpression(N1, DAG, LegalOperations),
8349                            Flags);
8350     }
8351   }
8352
8353   // FMUL -> FMA combines:
8354   if (SDValue Fused = visitFMULForFMACombine(N)) {
8355     AddToWorklist(Fused.getNode());
8356     return Fused;
8357   }
8358
8359   return SDValue();
8360 }
8361
8362 SDValue DAGCombiner::visitFMA(SDNode *N) {
8363   SDValue N0 = N->getOperand(0);
8364   SDValue N1 = N->getOperand(1);
8365   SDValue N2 = N->getOperand(2);
8366   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8367   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8368   EVT VT = N->getValueType(0);
8369   SDLoc dl(N);
8370   const TargetOptions &Options = DAG.getTarget().Options;
8371
8372   // Constant fold FMA.
8373   if (isa<ConstantFPSDNode>(N0) &&
8374       isa<ConstantFPSDNode>(N1) &&
8375       isa<ConstantFPSDNode>(N2)) {
8376     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8377   }
8378
8379   if (Options.UnsafeFPMath) {
8380     if (N0CFP && N0CFP->isZero())
8381       return N2;
8382     if (N1CFP && N1CFP->isZero())
8383       return N2;
8384   }
8385   // TODO: The FMA node should have flags that propagate to these nodes.
8386   if (N0CFP && N0CFP->isExactlyValue(1.0))
8387     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8388   if (N1CFP && N1CFP->isExactlyValue(1.0))
8389     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8390
8391   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8392   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8393      !isConstantFPBuildVectorOrConstantFP(N1))
8394     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8395
8396   // TODO: FMA nodes should have flags that propagate to the created nodes.
8397   // For now, create a Flags object for use with all unsafe math transforms.
8398   SDNodeFlags Flags;
8399   Flags.setUnsafeAlgebra(true);
8400
8401   if (Options.UnsafeFPMath) {
8402     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8403     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8404         isConstantFPBuildVectorOrConstantFP(N1) &&
8405         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8406       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8407                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8408                                      &Flags), &Flags);
8409     }
8410
8411     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8412     if (N0.getOpcode() == ISD::FMUL &&
8413         isConstantFPBuildVectorOrConstantFP(N1) &&
8414         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8415       return DAG.getNode(ISD::FMA, dl, VT,
8416                          N0.getOperand(0),
8417                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8418                                      &Flags),
8419                          N2);
8420     }
8421   }
8422
8423   // (fma x, 1, y) -> (fadd x, y)
8424   // (fma x, -1, y) -> (fadd (fneg x), y)
8425   if (N1CFP) {
8426     if (N1CFP->isExactlyValue(1.0))
8427       // TODO: The FMA node should have flags that propagate to this node.
8428       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8429
8430     if (N1CFP->isExactlyValue(-1.0) &&
8431         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8432       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8433       AddToWorklist(RHSNeg.getNode());
8434       // TODO: The FMA node should have flags that propagate to this node.
8435       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8436     }
8437   }
8438
8439   if (Options.UnsafeFPMath) {
8440     // (fma x, c, x) -> (fmul x, (c+1))
8441     if (N1CFP && N0 == N2) {
8442     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8443                          DAG.getNode(ISD::FADD, dl, VT,
8444                                      N1, DAG.getConstantFP(1.0, dl, VT),
8445                                      &Flags), &Flags);
8446     }
8447
8448     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8449     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8450       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8451                          DAG.getNode(ISD::FADD, dl, VT,
8452                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8453                                      &Flags), &Flags);
8454     }
8455   }
8456
8457   return SDValue();
8458 }
8459
8460 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8461 // reciprocal.
8462 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8463 // Notice that this is not always beneficial. One reason is different target
8464 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8465 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8466 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8467 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8468   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8469   const SDNodeFlags *Flags = N->getFlags();
8470   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8471     return SDValue();
8472
8473   // Skip if current node is a reciprocal.
8474   SDValue N0 = N->getOperand(0);
8475   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8476   if (N0CFP && N0CFP->isExactlyValue(1.0))
8477     return SDValue();
8478
8479   // Exit early if the target does not want this transform or if there can't
8480   // possibly be enough uses of the divisor to make the transform worthwhile.
8481   SDValue N1 = N->getOperand(1);
8482   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8483   if (!MinUses || N1->use_size() < MinUses)
8484     return SDValue();
8485
8486   // Find all FDIV users of the same divisor.
8487   // Use a set because duplicates may be present in the user list.
8488   SetVector<SDNode *> Users;
8489   for (auto *U : N1->uses()) {
8490     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8491       // This division is eligible for optimization only if global unsafe math
8492       // is enabled or if this division allows reciprocal formation.
8493       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8494         Users.insert(U);
8495     }
8496   }
8497
8498   // Now that we have the actual number of divisor uses, make sure it meets
8499   // the minimum threshold specified by the target.
8500   if (Users.size() < MinUses)
8501     return SDValue();
8502
8503   EVT VT = N->getValueType(0);
8504   SDLoc DL(N);
8505   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8506   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8507
8508   // Dividend / Divisor -> Dividend * Reciprocal
8509   for (auto *U : Users) {
8510     SDValue Dividend = U->getOperand(0);
8511     if (Dividend != FPOne) {
8512       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8513                                     Reciprocal, Flags);
8514       CombineTo(U, NewNode);
8515     } else if (U != Reciprocal.getNode()) {
8516       // In the absence of fast-math-flags, this user node is always the
8517       // same node as Reciprocal, but with FMF they may be different nodes.
8518       CombineTo(U, Reciprocal);
8519     }
8520   }
8521   return SDValue(N, 0);  // N was replaced.
8522 }
8523
8524 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8525   SDValue N0 = N->getOperand(0);
8526   SDValue N1 = N->getOperand(1);
8527   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8528   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8529   EVT VT = N->getValueType(0);
8530   SDLoc DL(N);
8531   const TargetOptions &Options = DAG.getTarget().Options;
8532   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8533
8534   // fold vector ops
8535   if (VT.isVector())
8536     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8537       return FoldedVOp;
8538
8539   // fold (fdiv c1, c2) -> c1/c2
8540   if (N0CFP && N1CFP)
8541     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8542
8543   if (Options.UnsafeFPMath) {
8544     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8545     if (N1CFP) {
8546       // Compute the reciprocal 1.0 / c2.
8547       APFloat N1APF = N1CFP->getValueAPF();
8548       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8549       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8550       // Only do the transform if the reciprocal is a legal fp immediate that
8551       // isn't too nasty (eg NaN, denormal, ...).
8552       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8553           (!LegalOperations ||
8554            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8555            // backend)... we should handle this gracefully after Legalize.
8556            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8557            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8558            TLI.isFPImmLegal(Recip, VT)))
8559         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8560                            DAG.getConstantFP(Recip, DL, VT), Flags);
8561     }
8562
8563     // If this FDIV is part of a reciprocal square root, it may be folded
8564     // into a target-specific square root estimate instruction.
8565     if (N1.getOpcode() == ISD::FSQRT) {
8566       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8567         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8568       }
8569     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8570                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8571       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8572                                           Flags)) {
8573         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8574         AddToWorklist(RV.getNode());
8575         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8576       }
8577     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8578                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8579       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8580                                           Flags)) {
8581         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8582         AddToWorklist(RV.getNode());
8583         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8584       }
8585     } else if (N1.getOpcode() == ISD::FMUL) {
8586       // Look through an FMUL. Even though this won't remove the FDIV directly,
8587       // it's still worthwhile to get rid of the FSQRT if possible.
8588       SDValue SqrtOp;
8589       SDValue OtherOp;
8590       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8591         SqrtOp = N1.getOperand(0);
8592         OtherOp = N1.getOperand(1);
8593       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8594         SqrtOp = N1.getOperand(1);
8595         OtherOp = N1.getOperand(0);
8596       }
8597       if (SqrtOp.getNode()) {
8598         // We found a FSQRT, so try to make this fold:
8599         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8600         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8601           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8602           AddToWorklist(RV.getNode());
8603           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8604         }
8605       }
8606     }
8607
8608     // Fold into a reciprocal estimate and multiply instead of a real divide.
8609     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8610       AddToWorklist(RV.getNode());
8611       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8612     }
8613   }
8614
8615   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8616   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8617     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8618       // Both can be negated for free, check to see if at least one is cheaper
8619       // negated.
8620       if (LHSNeg == 2 || RHSNeg == 2)
8621         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8622                            GetNegatedExpression(N0, DAG, LegalOperations),
8623                            GetNegatedExpression(N1, DAG, LegalOperations),
8624                            Flags);
8625     }
8626   }
8627
8628   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8629     return CombineRepeatedDivisors;
8630
8631   return SDValue();
8632 }
8633
8634 SDValue DAGCombiner::visitFREM(SDNode *N) {
8635   SDValue N0 = N->getOperand(0);
8636   SDValue N1 = N->getOperand(1);
8637   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8638   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8639   EVT VT = N->getValueType(0);
8640
8641   // fold (frem c1, c2) -> fmod(c1,c2)
8642   if (N0CFP && N1CFP)
8643     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8644                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8645
8646   return SDValue();
8647 }
8648
8649 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8650   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8651     return SDValue();
8652
8653   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8654   // For now, create a Flags object for use with all unsafe math transforms.
8655   SDNodeFlags Flags;
8656   Flags.setUnsafeAlgebra(true);
8657
8658   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8659   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8660   if (!RV)
8661     return SDValue();
8662
8663   EVT VT = RV.getValueType();
8664   SDLoc DL(N);
8665   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8666   AddToWorklist(RV.getNode());
8667
8668   // Unfortunately, RV is now NaN if the input was exactly 0.
8669   // Select out this case and force the answer to 0.
8670   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8671   EVT CCVT = getSetCCResultType(VT);
8672   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8673   AddToWorklist(ZeroCmp.getNode());
8674   AddToWorklist(RV.getNode());
8675
8676   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8677                      ZeroCmp, Zero, RV);
8678 }
8679
8680 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8681   SDValue N0 = N->getOperand(0);
8682   SDValue N1 = N->getOperand(1);
8683   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8684   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8685   EVT VT = N->getValueType(0);
8686
8687   if (N0CFP && N1CFP)  // Constant fold
8688     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8689
8690   if (N1CFP) {
8691     const APFloat& V = N1CFP->getValueAPF();
8692     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8693     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8694     if (!V.isNegative()) {
8695       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8696         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8697     } else {
8698       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8699         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8700                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8701     }
8702   }
8703
8704   // copysign(fabs(x), y) -> copysign(x, y)
8705   // copysign(fneg(x), y) -> copysign(x, y)
8706   // copysign(copysign(x,z), y) -> copysign(x, y)
8707   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8708       N0.getOpcode() == ISD::FCOPYSIGN)
8709     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8710                        N0.getOperand(0), N1);
8711
8712   // copysign(x, abs(y)) -> abs(x)
8713   if (N1.getOpcode() == ISD::FABS)
8714     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8715
8716   // copysign(x, copysign(y,z)) -> copysign(x, z)
8717   if (N1.getOpcode() == ISD::FCOPYSIGN)
8718     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8719                        N0, N1.getOperand(1));
8720
8721   // copysign(x, fp_extend(y)) -> copysign(x, y)
8722   // copysign(x, fp_round(y)) -> copysign(x, y)
8723   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8724     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8725                        N0, N1.getOperand(0));
8726
8727   return SDValue();
8728 }
8729
8730 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8731   SDValue N0 = N->getOperand(0);
8732   EVT VT = N->getValueType(0);
8733   EVT OpVT = N0.getValueType();
8734
8735   // fold (sint_to_fp c1) -> c1fp
8736   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8737       // ...but only if the target supports immediate floating-point values
8738       (!LegalOperations ||
8739        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8740     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8741
8742   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8743   // but UINT_TO_FP is legal on this target, try to convert.
8744   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8745       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8746     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8747     if (DAG.SignBitIsZero(N0))
8748       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8749   }
8750
8751   // The next optimizations are desirable only if SELECT_CC can be lowered.
8752   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8753     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8754     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8755         !VT.isVector() &&
8756         (!LegalOperations ||
8757          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8758       SDLoc DL(N);
8759       SDValue Ops[] =
8760         { N0.getOperand(0), N0.getOperand(1),
8761           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8762           N0.getOperand(2) };
8763       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8764     }
8765
8766     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8767     //      (select_cc x, y, 1.0, 0.0,, cc)
8768     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8769         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8770         (!LegalOperations ||
8771          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8772       SDLoc DL(N);
8773       SDValue Ops[] =
8774         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8775           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8776           N0.getOperand(0).getOperand(2) };
8777       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8778     }
8779   }
8780
8781   return SDValue();
8782 }
8783
8784 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8785   SDValue N0 = N->getOperand(0);
8786   EVT VT = N->getValueType(0);
8787   EVT OpVT = N0.getValueType();
8788
8789   // fold (uint_to_fp c1) -> c1fp
8790   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8791       // ...but only if the target supports immediate floating-point values
8792       (!LegalOperations ||
8793        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8794     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8795
8796   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8797   // but SINT_TO_FP is legal on this target, try to convert.
8798   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8799       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8800     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8801     if (DAG.SignBitIsZero(N0))
8802       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8803   }
8804
8805   // The next optimizations are desirable only if SELECT_CC can be lowered.
8806   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8807     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8808
8809     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8810         (!LegalOperations ||
8811          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8812       SDLoc DL(N);
8813       SDValue Ops[] =
8814         { N0.getOperand(0), N0.getOperand(1),
8815           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8816           N0.getOperand(2) };
8817       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8818     }
8819   }
8820
8821   return SDValue();
8822 }
8823
8824 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8825 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8826   SDValue N0 = N->getOperand(0);
8827   EVT VT = N->getValueType(0);
8828
8829   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8830     return SDValue();
8831
8832   SDValue Src = N0.getOperand(0);
8833   EVT SrcVT = Src.getValueType();
8834   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8835   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8836
8837   // We can safely assume the conversion won't overflow the output range,
8838   // because (for example) (uint8_t)18293.f is undefined behavior.
8839
8840   // Since we can assume the conversion won't overflow, our decision as to
8841   // whether the input will fit in the float should depend on the minimum
8842   // of the input range and output range.
8843
8844   // This means this is also safe for a signed input and unsigned output, since
8845   // a negative input would lead to undefined behavior.
8846   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8847   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8848   unsigned ActualSize = std::min(InputSize, OutputSize);
8849   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8850
8851   // We can only fold away the float conversion if the input range can be
8852   // represented exactly in the float range.
8853   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8854     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8855       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8856                                                        : ISD::ZERO_EXTEND;
8857       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8858     }
8859     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8860       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8861     if (SrcVT == VT)
8862       return Src;
8863     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8864   }
8865   return SDValue();
8866 }
8867
8868 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8869   SDValue N0 = N->getOperand(0);
8870   EVT VT = N->getValueType(0);
8871
8872   // fold (fp_to_sint c1fp) -> c1
8873   if (isConstantFPBuildVectorOrConstantFP(N0))
8874     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8875
8876   return FoldIntToFPToInt(N, DAG);
8877 }
8878
8879 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8880   SDValue N0 = N->getOperand(0);
8881   EVT VT = N->getValueType(0);
8882
8883   // fold (fp_to_uint c1fp) -> c1
8884   if (isConstantFPBuildVectorOrConstantFP(N0))
8885     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8886
8887   return FoldIntToFPToInt(N, DAG);
8888 }
8889
8890 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8891   SDValue N0 = N->getOperand(0);
8892   SDValue N1 = N->getOperand(1);
8893   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8894   EVT VT = N->getValueType(0);
8895
8896   // fold (fp_round c1fp) -> c1fp
8897   if (N0CFP)
8898     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8899
8900   // fold (fp_round (fp_extend x)) -> x
8901   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8902     return N0.getOperand(0);
8903
8904   // fold (fp_round (fp_round x)) -> (fp_round x)
8905   if (N0.getOpcode() == ISD::FP_ROUND) {
8906     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8907     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8908     // If the first fp_round isn't a value preserving truncation, it might
8909     // introduce a tie in the second fp_round, that wouldn't occur in the
8910     // single-step fp_round we want to fold to.
8911     // In other words, double rounding isn't the same as rounding.
8912     // Also, this is a value preserving truncation iff both fp_round's are.
8913     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8914       SDLoc DL(N);
8915       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8916                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8917     }
8918   }
8919
8920   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8921   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8922     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8923                               N0.getOperand(0), N1);
8924     AddToWorklist(Tmp.getNode());
8925     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8926                        Tmp, N0.getOperand(1));
8927   }
8928
8929   return SDValue();
8930 }
8931
8932 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8933   SDValue N0 = N->getOperand(0);
8934   EVT VT = N->getValueType(0);
8935   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8936   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8937
8938   // fold (fp_round_inreg c1fp) -> c1fp
8939   if (N0CFP && isTypeLegal(EVT)) {
8940     SDLoc DL(N);
8941     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8942     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8943   }
8944
8945   return SDValue();
8946 }
8947
8948 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8949   SDValue N0 = N->getOperand(0);
8950   EVT VT = N->getValueType(0);
8951
8952   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8953   if (N->hasOneUse() &&
8954       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8955     return SDValue();
8956
8957   // fold (fp_extend c1fp) -> c1fp
8958   if (isConstantFPBuildVectorOrConstantFP(N0))
8959     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8960
8961   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8962   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8963       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8964     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8965
8966   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8967   // value of X.
8968   if (N0.getOpcode() == ISD::FP_ROUND
8969       && N0.getNode()->getConstantOperandVal(1) == 1) {
8970     SDValue In = N0.getOperand(0);
8971     if (In.getValueType() == VT) return In;
8972     if (VT.bitsLT(In.getValueType()))
8973       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8974                          In, N0.getOperand(1));
8975     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8976   }
8977
8978   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8979   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8980        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8981     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8982     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8983                                      LN0->getChain(),
8984                                      LN0->getBasePtr(), N0.getValueType(),
8985                                      LN0->getMemOperand());
8986     CombineTo(N, ExtLoad);
8987     CombineTo(N0.getNode(),
8988               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8989                           N0.getValueType(), ExtLoad,
8990                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8991               ExtLoad.getValue(1));
8992     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8993   }
8994
8995   return SDValue();
8996 }
8997
8998 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8999   SDValue N0 = N->getOperand(0);
9000   EVT VT = N->getValueType(0);
9001
9002   // fold (fceil c1) -> fceil(c1)
9003   if (isConstantFPBuildVectorOrConstantFP(N0))
9004     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9005
9006   return SDValue();
9007 }
9008
9009 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9010   SDValue N0 = N->getOperand(0);
9011   EVT VT = N->getValueType(0);
9012
9013   // fold (ftrunc c1) -> ftrunc(c1)
9014   if (isConstantFPBuildVectorOrConstantFP(N0))
9015     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9016
9017   return SDValue();
9018 }
9019
9020 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9021   SDValue N0 = N->getOperand(0);
9022   EVT VT = N->getValueType(0);
9023
9024   // fold (ffloor c1) -> ffloor(c1)
9025   if (isConstantFPBuildVectorOrConstantFP(N0))
9026     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9027
9028   return SDValue();
9029 }
9030
9031 // FIXME: FNEG and FABS have a lot in common; refactor.
9032 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9033   SDValue N0 = N->getOperand(0);
9034   EVT VT = N->getValueType(0);
9035
9036   // Constant fold FNEG.
9037   if (isConstantFPBuildVectorOrConstantFP(N0))
9038     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9039
9040   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9041                          &DAG.getTarget().Options))
9042     return GetNegatedExpression(N0, DAG, LegalOperations);
9043
9044   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9045   // constant pool values.
9046   if (!TLI.isFNegFree(VT) &&
9047       N0.getOpcode() == ISD::BITCAST &&
9048       N0.getNode()->hasOneUse()) {
9049     SDValue Int = N0.getOperand(0);
9050     EVT IntVT = Int.getValueType();
9051     if (IntVT.isInteger() && !IntVT.isVector()) {
9052       APInt SignMask;
9053       if (N0.getValueType().isVector()) {
9054         // For a vector, get a mask such as 0x80... per scalar element
9055         // and splat it.
9056         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9057         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9058       } else {
9059         // For a scalar, just generate 0x80...
9060         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9061       }
9062       SDLoc DL0(N0);
9063       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9064                         DAG.getConstant(SignMask, DL0, IntVT));
9065       AddToWorklist(Int.getNode());
9066       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9067     }
9068   }
9069
9070   // (fneg (fmul c, x)) -> (fmul -c, x)
9071   if (N0.getOpcode() == ISD::FMUL &&
9072       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9073     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9074     if (CFP1) {
9075       APFloat CVal = CFP1->getValueAPF();
9076       CVal.changeSign();
9077       if (Level >= AfterLegalizeDAG &&
9078           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9079            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9080         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9081                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9082                                        N0.getOperand(1)),
9083                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9084     }
9085   }
9086
9087   return SDValue();
9088 }
9089
9090 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9091   SDValue N0 = N->getOperand(0);
9092   SDValue N1 = N->getOperand(1);
9093   EVT VT = N->getValueType(0);
9094   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9095   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9096
9097   if (N0CFP && N1CFP) {
9098     const APFloat &C0 = N0CFP->getValueAPF();
9099     const APFloat &C1 = N1CFP->getValueAPF();
9100     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9101   }
9102
9103   // Canonicalize to constant on RHS.
9104   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9105      !isConstantFPBuildVectorOrConstantFP(N1))
9106     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9107
9108   return SDValue();
9109 }
9110
9111 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9112   SDValue N0 = N->getOperand(0);
9113   SDValue N1 = N->getOperand(1);
9114   EVT VT = N->getValueType(0);
9115   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9116   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9117
9118   if (N0CFP && N1CFP) {
9119     const APFloat &C0 = N0CFP->getValueAPF();
9120     const APFloat &C1 = N1CFP->getValueAPF();
9121     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9122   }
9123
9124   // Canonicalize to constant on RHS.
9125   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9126      !isConstantFPBuildVectorOrConstantFP(N1))
9127     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9128
9129   return SDValue();
9130 }
9131
9132 SDValue DAGCombiner::visitFABS(SDNode *N) {
9133   SDValue N0 = N->getOperand(0);
9134   EVT VT = N->getValueType(0);
9135
9136   // fold (fabs c1) -> fabs(c1)
9137   if (isConstantFPBuildVectorOrConstantFP(N0))
9138     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9139
9140   // fold (fabs (fabs x)) -> (fabs x)
9141   if (N0.getOpcode() == ISD::FABS)
9142     return N->getOperand(0);
9143
9144   // fold (fabs (fneg x)) -> (fabs x)
9145   // fold (fabs (fcopysign x, y)) -> (fabs x)
9146   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9147     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9148
9149   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9150   // constant pool values.
9151   if (!TLI.isFAbsFree(VT) &&
9152       N0.getOpcode() == ISD::BITCAST &&
9153       N0.getNode()->hasOneUse()) {
9154     SDValue Int = N0.getOperand(0);
9155     EVT IntVT = Int.getValueType();
9156     if (IntVT.isInteger() && !IntVT.isVector()) {
9157       APInt SignMask;
9158       if (N0.getValueType().isVector()) {
9159         // For a vector, get a mask such as 0x7f... per scalar element
9160         // and splat it.
9161         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9162         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9163       } else {
9164         // For a scalar, just generate 0x7f...
9165         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9166       }
9167       SDLoc DL(N0);
9168       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9169                         DAG.getConstant(SignMask, DL, IntVT));
9170       AddToWorklist(Int.getNode());
9171       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9172     }
9173   }
9174
9175   return SDValue();
9176 }
9177
9178 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9179   SDValue Chain = N->getOperand(0);
9180   SDValue N1 = N->getOperand(1);
9181   SDValue N2 = N->getOperand(2);
9182
9183   // If N is a constant we could fold this into a fallthrough or unconditional
9184   // branch. However that doesn't happen very often in normal code, because
9185   // Instcombine/SimplifyCFG should have handled the available opportunities.
9186   // If we did this folding here, it would be necessary to update the
9187   // MachineBasicBlock CFG, which is awkward.
9188
9189   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9190   // on the target.
9191   if (N1.getOpcode() == ISD::SETCC &&
9192       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9193                                    N1.getOperand(0).getValueType())) {
9194     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9195                        Chain, N1.getOperand(2),
9196                        N1.getOperand(0), N1.getOperand(1), N2);
9197   }
9198
9199   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9200       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9201        (N1.getOperand(0).hasOneUse() &&
9202         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9203     SDNode *Trunc = nullptr;
9204     if (N1.getOpcode() == ISD::TRUNCATE) {
9205       // Look pass the truncate.
9206       Trunc = N1.getNode();
9207       N1 = N1.getOperand(0);
9208     }
9209
9210     // Match this pattern so that we can generate simpler code:
9211     //
9212     //   %a = ...
9213     //   %b = and i32 %a, 2
9214     //   %c = srl i32 %b, 1
9215     //   brcond i32 %c ...
9216     //
9217     // into
9218     //
9219     //   %a = ...
9220     //   %b = and i32 %a, 2
9221     //   %c = setcc eq %b, 0
9222     //   brcond %c ...
9223     //
9224     // This applies only when the AND constant value has one bit set and the
9225     // SRL constant is equal to the log2 of the AND constant. The back-end is
9226     // smart enough to convert the result into a TEST/JMP sequence.
9227     SDValue Op0 = N1.getOperand(0);
9228     SDValue Op1 = N1.getOperand(1);
9229
9230     if (Op0.getOpcode() == ISD::AND &&
9231         Op1.getOpcode() == ISD::Constant) {
9232       SDValue AndOp1 = Op0.getOperand(1);
9233
9234       if (AndOp1.getOpcode() == ISD::Constant) {
9235         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9236
9237         if (AndConst.isPowerOf2() &&
9238             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9239           SDLoc DL(N);
9240           SDValue SetCC =
9241             DAG.getSetCC(DL,
9242                          getSetCCResultType(Op0.getValueType()),
9243                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9244                          ISD::SETNE);
9245
9246           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9247                                           MVT::Other, Chain, SetCC, N2);
9248           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9249           // will convert it back to (X & C1) >> C2.
9250           CombineTo(N, NewBRCond, false);
9251           // Truncate is dead.
9252           if (Trunc)
9253             deleteAndRecombine(Trunc);
9254           // Replace the uses of SRL with SETCC
9255           WorklistRemover DeadNodes(*this);
9256           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9257           deleteAndRecombine(N1.getNode());
9258           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9259         }
9260       }
9261     }
9262
9263     if (Trunc)
9264       // Restore N1 if the above transformation doesn't match.
9265       N1 = N->getOperand(1);
9266   }
9267
9268   // Transform br(xor(x, y)) -> br(x != y)
9269   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9270   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9271     SDNode *TheXor = N1.getNode();
9272     SDValue Op0 = TheXor->getOperand(0);
9273     SDValue Op1 = TheXor->getOperand(1);
9274     if (Op0.getOpcode() == Op1.getOpcode()) {
9275       // Avoid missing important xor optimizations.
9276       if (SDValue Tmp = visitXOR(TheXor)) {
9277         if (Tmp.getNode() != TheXor) {
9278           DEBUG(dbgs() << "\nReplacing.8 ";
9279                 TheXor->dump(&DAG);
9280                 dbgs() << "\nWith: ";
9281                 Tmp.getNode()->dump(&DAG);
9282                 dbgs() << '\n');
9283           WorklistRemover DeadNodes(*this);
9284           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9285           deleteAndRecombine(TheXor);
9286           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9287                              MVT::Other, Chain, Tmp, N2);
9288         }
9289
9290         // visitXOR has changed XOR's operands or replaced the XOR completely,
9291         // bail out.
9292         return SDValue(N, 0);
9293       }
9294     }
9295
9296     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9297       bool Equal = false;
9298       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9299           Op0.getOpcode() == ISD::XOR) {
9300         TheXor = Op0.getNode();
9301         Equal = true;
9302       }
9303
9304       EVT SetCCVT = N1.getValueType();
9305       if (LegalTypes)
9306         SetCCVT = getSetCCResultType(SetCCVT);
9307       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9308                                    SetCCVT,
9309                                    Op0, Op1,
9310                                    Equal ? ISD::SETEQ : ISD::SETNE);
9311       // Replace the uses of XOR with SETCC
9312       WorklistRemover DeadNodes(*this);
9313       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9314       deleteAndRecombine(N1.getNode());
9315       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9316                          MVT::Other, Chain, SetCC, N2);
9317     }
9318   }
9319
9320   return SDValue();
9321 }
9322
9323 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9324 //
9325 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9326   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9327   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9328
9329   // If N is a constant we could fold this into a fallthrough or unconditional
9330   // branch. However that doesn't happen very often in normal code, because
9331   // Instcombine/SimplifyCFG should have handled the available opportunities.
9332   // If we did this folding here, it would be necessary to update the
9333   // MachineBasicBlock CFG, which is awkward.
9334
9335   // Use SimplifySetCC to simplify SETCC's.
9336   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9337                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9338                                false);
9339   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9340
9341   // fold to a simpler setcc
9342   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9343     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9344                        N->getOperand(0), Simp.getOperand(2),
9345                        Simp.getOperand(0), Simp.getOperand(1),
9346                        N->getOperand(4));
9347
9348   return SDValue();
9349 }
9350
9351 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9352 /// and that N may be folded in the load / store addressing mode.
9353 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9354                                     SelectionDAG &DAG,
9355                                     const TargetLowering &TLI) {
9356   EVT VT;
9357   unsigned AS;
9358
9359   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9360     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9361       return false;
9362     VT = LD->getMemoryVT();
9363     AS = LD->getAddressSpace();
9364   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9365     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9366       return false;
9367     VT = ST->getMemoryVT();
9368     AS = ST->getAddressSpace();
9369   } else
9370     return false;
9371
9372   TargetLowering::AddrMode AM;
9373   if (N->getOpcode() == ISD::ADD) {
9374     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9375     if (Offset)
9376       // [reg +/- imm]
9377       AM.BaseOffs = Offset->getSExtValue();
9378     else
9379       // [reg +/- reg]
9380       AM.Scale = 1;
9381   } else if (N->getOpcode() == ISD::SUB) {
9382     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9383     if (Offset)
9384       // [reg +/- imm]
9385       AM.BaseOffs = -Offset->getSExtValue();
9386     else
9387       // [reg +/- reg]
9388       AM.Scale = 1;
9389   } else
9390     return false;
9391
9392   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9393                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9394 }
9395
9396 /// Try turning a load/store into a pre-indexed load/store when the base
9397 /// pointer is an add or subtract and it has other uses besides the load/store.
9398 /// After the transformation, the new indexed load/store has effectively folded
9399 /// the add/subtract in and all of its other uses are redirected to the
9400 /// new load/store.
9401 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9402   if (Level < AfterLegalizeDAG)
9403     return false;
9404
9405   bool isLoad = true;
9406   SDValue Ptr;
9407   EVT VT;
9408   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9409     if (LD->isIndexed())
9410       return false;
9411     VT = LD->getMemoryVT();
9412     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9413         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9414       return false;
9415     Ptr = LD->getBasePtr();
9416   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9417     if (ST->isIndexed())
9418       return false;
9419     VT = ST->getMemoryVT();
9420     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9421         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9422       return false;
9423     Ptr = ST->getBasePtr();
9424     isLoad = false;
9425   } else {
9426     return false;
9427   }
9428
9429   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9430   // out.  There is no reason to make this a preinc/predec.
9431   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9432       Ptr.getNode()->hasOneUse())
9433     return false;
9434
9435   // Ask the target to do addressing mode selection.
9436   SDValue BasePtr;
9437   SDValue Offset;
9438   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9439   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9440     return false;
9441
9442   // Backends without true r+i pre-indexed forms may need to pass a
9443   // constant base with a variable offset so that constant coercion
9444   // will work with the patterns in canonical form.
9445   bool Swapped = false;
9446   if (isa<ConstantSDNode>(BasePtr)) {
9447     std::swap(BasePtr, Offset);
9448     Swapped = true;
9449   }
9450
9451   // Don't create a indexed load / store with zero offset.
9452   if (isNullConstant(Offset))
9453     return false;
9454
9455   // Try turning it into a pre-indexed load / store except when:
9456   // 1) The new base ptr is a frame index.
9457   // 2) If N is a store and the new base ptr is either the same as or is a
9458   //    predecessor of the value being stored.
9459   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9460   //    that would create a cycle.
9461   // 4) All uses are load / store ops that use it as old base ptr.
9462
9463   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9464   // (plus the implicit offset) to a register to preinc anyway.
9465   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9466     return false;
9467
9468   // Check #2.
9469   if (!isLoad) {
9470     SDValue Val = cast<StoreSDNode>(N)->getValue();
9471     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9472       return false;
9473   }
9474
9475   // If the offset is a constant, there may be other adds of constants that
9476   // can be folded with this one. We should do this to avoid having to keep
9477   // a copy of the original base pointer.
9478   SmallVector<SDNode *, 16> OtherUses;
9479   if (isa<ConstantSDNode>(Offset))
9480     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9481                               UE = BasePtr.getNode()->use_end();
9482          UI != UE; ++UI) {
9483       SDUse &Use = UI.getUse();
9484       // Skip the use that is Ptr and uses of other results from BasePtr's
9485       // node (important for nodes that return multiple results).
9486       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9487         continue;
9488
9489       if (Use.getUser()->isPredecessorOf(N))
9490         continue;
9491
9492       if (Use.getUser()->getOpcode() != ISD::ADD &&
9493           Use.getUser()->getOpcode() != ISD::SUB) {
9494         OtherUses.clear();
9495         break;
9496       }
9497
9498       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9499       if (!isa<ConstantSDNode>(Op1)) {
9500         OtherUses.clear();
9501         break;
9502       }
9503
9504       // FIXME: In some cases, we can be smarter about this.
9505       if (Op1.getValueType() != Offset.getValueType()) {
9506         OtherUses.clear();
9507         break;
9508       }
9509
9510       OtherUses.push_back(Use.getUser());
9511     }
9512
9513   if (Swapped)
9514     std::swap(BasePtr, Offset);
9515
9516   // Now check for #3 and #4.
9517   bool RealUse = false;
9518
9519   // Caches for hasPredecessorHelper
9520   SmallPtrSet<const SDNode *, 32> Visited;
9521   SmallVector<const SDNode *, 16> Worklist;
9522
9523   for (SDNode *Use : Ptr.getNode()->uses()) {
9524     if (Use == N)
9525       continue;
9526     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9527       return false;
9528
9529     // If Ptr may be folded in addressing mode of other use, then it's
9530     // not profitable to do this transformation.
9531     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9532       RealUse = true;
9533   }
9534
9535   if (!RealUse)
9536     return false;
9537
9538   SDValue Result;
9539   if (isLoad)
9540     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9541                                 BasePtr, Offset, AM);
9542   else
9543     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9544                                  BasePtr, Offset, AM);
9545   ++PreIndexedNodes;
9546   ++NodesCombined;
9547   DEBUG(dbgs() << "\nReplacing.4 ";
9548         N->dump(&DAG);
9549         dbgs() << "\nWith: ";
9550         Result.getNode()->dump(&DAG);
9551         dbgs() << '\n');
9552   WorklistRemover DeadNodes(*this);
9553   if (isLoad) {
9554     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9555     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9556   } else {
9557     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9558   }
9559
9560   // Finally, since the node is now dead, remove it from the graph.
9561   deleteAndRecombine(N);
9562
9563   if (Swapped)
9564     std::swap(BasePtr, Offset);
9565
9566   // Replace other uses of BasePtr that can be updated to use Ptr
9567   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9568     unsigned OffsetIdx = 1;
9569     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9570       OffsetIdx = 0;
9571     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9572            BasePtr.getNode() && "Expected BasePtr operand");
9573
9574     // We need to replace ptr0 in the following expression:
9575     //   x0 * offset0 + y0 * ptr0 = t0
9576     // knowing that
9577     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9578     //
9579     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9580     // indexed load/store and the expresion that needs to be re-written.
9581     //
9582     // Therefore, we have:
9583     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9584
9585     ConstantSDNode *CN =
9586       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9587     int X0, X1, Y0, Y1;
9588     APInt Offset0 = CN->getAPIntValue();
9589     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9590
9591     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9592     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9593     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9594     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9595
9596     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9597
9598     APInt CNV = Offset0;
9599     if (X0 < 0) CNV = -CNV;
9600     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9601     else CNV = CNV - Offset1;
9602
9603     SDLoc DL(OtherUses[i]);
9604
9605     // We can now generate the new expression.
9606     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9607     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9608
9609     SDValue NewUse = DAG.getNode(Opcode,
9610                                  DL,
9611                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9612     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9613     deleteAndRecombine(OtherUses[i]);
9614   }
9615
9616   // Replace the uses of Ptr with uses of the updated base value.
9617   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9618   deleteAndRecombine(Ptr.getNode());
9619
9620   return true;
9621 }
9622
9623 /// Try to combine a load/store with a add/sub of the base pointer node into a
9624 /// post-indexed load/store. The transformation folded the add/subtract into the
9625 /// new indexed load/store effectively and all of its uses are redirected to the
9626 /// new load/store.
9627 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9628   if (Level < AfterLegalizeDAG)
9629     return false;
9630
9631   bool isLoad = true;
9632   SDValue Ptr;
9633   EVT VT;
9634   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9635     if (LD->isIndexed())
9636       return false;
9637     VT = LD->getMemoryVT();
9638     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9639         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9640       return false;
9641     Ptr = LD->getBasePtr();
9642   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9643     if (ST->isIndexed())
9644       return false;
9645     VT = ST->getMemoryVT();
9646     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9647         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9648       return false;
9649     Ptr = ST->getBasePtr();
9650     isLoad = false;
9651   } else {
9652     return false;
9653   }
9654
9655   if (Ptr.getNode()->hasOneUse())
9656     return false;
9657
9658   for (SDNode *Op : Ptr.getNode()->uses()) {
9659     if (Op == N ||
9660         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9661       continue;
9662
9663     SDValue BasePtr;
9664     SDValue Offset;
9665     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9666     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9667       // Don't create a indexed load / store with zero offset.
9668       if (isNullConstant(Offset))
9669         continue;
9670
9671       // Try turning it into a post-indexed load / store except when
9672       // 1) All uses are load / store ops that use it as base ptr (and
9673       //    it may be folded as addressing mmode).
9674       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9675       //    nor a successor of N. Otherwise, if Op is folded that would
9676       //    create a cycle.
9677
9678       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9679         continue;
9680
9681       // Check for #1.
9682       bool TryNext = false;
9683       for (SDNode *Use : BasePtr.getNode()->uses()) {
9684         if (Use == Ptr.getNode())
9685           continue;
9686
9687         // If all the uses are load / store addresses, then don't do the
9688         // transformation.
9689         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9690           bool RealUse = false;
9691           for (SDNode *UseUse : Use->uses()) {
9692             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9693               RealUse = true;
9694           }
9695
9696           if (!RealUse) {
9697             TryNext = true;
9698             break;
9699           }
9700         }
9701       }
9702
9703       if (TryNext)
9704         continue;
9705
9706       // Check for #2
9707       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9708         SDValue Result = isLoad
9709           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9710                                BasePtr, Offset, AM)
9711           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9712                                 BasePtr, Offset, AM);
9713         ++PostIndexedNodes;
9714         ++NodesCombined;
9715         DEBUG(dbgs() << "\nReplacing.5 ";
9716               N->dump(&DAG);
9717               dbgs() << "\nWith: ";
9718               Result.getNode()->dump(&DAG);
9719               dbgs() << '\n');
9720         WorklistRemover DeadNodes(*this);
9721         if (isLoad) {
9722           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9723           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9724         } else {
9725           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9726         }
9727
9728         // Finally, since the node is now dead, remove it from the graph.
9729         deleteAndRecombine(N);
9730
9731         // Replace the uses of Use with uses of the updated base value.
9732         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9733                                       Result.getValue(isLoad ? 1 : 0));
9734         deleteAndRecombine(Op);
9735         return true;
9736       }
9737     }
9738   }
9739
9740   return false;
9741 }
9742
9743 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9744 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9745   ISD::MemIndexedMode AM = LD->getAddressingMode();
9746   assert(AM != ISD::UNINDEXED);
9747   SDValue BP = LD->getOperand(1);
9748   SDValue Inc = LD->getOperand(2);
9749
9750   // Some backends use TargetConstants for load offsets, but don't expect
9751   // TargetConstants in general ADD nodes. We can convert these constants into
9752   // regular Constants (if the constant is not opaque).
9753   assert((Inc.getOpcode() != ISD::TargetConstant ||
9754           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9755          "Cannot split out indexing using opaque target constants");
9756   if (Inc.getOpcode() == ISD::TargetConstant) {
9757     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9758     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9759                           ConstInc->getValueType(0));
9760   }
9761
9762   unsigned Opc =
9763       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9764   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9765 }
9766
9767 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9768   LoadSDNode *LD  = cast<LoadSDNode>(N);
9769   SDValue Chain = LD->getChain();
9770   SDValue Ptr   = LD->getBasePtr();
9771
9772   // If load is not volatile and there are no uses of the loaded value (and
9773   // the updated indexed value in case of indexed loads), change uses of the
9774   // chain value into uses of the chain input (i.e. delete the dead load).
9775   if (!LD->isVolatile()) {
9776     if (N->getValueType(1) == MVT::Other) {
9777       // Unindexed loads.
9778       if (!N->hasAnyUseOfValue(0)) {
9779         // It's not safe to use the two value CombineTo variant here. e.g.
9780         // v1, chain2 = load chain1, loc
9781         // v2, chain3 = load chain2, loc
9782         // v3         = add v2, c
9783         // Now we replace use of chain2 with chain1.  This makes the second load
9784         // isomorphic to the one we are deleting, and thus makes this load live.
9785         DEBUG(dbgs() << "\nReplacing.6 ";
9786               N->dump(&DAG);
9787               dbgs() << "\nWith chain: ";
9788               Chain.getNode()->dump(&DAG);
9789               dbgs() << "\n");
9790         WorklistRemover DeadNodes(*this);
9791         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9792
9793         if (N->use_empty())
9794           deleteAndRecombine(N);
9795
9796         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9797       }
9798     } else {
9799       // Indexed loads.
9800       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9801
9802       // If this load has an opaque TargetConstant offset, then we cannot split
9803       // the indexing into an add/sub directly (that TargetConstant may not be
9804       // valid for a different type of node, and we cannot convert an opaque
9805       // target constant into a regular constant).
9806       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9807                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9808
9809       if (!N->hasAnyUseOfValue(0) &&
9810           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9811         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9812         SDValue Index;
9813         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9814           Index = SplitIndexingFromLoad(LD);
9815           // Try to fold the base pointer arithmetic into subsequent loads and
9816           // stores.
9817           AddUsersToWorklist(N);
9818         } else
9819           Index = DAG.getUNDEF(N->getValueType(1));
9820         DEBUG(dbgs() << "\nReplacing.7 ";
9821               N->dump(&DAG);
9822               dbgs() << "\nWith: ";
9823               Undef.getNode()->dump(&DAG);
9824               dbgs() << " and 2 other values\n");
9825         WorklistRemover DeadNodes(*this);
9826         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9827         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9828         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9829         deleteAndRecombine(N);
9830         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9831       }
9832     }
9833   }
9834
9835   // If this load is directly stored, replace the load value with the stored
9836   // value.
9837   // TODO: Handle store large -> read small portion.
9838   // TODO: Handle TRUNCSTORE/LOADEXT
9839   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9840     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9841       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9842       if (PrevST->getBasePtr() == Ptr &&
9843           PrevST->getValue().getValueType() == N->getValueType(0))
9844       return CombineTo(N, Chain.getOperand(1), Chain);
9845     }
9846   }
9847
9848   // Try to infer better alignment information than the load already has.
9849   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9850     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9851       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9852         SDValue NewLoad =
9853                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9854                               LD->getValueType(0),
9855                               Chain, Ptr, LD->getPointerInfo(),
9856                               LD->getMemoryVT(),
9857                               LD->isVolatile(), LD->isNonTemporal(),
9858                               LD->isInvariant(), Align, LD->getAAInfo());
9859         if (NewLoad.getNode() != N)
9860           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9861       }
9862     }
9863   }
9864
9865   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9866                                                   : DAG.getSubtarget().useAA();
9867 #ifndef NDEBUG
9868   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9869       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9870     UseAA = false;
9871 #endif
9872   if (UseAA && LD->isUnindexed()) {
9873     // Walk up chain skipping non-aliasing memory nodes.
9874     SDValue BetterChain = FindBetterChain(N, Chain);
9875
9876     // If there is a better chain.
9877     if (Chain != BetterChain) {
9878       SDValue ReplLoad;
9879
9880       // Replace the chain to void dependency.
9881       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9882         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9883                                BetterChain, Ptr, LD->getMemOperand());
9884       } else {
9885         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9886                                   LD->getValueType(0),
9887                                   BetterChain, Ptr, LD->getMemoryVT(),
9888                                   LD->getMemOperand());
9889       }
9890
9891       // Create token factor to keep old chain connected.
9892       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9893                                   MVT::Other, Chain, ReplLoad.getValue(1));
9894
9895       // Make sure the new and old chains are cleaned up.
9896       AddToWorklist(Token.getNode());
9897
9898       // Replace uses with load result and token factor. Don't add users
9899       // to work list.
9900       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9901     }
9902   }
9903
9904   // Try transforming N to an indexed load.
9905   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9906     return SDValue(N, 0);
9907
9908   // Try to slice up N to more direct loads if the slices are mapped to
9909   // different register banks or pairing can take place.
9910   if (SliceUpLoad(N))
9911     return SDValue(N, 0);
9912
9913   return SDValue();
9914 }
9915
9916 namespace {
9917 /// \brief Helper structure used to slice a load in smaller loads.
9918 /// Basically a slice is obtained from the following sequence:
9919 /// Origin = load Ty1, Base
9920 /// Shift = srl Ty1 Origin, CstTy Amount
9921 /// Inst = trunc Shift to Ty2
9922 ///
9923 /// Then, it will be rewriten into:
9924 /// Slice = load SliceTy, Base + SliceOffset
9925 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9926 ///
9927 /// SliceTy is deduced from the number of bits that are actually used to
9928 /// build Inst.
9929 struct LoadedSlice {
9930   /// \brief Helper structure used to compute the cost of a slice.
9931   struct Cost {
9932     /// Are we optimizing for code size.
9933     bool ForCodeSize;
9934     /// Various cost.
9935     unsigned Loads;
9936     unsigned Truncates;
9937     unsigned CrossRegisterBanksCopies;
9938     unsigned ZExts;
9939     unsigned Shift;
9940
9941     Cost(bool ForCodeSize = false)
9942         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9943           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9944
9945     /// \brief Get the cost of one isolated slice.
9946     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9947         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9948           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9949       EVT TruncType = LS.Inst->getValueType(0);
9950       EVT LoadedType = LS.getLoadedType();
9951       if (TruncType != LoadedType &&
9952           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9953         ZExts = 1;
9954     }
9955
9956     /// \brief Account for slicing gain in the current cost.
9957     /// Slicing provide a few gains like removing a shift or a
9958     /// truncate. This method allows to grow the cost of the original
9959     /// load with the gain from this slice.
9960     void addSliceGain(const LoadedSlice &LS) {
9961       // Each slice saves a truncate.
9962       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9963       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9964                               LS.Inst->getValueType(0)))
9965         ++Truncates;
9966       // If there is a shift amount, this slice gets rid of it.
9967       if (LS.Shift)
9968         ++Shift;
9969       // If this slice can merge a cross register bank copy, account for it.
9970       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9971         ++CrossRegisterBanksCopies;
9972     }
9973
9974     Cost &operator+=(const Cost &RHS) {
9975       Loads += RHS.Loads;
9976       Truncates += RHS.Truncates;
9977       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9978       ZExts += RHS.ZExts;
9979       Shift += RHS.Shift;
9980       return *this;
9981     }
9982
9983     bool operator==(const Cost &RHS) const {
9984       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9985              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9986              ZExts == RHS.ZExts && Shift == RHS.Shift;
9987     }
9988
9989     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9990
9991     bool operator<(const Cost &RHS) const {
9992       // Assume cross register banks copies are as expensive as loads.
9993       // FIXME: Do we want some more target hooks?
9994       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9995       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9996       // Unless we are optimizing for code size, consider the
9997       // expensive operation first.
9998       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9999         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10000       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10001              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10002     }
10003
10004     bool operator>(const Cost &RHS) const { return RHS < *this; }
10005
10006     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10007
10008     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10009   };
10010   // The last instruction that represent the slice. This should be a
10011   // truncate instruction.
10012   SDNode *Inst;
10013   // The original load instruction.
10014   LoadSDNode *Origin;
10015   // The right shift amount in bits from the original load.
10016   unsigned Shift;
10017   // The DAG from which Origin came from.
10018   // This is used to get some contextual information about legal types, etc.
10019   SelectionDAG *DAG;
10020
10021   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10022               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10023       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10024
10025   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10026   /// \return Result is \p BitWidth and has used bits set to 1 and
10027   ///         not used bits set to 0.
10028   APInt getUsedBits() const {
10029     // Reproduce the trunc(lshr) sequence:
10030     // - Start from the truncated value.
10031     // - Zero extend to the desired bit width.
10032     // - Shift left.
10033     assert(Origin && "No original load to compare against.");
10034     unsigned BitWidth = Origin->getValueSizeInBits(0);
10035     assert(Inst && "This slice is not bound to an instruction");
10036     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10037            "Extracted slice is bigger than the whole type!");
10038     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10039     UsedBits.setAllBits();
10040     UsedBits = UsedBits.zext(BitWidth);
10041     UsedBits <<= Shift;
10042     return UsedBits;
10043   }
10044
10045   /// \brief Get the size of the slice to be loaded in bytes.
10046   unsigned getLoadedSize() const {
10047     unsigned SliceSize = getUsedBits().countPopulation();
10048     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10049     return SliceSize / 8;
10050   }
10051
10052   /// \brief Get the type that will be loaded for this slice.
10053   /// Note: This may not be the final type for the slice.
10054   EVT getLoadedType() const {
10055     assert(DAG && "Missing context");
10056     LLVMContext &Ctxt = *DAG->getContext();
10057     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10058   }
10059
10060   /// \brief Get the alignment of the load used for this slice.
10061   unsigned getAlignment() const {
10062     unsigned Alignment = Origin->getAlignment();
10063     unsigned Offset = getOffsetFromBase();
10064     if (Offset != 0)
10065       Alignment = MinAlign(Alignment, Alignment + Offset);
10066     return Alignment;
10067   }
10068
10069   /// \brief Check if this slice can be rewritten with legal operations.
10070   bool isLegal() const {
10071     // An invalid slice is not legal.
10072     if (!Origin || !Inst || !DAG)
10073       return false;
10074
10075     // Offsets are for indexed load only, we do not handle that.
10076     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10077       return false;
10078
10079     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10080
10081     // Check that the type is legal.
10082     EVT SliceType = getLoadedType();
10083     if (!TLI.isTypeLegal(SliceType))
10084       return false;
10085
10086     // Check that the load is legal for this type.
10087     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10088       return false;
10089
10090     // Check that the offset can be computed.
10091     // 1. Check its type.
10092     EVT PtrType = Origin->getBasePtr().getValueType();
10093     if (PtrType == MVT::Untyped || PtrType.isExtended())
10094       return false;
10095
10096     // 2. Check that it fits in the immediate.
10097     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10098       return false;
10099
10100     // 3. Check that the computation is legal.
10101     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10102       return false;
10103
10104     // Check that the zext is legal if it needs one.
10105     EVT TruncateType = Inst->getValueType(0);
10106     if (TruncateType != SliceType &&
10107         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10108       return false;
10109
10110     return true;
10111   }
10112
10113   /// \brief Get the offset in bytes of this slice in the original chunk of
10114   /// bits.
10115   /// \pre DAG != nullptr.
10116   uint64_t getOffsetFromBase() const {
10117     assert(DAG && "Missing context.");
10118     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10119     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10120     uint64_t Offset = Shift / 8;
10121     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10122     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10123            "The size of the original loaded type is not a multiple of a"
10124            " byte.");
10125     // If Offset is bigger than TySizeInBytes, it means we are loading all
10126     // zeros. This should have been optimized before in the process.
10127     assert(TySizeInBytes > Offset &&
10128            "Invalid shift amount for given loaded size");
10129     if (IsBigEndian)
10130       Offset = TySizeInBytes - Offset - getLoadedSize();
10131     return Offset;
10132   }
10133
10134   /// \brief Generate the sequence of instructions to load the slice
10135   /// represented by this object and redirect the uses of this slice to
10136   /// this new sequence of instructions.
10137   /// \pre this->Inst && this->Origin are valid Instructions and this
10138   /// object passed the legal check: LoadedSlice::isLegal returned true.
10139   /// \return The last instruction of the sequence used to load the slice.
10140   SDValue loadSlice() const {
10141     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10142     const SDValue &OldBaseAddr = Origin->getBasePtr();
10143     SDValue BaseAddr = OldBaseAddr;
10144     // Get the offset in that chunk of bytes w.r.t. the endianess.
10145     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10146     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10147     if (Offset) {
10148       // BaseAddr = BaseAddr + Offset.
10149       EVT ArithType = BaseAddr.getValueType();
10150       SDLoc DL(Origin);
10151       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10152                               DAG->getConstant(Offset, DL, ArithType));
10153     }
10154
10155     // Create the type of the loaded slice according to its size.
10156     EVT SliceType = getLoadedType();
10157
10158     // Create the load for the slice.
10159     SDValue LastInst = DAG->getLoad(
10160         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10161         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10162         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10163     // If the final type is not the same as the loaded type, this means that
10164     // we have to pad with zero. Create a zero extend for that.
10165     EVT FinalType = Inst->getValueType(0);
10166     if (SliceType != FinalType)
10167       LastInst =
10168           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10169     return LastInst;
10170   }
10171
10172   /// \brief Check if this slice can be merged with an expensive cross register
10173   /// bank copy. E.g.,
10174   /// i = load i32
10175   /// f = bitcast i32 i to float
10176   bool canMergeExpensiveCrossRegisterBankCopy() const {
10177     if (!Inst || !Inst->hasOneUse())
10178       return false;
10179     SDNode *Use = *Inst->use_begin();
10180     if (Use->getOpcode() != ISD::BITCAST)
10181       return false;
10182     assert(DAG && "Missing context");
10183     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10184     EVT ResVT = Use->getValueType(0);
10185     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10186     const TargetRegisterClass *ArgRC =
10187         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10188     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10189       return false;
10190
10191     // At this point, we know that we perform a cross-register-bank copy.
10192     // Check if it is expensive.
10193     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10194     // Assume bitcasts are cheap, unless both register classes do not
10195     // explicitly share a common sub class.
10196     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10197       return false;
10198
10199     // Check if it will be merged with the load.
10200     // 1. Check the alignment constraint.
10201     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10202         ResVT.getTypeForEVT(*DAG->getContext()));
10203
10204     if (RequiredAlignment > getAlignment())
10205       return false;
10206
10207     // 2. Check that the load is a legal operation for that type.
10208     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10209       return false;
10210
10211     // 3. Check that we do not have a zext in the way.
10212     if (Inst->getValueType(0) != getLoadedType())
10213       return false;
10214
10215     return true;
10216   }
10217 };
10218 }
10219
10220 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10221 /// \p UsedBits looks like 0..0 1..1 0..0.
10222 static bool areUsedBitsDense(const APInt &UsedBits) {
10223   // If all the bits are one, this is dense!
10224   if (UsedBits.isAllOnesValue())
10225     return true;
10226
10227   // Get rid of the unused bits on the right.
10228   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10229   // Get rid of the unused bits on the left.
10230   if (NarrowedUsedBits.countLeadingZeros())
10231     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10232   // Check that the chunk of bits is completely used.
10233   return NarrowedUsedBits.isAllOnesValue();
10234 }
10235
10236 /// \brief Check whether or not \p First and \p Second are next to each other
10237 /// in memory. This means that there is no hole between the bits loaded
10238 /// by \p First and the bits loaded by \p Second.
10239 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10240                                      const LoadedSlice &Second) {
10241   assert(First.Origin == Second.Origin && First.Origin &&
10242          "Unable to match different memory origins.");
10243   APInt UsedBits = First.getUsedBits();
10244   assert((UsedBits & Second.getUsedBits()) == 0 &&
10245          "Slices are not supposed to overlap.");
10246   UsedBits |= Second.getUsedBits();
10247   return areUsedBitsDense(UsedBits);
10248 }
10249
10250 /// \brief Adjust the \p GlobalLSCost according to the target
10251 /// paring capabilities and the layout of the slices.
10252 /// \pre \p GlobalLSCost should account for at least as many loads as
10253 /// there is in the slices in \p LoadedSlices.
10254 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10255                                  LoadedSlice::Cost &GlobalLSCost) {
10256   unsigned NumberOfSlices = LoadedSlices.size();
10257   // If there is less than 2 elements, no pairing is possible.
10258   if (NumberOfSlices < 2)
10259     return;
10260
10261   // Sort the slices so that elements that are likely to be next to each
10262   // other in memory are next to each other in the list.
10263   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10264             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10265     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10266     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10267   });
10268   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10269   // First (resp. Second) is the first (resp. Second) potentially candidate
10270   // to be placed in a paired load.
10271   const LoadedSlice *First = nullptr;
10272   const LoadedSlice *Second = nullptr;
10273   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10274                 // Set the beginning of the pair.
10275                                                            First = Second) {
10276
10277     Second = &LoadedSlices[CurrSlice];
10278
10279     // If First is NULL, it means we start a new pair.
10280     // Get to the next slice.
10281     if (!First)
10282       continue;
10283
10284     EVT LoadedType = First->getLoadedType();
10285
10286     // If the types of the slices are different, we cannot pair them.
10287     if (LoadedType != Second->getLoadedType())
10288       continue;
10289
10290     // Check if the target supplies paired loads for this type.
10291     unsigned RequiredAlignment = 0;
10292     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10293       // move to the next pair, this type is hopeless.
10294       Second = nullptr;
10295       continue;
10296     }
10297     // Check if we meet the alignment requirement.
10298     if (RequiredAlignment > First->getAlignment())
10299       continue;
10300
10301     // Check that both loads are next to each other in memory.
10302     if (!areSlicesNextToEachOther(*First, *Second))
10303       continue;
10304
10305     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10306     --GlobalLSCost.Loads;
10307     // Move to the next pair.
10308     Second = nullptr;
10309   }
10310 }
10311
10312 /// \brief Check the profitability of all involved LoadedSlice.
10313 /// Currently, it is considered profitable if there is exactly two
10314 /// involved slices (1) which are (2) next to each other in memory, and
10315 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10316 ///
10317 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10318 /// the elements themselves.
10319 ///
10320 /// FIXME: When the cost model will be mature enough, we can relax
10321 /// constraints (1) and (2).
10322 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10323                                 const APInt &UsedBits, bool ForCodeSize) {
10324   unsigned NumberOfSlices = LoadedSlices.size();
10325   if (StressLoadSlicing)
10326     return NumberOfSlices > 1;
10327
10328   // Check (1).
10329   if (NumberOfSlices != 2)
10330     return false;
10331
10332   // Check (2).
10333   if (!areUsedBitsDense(UsedBits))
10334     return false;
10335
10336   // Check (3).
10337   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10338   // The original code has one big load.
10339   OrigCost.Loads = 1;
10340   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10341     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10342     // Accumulate the cost of all the slices.
10343     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10344     GlobalSlicingCost += SliceCost;
10345
10346     // Account as cost in the original configuration the gain obtained
10347     // with the current slices.
10348     OrigCost.addSliceGain(LS);
10349   }
10350
10351   // If the target supports paired load, adjust the cost accordingly.
10352   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10353   return OrigCost > GlobalSlicingCost;
10354 }
10355
10356 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10357 /// operations, split it in the various pieces being extracted.
10358 ///
10359 /// This sort of thing is introduced by SROA.
10360 /// This slicing takes care not to insert overlapping loads.
10361 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10362 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10363   if (Level < AfterLegalizeDAG)
10364     return false;
10365
10366   LoadSDNode *LD = cast<LoadSDNode>(N);
10367   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10368       !LD->getValueType(0).isInteger())
10369     return false;
10370
10371   // Keep track of already used bits to detect overlapping values.
10372   // In that case, we will just abort the transformation.
10373   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10374
10375   SmallVector<LoadedSlice, 4> LoadedSlices;
10376
10377   // Check if this load is used as several smaller chunks of bits.
10378   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10379   // of computation for each trunc.
10380   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10381        UI != UIEnd; ++UI) {
10382     // Skip the uses of the chain.
10383     if (UI.getUse().getResNo() != 0)
10384       continue;
10385
10386     SDNode *User = *UI;
10387     unsigned Shift = 0;
10388
10389     // Check if this is a trunc(lshr).
10390     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10391         isa<ConstantSDNode>(User->getOperand(1))) {
10392       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10393       User = *User->use_begin();
10394     }
10395
10396     // At this point, User is a Truncate, iff we encountered, trunc or
10397     // trunc(lshr).
10398     if (User->getOpcode() != ISD::TRUNCATE)
10399       return false;
10400
10401     // The width of the type must be a power of 2 and greater than 8-bits.
10402     // Otherwise the load cannot be represented in LLVM IR.
10403     // Moreover, if we shifted with a non-8-bits multiple, the slice
10404     // will be across several bytes. We do not support that.
10405     unsigned Width = User->getValueSizeInBits(0);
10406     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10407       return 0;
10408
10409     // Build the slice for this chain of computations.
10410     LoadedSlice LS(User, LD, Shift, &DAG);
10411     APInt CurrentUsedBits = LS.getUsedBits();
10412
10413     // Check if this slice overlaps with another.
10414     if ((CurrentUsedBits & UsedBits) != 0)
10415       return false;
10416     // Update the bits used globally.
10417     UsedBits |= CurrentUsedBits;
10418
10419     // Check if the new slice would be legal.
10420     if (!LS.isLegal())
10421       return false;
10422
10423     // Record the slice.
10424     LoadedSlices.push_back(LS);
10425   }
10426
10427   // Abort slicing if it does not seem to be profitable.
10428   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10429     return false;
10430
10431   ++SlicedLoads;
10432
10433   // Rewrite each chain to use an independent load.
10434   // By construction, each chain can be represented by a unique load.
10435
10436   // Prepare the argument for the new token factor for all the slices.
10437   SmallVector<SDValue, 8> ArgChains;
10438   for (SmallVectorImpl<LoadedSlice>::const_iterator
10439            LSIt = LoadedSlices.begin(),
10440            LSItEnd = LoadedSlices.end();
10441        LSIt != LSItEnd; ++LSIt) {
10442     SDValue SliceInst = LSIt->loadSlice();
10443     CombineTo(LSIt->Inst, SliceInst, true);
10444     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10445       SliceInst = SliceInst.getOperand(0);
10446     assert(SliceInst->getOpcode() == ISD::LOAD &&
10447            "It takes more than a zext to get to the loaded slice!!");
10448     ArgChains.push_back(SliceInst.getValue(1));
10449   }
10450
10451   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10452                               ArgChains);
10453   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10454   return true;
10455 }
10456
10457 /// Check to see if V is (and load (ptr), imm), where the load is having
10458 /// specific bytes cleared out.  If so, return the byte size being masked out
10459 /// and the shift amount.
10460 static std::pair<unsigned, unsigned>
10461 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10462   std::pair<unsigned, unsigned> Result(0, 0);
10463
10464   // Check for the structure we're looking for.
10465   if (V->getOpcode() != ISD::AND ||
10466       !isa<ConstantSDNode>(V->getOperand(1)) ||
10467       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10468     return Result;
10469
10470   // Check the chain and pointer.
10471   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10472   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10473
10474   // The store should be chained directly to the load or be an operand of a
10475   // tokenfactor.
10476   if (LD == Chain.getNode())
10477     ; // ok.
10478   else if (Chain->getOpcode() != ISD::TokenFactor)
10479     return Result; // Fail.
10480   else {
10481     bool isOk = false;
10482     for (const SDValue &ChainOp : Chain->op_values())
10483       if (ChainOp.getNode() == LD) {
10484         isOk = true;
10485         break;
10486       }
10487     if (!isOk) return Result;
10488   }
10489
10490   // This only handles simple types.
10491   if (V.getValueType() != MVT::i16 &&
10492       V.getValueType() != MVT::i32 &&
10493       V.getValueType() != MVT::i64)
10494     return Result;
10495
10496   // Check the constant mask.  Invert it so that the bits being masked out are
10497   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10498   // follow the sign bit for uniformity.
10499   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10500   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10501   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10502   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10503   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10504   if (NotMaskLZ == 64) return Result;  // All zero mask.
10505
10506   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10507   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10508     return Result;
10509
10510   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10511   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10512     NotMaskLZ -= 64-V.getValueSizeInBits();
10513
10514   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10515   switch (MaskedBytes) {
10516   case 1:
10517   case 2:
10518   case 4: break;
10519   default: return Result; // All one mask, or 5-byte mask.
10520   }
10521
10522   // Verify that the first bit starts at a multiple of mask so that the access
10523   // is aligned the same as the access width.
10524   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10525
10526   Result.first = MaskedBytes;
10527   Result.second = NotMaskTZ/8;
10528   return Result;
10529 }
10530
10531
10532 /// Check to see if IVal is something that provides a value as specified by
10533 /// MaskInfo. If so, replace the specified store with a narrower store of
10534 /// truncated IVal.
10535 static SDNode *
10536 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10537                                 SDValue IVal, StoreSDNode *St,
10538                                 DAGCombiner *DC) {
10539   unsigned NumBytes = MaskInfo.first;
10540   unsigned ByteShift = MaskInfo.second;
10541   SelectionDAG &DAG = DC->getDAG();
10542
10543   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10544   // that uses this.  If not, this is not a replacement.
10545   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10546                                   ByteShift*8, (ByteShift+NumBytes)*8);
10547   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10548
10549   // Check that it is legal on the target to do this.  It is legal if the new
10550   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10551   // legalization.
10552   MVT VT = MVT::getIntegerVT(NumBytes*8);
10553   if (!DC->isTypeLegal(VT))
10554     return nullptr;
10555
10556   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10557   // shifted by ByteShift and truncated down to NumBytes.
10558   if (ByteShift) {
10559     SDLoc DL(IVal);
10560     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10561                        DAG.getConstant(ByteShift*8, DL,
10562                                     DC->getShiftAmountTy(IVal.getValueType())));
10563   }
10564
10565   // Figure out the offset for the store and the alignment of the access.
10566   unsigned StOffset;
10567   unsigned NewAlign = St->getAlignment();
10568
10569   if (DAG.getDataLayout().isLittleEndian())
10570     StOffset = ByteShift;
10571   else
10572     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10573
10574   SDValue Ptr = St->getBasePtr();
10575   if (StOffset) {
10576     SDLoc DL(IVal);
10577     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10578                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10579     NewAlign = MinAlign(NewAlign, StOffset);
10580   }
10581
10582   // Truncate down to the new size.
10583   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10584
10585   ++OpsNarrowed;
10586   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10587                       St->getPointerInfo().getWithOffset(StOffset),
10588                       false, false, NewAlign).getNode();
10589 }
10590
10591
10592 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10593 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10594 /// narrowing the load and store if it would end up being a win for performance
10595 /// or code size.
10596 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10597   StoreSDNode *ST  = cast<StoreSDNode>(N);
10598   if (ST->isVolatile())
10599     return SDValue();
10600
10601   SDValue Chain = ST->getChain();
10602   SDValue Value = ST->getValue();
10603   SDValue Ptr   = ST->getBasePtr();
10604   EVT VT = Value.getValueType();
10605
10606   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10607     return SDValue();
10608
10609   unsigned Opc = Value.getOpcode();
10610
10611   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10612   // is a byte mask indicating a consecutive number of bytes, check to see if
10613   // Y is known to provide just those bytes.  If so, we try to replace the
10614   // load + replace + store sequence with a single (narrower) store, which makes
10615   // the load dead.
10616   if (Opc == ISD::OR) {
10617     std::pair<unsigned, unsigned> MaskedLoad;
10618     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10619     if (MaskedLoad.first)
10620       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10621                                                   Value.getOperand(1), ST,this))
10622         return SDValue(NewST, 0);
10623
10624     // Or is commutative, so try swapping X and Y.
10625     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10626     if (MaskedLoad.first)
10627       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10628                                                   Value.getOperand(0), ST,this))
10629         return SDValue(NewST, 0);
10630   }
10631
10632   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10633       Value.getOperand(1).getOpcode() != ISD::Constant)
10634     return SDValue();
10635
10636   SDValue N0 = Value.getOperand(0);
10637   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10638       Chain == SDValue(N0.getNode(), 1)) {
10639     LoadSDNode *LD = cast<LoadSDNode>(N0);
10640     if (LD->getBasePtr() != Ptr ||
10641         LD->getPointerInfo().getAddrSpace() !=
10642         ST->getPointerInfo().getAddrSpace())
10643       return SDValue();
10644
10645     // Find the type to narrow it the load / op / store to.
10646     SDValue N1 = Value.getOperand(1);
10647     unsigned BitWidth = N1.getValueSizeInBits();
10648     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10649     if (Opc == ISD::AND)
10650       Imm ^= APInt::getAllOnesValue(BitWidth);
10651     if (Imm == 0 || Imm.isAllOnesValue())
10652       return SDValue();
10653     unsigned ShAmt = Imm.countTrailingZeros();
10654     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10655     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10656     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10657     // The narrowing should be profitable, the load/store operation should be
10658     // legal (or custom) and the store size should be equal to the NewVT width.
10659     while (NewBW < BitWidth &&
10660            (NewVT.getStoreSizeInBits() != NewBW ||
10661             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10662             !TLI.isNarrowingProfitable(VT, NewVT))) {
10663       NewBW = NextPowerOf2(NewBW);
10664       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10665     }
10666     if (NewBW >= BitWidth)
10667       return SDValue();
10668
10669     // If the lsb changed does not start at the type bitwidth boundary,
10670     // start at the previous one.
10671     if (ShAmt % NewBW)
10672       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10673     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10674                                    std::min(BitWidth, ShAmt + NewBW));
10675     if ((Imm & Mask) == Imm) {
10676       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10677       if (Opc == ISD::AND)
10678         NewImm ^= APInt::getAllOnesValue(NewBW);
10679       uint64_t PtrOff = ShAmt / 8;
10680       // For big endian targets, we need to adjust the offset to the pointer to
10681       // load the correct bytes.
10682       if (DAG.getDataLayout().isBigEndian())
10683         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10684
10685       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10686       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10687       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10688         return SDValue();
10689
10690       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10691                                    Ptr.getValueType(), Ptr,
10692                                    DAG.getConstant(PtrOff, SDLoc(LD),
10693                                                    Ptr.getValueType()));
10694       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10695                                   LD->getChain(), NewPtr,
10696                                   LD->getPointerInfo().getWithOffset(PtrOff),
10697                                   LD->isVolatile(), LD->isNonTemporal(),
10698                                   LD->isInvariant(), NewAlign,
10699                                   LD->getAAInfo());
10700       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10701                                    DAG.getConstant(NewImm, SDLoc(Value),
10702                                                    NewVT));
10703       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10704                                    NewVal, NewPtr,
10705                                    ST->getPointerInfo().getWithOffset(PtrOff),
10706                                    false, false, NewAlign);
10707
10708       AddToWorklist(NewPtr.getNode());
10709       AddToWorklist(NewLD.getNode());
10710       AddToWorklist(NewVal.getNode());
10711       WorklistRemover DeadNodes(*this);
10712       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10713       ++OpsNarrowed;
10714       return NewST;
10715     }
10716   }
10717
10718   return SDValue();
10719 }
10720
10721 /// For a given floating point load / store pair, if the load value isn't used
10722 /// by any other operations, then consider transforming the pair to integer
10723 /// load / store operations if the target deems the transformation profitable.
10724 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10725   StoreSDNode *ST  = cast<StoreSDNode>(N);
10726   SDValue Chain = ST->getChain();
10727   SDValue Value = ST->getValue();
10728   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10729       Value.hasOneUse() &&
10730       Chain == SDValue(Value.getNode(), 1)) {
10731     LoadSDNode *LD = cast<LoadSDNode>(Value);
10732     EVT VT = LD->getMemoryVT();
10733     if (!VT.isFloatingPoint() ||
10734         VT != ST->getMemoryVT() ||
10735         LD->isNonTemporal() ||
10736         ST->isNonTemporal() ||
10737         LD->getPointerInfo().getAddrSpace() != 0 ||
10738         ST->getPointerInfo().getAddrSpace() != 0)
10739       return SDValue();
10740
10741     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10742     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10743         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10744         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10745         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10746       return SDValue();
10747
10748     unsigned LDAlign = LD->getAlignment();
10749     unsigned STAlign = ST->getAlignment();
10750     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10751     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10752     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10753       return SDValue();
10754
10755     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10756                                 LD->getChain(), LD->getBasePtr(),
10757                                 LD->getPointerInfo(),
10758                                 false, false, false, LDAlign);
10759
10760     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10761                                  NewLD, ST->getBasePtr(),
10762                                  ST->getPointerInfo(),
10763                                  false, false, STAlign);
10764
10765     AddToWorklist(NewLD.getNode());
10766     AddToWorklist(NewST.getNode());
10767     WorklistRemover DeadNodes(*this);
10768     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10769     ++LdStFP2Int;
10770     return NewST;
10771   }
10772
10773   return SDValue();
10774 }
10775
10776 namespace {
10777 /// Helper struct to parse and store a memory address as base + index + offset.
10778 /// We ignore sign extensions when it is safe to do so.
10779 /// The following two expressions are not equivalent. To differentiate we need
10780 /// to store whether there was a sign extension involved in the index
10781 /// computation.
10782 ///  (load (i64 add (i64 copyfromreg %c)
10783 ///                 (i64 signextend (add (i8 load %index)
10784 ///                                      (i8 1))))
10785 /// vs
10786 ///
10787 /// (load (i64 add (i64 copyfromreg %c)
10788 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10789 ///                                         (i32 1)))))
10790 struct BaseIndexOffset {
10791   SDValue Base;
10792   SDValue Index;
10793   int64_t Offset;
10794   bool IsIndexSignExt;
10795
10796   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10797
10798   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10799                   bool IsIndexSignExt) :
10800     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10801
10802   bool equalBaseIndex(const BaseIndexOffset &Other) {
10803     return Other.Base == Base && Other.Index == Index &&
10804       Other.IsIndexSignExt == IsIndexSignExt;
10805   }
10806
10807   /// Parses tree in Ptr for base, index, offset addresses.
10808   static BaseIndexOffset match(SDValue Ptr) {
10809     bool IsIndexSignExt = false;
10810
10811     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10812     // instruction, then it could be just the BASE or everything else we don't
10813     // know how to handle. Just use Ptr as BASE and give up.
10814     if (Ptr->getOpcode() != ISD::ADD)
10815       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10816
10817     // We know that we have at least an ADD instruction. Try to pattern match
10818     // the simple case of BASE + OFFSET.
10819     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10820       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10821       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10822                               IsIndexSignExt);
10823     }
10824
10825     // Inside a loop the current BASE pointer is calculated using an ADD and a
10826     // MUL instruction. In this case Ptr is the actual BASE pointer.
10827     // (i64 add (i64 %array_ptr)
10828     //          (i64 mul (i64 %induction_var)
10829     //                   (i64 %element_size)))
10830     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10831       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10832
10833     // Look at Base + Index + Offset cases.
10834     SDValue Base = Ptr->getOperand(0);
10835     SDValue IndexOffset = Ptr->getOperand(1);
10836
10837     // Skip signextends.
10838     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10839       IndexOffset = IndexOffset->getOperand(0);
10840       IsIndexSignExt = true;
10841     }
10842
10843     // Either the case of Base + Index (no offset) or something else.
10844     if (IndexOffset->getOpcode() != ISD::ADD)
10845       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10846
10847     // Now we have the case of Base + Index + offset.
10848     SDValue Index = IndexOffset->getOperand(0);
10849     SDValue Offset = IndexOffset->getOperand(1);
10850
10851     if (!isa<ConstantSDNode>(Offset))
10852       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10853
10854     // Ignore signextends.
10855     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10856       Index = Index->getOperand(0);
10857       IsIndexSignExt = true;
10858     } else IsIndexSignExt = false;
10859
10860     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10861     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10862   }
10863 };
10864 } // namespace
10865
10866 // This is a helper function for visitMUL to check the profitability
10867 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
10868 // MulNode is the original multiply, AddNode is (add x, c1),
10869 // and ConstNode is c2.
10870 //
10871 // If the (add x, c1) has multiple uses, we could increase
10872 // the number of adds if we make this transformation.
10873 // It would only be worth doing this if we can remove a
10874 // multiply in the process. Check for that here.
10875 // To illustrate:
10876 //     (A + c1) * c3
10877 //     (A + c2) * c3
10878 // We're checking for cases where we have common "c3 * A" expressions.
10879 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
10880                                               SDValue &AddNode,
10881                                               SDValue &ConstNode) {
10882   APInt Val;
10883
10884   // If the add only has one use, this would be OK to do.
10885   if (AddNode.getNode()->hasOneUse())
10886     return true;
10887
10888   // Walk all the users of the constant with which we're multiplying.
10889   for (SDNode *Use : ConstNode->uses()) {
10890
10891     if (Use == MulNode) // This use is the one we're on right now. Skip it.
10892       continue;
10893
10894     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
10895       SDNode *OtherOp;
10896       SDNode *MulVar = AddNode.getOperand(0).getNode();
10897
10898       // OtherOp is what we're multiplying against the constant.
10899       if (Use->getOperand(0) == ConstNode)
10900         OtherOp = Use->getOperand(1).getNode();
10901       else
10902         OtherOp = Use->getOperand(0).getNode();
10903
10904       // Check to see if multiply is with the same operand of our "add".
10905       //
10906       //     ConstNode  = CONST
10907       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
10908       //     ...
10909       //     AddNode  = (A + c1)  <-- MulVar is A.
10910       //         = AddNode * ConstNode   <-- current visiting instruction.
10911       //
10912       // If we make this transformation, we will have a common
10913       // multiply (ConstNode * A) that we can save.
10914       if (OtherOp == MulVar)
10915         return true;
10916
10917       // Now check to see if a future expansion will give us a common
10918       // multiply.
10919       //
10920       //     ConstNode  = CONST
10921       //     AddNode    = (A + c1)
10922       //     ...   = AddNode * ConstNode <-- current visiting instruction.
10923       //     ...
10924       //     OtherOp = (A + c2)
10925       //     Use     = OtherOp * ConstNode <-- visiting Use.
10926       //
10927       // If we make this transformation, we will have a common
10928       // multiply (CONST * A) after we also do the same transformation
10929       // to the "t2" instruction.
10930       if (OtherOp->getOpcode() == ISD::ADD &&
10931           isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
10932           OtherOp->getOperand(0).getNode() == MulVar)
10933         return true;
10934     }
10935   }
10936
10937   // Didn't find a case where this would be profitable.
10938   return false;
10939 }
10940
10941 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10942                                                   SDLoc SL,
10943                                                   ArrayRef<MemOpLink> Stores,
10944                                                   SmallVectorImpl<SDValue> &Chains,
10945                                                   EVT Ty) const {
10946   SmallVector<SDValue, 8> BuildVector;
10947
10948   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10949     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10950     Chains.push_back(St->getChain());
10951     BuildVector.push_back(St->getValue());
10952   }
10953
10954   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10955 }
10956
10957 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10958                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10959                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10960   // Make sure we have something to merge.
10961   if (NumStores < 2)
10962     return false;
10963
10964   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10965   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10966   unsigned LatestNodeUsed = 0;
10967
10968   for (unsigned i=0; i < NumStores; ++i) {
10969     // Find a chain for the new wide-store operand. Notice that some
10970     // of the store nodes that we found may not be selected for inclusion
10971     // in the wide store. The chain we use needs to be the chain of the
10972     // latest store node which is *used* and replaced by the wide store.
10973     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10974       LatestNodeUsed = i;
10975   }
10976
10977   SmallVector<SDValue, 8> Chains;
10978
10979   // The latest Node in the DAG.
10980   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10981   SDLoc DL(StoreNodes[0].MemNode);
10982
10983   SDValue StoredVal;
10984   if (UseVector) {
10985     bool IsVec = MemVT.isVector();
10986     unsigned Elts = NumStores;
10987     if (IsVec) {
10988       // When merging vector stores, get the total number of elements.
10989       Elts *= MemVT.getVectorNumElements();
10990     }
10991     // Get the type for the merged vector store.
10992     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10993     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10994
10995     if (IsConstantSrc) {
10996       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10997     } else {
10998       SmallVector<SDValue, 8> Ops;
10999       for (unsigned i = 0; i < NumStores; ++i) {
11000         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11001         SDValue Val = St->getValue();
11002         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11003         if (Val.getValueType() != MemVT)
11004           return false;
11005         Ops.push_back(Val);
11006         Chains.push_back(St->getChain());
11007       }
11008
11009       // Build the extracted vector elements back into a vector.
11010       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11011                               DL, Ty, Ops);    }
11012   } else {
11013     // We should always use a vector store when merging extracted vector
11014     // elements, so this path implies a store of constants.
11015     assert(IsConstantSrc && "Merged vector elements should use vector store");
11016
11017     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11018     APInt StoreInt(SizeInBits, 0);
11019
11020     // Construct a single integer constant which is made of the smaller
11021     // constant inputs.
11022     bool IsLE = DAG.getDataLayout().isLittleEndian();
11023     for (unsigned i = 0; i < NumStores; ++i) {
11024       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11025       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11026       Chains.push_back(St->getChain());
11027
11028       SDValue Val = St->getValue();
11029       StoreInt <<= ElementSizeBytes * 8;
11030       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11031         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11032       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11033         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11034       } else {
11035         llvm_unreachable("Invalid constant element type");
11036       }
11037     }
11038
11039     // Create the new Load and Store operations.
11040     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11041     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11042   }
11043
11044   assert(!Chains.empty());
11045
11046   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11047   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11048                                   FirstInChain->getBasePtr(),
11049                                   FirstInChain->getPointerInfo(),
11050                                   false, false,
11051                                   FirstInChain->getAlignment());
11052
11053   // Replace the last store with the new store
11054   CombineTo(LatestOp, NewStore);
11055   // Erase all other stores.
11056   for (unsigned i = 0; i < NumStores; ++i) {
11057     if (StoreNodes[i].MemNode == LatestOp)
11058       continue;
11059     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11060     // ReplaceAllUsesWith will replace all uses that existed when it was
11061     // called, but graph optimizations may cause new ones to appear. For
11062     // example, the case in pr14333 looks like
11063     //
11064     //  St's chain -> St -> another store -> X
11065     //
11066     // And the only difference from St to the other store is the chain.
11067     // When we change it's chain to be St's chain they become identical,
11068     // get CSEed and the net result is that X is now a use of St.
11069     // Since we know that St is redundant, just iterate.
11070     while (!St->use_empty())
11071       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11072     deleteAndRecombine(St);
11073   }
11074
11075   return true;
11076 }
11077
11078 void DAGCombiner::getStoreMergeAndAliasCandidates(
11079     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11080     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11081   // This holds the base pointer, index, and the offset in bytes from the base
11082   // pointer.
11083   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11084
11085   // We must have a base and an offset.
11086   if (!BasePtr.Base.getNode())
11087     return;
11088
11089   // Do not handle stores to undef base pointers.
11090   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11091     return;
11092
11093   // Walk up the chain and look for nodes with offsets from the same
11094   // base pointer. Stop when reaching an instruction with a different kind
11095   // or instruction which has a different base pointer.
11096   EVT MemVT = St->getMemoryVT();
11097   unsigned Seq = 0;
11098   StoreSDNode *Index = St;
11099
11100
11101   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11102                                                   : DAG.getSubtarget().useAA();
11103
11104   if (UseAA) {
11105     // Look at other users of the same chain. Stores on the same chain do not
11106     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11107     // to be on the same chain, so don't bother looking at adjacent chains.
11108
11109     SDValue Chain = St->getChain();
11110     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11111       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11112         if (I.getOperandNo() != 0)
11113           continue;
11114
11115         if (OtherST->isVolatile() || OtherST->isIndexed())
11116           continue;
11117
11118         if (OtherST->getMemoryVT() != MemVT)
11119           continue;
11120
11121         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11122
11123         if (Ptr.equalBaseIndex(BasePtr))
11124           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11125       }
11126     }
11127
11128     return;
11129   }
11130
11131   while (Index) {
11132     // If the chain has more than one use, then we can't reorder the mem ops.
11133     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11134       break;
11135
11136     // Find the base pointer and offset for this memory node.
11137     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11138
11139     // Check that the base pointer is the same as the original one.
11140     if (!Ptr.equalBaseIndex(BasePtr))
11141       break;
11142
11143     // The memory operands must not be volatile.
11144     if (Index->isVolatile() || Index->isIndexed())
11145       break;
11146
11147     // No truncation.
11148     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11149       if (St->isTruncatingStore())
11150         break;
11151
11152     // The stored memory type must be the same.
11153     if (Index->getMemoryVT() != MemVT)
11154       break;
11155
11156     // We do not allow under-aligned stores in order to prevent
11157     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11158     // be irrelevant here; what MATTERS is that we not move memory
11159     // operations that potentially overlap past each-other.
11160     if (Index->getAlignment() < MemVT.getStoreSize())
11161       break;
11162
11163     // We found a potential memory operand to merge.
11164     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11165
11166     // Find the next memory operand in the chain. If the next operand in the
11167     // chain is a store then move up and continue the scan with the next
11168     // memory operand. If the next operand is a load save it and use alias
11169     // information to check if it interferes with anything.
11170     SDNode *NextInChain = Index->getChain().getNode();
11171     while (1) {
11172       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11173         // We found a store node. Use it for the next iteration.
11174         Index = STn;
11175         break;
11176       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11177         if (Ldn->isVolatile()) {
11178           Index = nullptr;
11179           break;
11180         }
11181
11182         // Save the load node for later. Continue the scan.
11183         AliasLoadNodes.push_back(Ldn);
11184         NextInChain = Ldn->getChain().getNode();
11185         continue;
11186       } else {
11187         Index = nullptr;
11188         break;
11189       }
11190     }
11191   }
11192 }
11193
11194 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11195   if (OptLevel == CodeGenOpt::None)
11196     return false;
11197
11198   EVT MemVT = St->getMemoryVT();
11199   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11200   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11201       Attribute::NoImplicitFloat);
11202
11203   // This function cannot currently deal with non-byte-sized memory sizes.
11204   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11205     return false;
11206
11207   if (!MemVT.isSimple())
11208     return false;
11209
11210   // Perform an early exit check. Do not bother looking at stored values that
11211   // are not constants, loads, or extracted vector elements.
11212   SDValue StoredVal = St->getValue();
11213   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11214   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11215                        isa<ConstantFPSDNode>(StoredVal);
11216   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11217                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11218
11219   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11220     return false;
11221
11222   // Don't merge vectors into wider vectors if the source data comes from loads.
11223   // TODO: This restriction can be lifted by using logic similar to the
11224   // ExtractVecSrc case.
11225   if (MemVT.isVector() && IsLoadSrc)
11226     return false;
11227
11228   // Only look at ends of store sequences.
11229   SDValue Chain = SDValue(St, 0);
11230   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11231     return false;
11232
11233   // Save the LoadSDNodes that we find in the chain.
11234   // We need to make sure that these nodes do not interfere with
11235   // any of the store nodes.
11236   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11237
11238   // Save the StoreSDNodes that we find in the chain.
11239   SmallVector<MemOpLink, 8> StoreNodes;
11240
11241   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11242
11243   // Check if there is anything to merge.
11244   if (StoreNodes.size() < 2)
11245     return false;
11246
11247   // Sort the memory operands according to their distance from the
11248   // base pointer.  As a secondary criteria: make sure stores coming
11249   // later in the code come first in the list. This is important for
11250   // the non-UseAA case, because we're merging stores into the FINAL
11251   // store along a chain which potentially contains aliasing stores.
11252   // Thus, if there are multiple stores to the same address, the last
11253   // one can be considered for merging but not the others.
11254   std::sort(StoreNodes.begin(), StoreNodes.end(),
11255             [](MemOpLink LHS, MemOpLink RHS) {
11256     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11257            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11258             LHS.SequenceNum < RHS.SequenceNum);
11259   });
11260
11261   // Scan the memory operations on the chain and find the first non-consecutive
11262   // store memory address.
11263   unsigned LastConsecutiveStore = 0;
11264   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11265   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11266
11267     // Check that the addresses are consecutive starting from the second
11268     // element in the list of stores.
11269     if (i > 0) {
11270       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11271       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11272         break;
11273     }
11274
11275     bool Alias = false;
11276     // Check if this store interferes with any of the loads that we found.
11277     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11278       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11279         Alias = true;
11280         break;
11281       }
11282     // We found a load that alias with this store. Stop the sequence.
11283     if (Alias)
11284       break;
11285
11286     // Mark this node as useful.
11287     LastConsecutiveStore = i;
11288   }
11289
11290   // The node with the lowest store address.
11291   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11292   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11293   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11294   LLVMContext &Context = *DAG.getContext();
11295   const DataLayout &DL = DAG.getDataLayout();
11296
11297   // Store the constants into memory as one consecutive store.
11298   if (IsConstantSrc) {
11299     unsigned LastLegalType = 0;
11300     unsigned LastLegalVectorType = 0;
11301     bool NonZero = false;
11302     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11303       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11304       SDValue StoredVal = St->getValue();
11305
11306       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11307         NonZero |= !C->isNullValue();
11308       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11309         NonZero |= !C->getConstantFPValue()->isNullValue();
11310       } else {
11311         // Non-constant.
11312         break;
11313       }
11314
11315       // Find a legal type for the constant store.
11316       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11317       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11318       bool IsFast;
11319       if (TLI.isTypeLegal(StoreTy) &&
11320           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11321                                  FirstStoreAlign, &IsFast) && IsFast) {
11322         LastLegalType = i+1;
11323       // Or check whether a truncstore is legal.
11324       } else if (TLI.getTypeAction(Context, StoreTy) ==
11325                  TargetLowering::TypePromoteInteger) {
11326         EVT LegalizedStoredValueTy =
11327           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11328         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11329             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11330                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11331             IsFast) {
11332           LastLegalType = i + 1;
11333         }
11334       }
11335
11336       // We only use vectors if the constant is known to be zero or the target
11337       // allows it and the function is not marked with the noimplicitfloat
11338       // attribute.
11339       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11340                                                         FirstStoreAS)) &&
11341           !NoVectors) {
11342         // Find a legal type for the vector store.
11343         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11344         if (TLI.isTypeLegal(Ty) &&
11345             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11346                                    FirstStoreAlign, &IsFast) && IsFast)
11347           LastLegalVectorType = i + 1;
11348       }
11349     }
11350
11351     // Check if we found a legal integer type to store.
11352     if (LastLegalType == 0 && LastLegalVectorType == 0)
11353       return false;
11354
11355     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11356     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11357
11358     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11359                                            true, UseVector);
11360   }
11361
11362   // When extracting multiple vector elements, try to store them
11363   // in one vector store rather than a sequence of scalar stores.
11364   if (IsExtractVecSrc) {
11365     unsigned NumStoresToMerge = 0;
11366     bool IsVec = MemVT.isVector();
11367     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11368       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11369       unsigned StoreValOpcode = St->getValue().getOpcode();
11370       // This restriction could be loosened.
11371       // Bail out if any stored values are not elements extracted from a vector.
11372       // It should be possible to handle mixed sources, but load sources need
11373       // more careful handling (see the block of code below that handles
11374       // consecutive loads).
11375       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11376           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11377         return false;
11378
11379       // Find a legal type for the vector store.
11380       unsigned Elts = i + 1;
11381       if (IsVec) {
11382         // When merging vector stores, get the total number of elements.
11383         Elts *= MemVT.getVectorNumElements();
11384       }
11385       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11386       bool IsFast;
11387       if (TLI.isTypeLegal(Ty) &&
11388           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11389                                  FirstStoreAlign, &IsFast) && IsFast)
11390         NumStoresToMerge = i + 1;
11391     }
11392
11393     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11394                                            false, true);
11395   }
11396
11397   // Below we handle the case of multiple consecutive stores that
11398   // come from multiple consecutive loads. We merge them into a single
11399   // wide load and a single wide store.
11400
11401   // Look for load nodes which are used by the stored values.
11402   SmallVector<MemOpLink, 8> LoadNodes;
11403
11404   // Find acceptable loads. Loads need to have the same chain (token factor),
11405   // must not be zext, volatile, indexed, and they must be consecutive.
11406   BaseIndexOffset LdBasePtr;
11407   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11408     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11409     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11410     if (!Ld) break;
11411
11412     // Loads must only have one use.
11413     if (!Ld->hasNUsesOfValue(1, 0))
11414       break;
11415
11416     // The memory operands must not be volatile.
11417     if (Ld->isVolatile() || Ld->isIndexed())
11418       break;
11419
11420     // We do not accept ext loads.
11421     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11422       break;
11423
11424     // The stored memory type must be the same.
11425     if (Ld->getMemoryVT() != MemVT)
11426       break;
11427
11428     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11429     // If this is not the first ptr that we check.
11430     if (LdBasePtr.Base.getNode()) {
11431       // The base ptr must be the same.
11432       if (!LdPtr.equalBaseIndex(LdBasePtr))
11433         break;
11434     } else {
11435       // Check that all other base pointers are the same as this one.
11436       LdBasePtr = LdPtr;
11437     }
11438
11439     // We found a potential memory operand to merge.
11440     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11441   }
11442
11443   if (LoadNodes.size() < 2)
11444     return false;
11445
11446   // If we have load/store pair instructions and we only have two values,
11447   // don't bother.
11448   unsigned RequiredAlignment;
11449   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11450       St->getAlignment() >= RequiredAlignment)
11451     return false;
11452
11453   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11454   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11455   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11456
11457   // Scan the memory operations on the chain and find the first non-consecutive
11458   // load memory address. These variables hold the index in the store node
11459   // array.
11460   unsigned LastConsecutiveLoad = 0;
11461   // This variable refers to the size and not index in the array.
11462   unsigned LastLegalVectorType = 0;
11463   unsigned LastLegalIntegerType = 0;
11464   StartAddress = LoadNodes[0].OffsetFromBase;
11465   SDValue FirstChain = FirstLoad->getChain();
11466   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11467     // All loads much share the same chain.
11468     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11469       break;
11470
11471     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11472     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11473       break;
11474     LastConsecutiveLoad = i;
11475     // Find a legal type for the vector store.
11476     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11477     bool IsFastSt, IsFastLd;
11478     if (TLI.isTypeLegal(StoreTy) &&
11479         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11480                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11481         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11482                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11483       LastLegalVectorType = i + 1;
11484     }
11485
11486     // Find a legal type for the integer store.
11487     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11488     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11489     if (TLI.isTypeLegal(StoreTy) &&
11490         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11491                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11492         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11493                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11494       LastLegalIntegerType = i + 1;
11495     // Or check whether a truncstore and extload is legal.
11496     else if (TLI.getTypeAction(Context, StoreTy) ==
11497              TargetLowering::TypePromoteInteger) {
11498       EVT LegalizedStoredValueTy =
11499         TLI.getTypeToTransformTo(Context, StoreTy);
11500       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11501           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11502           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11503           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11504           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11505                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11506           IsFastSt &&
11507           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11508                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11509           IsFastLd)
11510         LastLegalIntegerType = i+1;
11511     }
11512   }
11513
11514   // Only use vector types if the vector type is larger than the integer type.
11515   // If they are the same, use integers.
11516   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11517   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11518
11519   // We add +1 here because the LastXXX variables refer to location while
11520   // the NumElem refers to array/index size.
11521   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11522   NumElem = std::min(LastLegalType, NumElem);
11523
11524   if (NumElem < 2)
11525     return false;
11526
11527   // Collect the chains from all merged stores.
11528   SmallVector<SDValue, 8> MergeStoreChains;
11529   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11530
11531   // The latest Node in the DAG.
11532   unsigned LatestNodeUsed = 0;
11533   for (unsigned i=1; i<NumElem; ++i) {
11534     // Find a chain for the new wide-store operand. Notice that some
11535     // of the store nodes that we found may not be selected for inclusion
11536     // in the wide store. The chain we use needs to be the chain of the
11537     // latest store node which is *used* and replaced by the wide store.
11538     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11539       LatestNodeUsed = i;
11540
11541     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11542   }
11543
11544   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11545
11546   // Find if it is better to use vectors or integers to load and store
11547   // to memory.
11548   EVT JointMemOpVT;
11549   if (UseVectorTy) {
11550     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11551   } else {
11552     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11553     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11554   }
11555
11556   SDLoc LoadDL(LoadNodes[0].MemNode);
11557   SDLoc StoreDL(StoreNodes[0].MemNode);
11558
11559   // The merged loads are required to have the same chain, so using the first's
11560   // chain is acceptable.
11561   SDValue NewLoad = DAG.getLoad(
11562       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11563       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11564
11565   SDValue NewStoreChain =
11566     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11567
11568   SDValue NewStore = DAG.getStore(
11569     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11570       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11571
11572   // Replace one of the loads with the new load.
11573   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11574   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11575                                 SDValue(NewLoad.getNode(), 1));
11576
11577   // Remove the rest of the load chains.
11578   for (unsigned i = 1; i < NumElem ; ++i) {
11579     // Replace all chain users of the old load nodes with the chain of the new
11580     // load node.
11581     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11582     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11583   }
11584
11585   // Replace the last store with the new store.
11586   CombineTo(LatestOp, NewStore);
11587   // Erase all other stores.
11588   for (unsigned i = 0; i < NumElem ; ++i) {
11589     // Remove all Store nodes.
11590     if (StoreNodes[i].MemNode == LatestOp)
11591       continue;
11592     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11593     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11594     deleteAndRecombine(St);
11595   }
11596
11597   return true;
11598 }
11599
11600 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11601   SDLoc SL(ST);
11602   SDValue ReplStore;
11603
11604   // Replace the chain to avoid dependency.
11605   if (ST->isTruncatingStore()) {
11606     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11607                                   ST->getBasePtr(), ST->getMemoryVT(),
11608                                   ST->getMemOperand());
11609   } else {
11610     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11611                              ST->getMemOperand());
11612   }
11613
11614   // Create token to keep both nodes around.
11615   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11616                               MVT::Other, ST->getChain(), ReplStore);
11617
11618   // Make sure the new and old chains are cleaned up.
11619   AddToWorklist(Token.getNode());
11620
11621   // Don't add users to work list.
11622   return CombineTo(ST, Token, false);
11623 }
11624
11625 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11626   SDValue Value = ST->getValue();
11627   if (Value.getOpcode() == ISD::TargetConstantFP)
11628     return SDValue();
11629
11630   SDLoc DL(ST);
11631
11632   SDValue Chain = ST->getChain();
11633   SDValue Ptr = ST->getBasePtr();
11634
11635   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11636
11637   // NOTE: If the original store is volatile, this transform must not increase
11638   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11639   // processor operation but an i64 (which is not legal) requires two.  So the
11640   // transform should not be done in this case.
11641
11642   SDValue Tmp;
11643   switch (CFP->getSimpleValueType(0).SimpleTy) {
11644   default:
11645     llvm_unreachable("Unknown FP type");
11646   case MVT::f16:    // We don't do this for these yet.
11647   case MVT::f80:
11648   case MVT::f128:
11649   case MVT::ppcf128:
11650     return SDValue();
11651   case MVT::f32:
11652     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11653         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11654       ;
11655       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11656                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11657                             MVT::i32);
11658       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11659     }
11660
11661     return SDValue();
11662   case MVT::f64:
11663     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11664          !ST->isVolatile()) ||
11665         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11666       ;
11667       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11668                             getZExtValue(), SDLoc(CFP), MVT::i64);
11669       return DAG.getStore(Chain, DL, Tmp,
11670                           Ptr, ST->getMemOperand());
11671     }
11672
11673     if (!ST->isVolatile() &&
11674         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11675       // Many FP stores are not made apparent until after legalize, e.g. for
11676       // argument passing.  Since this is so common, custom legalize the
11677       // 64-bit integer store into two 32-bit stores.
11678       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11679       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11680       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11681       if (DAG.getDataLayout().isBigEndian())
11682         std::swap(Lo, Hi);
11683
11684       unsigned Alignment = ST->getAlignment();
11685       bool isVolatile = ST->isVolatile();
11686       bool isNonTemporal = ST->isNonTemporal();
11687       AAMDNodes AAInfo = ST->getAAInfo();
11688
11689       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11690                                  Ptr, ST->getPointerInfo(),
11691                                  isVolatile, isNonTemporal,
11692                                  ST->getAlignment(), AAInfo);
11693       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11694                         DAG.getConstant(4, DL, Ptr.getValueType()));
11695       Alignment = MinAlign(Alignment, 4U);
11696       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11697                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11698                                  isVolatile, isNonTemporal,
11699                                  Alignment, AAInfo);
11700       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11701                          St0, St1);
11702     }
11703
11704     return SDValue();
11705   }
11706 }
11707
11708 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11709   StoreSDNode *ST  = cast<StoreSDNode>(N);
11710   SDValue Chain = ST->getChain();
11711   SDValue Value = ST->getValue();
11712   SDValue Ptr   = ST->getBasePtr();
11713
11714   // If this is a store of a bit convert, store the input value if the
11715   // resultant store does not need a higher alignment than the original.
11716   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11717       ST->isUnindexed()) {
11718     unsigned OrigAlign = ST->getAlignment();
11719     EVT SVT = Value.getOperand(0).getValueType();
11720     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11721         SVT.getTypeForEVT(*DAG.getContext()));
11722     if (Align <= OrigAlign &&
11723         ((!LegalOperations && !ST->isVolatile()) ||
11724          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11725       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11726                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11727                           ST->isNonTemporal(), OrigAlign,
11728                           ST->getAAInfo());
11729   }
11730
11731   // Turn 'store undef, Ptr' -> nothing.
11732   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11733     return Chain;
11734
11735   // Try to infer better alignment information than the store already has.
11736   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11737     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11738       if (Align > ST->getAlignment()) {
11739         SDValue NewStore =
11740                DAG.getTruncStore(Chain, SDLoc(N), Value,
11741                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11742                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11743                                  ST->getAAInfo());
11744         if (NewStore.getNode() != N)
11745           return CombineTo(ST, NewStore, true);
11746       }
11747     }
11748   }
11749
11750   // Try transforming a pair floating point load / store ops to integer
11751   // load / store ops.
11752   if (SDValue NewST = TransformFPLoadStorePair(N))
11753     return NewST;
11754
11755   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11756                                                   : DAG.getSubtarget().useAA();
11757 #ifndef NDEBUG
11758   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11759       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11760     UseAA = false;
11761 #endif
11762   if (UseAA && ST->isUnindexed()) {
11763     // FIXME: We should do this even without AA enabled. AA will just allow
11764     // FindBetterChain to work in more situations. The problem with this is that
11765     // any combine that expects memory operations to be on consecutive chains
11766     // first needs to be updated to look for users of the same chain.
11767
11768     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11769     // adjacent stores.
11770     if (findBetterNeighborChains(ST)) {
11771       // replaceStoreChain uses CombineTo, which handled all of the worklist
11772       // manipulation. Return the original node to not do anything else.
11773       return SDValue(ST, 0);
11774     }
11775   }
11776
11777   // Try transforming N to an indexed store.
11778   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11779     return SDValue(N, 0);
11780
11781   // FIXME: is there such a thing as a truncating indexed store?
11782   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11783       Value.getValueType().isInteger()) {
11784     // See if we can simplify the input to this truncstore with knowledge that
11785     // only the low bits are being used.  For example:
11786     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11787     SDValue Shorter =
11788       GetDemandedBits(Value,
11789                       APInt::getLowBitsSet(
11790                         Value.getValueType().getScalarType().getSizeInBits(),
11791                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11792     AddToWorklist(Value.getNode());
11793     if (Shorter.getNode())
11794       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11795                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11796
11797     // Otherwise, see if we can simplify the operation with
11798     // SimplifyDemandedBits, which only works if the value has a single use.
11799     if (SimplifyDemandedBits(Value,
11800                         APInt::getLowBitsSet(
11801                           Value.getValueType().getScalarType().getSizeInBits(),
11802                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11803       return SDValue(N, 0);
11804   }
11805
11806   // If this is a load followed by a store to the same location, then the store
11807   // is dead/noop.
11808   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11809     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11810         ST->isUnindexed() && !ST->isVolatile() &&
11811         // There can't be any side effects between the load and store, such as
11812         // a call or store.
11813         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11814       // The store is dead, remove it.
11815       return Chain;
11816     }
11817   }
11818
11819   // If this is a store followed by a store with the same value to the same
11820   // location, then the store is dead/noop.
11821   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11822     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11823         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11824         ST1->isUnindexed() && !ST1->isVolatile()) {
11825       // The store is dead, remove it.
11826       return Chain;
11827     }
11828   }
11829
11830   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11831   // truncating store.  We can do this even if this is already a truncstore.
11832   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11833       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11834       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11835                             ST->getMemoryVT())) {
11836     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11837                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11838   }
11839
11840   // Only perform this optimization before the types are legal, because we
11841   // don't want to perform this optimization on every DAGCombine invocation.
11842   if (!LegalTypes) {
11843     bool EverChanged = false;
11844
11845     do {
11846       // There can be multiple store sequences on the same chain.
11847       // Keep trying to merge store sequences until we are unable to do so
11848       // or until we merge the last store on the chain.
11849       bool Changed = MergeConsecutiveStores(ST);
11850       EverChanged |= Changed;
11851       if (!Changed) break;
11852     } while (ST->getOpcode() != ISD::DELETED_NODE);
11853
11854     if (EverChanged)
11855       return SDValue(N, 0);
11856   }
11857
11858   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11859   //
11860   // Make sure to do this only after attempting to merge stores in order to
11861   //  avoid changing the types of some subset of stores due to visit order,
11862   //  preventing their merging.
11863   if (isa<ConstantFPSDNode>(Value)) {
11864     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11865       return NewSt;
11866   }
11867
11868   return ReduceLoadOpStoreWidth(N);
11869 }
11870
11871 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11872   SDValue InVec = N->getOperand(0);
11873   SDValue InVal = N->getOperand(1);
11874   SDValue EltNo = N->getOperand(2);
11875   SDLoc dl(N);
11876
11877   // If the inserted element is an UNDEF, just use the input vector.
11878   if (InVal.getOpcode() == ISD::UNDEF)
11879     return InVec;
11880
11881   EVT VT = InVec.getValueType();
11882
11883   // If we can't generate a legal BUILD_VECTOR, exit
11884   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11885     return SDValue();
11886
11887   // Check that we know which element is being inserted
11888   if (!isa<ConstantSDNode>(EltNo))
11889     return SDValue();
11890   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11891
11892   // Canonicalize insert_vector_elt dag nodes.
11893   // Example:
11894   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11895   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11896   //
11897   // Do this only if the child insert_vector node has one use; also
11898   // do this only if indices are both constants and Idx1 < Idx0.
11899   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11900       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11901     unsigned OtherElt =
11902       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11903     if (Elt < OtherElt) {
11904       // Swap nodes.
11905       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11906                                   InVec.getOperand(0), InVal, EltNo);
11907       AddToWorklist(NewOp.getNode());
11908       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11909                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11910     }
11911   }
11912
11913   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11914   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11915   // vector elements.
11916   SmallVector<SDValue, 8> Ops;
11917   // Do not combine these two vectors if the output vector will not replace
11918   // the input vector.
11919   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11920     Ops.append(InVec.getNode()->op_begin(),
11921                InVec.getNode()->op_end());
11922   } else if (InVec.getOpcode() == ISD::UNDEF) {
11923     unsigned NElts = VT.getVectorNumElements();
11924     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11925   } else {
11926     return SDValue();
11927   }
11928
11929   // Insert the element
11930   if (Elt < Ops.size()) {
11931     // All the operands of BUILD_VECTOR must have the same type;
11932     // we enforce that here.
11933     EVT OpVT = Ops[0].getValueType();
11934     if (InVal.getValueType() != OpVT)
11935       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11936                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11937                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11938     Ops[Elt] = InVal;
11939   }
11940
11941   // Return the new vector
11942   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11943 }
11944
11945 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11946     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11947   EVT ResultVT = EVE->getValueType(0);
11948   EVT VecEltVT = InVecVT.getVectorElementType();
11949   unsigned Align = OriginalLoad->getAlignment();
11950   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11951       VecEltVT.getTypeForEVT(*DAG.getContext()));
11952
11953   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11954     return SDValue();
11955
11956   Align = NewAlign;
11957
11958   SDValue NewPtr = OriginalLoad->getBasePtr();
11959   SDValue Offset;
11960   EVT PtrType = NewPtr.getValueType();
11961   MachinePointerInfo MPI;
11962   SDLoc DL(EVE);
11963   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11964     int Elt = ConstEltNo->getZExtValue();
11965     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11966     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11967     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11968   } else {
11969     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11970     Offset = DAG.getNode(
11971         ISD::MUL, DL, PtrType, Offset,
11972         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11973     MPI = OriginalLoad->getPointerInfo();
11974   }
11975   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11976
11977   // The replacement we need to do here is a little tricky: we need to
11978   // replace an extractelement of a load with a load.
11979   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11980   // Note that this replacement assumes that the extractvalue is the only
11981   // use of the load; that's okay because we don't want to perform this
11982   // transformation in other cases anyway.
11983   SDValue Load;
11984   SDValue Chain;
11985   if (ResultVT.bitsGT(VecEltVT)) {
11986     // If the result type of vextract is wider than the load, then issue an
11987     // extending load instead.
11988     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11989                                                   VecEltVT)
11990                                    ? ISD::ZEXTLOAD
11991                                    : ISD::EXTLOAD;
11992     Load = DAG.getExtLoad(
11993         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11994         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11995         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11996     Chain = Load.getValue(1);
11997   } else {
11998     Load = DAG.getLoad(
11999         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12000         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12001         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12002     Chain = Load.getValue(1);
12003     if (ResultVT.bitsLT(VecEltVT))
12004       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12005     else
12006       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12007   }
12008   WorklistRemover DeadNodes(*this);
12009   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12010   SDValue To[] = { Load, Chain };
12011   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12012   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12013   // worklist explicitly as well.
12014   AddToWorklist(Load.getNode());
12015   AddUsersToWorklist(Load.getNode()); // Add users too
12016   // Make sure to revisit this node to clean it up; it will usually be dead.
12017   AddToWorklist(EVE);
12018   ++OpsNarrowed;
12019   return SDValue(EVE, 0);
12020 }
12021
12022 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12023   // (vextract (scalar_to_vector val, 0) -> val
12024   SDValue InVec = N->getOperand(0);
12025   EVT VT = InVec.getValueType();
12026   EVT NVT = N->getValueType(0);
12027
12028   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12029     // Check if the result type doesn't match the inserted element type. A
12030     // SCALAR_TO_VECTOR may truncate the inserted element and the
12031     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12032     SDValue InOp = InVec.getOperand(0);
12033     if (InOp.getValueType() != NVT) {
12034       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12035       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12036     }
12037     return InOp;
12038   }
12039
12040   SDValue EltNo = N->getOperand(1);
12041   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12042
12043   // extract_vector_elt (build_vector x, y), 1 -> y
12044   if (ConstEltNo &&
12045       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12046       TLI.isTypeLegal(VT) &&
12047       (InVec.hasOneUse() ||
12048        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12049     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12050     EVT InEltVT = Elt.getValueType();
12051
12052     // Sometimes build_vector's scalar input types do not match result type.
12053     if (NVT == InEltVT)
12054       return Elt;
12055
12056     // TODO: It may be useful to truncate if free if the build_vector implicitly
12057     // converts.
12058   }
12059
12060   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12061   // We only perform this optimization before the op legalization phase because
12062   // we may introduce new vector instructions which are not backed by TD
12063   // patterns. For example on AVX, extracting elements from a wide vector
12064   // without using extract_subvector. However, if we can find an underlying
12065   // scalar value, then we can always use that.
12066   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12067     int NumElem = VT.getVectorNumElements();
12068     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12069     // Find the new index to extract from.
12070     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12071
12072     // Extracting an undef index is undef.
12073     if (OrigElt == -1)
12074       return DAG.getUNDEF(NVT);
12075
12076     // Select the right vector half to extract from.
12077     SDValue SVInVec;
12078     if (OrigElt < NumElem) {
12079       SVInVec = InVec->getOperand(0);
12080     } else {
12081       SVInVec = InVec->getOperand(1);
12082       OrigElt -= NumElem;
12083     }
12084
12085     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12086       SDValue InOp = SVInVec.getOperand(OrigElt);
12087       if (InOp.getValueType() != NVT) {
12088         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12089         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12090       }
12091
12092       return InOp;
12093     }
12094
12095     // FIXME: We should handle recursing on other vector shuffles and
12096     // scalar_to_vector here as well.
12097
12098     if (!LegalOperations) {
12099       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12100       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12101                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12102     }
12103   }
12104
12105   bool BCNumEltsChanged = false;
12106   EVT ExtVT = VT.getVectorElementType();
12107   EVT LVT = ExtVT;
12108
12109   // If the result of load has to be truncated, then it's not necessarily
12110   // profitable.
12111   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12112     return SDValue();
12113
12114   if (InVec.getOpcode() == ISD::BITCAST) {
12115     // Don't duplicate a load with other uses.
12116     if (!InVec.hasOneUse())
12117       return SDValue();
12118
12119     EVT BCVT = InVec.getOperand(0).getValueType();
12120     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12121       return SDValue();
12122     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12123       BCNumEltsChanged = true;
12124     InVec = InVec.getOperand(0);
12125     ExtVT = BCVT.getVectorElementType();
12126   }
12127
12128   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12129   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12130       ISD::isNormalLoad(InVec.getNode()) &&
12131       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12132     SDValue Index = N->getOperand(1);
12133     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12134       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12135                                                            OrigLoad);
12136   }
12137
12138   // Perform only after legalization to ensure build_vector / vector_shuffle
12139   // optimizations have already been done.
12140   if (!LegalOperations) return SDValue();
12141
12142   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12143   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12144   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12145
12146   if (ConstEltNo) {
12147     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12148
12149     LoadSDNode *LN0 = nullptr;
12150     const ShuffleVectorSDNode *SVN = nullptr;
12151     if (ISD::isNormalLoad(InVec.getNode())) {
12152       LN0 = cast<LoadSDNode>(InVec);
12153     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12154                InVec.getOperand(0).getValueType() == ExtVT &&
12155                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12156       // Don't duplicate a load with other uses.
12157       if (!InVec.hasOneUse())
12158         return SDValue();
12159
12160       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12161     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12162       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12163       // =>
12164       // (load $addr+1*size)
12165
12166       // Don't duplicate a load with other uses.
12167       if (!InVec.hasOneUse())
12168         return SDValue();
12169
12170       // If the bit convert changed the number of elements, it is unsafe
12171       // to examine the mask.
12172       if (BCNumEltsChanged)
12173         return SDValue();
12174
12175       // Select the input vector, guarding against out of range extract vector.
12176       unsigned NumElems = VT.getVectorNumElements();
12177       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12178       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12179
12180       if (InVec.getOpcode() == ISD::BITCAST) {
12181         // Don't duplicate a load with other uses.
12182         if (!InVec.hasOneUse())
12183           return SDValue();
12184
12185         InVec = InVec.getOperand(0);
12186       }
12187       if (ISD::isNormalLoad(InVec.getNode())) {
12188         LN0 = cast<LoadSDNode>(InVec);
12189         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12190         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12191       }
12192     }
12193
12194     // Make sure we found a non-volatile load and the extractelement is
12195     // the only use.
12196     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12197       return SDValue();
12198
12199     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12200     if (Elt == -1)
12201       return DAG.getUNDEF(LVT);
12202
12203     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12204   }
12205
12206   return SDValue();
12207 }
12208
12209 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12210 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12211   // We perform this optimization post type-legalization because
12212   // the type-legalizer often scalarizes integer-promoted vectors.
12213   // Performing this optimization before may create bit-casts which
12214   // will be type-legalized to complex code sequences.
12215   // We perform this optimization only before the operation legalizer because we
12216   // may introduce illegal operations.
12217   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12218     return SDValue();
12219
12220   unsigned NumInScalars = N->getNumOperands();
12221   SDLoc dl(N);
12222   EVT VT = N->getValueType(0);
12223
12224   // Check to see if this is a BUILD_VECTOR of a bunch of values
12225   // which come from any_extend or zero_extend nodes. If so, we can create
12226   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12227   // optimizations. We do not handle sign-extend because we can't fill the sign
12228   // using shuffles.
12229   EVT SourceType = MVT::Other;
12230   bool AllAnyExt = true;
12231
12232   for (unsigned i = 0; i != NumInScalars; ++i) {
12233     SDValue In = N->getOperand(i);
12234     // Ignore undef inputs.
12235     if (In.getOpcode() == ISD::UNDEF) continue;
12236
12237     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12238     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12239
12240     // Abort if the element is not an extension.
12241     if (!ZeroExt && !AnyExt) {
12242       SourceType = MVT::Other;
12243       break;
12244     }
12245
12246     // The input is a ZeroExt or AnyExt. Check the original type.
12247     EVT InTy = In.getOperand(0).getValueType();
12248
12249     // Check that all of the widened source types are the same.
12250     if (SourceType == MVT::Other)
12251       // First time.
12252       SourceType = InTy;
12253     else if (InTy != SourceType) {
12254       // Multiple income types. Abort.
12255       SourceType = MVT::Other;
12256       break;
12257     }
12258
12259     // Check if all of the extends are ANY_EXTENDs.
12260     AllAnyExt &= AnyExt;
12261   }
12262
12263   // In order to have valid types, all of the inputs must be extended from the
12264   // same source type and all of the inputs must be any or zero extend.
12265   // Scalar sizes must be a power of two.
12266   EVT OutScalarTy = VT.getScalarType();
12267   bool ValidTypes = SourceType != MVT::Other &&
12268                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12269                  isPowerOf2_32(SourceType.getSizeInBits());
12270
12271   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12272   // turn into a single shuffle instruction.
12273   if (!ValidTypes)
12274     return SDValue();
12275
12276   bool isLE = DAG.getDataLayout().isLittleEndian();
12277   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12278   assert(ElemRatio > 1 && "Invalid element size ratio");
12279   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12280                                DAG.getConstant(0, SDLoc(N), SourceType);
12281
12282   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12283   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12284
12285   // Populate the new build_vector
12286   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12287     SDValue Cast = N->getOperand(i);
12288     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12289             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12290             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12291     SDValue In;
12292     if (Cast.getOpcode() == ISD::UNDEF)
12293       In = DAG.getUNDEF(SourceType);
12294     else
12295       In = Cast->getOperand(0);
12296     unsigned Index = isLE ? (i * ElemRatio) :
12297                             (i * ElemRatio + (ElemRatio - 1));
12298
12299     assert(Index < Ops.size() && "Invalid index");
12300     Ops[Index] = In;
12301   }
12302
12303   // The type of the new BUILD_VECTOR node.
12304   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12305   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12306          "Invalid vector size");
12307   // Check if the new vector type is legal.
12308   if (!isTypeLegal(VecVT)) return SDValue();
12309
12310   // Make the new BUILD_VECTOR.
12311   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12312
12313   // The new BUILD_VECTOR node has the potential to be further optimized.
12314   AddToWorklist(BV.getNode());
12315   // Bitcast to the desired type.
12316   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12317 }
12318
12319 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12320   EVT VT = N->getValueType(0);
12321
12322   unsigned NumInScalars = N->getNumOperands();
12323   SDLoc dl(N);
12324
12325   EVT SrcVT = MVT::Other;
12326   unsigned Opcode = ISD::DELETED_NODE;
12327   unsigned NumDefs = 0;
12328
12329   for (unsigned i = 0; i != NumInScalars; ++i) {
12330     SDValue In = N->getOperand(i);
12331     unsigned Opc = In.getOpcode();
12332
12333     if (Opc == ISD::UNDEF)
12334       continue;
12335
12336     // If all scalar values are floats and converted from integers.
12337     if (Opcode == ISD::DELETED_NODE &&
12338         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12339       Opcode = Opc;
12340     }
12341
12342     if (Opc != Opcode)
12343       return SDValue();
12344
12345     EVT InVT = In.getOperand(0).getValueType();
12346
12347     // If all scalar values are typed differently, bail out. It's chosen to
12348     // simplify BUILD_VECTOR of integer types.
12349     if (SrcVT == MVT::Other)
12350       SrcVT = InVT;
12351     if (SrcVT != InVT)
12352       return SDValue();
12353     NumDefs++;
12354   }
12355
12356   // If the vector has just one element defined, it's not worth to fold it into
12357   // a vectorized one.
12358   if (NumDefs < 2)
12359     return SDValue();
12360
12361   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12362          && "Should only handle conversion from integer to float.");
12363   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12364
12365   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12366
12367   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12368     return SDValue();
12369
12370   // Just because the floating-point vector type is legal does not necessarily
12371   // mean that the corresponding integer vector type is.
12372   if (!isTypeLegal(NVT))
12373     return SDValue();
12374
12375   SmallVector<SDValue, 8> Opnds;
12376   for (unsigned i = 0; i != NumInScalars; ++i) {
12377     SDValue In = N->getOperand(i);
12378
12379     if (In.getOpcode() == ISD::UNDEF)
12380       Opnds.push_back(DAG.getUNDEF(SrcVT));
12381     else
12382       Opnds.push_back(In.getOperand(0));
12383   }
12384   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12385   AddToWorklist(BV.getNode());
12386
12387   return DAG.getNode(Opcode, dl, VT, BV);
12388 }
12389
12390 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12391   unsigned NumInScalars = N->getNumOperands();
12392   SDLoc dl(N);
12393   EVT VT = N->getValueType(0);
12394
12395   // A vector built entirely of undefs is undef.
12396   if (ISD::allOperandsUndef(N))
12397     return DAG.getUNDEF(VT);
12398
12399   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12400     return V;
12401
12402   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12403     return V;
12404
12405   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12406   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12407   // at most two distinct vectors, turn this into a shuffle node.
12408
12409   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12410   if (!isTypeLegal(VT))
12411     return SDValue();
12412
12413   // May only combine to shuffle after legalize if shuffle is legal.
12414   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12415     return SDValue();
12416
12417   SDValue VecIn1, VecIn2;
12418   bool UsesZeroVector = false;
12419   for (unsigned i = 0; i != NumInScalars; ++i) {
12420     SDValue Op = N->getOperand(i);
12421     // Ignore undef inputs.
12422     if (Op.getOpcode() == ISD::UNDEF) continue;
12423
12424     // See if we can combine this build_vector into a blend with a zero vector.
12425     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12426       UsesZeroVector = true;
12427       continue;
12428     }
12429
12430     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12431     // constant index, bail out.
12432     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12433         !isa<ConstantSDNode>(Op.getOperand(1))) {
12434       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12435       break;
12436     }
12437
12438     // We allow up to two distinct input vectors.
12439     SDValue ExtractedFromVec = Op.getOperand(0);
12440     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12441       continue;
12442
12443     if (!VecIn1.getNode()) {
12444       VecIn1 = ExtractedFromVec;
12445     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12446       VecIn2 = ExtractedFromVec;
12447     } else {
12448       // Too many inputs.
12449       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12450       break;
12451     }
12452   }
12453
12454   // If everything is good, we can make a shuffle operation.
12455   if (VecIn1.getNode()) {
12456     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12457     SmallVector<int, 8> Mask;
12458     for (unsigned i = 0; i != NumInScalars; ++i) {
12459       unsigned Opcode = N->getOperand(i).getOpcode();
12460       if (Opcode == ISD::UNDEF) {
12461         Mask.push_back(-1);
12462         continue;
12463       }
12464
12465       // Operands can also be zero.
12466       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12467         assert(UsesZeroVector &&
12468                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12469                "Unexpected node found!");
12470         Mask.push_back(NumInScalars+i);
12471         continue;
12472       }
12473
12474       // If extracting from the first vector, just use the index directly.
12475       SDValue Extract = N->getOperand(i);
12476       SDValue ExtVal = Extract.getOperand(1);
12477       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12478       if (Extract.getOperand(0) == VecIn1) {
12479         Mask.push_back(ExtIndex);
12480         continue;
12481       }
12482
12483       // Otherwise, use InIdx + InputVecSize
12484       Mask.push_back(InNumElements + ExtIndex);
12485     }
12486
12487     // Avoid introducing illegal shuffles with zero.
12488     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12489       return SDValue();
12490
12491     // We can't generate a shuffle node with mismatched input and output types.
12492     // Attempt to transform a single input vector to the correct type.
12493     if ((VT != VecIn1.getValueType())) {
12494       // If the input vector type has a different base type to the output
12495       // vector type, bail out.
12496       EVT VTElemType = VT.getVectorElementType();
12497       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12498           (VecIn2.getNode() &&
12499            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12500         return SDValue();
12501
12502       // If the input vector is too small, widen it.
12503       // We only support widening of vectors which are half the size of the
12504       // output registers. For example XMM->YMM widening on X86 with AVX.
12505       EVT VecInT = VecIn1.getValueType();
12506       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12507         // If we only have one small input, widen it by adding undef values.
12508         if (!VecIn2.getNode())
12509           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12510                                DAG.getUNDEF(VecIn1.getValueType()));
12511         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12512           // If we have two small inputs of the same type, try to concat them.
12513           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12514           VecIn2 = SDValue(nullptr, 0);
12515         } else
12516           return SDValue();
12517       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12518         // If the input vector is too large, try to split it.
12519         // We don't support having two input vectors that are too large.
12520         // If the zero vector was used, we can not split the vector,
12521         // since we'd need 3 inputs.
12522         if (UsesZeroVector || VecIn2.getNode())
12523           return SDValue();
12524
12525         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12526           return SDValue();
12527
12528         // Try to replace VecIn1 with two extract_subvectors
12529         // No need to update the masks, they should still be correct.
12530         VecIn2 = DAG.getNode(
12531             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12532             DAG.getConstant(VT.getVectorNumElements(), dl,
12533                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12534         VecIn1 = DAG.getNode(
12535             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12536             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12537       } else
12538         return SDValue();
12539     }
12540
12541     if (UsesZeroVector)
12542       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12543                                 DAG.getConstantFP(0.0, dl, VT);
12544     else
12545       // If VecIn2 is unused then change it to undef.
12546       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12547
12548     // Check that we were able to transform all incoming values to the same
12549     // type.
12550     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12551         VecIn1.getValueType() != VT)
12552           return SDValue();
12553
12554     // Return the new VECTOR_SHUFFLE node.
12555     SDValue Ops[2];
12556     Ops[0] = VecIn1;
12557     Ops[1] = VecIn2;
12558     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12559   }
12560
12561   return SDValue();
12562 }
12563
12564 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12565   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12566   EVT OpVT = N->getOperand(0).getValueType();
12567
12568   // If the operands are legal vectors, leave them alone.
12569   if (TLI.isTypeLegal(OpVT))
12570     return SDValue();
12571
12572   SDLoc DL(N);
12573   EVT VT = N->getValueType(0);
12574   SmallVector<SDValue, 8> Ops;
12575
12576   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12577   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12578
12579   // Keep track of what we encounter.
12580   bool AnyInteger = false;
12581   bool AnyFP = false;
12582   for (const SDValue &Op : N->ops()) {
12583     if (ISD::BITCAST == Op.getOpcode() &&
12584         !Op.getOperand(0).getValueType().isVector())
12585       Ops.push_back(Op.getOperand(0));
12586     else if (ISD::UNDEF == Op.getOpcode())
12587       Ops.push_back(ScalarUndef);
12588     else
12589       return SDValue();
12590
12591     // Note whether we encounter an integer or floating point scalar.
12592     // If it's neither, bail out, it could be something weird like x86mmx.
12593     EVT LastOpVT = Ops.back().getValueType();
12594     if (LastOpVT.isFloatingPoint())
12595       AnyFP = true;
12596     else if (LastOpVT.isInteger())
12597       AnyInteger = true;
12598     else
12599       return SDValue();
12600   }
12601
12602   // If any of the operands is a floating point scalar bitcast to a vector,
12603   // use floating point types throughout, and bitcast everything.
12604   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12605   if (AnyFP) {
12606     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12607     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12608     if (AnyInteger) {
12609       for (SDValue &Op : Ops) {
12610         if (Op.getValueType() == SVT)
12611           continue;
12612         if (Op.getOpcode() == ISD::UNDEF)
12613           Op = ScalarUndef;
12614         else
12615           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12616       }
12617     }
12618   }
12619
12620   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12621                                VT.getSizeInBits() / SVT.getSizeInBits());
12622   return DAG.getNode(ISD::BITCAST, DL, VT,
12623                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12624 }
12625
12626 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12627 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12628 // most two distinct vectors the same size as the result, attempt to turn this
12629 // into a legal shuffle.
12630 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12631   EVT VT = N->getValueType(0);
12632   EVT OpVT = N->getOperand(0).getValueType();
12633   int NumElts = VT.getVectorNumElements();
12634   int NumOpElts = OpVT.getVectorNumElements();
12635
12636   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12637   SmallVector<int, 8> Mask;
12638
12639   for (SDValue Op : N->ops()) {
12640     // Peek through any bitcast.
12641     while (Op.getOpcode() == ISD::BITCAST)
12642       Op = Op.getOperand(0);
12643
12644     // UNDEF nodes convert to UNDEF shuffle mask values.
12645     if (Op.getOpcode() == ISD::UNDEF) {
12646       Mask.append((unsigned)NumOpElts, -1);
12647       continue;
12648     }
12649
12650     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12651       return SDValue();
12652
12653     // What vector are we extracting the subvector from and at what index?
12654     SDValue ExtVec = Op.getOperand(0);
12655
12656     // We want the EVT of the original extraction to correctly scale the
12657     // extraction index.
12658     EVT ExtVT = ExtVec.getValueType();
12659
12660     // Peek through any bitcast.
12661     while (ExtVec.getOpcode() == ISD::BITCAST)
12662       ExtVec = ExtVec.getOperand(0);
12663
12664     // UNDEF nodes convert to UNDEF shuffle mask values.
12665     if (ExtVec.getOpcode() == ISD::UNDEF) {
12666       Mask.append((unsigned)NumOpElts, -1);
12667       continue;
12668     }
12669
12670     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12671       return SDValue();
12672     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12673
12674     // Ensure that we are extracting a subvector from a vector the same
12675     // size as the result.
12676     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12677       return SDValue();
12678
12679     // Scale the subvector index to account for any bitcast.
12680     int NumExtElts = ExtVT.getVectorNumElements();
12681     if (0 == (NumExtElts % NumElts))
12682       ExtIdx /= (NumExtElts / NumElts);
12683     else if (0 == (NumElts % NumExtElts))
12684       ExtIdx *= (NumElts / NumExtElts);
12685     else
12686       return SDValue();
12687
12688     // At most we can reference 2 inputs in the final shuffle.
12689     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12690       SV0 = ExtVec;
12691       for (int i = 0; i != NumOpElts; ++i)
12692         Mask.push_back(i + ExtIdx);
12693     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12694       SV1 = ExtVec;
12695       for (int i = 0; i != NumOpElts; ++i)
12696         Mask.push_back(i + ExtIdx + NumElts);
12697     } else {
12698       return SDValue();
12699     }
12700   }
12701
12702   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12703     return SDValue();
12704
12705   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12706                               DAG.getBitcast(VT, SV1), Mask);
12707 }
12708
12709 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12710   // If we only have one input vector, we don't need to do any concatenation.
12711   if (N->getNumOperands() == 1)
12712     return N->getOperand(0);
12713
12714   // Check if all of the operands are undefs.
12715   EVT VT = N->getValueType(0);
12716   if (ISD::allOperandsUndef(N))
12717     return DAG.getUNDEF(VT);
12718
12719   // Optimize concat_vectors where all but the first of the vectors are undef.
12720   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12721         return Op.getOpcode() == ISD::UNDEF;
12722       })) {
12723     SDValue In = N->getOperand(0);
12724     assert(In.getValueType().isVector() && "Must concat vectors");
12725
12726     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12727     if (In->getOpcode() == ISD::BITCAST &&
12728         !In->getOperand(0)->getValueType(0).isVector()) {
12729       SDValue Scalar = In->getOperand(0);
12730
12731       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12732       // look through the trunc so we can still do the transform:
12733       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12734       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12735           !TLI.isTypeLegal(Scalar.getValueType()) &&
12736           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12737         Scalar = Scalar->getOperand(0);
12738
12739       EVT SclTy = Scalar->getValueType(0);
12740
12741       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12742         return SDValue();
12743
12744       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12745                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12746       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12747         return SDValue();
12748
12749       SDLoc dl = SDLoc(N);
12750       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12751       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12752     }
12753   }
12754
12755   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12756   // We have already tested above for an UNDEF only concatenation.
12757   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12758   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12759   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12760     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12761   };
12762   bool AllBuildVectorsOrUndefs =
12763       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12764   if (AllBuildVectorsOrUndefs) {
12765     SmallVector<SDValue, 8> Opnds;
12766     EVT SVT = VT.getScalarType();
12767
12768     EVT MinVT = SVT;
12769     if (!SVT.isFloatingPoint()) {
12770       // If BUILD_VECTOR are from built from integer, they may have different
12771       // operand types. Get the smallest type and truncate all operands to it.
12772       bool FoundMinVT = false;
12773       for (const SDValue &Op : N->ops())
12774         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12775           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12776           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12777           FoundMinVT = true;
12778         }
12779       assert(FoundMinVT && "Concat vector type mismatch");
12780     }
12781
12782     for (const SDValue &Op : N->ops()) {
12783       EVT OpVT = Op.getValueType();
12784       unsigned NumElts = OpVT.getVectorNumElements();
12785
12786       if (ISD::UNDEF == Op.getOpcode())
12787         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12788
12789       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12790         if (SVT.isFloatingPoint()) {
12791           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12792           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12793         } else {
12794           for (unsigned i = 0; i != NumElts; ++i)
12795             Opnds.push_back(
12796                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12797         }
12798       }
12799     }
12800
12801     assert(VT.getVectorNumElements() == Opnds.size() &&
12802            "Concat vector type mismatch");
12803     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12804   }
12805
12806   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12807   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12808     return V;
12809
12810   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12811   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12812     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12813       return V;
12814
12815   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12816   // nodes often generate nop CONCAT_VECTOR nodes.
12817   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12818   // place the incoming vectors at the exact same location.
12819   SDValue SingleSource = SDValue();
12820   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12821
12822   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12823     SDValue Op = N->getOperand(i);
12824
12825     if (Op.getOpcode() == ISD::UNDEF)
12826       continue;
12827
12828     // Check if this is the identity extract:
12829     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12830       return SDValue();
12831
12832     // Find the single incoming vector for the extract_subvector.
12833     if (SingleSource.getNode()) {
12834       if (Op.getOperand(0) != SingleSource)
12835         return SDValue();
12836     } else {
12837       SingleSource = Op.getOperand(0);
12838
12839       // Check the source type is the same as the type of the result.
12840       // If not, this concat may extend the vector, so we can not
12841       // optimize it away.
12842       if (SingleSource.getValueType() != N->getValueType(0))
12843         return SDValue();
12844     }
12845
12846     unsigned IdentityIndex = i * PartNumElem;
12847     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12848     // The extract index must be constant.
12849     if (!CS)
12850       return SDValue();
12851
12852     // Check that we are reading from the identity index.
12853     if (CS->getZExtValue() != IdentityIndex)
12854       return SDValue();
12855   }
12856
12857   if (SingleSource.getNode())
12858     return SingleSource;
12859
12860   return SDValue();
12861 }
12862
12863 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12864   EVT NVT = N->getValueType(0);
12865   SDValue V = N->getOperand(0);
12866
12867   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12868     // Combine:
12869     //    (extract_subvec (concat V1, V2, ...), i)
12870     // Into:
12871     //    Vi if possible
12872     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12873     // type.
12874     if (V->getOperand(0).getValueType() != NVT)
12875       return SDValue();
12876     unsigned Idx = N->getConstantOperandVal(1);
12877     unsigned NumElems = NVT.getVectorNumElements();
12878     assert((Idx % NumElems) == 0 &&
12879            "IDX in concat is not a multiple of the result vector length.");
12880     return V->getOperand(Idx / NumElems);
12881   }
12882
12883   // Skip bitcasting
12884   if (V->getOpcode() == ISD::BITCAST)
12885     V = V.getOperand(0);
12886
12887   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12888     SDLoc dl(N);
12889     // Handle only simple case where vector being inserted and vector
12890     // being extracted are of same type, and are half size of larger vectors.
12891     EVT BigVT = V->getOperand(0).getValueType();
12892     EVT SmallVT = V->getOperand(1).getValueType();
12893     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12894       return SDValue();
12895
12896     // Only handle cases where both indexes are constants with the same type.
12897     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12898     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12899
12900     if (InsIdx && ExtIdx &&
12901         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12902         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12903       // Combine:
12904       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12905       // Into:
12906       //    indices are equal or bit offsets are equal => V1
12907       //    otherwise => (extract_subvec V1, ExtIdx)
12908       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12909           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12910         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12911       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12912                          DAG.getNode(ISD::BITCAST, dl,
12913                                      N->getOperand(0).getValueType(),
12914                                      V->getOperand(0)), N->getOperand(1));
12915     }
12916   }
12917
12918   return SDValue();
12919 }
12920
12921 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12922                                                  SDValue V, SelectionDAG &DAG) {
12923   SDLoc DL(V);
12924   EVT VT = V.getValueType();
12925
12926   switch (V.getOpcode()) {
12927   default:
12928     return V;
12929
12930   case ISD::CONCAT_VECTORS: {
12931     EVT OpVT = V->getOperand(0).getValueType();
12932     int OpSize = OpVT.getVectorNumElements();
12933     SmallBitVector OpUsedElements(OpSize, false);
12934     bool FoundSimplification = false;
12935     SmallVector<SDValue, 4> NewOps;
12936     NewOps.reserve(V->getNumOperands());
12937     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12938       SDValue Op = V->getOperand(i);
12939       bool OpUsed = false;
12940       for (int j = 0; j < OpSize; ++j)
12941         if (UsedElements[i * OpSize + j]) {
12942           OpUsedElements[j] = true;
12943           OpUsed = true;
12944         }
12945       NewOps.push_back(
12946           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12947                  : DAG.getUNDEF(OpVT));
12948       FoundSimplification |= Op == NewOps.back();
12949       OpUsedElements.reset();
12950     }
12951     if (FoundSimplification)
12952       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12953     return V;
12954   }
12955
12956   case ISD::INSERT_SUBVECTOR: {
12957     SDValue BaseV = V->getOperand(0);
12958     SDValue SubV = V->getOperand(1);
12959     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12960     if (!IdxN)
12961       return V;
12962
12963     int SubSize = SubV.getValueType().getVectorNumElements();
12964     int Idx = IdxN->getZExtValue();
12965     bool SubVectorUsed = false;
12966     SmallBitVector SubUsedElements(SubSize, false);
12967     for (int i = 0; i < SubSize; ++i)
12968       if (UsedElements[i + Idx]) {
12969         SubVectorUsed = true;
12970         SubUsedElements[i] = true;
12971         UsedElements[i + Idx] = false;
12972       }
12973
12974     // Now recurse on both the base and sub vectors.
12975     SDValue SimplifiedSubV =
12976         SubVectorUsed
12977             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12978             : DAG.getUNDEF(SubV.getValueType());
12979     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12980     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12981       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12982                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12983     return V;
12984   }
12985   }
12986 }
12987
12988 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12989                                        SDValue N1, SelectionDAG &DAG) {
12990   EVT VT = SVN->getValueType(0);
12991   int NumElts = VT.getVectorNumElements();
12992   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12993   for (int M : SVN->getMask())
12994     if (M >= 0 && M < NumElts)
12995       N0UsedElements[M] = true;
12996     else if (M >= NumElts)
12997       N1UsedElements[M - NumElts] = true;
12998
12999   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13000   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13001   if (S0 == N0 && S1 == N1)
13002     return SDValue();
13003
13004   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13005 }
13006
13007 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13008 // or turn a shuffle of a single concat into simpler shuffle then concat.
13009 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13010   EVT VT = N->getValueType(0);
13011   unsigned NumElts = VT.getVectorNumElements();
13012
13013   SDValue N0 = N->getOperand(0);
13014   SDValue N1 = N->getOperand(1);
13015   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13016
13017   SmallVector<SDValue, 4> Ops;
13018   EVT ConcatVT = N0.getOperand(0).getValueType();
13019   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13020   unsigned NumConcats = NumElts / NumElemsPerConcat;
13021
13022   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13023   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13024   // half vector elements.
13025   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13026       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13027                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13028     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13029                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13030     N1 = DAG.getUNDEF(ConcatVT);
13031     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13032   }
13033
13034   // Look at every vector that's inserted. We're looking for exact
13035   // subvector-sized copies from a concatenated vector
13036   for (unsigned I = 0; I != NumConcats; ++I) {
13037     // Make sure we're dealing with a copy.
13038     unsigned Begin = I * NumElemsPerConcat;
13039     bool AllUndef = true, NoUndef = true;
13040     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13041       if (SVN->getMaskElt(J) >= 0)
13042         AllUndef = false;
13043       else
13044         NoUndef = false;
13045     }
13046
13047     if (NoUndef) {
13048       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13049         return SDValue();
13050
13051       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13052         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13053           return SDValue();
13054
13055       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13056       if (FirstElt < N0.getNumOperands())
13057         Ops.push_back(N0.getOperand(FirstElt));
13058       else
13059         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13060
13061     } else if (AllUndef) {
13062       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13063     } else { // Mixed with general masks and undefs, can't do optimization.
13064       return SDValue();
13065     }
13066   }
13067
13068   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13069 }
13070
13071 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13072   EVT VT = N->getValueType(0);
13073   unsigned NumElts = VT.getVectorNumElements();
13074
13075   SDValue N0 = N->getOperand(0);
13076   SDValue N1 = N->getOperand(1);
13077
13078   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13079
13080   // Canonicalize shuffle undef, undef -> undef
13081   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13082     return DAG.getUNDEF(VT);
13083
13084   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13085
13086   // Canonicalize shuffle v, v -> v, undef
13087   if (N0 == N1) {
13088     SmallVector<int, 8> NewMask;
13089     for (unsigned i = 0; i != NumElts; ++i) {
13090       int Idx = SVN->getMaskElt(i);
13091       if (Idx >= (int)NumElts) Idx -= NumElts;
13092       NewMask.push_back(Idx);
13093     }
13094     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13095                                 &NewMask[0]);
13096   }
13097
13098   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13099   if (N0.getOpcode() == ISD::UNDEF) {
13100     SmallVector<int, 8> NewMask;
13101     for (unsigned i = 0; i != NumElts; ++i) {
13102       int Idx = SVN->getMaskElt(i);
13103       if (Idx >= 0) {
13104         if (Idx >= (int)NumElts)
13105           Idx -= NumElts;
13106         else
13107           Idx = -1; // remove reference to lhs
13108       }
13109       NewMask.push_back(Idx);
13110     }
13111     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13112                                 &NewMask[0]);
13113   }
13114
13115   // Remove references to rhs if it is undef
13116   if (N1.getOpcode() == ISD::UNDEF) {
13117     bool Changed = false;
13118     SmallVector<int, 8> NewMask;
13119     for (unsigned i = 0; i != NumElts; ++i) {
13120       int Idx = SVN->getMaskElt(i);
13121       if (Idx >= (int)NumElts) {
13122         Idx = -1;
13123         Changed = true;
13124       }
13125       NewMask.push_back(Idx);
13126     }
13127     if (Changed)
13128       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13129   }
13130
13131   // If it is a splat, check if the argument vector is another splat or a
13132   // build_vector.
13133   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13134     SDNode *V = N0.getNode();
13135
13136     // If this is a bit convert that changes the element type of the vector but
13137     // not the number of vector elements, look through it.  Be careful not to
13138     // look though conversions that change things like v4f32 to v2f64.
13139     if (V->getOpcode() == ISD::BITCAST) {
13140       SDValue ConvInput = V->getOperand(0);
13141       if (ConvInput.getValueType().isVector() &&
13142           ConvInput.getValueType().getVectorNumElements() == NumElts)
13143         V = ConvInput.getNode();
13144     }
13145
13146     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13147       assert(V->getNumOperands() == NumElts &&
13148              "BUILD_VECTOR has wrong number of operands");
13149       SDValue Base;
13150       bool AllSame = true;
13151       for (unsigned i = 0; i != NumElts; ++i) {
13152         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13153           Base = V->getOperand(i);
13154           break;
13155         }
13156       }
13157       // Splat of <u, u, u, u>, return <u, u, u, u>
13158       if (!Base.getNode())
13159         return N0;
13160       for (unsigned i = 0; i != NumElts; ++i) {
13161         if (V->getOperand(i) != Base) {
13162           AllSame = false;
13163           break;
13164         }
13165       }
13166       // Splat of <x, x, x, x>, return <x, x, x, x>
13167       if (AllSame)
13168         return N0;
13169
13170       // Canonicalize any other splat as a build_vector.
13171       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13172       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13173       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13174                                   V->getValueType(0), Ops);
13175
13176       // We may have jumped through bitcasts, so the type of the
13177       // BUILD_VECTOR may not match the type of the shuffle.
13178       if (V->getValueType(0) != VT)
13179         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13180       return NewBV;
13181     }
13182   }
13183
13184   // There are various patterns used to build up a vector from smaller vectors,
13185   // subvectors, or elements. Scan chains of these and replace unused insertions
13186   // or components with undef.
13187   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13188     return S;
13189
13190   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13191       Level < AfterLegalizeVectorOps &&
13192       (N1.getOpcode() == ISD::UNDEF ||
13193       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13194        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13195     SDValue V = partitionShuffleOfConcats(N, DAG);
13196
13197     if (V.getNode())
13198       return V;
13199   }
13200
13201   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13202   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13203   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13204     SmallVector<SDValue, 8> Ops;
13205     for (int M : SVN->getMask()) {
13206       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13207       if (M >= 0) {
13208         int Idx = M % NumElts;
13209         SDValue &S = (M < (int)NumElts ? N0 : N1);
13210         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13211           Op = S.getOperand(Idx);
13212         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13213           if (Idx == 0)
13214             Op = S.getOperand(0);
13215         } else {
13216           // Operand can't be combined - bail out.
13217           break;
13218         }
13219       }
13220       Ops.push_back(Op);
13221     }
13222     if (Ops.size() == VT.getVectorNumElements()) {
13223       // BUILD_VECTOR requires all inputs to be of the same type, find the
13224       // maximum type and extend them all.
13225       EVT SVT = VT.getScalarType();
13226       if (SVT.isInteger())
13227         for (SDValue &Op : Ops)
13228           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13229       if (SVT != VT.getScalarType())
13230         for (SDValue &Op : Ops)
13231           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13232                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13233                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13234       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13235     }
13236   }
13237
13238   // If this shuffle only has a single input that is a bitcasted shuffle,
13239   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13240   // back to their original types.
13241   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13242       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13243       TLI.isTypeLegal(VT)) {
13244
13245     // Peek through the bitcast only if there is one user.
13246     SDValue BC0 = N0;
13247     while (BC0.getOpcode() == ISD::BITCAST) {
13248       if (!BC0.hasOneUse())
13249         break;
13250       BC0 = BC0.getOperand(0);
13251     }
13252
13253     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13254       if (Scale == 1)
13255         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13256
13257       SmallVector<int, 8> NewMask;
13258       for (int M : Mask)
13259         for (int s = 0; s != Scale; ++s)
13260           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13261       return NewMask;
13262     };
13263
13264     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13265       EVT SVT = VT.getScalarType();
13266       EVT InnerVT = BC0->getValueType(0);
13267       EVT InnerSVT = InnerVT.getScalarType();
13268
13269       // Determine which shuffle works with the smaller scalar type.
13270       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13271       EVT ScaleSVT = ScaleVT.getScalarType();
13272
13273       if (TLI.isTypeLegal(ScaleVT) &&
13274           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13275           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13276
13277         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13278         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13279
13280         // Scale the shuffle masks to the smaller scalar type.
13281         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13282         SmallVector<int, 8> InnerMask =
13283             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13284         SmallVector<int, 8> OuterMask =
13285             ScaleShuffleMask(SVN->getMask(), OuterScale);
13286
13287         // Merge the shuffle masks.
13288         SmallVector<int, 8> NewMask;
13289         for (int M : OuterMask)
13290           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13291
13292         // Test for shuffle mask legality over both commutations.
13293         SDValue SV0 = BC0->getOperand(0);
13294         SDValue SV1 = BC0->getOperand(1);
13295         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13296         if (!LegalMask) {
13297           std::swap(SV0, SV1);
13298           ShuffleVectorSDNode::commuteMask(NewMask);
13299           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13300         }
13301
13302         if (LegalMask) {
13303           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13304           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13305           return DAG.getNode(
13306               ISD::BITCAST, SDLoc(N), VT,
13307               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13308         }
13309       }
13310     }
13311   }
13312
13313   // Canonicalize shuffles according to rules:
13314   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13315   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13316   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13317   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13318       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13319       TLI.isTypeLegal(VT)) {
13320     // The incoming shuffle must be of the same type as the result of the
13321     // current shuffle.
13322     assert(N1->getOperand(0).getValueType() == VT &&
13323            "Shuffle types don't match");
13324
13325     SDValue SV0 = N1->getOperand(0);
13326     SDValue SV1 = N1->getOperand(1);
13327     bool HasSameOp0 = N0 == SV0;
13328     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13329     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13330       // Commute the operands of this shuffle so that next rule
13331       // will trigger.
13332       return DAG.getCommutedVectorShuffle(*SVN);
13333   }
13334
13335   // Try to fold according to rules:
13336   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13337   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13338   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13339   // Don't try to fold shuffles with illegal type.
13340   // Only fold if this shuffle is the only user of the other shuffle.
13341   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13342       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13343     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13344
13345     // The incoming shuffle must be of the same type as the result of the
13346     // current shuffle.
13347     assert(OtherSV->getOperand(0).getValueType() == VT &&
13348            "Shuffle types don't match");
13349
13350     SDValue SV0, SV1;
13351     SmallVector<int, 4> Mask;
13352     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13353     // operand, and SV1 as the second operand.
13354     for (unsigned i = 0; i != NumElts; ++i) {
13355       int Idx = SVN->getMaskElt(i);
13356       if (Idx < 0) {
13357         // Propagate Undef.
13358         Mask.push_back(Idx);
13359         continue;
13360       }
13361
13362       SDValue CurrentVec;
13363       if (Idx < (int)NumElts) {
13364         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13365         // shuffle mask to identify which vector is actually referenced.
13366         Idx = OtherSV->getMaskElt(Idx);
13367         if (Idx < 0) {
13368           // Propagate Undef.
13369           Mask.push_back(Idx);
13370           continue;
13371         }
13372
13373         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13374                                            : OtherSV->getOperand(1);
13375       } else {
13376         // This shuffle index references an element within N1.
13377         CurrentVec = N1;
13378       }
13379
13380       // Simple case where 'CurrentVec' is UNDEF.
13381       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13382         Mask.push_back(-1);
13383         continue;
13384       }
13385
13386       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13387       // will be the first or second operand of the combined shuffle.
13388       Idx = Idx % NumElts;
13389       if (!SV0.getNode() || SV0 == CurrentVec) {
13390         // Ok. CurrentVec is the left hand side.
13391         // Update the mask accordingly.
13392         SV0 = CurrentVec;
13393         Mask.push_back(Idx);
13394         continue;
13395       }
13396
13397       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13398       if (SV1.getNode() && SV1 != CurrentVec)
13399         return SDValue();
13400
13401       // Ok. CurrentVec is the right hand side.
13402       // Update the mask accordingly.
13403       SV1 = CurrentVec;
13404       Mask.push_back(Idx + NumElts);
13405     }
13406
13407     // Check if all indices in Mask are Undef. In case, propagate Undef.
13408     bool isUndefMask = true;
13409     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13410       isUndefMask &= Mask[i] < 0;
13411
13412     if (isUndefMask)
13413       return DAG.getUNDEF(VT);
13414
13415     if (!SV0.getNode())
13416       SV0 = DAG.getUNDEF(VT);
13417     if (!SV1.getNode())
13418       SV1 = DAG.getUNDEF(VT);
13419
13420     // Avoid introducing shuffles with illegal mask.
13421     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13422       ShuffleVectorSDNode::commuteMask(Mask);
13423
13424       if (!TLI.isShuffleMaskLegal(Mask, VT))
13425         return SDValue();
13426
13427       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13428       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13429       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13430       std::swap(SV0, SV1);
13431     }
13432
13433     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13434     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13435     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13436     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13437   }
13438
13439   return SDValue();
13440 }
13441
13442 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13443   SDValue InVal = N->getOperand(0);
13444   EVT VT = N->getValueType(0);
13445
13446   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13447   // with a VECTOR_SHUFFLE.
13448   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13449     SDValue InVec = InVal->getOperand(0);
13450     SDValue EltNo = InVal->getOperand(1);
13451
13452     // FIXME: We could support implicit truncation if the shuffle can be
13453     // scaled to a smaller vector scalar type.
13454     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13455     if (C0 && VT == InVec.getValueType() &&
13456         VT.getScalarType() == InVal.getValueType()) {
13457       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13458       int Elt = C0->getZExtValue();
13459       NewMask[0] = Elt;
13460
13461       if (TLI.isShuffleMaskLegal(NewMask, VT))
13462         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13463                                     NewMask);
13464     }
13465   }
13466
13467   return SDValue();
13468 }
13469
13470 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13471   SDValue N0 = N->getOperand(0);
13472   SDValue N2 = N->getOperand(2);
13473
13474   // If the input vector is a concatenation, and the insert replaces
13475   // one of the halves, we can optimize into a single concat_vectors.
13476   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13477       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13478     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13479     EVT VT = N->getValueType(0);
13480
13481     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13482     // (concat_vectors Z, Y)
13483     if (InsIdx == 0)
13484       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13485                          N->getOperand(1), N0.getOperand(1));
13486
13487     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13488     // (concat_vectors X, Z)
13489     if (InsIdx == VT.getVectorNumElements()/2)
13490       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13491                          N0.getOperand(0), N->getOperand(1));
13492   }
13493
13494   return SDValue();
13495 }
13496
13497 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13498   SDValue N0 = N->getOperand(0);
13499
13500   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13501   if (N0->getOpcode() == ISD::FP16_TO_FP)
13502     return N0->getOperand(0);
13503
13504   return SDValue();
13505 }
13506
13507 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13508   SDValue N0 = N->getOperand(0);
13509
13510   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13511   if (N0->getOpcode() == ISD::AND) {
13512     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13513     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13514       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13515                          N0.getOperand(0));
13516     }
13517   }
13518
13519   return SDValue();
13520 }
13521
13522 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13523 /// with the destination vector and a zero vector.
13524 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13525 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13526 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13527   EVT VT = N->getValueType(0);
13528   SDValue LHS = N->getOperand(0);
13529   SDValue RHS = N->getOperand(1);
13530   SDLoc dl(N);
13531
13532   // Make sure we're not running after operation legalization where it
13533   // may have custom lowered the vector shuffles.
13534   if (LegalOperations)
13535     return SDValue();
13536
13537   if (N->getOpcode() != ISD::AND)
13538     return SDValue();
13539
13540   if (RHS.getOpcode() == ISD::BITCAST)
13541     RHS = RHS.getOperand(0);
13542
13543   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13544     return SDValue();
13545
13546   EVT RVT = RHS.getValueType();
13547   unsigned NumElts = RHS.getNumOperands();
13548
13549   // Attempt to create a valid clear mask, splitting the mask into
13550   // sub elements and checking to see if each is
13551   // all zeros or all ones - suitable for shuffle masking.
13552   auto BuildClearMask = [&](int Split) {
13553     int NumSubElts = NumElts * Split;
13554     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13555
13556     SmallVector<int, 8> Indices;
13557     for (int i = 0; i != NumSubElts; ++i) {
13558       int EltIdx = i / Split;
13559       int SubIdx = i % Split;
13560       SDValue Elt = RHS.getOperand(EltIdx);
13561       if (Elt.getOpcode() == ISD::UNDEF) {
13562         Indices.push_back(-1);
13563         continue;
13564       }
13565
13566       APInt Bits;
13567       if (isa<ConstantSDNode>(Elt))
13568         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13569       else if (isa<ConstantFPSDNode>(Elt))
13570         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13571       else
13572         return SDValue();
13573
13574       // Extract the sub element from the constant bit mask.
13575       if (DAG.getDataLayout().isBigEndian()) {
13576         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13577       } else {
13578         Bits = Bits.lshr(SubIdx * NumSubBits);
13579       }
13580
13581       if (Split > 1)
13582         Bits = Bits.trunc(NumSubBits);
13583
13584       if (Bits.isAllOnesValue())
13585         Indices.push_back(i);
13586       else if (Bits == 0)
13587         Indices.push_back(i + NumSubElts);
13588       else
13589         return SDValue();
13590     }
13591
13592     // Let's see if the target supports this vector_shuffle.
13593     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13594     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13595     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13596       return SDValue();
13597
13598     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13599     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13600                                                    DAG.getBitcast(ClearVT, LHS),
13601                                                    Zero, &Indices[0]));
13602   };
13603
13604   // Determine maximum split level (byte level masking).
13605   int MaxSplit = 1;
13606   if (RVT.getScalarSizeInBits() % 8 == 0)
13607     MaxSplit = RVT.getScalarSizeInBits() / 8;
13608
13609   for (int Split = 1; Split <= MaxSplit; ++Split)
13610     if (RVT.getScalarSizeInBits() % Split == 0)
13611       if (SDValue S = BuildClearMask(Split))
13612         return S;
13613
13614   return SDValue();
13615 }
13616
13617 /// Visit a binary vector operation, like ADD.
13618 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13619   assert(N->getValueType(0).isVector() &&
13620          "SimplifyVBinOp only works on vectors!");
13621
13622   SDValue LHS = N->getOperand(0);
13623   SDValue RHS = N->getOperand(1);
13624   SDValue Ops[] = {LHS, RHS};
13625
13626   // See if we can constant fold the vector operation.
13627   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13628           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13629     return Fold;
13630
13631   // Try to convert a constant mask AND into a shuffle clear mask.
13632   if (SDValue Shuffle = XformToShuffleWithZero(N))
13633     return Shuffle;
13634
13635   // Type legalization might introduce new shuffles in the DAG.
13636   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13637   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13638   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13639       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13640       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13641       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13642     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13643     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13644
13645     if (SVN0->getMask().equals(SVN1->getMask())) {
13646       EVT VT = N->getValueType(0);
13647       SDValue UndefVector = LHS.getOperand(1);
13648       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13649                                      LHS.getOperand(0), RHS.getOperand(0),
13650                                      N->getFlags());
13651       AddUsersToWorklist(N);
13652       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13653                                   &SVN0->getMask()[0]);
13654     }
13655   }
13656
13657   return SDValue();
13658 }
13659
13660 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13661                                     SDValue N1, SDValue N2){
13662   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13663
13664   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13665                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13666
13667   // If we got a simplified select_cc node back from SimplifySelectCC, then
13668   // break it down into a new SETCC node, and a new SELECT node, and then return
13669   // the SELECT node, since we were called with a SELECT node.
13670   if (SCC.getNode()) {
13671     // Check to see if we got a select_cc back (to turn into setcc/select).
13672     // Otherwise, just return whatever node we got back, like fabs.
13673     if (SCC.getOpcode() == ISD::SELECT_CC) {
13674       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13675                                   N0.getValueType(),
13676                                   SCC.getOperand(0), SCC.getOperand(1),
13677                                   SCC.getOperand(4));
13678       AddToWorklist(SETCC.getNode());
13679       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13680                            SCC.getOperand(2), SCC.getOperand(3));
13681     }
13682
13683     return SCC;
13684   }
13685   return SDValue();
13686 }
13687
13688 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13689 /// being selected between, see if we can simplify the select.  Callers of this
13690 /// should assume that TheSelect is deleted if this returns true.  As such, they
13691 /// should return the appropriate thing (e.g. the node) back to the top-level of
13692 /// the DAG combiner loop to avoid it being looked at.
13693 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13694                                     SDValue RHS) {
13695
13696   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13697   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13698   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13699     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13700       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13701       SDValue Sqrt = RHS;
13702       ISD::CondCode CC;
13703       SDValue CmpLHS;
13704       const ConstantFPSDNode *NegZero = nullptr;
13705
13706       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13707         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13708         CmpLHS = TheSelect->getOperand(0);
13709         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13710       } else {
13711         // SELECT or VSELECT
13712         SDValue Cmp = TheSelect->getOperand(0);
13713         if (Cmp.getOpcode() == ISD::SETCC) {
13714           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13715           CmpLHS = Cmp.getOperand(0);
13716           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13717         }
13718       }
13719       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13720           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13721           CC == ISD::SETULT || CC == ISD::SETLT)) {
13722         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13723         CombineTo(TheSelect, Sqrt);
13724         return true;
13725       }
13726     }
13727   }
13728   // Cannot simplify select with vector condition
13729   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13730
13731   // If this is a select from two identical things, try to pull the operation
13732   // through the select.
13733   if (LHS.getOpcode() != RHS.getOpcode() ||
13734       !LHS.hasOneUse() || !RHS.hasOneUse())
13735     return false;
13736
13737   // If this is a load and the token chain is identical, replace the select
13738   // of two loads with a load through a select of the address to load from.
13739   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13740   // constants have been dropped into the constant pool.
13741   if (LHS.getOpcode() == ISD::LOAD) {
13742     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13743     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13744
13745     // Token chains must be identical.
13746     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13747         // Do not let this transformation reduce the number of volatile loads.
13748         LLD->isVolatile() || RLD->isVolatile() ||
13749         // FIXME: If either is a pre/post inc/dec load,
13750         // we'd need to split out the address adjustment.
13751         LLD->isIndexed() || RLD->isIndexed() ||
13752         // If this is an EXTLOAD, the VT's must match.
13753         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13754         // If this is an EXTLOAD, the kind of extension must match.
13755         (LLD->getExtensionType() != RLD->getExtensionType() &&
13756          // The only exception is if one of the extensions is anyext.
13757          LLD->getExtensionType() != ISD::EXTLOAD &&
13758          RLD->getExtensionType() != ISD::EXTLOAD) ||
13759         // FIXME: this discards src value information.  This is
13760         // over-conservative. It would be beneficial to be able to remember
13761         // both potential memory locations.  Since we are discarding
13762         // src value info, don't do the transformation if the memory
13763         // locations are not in the default address space.
13764         LLD->getPointerInfo().getAddrSpace() != 0 ||
13765         RLD->getPointerInfo().getAddrSpace() != 0 ||
13766         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13767                                       LLD->getBasePtr().getValueType()))
13768       return false;
13769
13770     // Check that the select condition doesn't reach either load.  If so,
13771     // folding this will induce a cycle into the DAG.  If not, this is safe to
13772     // xform, so create a select of the addresses.
13773     SDValue Addr;
13774     if (TheSelect->getOpcode() == ISD::SELECT) {
13775       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13776       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13777           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13778         return false;
13779       // The loads must not depend on one another.
13780       if (LLD->isPredecessorOf(RLD) ||
13781           RLD->isPredecessorOf(LLD))
13782         return false;
13783       Addr = DAG.getSelect(SDLoc(TheSelect),
13784                            LLD->getBasePtr().getValueType(),
13785                            TheSelect->getOperand(0), LLD->getBasePtr(),
13786                            RLD->getBasePtr());
13787     } else {  // Otherwise SELECT_CC
13788       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13789       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13790
13791       if ((LLD->hasAnyUseOfValue(1) &&
13792            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13793           (RLD->hasAnyUseOfValue(1) &&
13794            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13795         return false;
13796
13797       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13798                          LLD->getBasePtr().getValueType(),
13799                          TheSelect->getOperand(0),
13800                          TheSelect->getOperand(1),
13801                          LLD->getBasePtr(), RLD->getBasePtr(),
13802                          TheSelect->getOperand(4));
13803     }
13804
13805     SDValue Load;
13806     // It is safe to replace the two loads if they have different alignments,
13807     // but the new load must be the minimum (most restrictive) alignment of the
13808     // inputs.
13809     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13810     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13811     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13812       Load = DAG.getLoad(TheSelect->getValueType(0),
13813                          SDLoc(TheSelect),
13814                          // FIXME: Discards pointer and AA info.
13815                          LLD->getChain(), Addr, MachinePointerInfo(),
13816                          LLD->isVolatile(), LLD->isNonTemporal(),
13817                          isInvariant, Alignment);
13818     } else {
13819       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13820                             RLD->getExtensionType() : LLD->getExtensionType(),
13821                             SDLoc(TheSelect),
13822                             TheSelect->getValueType(0),
13823                             // FIXME: Discards pointer and AA info.
13824                             LLD->getChain(), Addr, MachinePointerInfo(),
13825                             LLD->getMemoryVT(), LLD->isVolatile(),
13826                             LLD->isNonTemporal(), isInvariant, Alignment);
13827     }
13828
13829     // Users of the select now use the result of the load.
13830     CombineTo(TheSelect, Load);
13831
13832     // Users of the old loads now use the new load's chain.  We know the
13833     // old-load value is dead now.
13834     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13835     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13836     return true;
13837   }
13838
13839   return false;
13840 }
13841
13842 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13843 /// where 'cond' is the comparison specified by CC.
13844 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13845                                       SDValue N2, SDValue N3,
13846                                       ISD::CondCode CC, bool NotExtCompare) {
13847   // (x ? y : y) -> y.
13848   if (N2 == N3) return N2;
13849
13850   EVT VT = N2.getValueType();
13851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13852   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13853
13854   // Determine if the condition we're dealing with is constant
13855   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13856                               N0, N1, CC, DL, false);
13857   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13858
13859   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13860     // fold select_cc true, x, y -> x
13861     // fold select_cc false, x, y -> y
13862     return !SCCC->isNullValue() ? N2 : N3;
13863   }
13864
13865   // Check to see if we can simplify the select into an fabs node
13866   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13867     // Allow either -0.0 or 0.0
13868     if (CFP->isZero()) {
13869       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13870       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13871           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13872           N2 == N3.getOperand(0))
13873         return DAG.getNode(ISD::FABS, DL, VT, N0);
13874
13875       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13876       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13877           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13878           N2.getOperand(0) == N3)
13879         return DAG.getNode(ISD::FABS, DL, VT, N3);
13880     }
13881   }
13882
13883   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13884   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13885   // in it.  This is a win when the constant is not otherwise available because
13886   // it replaces two constant pool loads with one.  We only do this if the FP
13887   // type is known to be legal, because if it isn't, then we are before legalize
13888   // types an we want the other legalization to happen first (e.g. to avoid
13889   // messing with soft float) and if the ConstantFP is not legal, because if
13890   // it is legal, we may not need to store the FP constant in a constant pool.
13891   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13892     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13893       if (TLI.isTypeLegal(N2.getValueType()) &&
13894           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13895                TargetLowering::Legal &&
13896            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13897            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13898           // If both constants have multiple uses, then we won't need to do an
13899           // extra load, they are likely around in registers for other users.
13900           (TV->hasOneUse() || FV->hasOneUse())) {
13901         Constant *Elts[] = {
13902           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13903           const_cast<ConstantFP*>(TV->getConstantFPValue())
13904         };
13905         Type *FPTy = Elts[0]->getType();
13906         const DataLayout &TD = DAG.getDataLayout();
13907
13908         // Create a ConstantArray of the two constants.
13909         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13910         SDValue CPIdx =
13911             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13912                                 TD.getPrefTypeAlignment(FPTy));
13913         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13914
13915         // Get the offsets to the 0 and 1 element of the array so that we can
13916         // select between them.
13917         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13918         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13919         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13920
13921         SDValue Cond = DAG.getSetCC(DL,
13922                                     getSetCCResultType(N0.getValueType()),
13923                                     N0, N1, CC);
13924         AddToWorklist(Cond.getNode());
13925         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13926                                           Cond, One, Zero);
13927         AddToWorklist(CstOffset.getNode());
13928         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13929                             CstOffset);
13930         AddToWorklist(CPIdx.getNode());
13931         return DAG.getLoad(
13932             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13933             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13934             false, false, false, Alignment);
13935       }
13936     }
13937
13938   // Check to see if we can perform the "gzip trick", transforming
13939   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13940   if (isNullConstant(N3) && CC == ISD::SETLT &&
13941       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13942        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13943     EVT XType = N0.getValueType();
13944     EVT AType = N2.getValueType();
13945     if (XType.bitsGE(AType)) {
13946       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13947       // single-bit constant.
13948       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13949         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13950         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13951         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13952                                        getShiftAmountTy(N0.getValueType()));
13953         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13954                                     XType, N0, ShCt);
13955         AddToWorklist(Shift.getNode());
13956
13957         if (XType.bitsGT(AType)) {
13958           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13959           AddToWorklist(Shift.getNode());
13960         }
13961
13962         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13963       }
13964
13965       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13966                                   XType, N0,
13967                                   DAG.getConstant(XType.getSizeInBits() - 1,
13968                                                   SDLoc(N0),
13969                                          getShiftAmountTy(N0.getValueType())));
13970       AddToWorklist(Shift.getNode());
13971
13972       if (XType.bitsGT(AType)) {
13973         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13974         AddToWorklist(Shift.getNode());
13975       }
13976
13977       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13978     }
13979   }
13980
13981   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13982   // where y is has a single bit set.
13983   // A plaintext description would be, we can turn the SELECT_CC into an AND
13984   // when the condition can be materialized as an all-ones register.  Any
13985   // single bit-test can be materialized as an all-ones register with
13986   // shift-left and shift-right-arith.
13987   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13988       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13989     SDValue AndLHS = N0->getOperand(0);
13990     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13991     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13992       // Shift the tested bit over the sign bit.
13993       APInt AndMask = ConstAndRHS->getAPIntValue();
13994       SDValue ShlAmt =
13995         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13996                         getShiftAmountTy(AndLHS.getValueType()));
13997       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13998
13999       // Now arithmetic right shift it all the way over, so the result is either
14000       // all-ones, or zero.
14001       SDValue ShrAmt =
14002         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14003                         getShiftAmountTy(Shl.getValueType()));
14004       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14005
14006       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14007     }
14008   }
14009
14010   // fold select C, 16, 0 -> shl C, 4
14011   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14012       TLI.getBooleanContents(N0.getValueType()) ==
14013           TargetLowering::ZeroOrOneBooleanContent) {
14014
14015     // If the caller doesn't want us to simplify this into a zext of a compare,
14016     // don't do it.
14017     if (NotExtCompare && N2C->isOne())
14018       return SDValue();
14019
14020     // Get a SetCC of the condition
14021     // NOTE: Don't create a SETCC if it's not legal on this target.
14022     if (!LegalOperations ||
14023         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14024       SDValue Temp, SCC;
14025       // cast from setcc result type to select result type
14026       if (LegalTypes) {
14027         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14028                             N0, N1, CC);
14029         if (N2.getValueType().bitsLT(SCC.getValueType()))
14030           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14031                                         N2.getValueType());
14032         else
14033           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14034                              N2.getValueType(), SCC);
14035       } else {
14036         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14037         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14038                            N2.getValueType(), SCC);
14039       }
14040
14041       AddToWorklist(SCC.getNode());
14042       AddToWorklist(Temp.getNode());
14043
14044       if (N2C->isOne())
14045         return Temp;
14046
14047       // shl setcc result by log2 n2c
14048       return DAG.getNode(
14049           ISD::SHL, DL, N2.getValueType(), Temp,
14050           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14051                           getShiftAmountTy(Temp.getValueType())));
14052     }
14053   }
14054
14055   // Check to see if this is an integer abs.
14056   // select_cc setg[te] X,  0,  X, -X ->
14057   // select_cc setgt    X, -1,  X, -X ->
14058   // select_cc setl[te] X,  0, -X,  X ->
14059   // select_cc setlt    X,  1, -X,  X ->
14060   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14061   if (N1C) {
14062     ConstantSDNode *SubC = nullptr;
14063     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14064          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14065         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14066       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14067     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14068               (N1C->isOne() && CC == ISD::SETLT)) &&
14069              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14070       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14071
14072     EVT XType = N0.getValueType();
14073     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14074       SDLoc DL(N0);
14075       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14076                                   N0,
14077                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14078                                          getShiftAmountTy(N0.getValueType())));
14079       SDValue Add = DAG.getNode(ISD::ADD, DL,
14080                                 XType, N0, Shift);
14081       AddToWorklist(Shift.getNode());
14082       AddToWorklist(Add.getNode());
14083       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14084     }
14085   }
14086
14087   return SDValue();
14088 }
14089
14090 /// This is a stub for TargetLowering::SimplifySetCC.
14091 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14092                                    SDValue N1, ISD::CondCode Cond,
14093                                    SDLoc DL, bool foldBooleans) {
14094   TargetLowering::DAGCombinerInfo
14095     DagCombineInfo(DAG, Level, false, this);
14096   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14097 }
14098
14099 /// Given an ISD::SDIV node expressing a divide by constant, return
14100 /// a DAG expression to select that will generate the same value by multiplying
14101 /// by a magic number.
14102 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14103 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14104   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14105   if (!C)
14106     return SDValue();
14107
14108   // Avoid division by zero.
14109   if (C->isNullValue())
14110     return SDValue();
14111
14112   std::vector<SDNode*> Built;
14113   SDValue S =
14114       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14115
14116   for (SDNode *N : Built)
14117     AddToWorklist(N);
14118   return S;
14119 }
14120
14121 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14122 /// DAG expression that will generate the same value by right shifting.
14123 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14124   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14125   if (!C)
14126     return SDValue();
14127
14128   // Avoid division by zero.
14129   if (C->isNullValue())
14130     return SDValue();
14131
14132   std::vector<SDNode *> Built;
14133   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14134
14135   for (SDNode *N : Built)
14136     AddToWorklist(N);
14137   return S;
14138 }
14139
14140 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14141 /// expression that will generate the same value by multiplying by a magic
14142 /// number.
14143 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14144 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14145   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14146   if (!C)
14147     return SDValue();
14148
14149   // Avoid division by zero.
14150   if (C->isNullValue())
14151     return SDValue();
14152
14153   std::vector<SDNode*> Built;
14154   SDValue S =
14155       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14156
14157   for (SDNode *N : Built)
14158     AddToWorklist(N);
14159   return S;
14160 }
14161
14162 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14163   if (Level >= AfterLegalizeDAG)
14164     return SDValue();
14165
14166   // Expose the DAG combiner to the target combiner implementations.
14167   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14168
14169   unsigned Iterations = 0;
14170   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14171     if (Iterations) {
14172       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14173       // For the reciprocal, we need to find the zero of the function:
14174       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14175       //     =>
14176       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14177       //     does not require additional intermediate precision]
14178       EVT VT = Op.getValueType();
14179       SDLoc DL(Op);
14180       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14181
14182       AddToWorklist(Est.getNode());
14183
14184       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14185       for (unsigned i = 0; i < Iterations; ++i) {
14186         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14187         AddToWorklist(NewEst.getNode());
14188
14189         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14190         AddToWorklist(NewEst.getNode());
14191
14192         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14193         AddToWorklist(NewEst.getNode());
14194
14195         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14196         AddToWorklist(Est.getNode());
14197       }
14198     }
14199     return Est;
14200   }
14201
14202   return SDValue();
14203 }
14204
14205 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14206 /// For the reciprocal sqrt, we need to find the zero of the function:
14207 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14208 ///     =>
14209 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14210 /// As a result, we precompute A/2 prior to the iteration loop.
14211 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14212                                           unsigned Iterations,
14213                                           SDNodeFlags *Flags) {
14214   EVT VT = Arg.getValueType();
14215   SDLoc DL(Arg);
14216   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14217
14218   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14219   // this entire sequence requires only one FP constant.
14220   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14221   AddToWorklist(HalfArg.getNode());
14222
14223   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14224   AddToWorklist(HalfArg.getNode());
14225
14226   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14227   for (unsigned i = 0; i < Iterations; ++i) {
14228     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14229     AddToWorklist(NewEst.getNode());
14230
14231     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14232     AddToWorklist(NewEst.getNode());
14233
14234     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14235     AddToWorklist(NewEst.getNode());
14236
14237     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14238     AddToWorklist(Est.getNode());
14239   }
14240   return Est;
14241 }
14242
14243 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14244 /// For the reciprocal sqrt, we need to find the zero of the function:
14245 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14246 ///     =>
14247 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14248 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14249                                           unsigned Iterations,
14250                                           SDNodeFlags *Flags) {
14251   EVT VT = Arg.getValueType();
14252   SDLoc DL(Arg);
14253   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14254   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14255
14256   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14257   for (unsigned i = 0; i < Iterations; ++i) {
14258     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14259     AddToWorklist(HalfEst.getNode());
14260
14261     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14262     AddToWorklist(Est.getNode());
14263
14264     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14265     AddToWorklist(Est.getNode());
14266
14267     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14268     AddToWorklist(Est.getNode());
14269
14270     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14271     AddToWorklist(Est.getNode());
14272   }
14273   return Est;
14274 }
14275
14276 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14277   if (Level >= AfterLegalizeDAG)
14278     return SDValue();
14279
14280   // Expose the DAG combiner to the target combiner implementations.
14281   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14282   unsigned Iterations = 0;
14283   bool UseOneConstNR = false;
14284   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14285     AddToWorklist(Est.getNode());
14286     if (Iterations) {
14287       Est = UseOneConstNR ?
14288         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14289         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14290     }
14291     return Est;
14292   }
14293
14294   return SDValue();
14295 }
14296
14297 /// Return true if base is a frame index, which is known not to alias with
14298 /// anything but itself.  Provides base object and offset as results.
14299 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14300                            const GlobalValue *&GV, const void *&CV) {
14301   // Assume it is a primitive operation.
14302   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14303
14304   // If it's an adding a simple constant then integrate the offset.
14305   if (Base.getOpcode() == ISD::ADD) {
14306     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14307       Base = Base.getOperand(0);
14308       Offset += C->getZExtValue();
14309     }
14310   }
14311
14312   // Return the underlying GlobalValue, and update the Offset.  Return false
14313   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14314   // by multiple nodes with different offsets.
14315   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14316     GV = G->getGlobal();
14317     Offset += G->getOffset();
14318     return false;
14319   }
14320
14321   // Return the underlying Constant value, and update the Offset.  Return false
14322   // for ConstantSDNodes since the same constant pool entry may be represented
14323   // by multiple nodes with different offsets.
14324   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14325     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14326                                          : (const void *)C->getConstVal();
14327     Offset += C->getOffset();
14328     return false;
14329   }
14330   // If it's any of the following then it can't alias with anything but itself.
14331   return isa<FrameIndexSDNode>(Base);
14332 }
14333
14334 /// Return true if there is any possibility that the two addresses overlap.
14335 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14336   // If they are the same then they must be aliases.
14337   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14338
14339   // If they are both volatile then they cannot be reordered.
14340   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14341
14342   // If one operation reads from invariant memory, and the other may store, they
14343   // cannot alias. These should really be checking the equivalent of mayWrite,
14344   // but it only matters for memory nodes other than load /store.
14345   if (Op0->isInvariant() && Op1->writeMem())
14346     return false;
14347
14348   if (Op1->isInvariant() && Op0->writeMem())
14349     return false;
14350
14351   // Gather base node and offset information.
14352   SDValue Base1, Base2;
14353   int64_t Offset1, Offset2;
14354   const GlobalValue *GV1, *GV2;
14355   const void *CV1, *CV2;
14356   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14357                                       Base1, Offset1, GV1, CV1);
14358   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14359                                       Base2, Offset2, GV2, CV2);
14360
14361   // If they have a same base address then check to see if they overlap.
14362   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14363     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14364              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14365
14366   // It is possible for different frame indices to alias each other, mostly
14367   // when tail call optimization reuses return address slots for arguments.
14368   // To catch this case, look up the actual index of frame indices to compute
14369   // the real alias relationship.
14370   if (isFrameIndex1 && isFrameIndex2) {
14371     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14372     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14373     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14374     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14375              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14376   }
14377
14378   // Otherwise, if we know what the bases are, and they aren't identical, then
14379   // we know they cannot alias.
14380   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14381     return false;
14382
14383   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14384   // compared to the size and offset of the access, we may be able to prove they
14385   // do not alias.  This check is conservative for now to catch cases created by
14386   // splitting vector types.
14387   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14388       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14389       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14390        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14391       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14392     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14393     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14394
14395     // There is no overlap between these relatively aligned accesses of similar
14396     // size, return no alias.
14397     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14398         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14399       return false;
14400   }
14401
14402   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14403                    ? CombinerGlobalAA
14404                    : DAG.getSubtarget().useAA();
14405 #ifndef NDEBUG
14406   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14407       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14408     UseAA = false;
14409 #endif
14410   if (UseAA &&
14411       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14412     // Use alias analysis information.
14413     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14414                                  Op1->getSrcValueOffset());
14415     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14416         Op0->getSrcValueOffset() - MinOffset;
14417     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14418         Op1->getSrcValueOffset() - MinOffset;
14419     AliasResult AAResult =
14420         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14421                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14422                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14423                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14424     if (AAResult == NoAlias)
14425       return false;
14426   }
14427
14428   // Otherwise we have to assume they alias.
14429   return true;
14430 }
14431
14432 /// Walk up chain skipping non-aliasing memory nodes,
14433 /// looking for aliasing nodes and adding them to the Aliases vector.
14434 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14435                                    SmallVectorImpl<SDValue> &Aliases) {
14436   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14437   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14438
14439   // Get alias information for node.
14440   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14441
14442   // Starting off.
14443   Chains.push_back(OriginalChain);
14444   unsigned Depth = 0;
14445
14446   // Look at each chain and determine if it is an alias.  If so, add it to the
14447   // aliases list.  If not, then continue up the chain looking for the next
14448   // candidate.
14449   while (!Chains.empty()) {
14450     SDValue Chain = Chains.pop_back_val();
14451
14452     // For TokenFactor nodes, look at each operand and only continue up the
14453     // chain until we reach the depth limit.
14454     //
14455     // FIXME: The depth check could be made to return the last non-aliasing
14456     // chain we found before we hit a tokenfactor rather than the original
14457     // chain.
14458     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14459       Aliases.clear();
14460       Aliases.push_back(OriginalChain);
14461       return;
14462     }
14463
14464     // Don't bother if we've been before.
14465     if (!Visited.insert(Chain.getNode()).second)
14466       continue;
14467
14468     switch (Chain.getOpcode()) {
14469     case ISD::EntryToken:
14470       // Entry token is ideal chain operand, but handled in FindBetterChain.
14471       break;
14472
14473     case ISD::LOAD:
14474     case ISD::STORE: {
14475       // Get alias information for Chain.
14476       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14477           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14478
14479       // If chain is alias then stop here.
14480       if (!(IsLoad && IsOpLoad) &&
14481           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14482         Aliases.push_back(Chain);
14483       } else {
14484         // Look further up the chain.
14485         Chains.push_back(Chain.getOperand(0));
14486         ++Depth;
14487       }
14488       break;
14489     }
14490
14491     case ISD::TokenFactor:
14492       // We have to check each of the operands of the token factor for "small"
14493       // token factors, so we queue them up.  Adding the operands to the queue
14494       // (stack) in reverse order maintains the original order and increases the
14495       // likelihood that getNode will find a matching token factor (CSE.)
14496       if (Chain.getNumOperands() > 16) {
14497         Aliases.push_back(Chain);
14498         break;
14499       }
14500       for (unsigned n = Chain.getNumOperands(); n;)
14501         Chains.push_back(Chain.getOperand(--n));
14502       ++Depth;
14503       break;
14504
14505     default:
14506       // For all other instructions we will just have to take what we can get.
14507       Aliases.push_back(Chain);
14508       break;
14509     }
14510   }
14511
14512   // We need to be careful here to also search for aliases through the
14513   // value operand of a store, etc. Consider the following situation:
14514   //   Token1 = ...
14515   //   L1 = load Token1, %52
14516   //   S1 = store Token1, L1, %51
14517   //   L2 = load Token1, %52+8
14518   //   S2 = store Token1, L2, %51+8
14519   //   Token2 = Token(S1, S2)
14520   //   L3 = load Token2, %53
14521   //   S3 = store Token2, L3, %52
14522   //   L4 = load Token2, %53+8
14523   //   S4 = store Token2, L4, %52+8
14524   // If we search for aliases of S3 (which loads address %52), and we look
14525   // only through the chain, then we'll miss the trivial dependence on L1
14526   // (which also loads from %52). We then might change all loads and
14527   // stores to use Token1 as their chain operand, which could result in
14528   // copying %53 into %52 before copying %52 into %51 (which should
14529   // happen first).
14530   //
14531   // The problem is, however, that searching for such data dependencies
14532   // can become expensive, and the cost is not directly related to the
14533   // chain depth. Instead, we'll rule out such configurations here by
14534   // insisting that we've visited all chain users (except for users
14535   // of the original chain, which is not necessary). When doing this,
14536   // we need to look through nodes we don't care about (otherwise, things
14537   // like register copies will interfere with trivial cases).
14538
14539   SmallVector<const SDNode *, 16> Worklist;
14540   for (const SDNode *N : Visited)
14541     if (N != OriginalChain.getNode())
14542       Worklist.push_back(N);
14543
14544   while (!Worklist.empty()) {
14545     const SDNode *M = Worklist.pop_back_val();
14546
14547     // We have already visited M, and want to make sure we've visited any uses
14548     // of M that we care about. For uses that we've not visisted, and don't
14549     // care about, queue them to the worklist.
14550
14551     for (SDNode::use_iterator UI = M->use_begin(),
14552          UIE = M->use_end(); UI != UIE; ++UI)
14553       if (UI.getUse().getValueType() == MVT::Other &&
14554           Visited.insert(*UI).second) {
14555         if (isa<MemSDNode>(*UI)) {
14556           // We've not visited this use, and we care about it (it could have an
14557           // ordering dependency with the original node).
14558           Aliases.clear();
14559           Aliases.push_back(OriginalChain);
14560           return;
14561         }
14562
14563         // We've not visited this use, but we don't care about it. Mark it as
14564         // visited and enqueue it to the worklist.
14565         Worklist.push_back(*UI);
14566       }
14567   }
14568 }
14569
14570 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14571 /// (aliasing node.)
14572 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14573   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14574
14575   // Accumulate all the aliases to this node.
14576   GatherAllAliases(N, OldChain, Aliases);
14577
14578   // If no operands then chain to entry token.
14579   if (Aliases.size() == 0)
14580     return DAG.getEntryNode();
14581
14582   // If a single operand then chain to it.  We don't need to revisit it.
14583   if (Aliases.size() == 1)
14584     return Aliases[0];
14585
14586   // Construct a custom tailored token factor.
14587   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14588 }
14589
14590 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14591   // This holds the base pointer, index, and the offset in bytes from the base
14592   // pointer.
14593   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14594
14595   // We must have a base and an offset.
14596   if (!BasePtr.Base.getNode())
14597     return false;
14598
14599   // Do not handle stores to undef base pointers.
14600   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14601     return false;
14602
14603   SmallVector<StoreSDNode *, 8> ChainedStores;
14604   ChainedStores.push_back(St);
14605
14606   // Walk up the chain and look for nodes with offsets from the same
14607   // base pointer. Stop when reaching an instruction with a different kind
14608   // or instruction which has a different base pointer.
14609   StoreSDNode *Index = St;
14610   while (Index) {
14611     // If the chain has more than one use, then we can't reorder the mem ops.
14612     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14613       break;
14614
14615     if (Index->isVolatile() || Index->isIndexed())
14616       break;
14617
14618     // Find the base pointer and offset for this memory node.
14619     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14620
14621     // Check that the base pointer is the same as the original one.
14622     if (!Ptr.equalBaseIndex(BasePtr))
14623       break;
14624
14625     // Find the next memory operand in the chain. If the next operand in the
14626     // chain is a store then move up and continue the scan with the next
14627     // memory operand. If the next operand is a load save it and use alias
14628     // information to check if it interferes with anything.
14629     SDNode *NextInChain = Index->getChain().getNode();
14630     while (true) {
14631       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14632         // We found a store node. Use it for the next iteration.
14633         ChainedStores.push_back(STn);
14634         Index = STn;
14635         break;
14636       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14637         NextInChain = Ldn->getChain().getNode();
14638         continue;
14639       } else {
14640         Index = nullptr;
14641         break;
14642       }
14643     }
14644   }
14645
14646   bool MadeChange = false;
14647   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14648
14649   for (StoreSDNode *ChainedStore : ChainedStores) {
14650     SDValue Chain = ChainedStore->getChain();
14651     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14652
14653     if (Chain != BetterChain) {
14654       MadeChange = true;
14655       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14656     }
14657   }
14658
14659   // Do all replacements after finding the replacements to make to avoid making
14660   // the chains more complicated by introducing new TokenFactors.
14661   for (auto Replacement : BetterChains)
14662     replaceStoreChain(Replacement.first, Replacement.second);
14663
14664   return MadeChange;
14665 }
14666
14667 /// This is the entry point for the file.
14668 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14669                            CodeGenOpt::Level OptLevel) {
14670   /// This is the main entry point to this class.
14671   DAGCombiner(*this, AA, OptLevel).Run(Level);
14672 }