Refactoring and enhancement to FMA combine.
[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     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310
311     SDValue visitFADDForFMACombine(SDNode *N);
312     SDValue visitFSUBForFMACombine(SDNode *N);
313
314     SDValue XformToShuffleWithZero(SDNode *N);
315     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
316
317     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
318
319     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
320     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
321     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
322     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
323                              SDValue N3, ISD::CondCode CC,
324                              bool NotExtCompare = false);
325     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
326                           SDLoc DL, bool foldBooleans = true);
327
328     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
329                            SDValue &CC) const;
330     bool isOneUseSetCC(SDValue N) const;
331
332     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
333                                          unsigned HiOp);
334     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
335     SDValue CombineExtLoad(SDNode *N);
336     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
337     SDValue BuildSDIV(SDNode *N);
338     SDValue BuildSDIVPow2(SDNode *N);
339     SDValue BuildUDIV(SDNode *N);
340     SDValue BuildReciprocalEstimate(SDValue Op);
341     SDValue BuildRsqrtEstimate(SDValue Op);
342     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
343     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
344     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
345                                bool DemandHighBits = true);
346     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
347     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
348                               SDValue InnerPos, SDValue InnerNeg,
349                               unsigned PosOpcode, unsigned NegOpcode,
350                               SDLoc DL);
351     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
352     SDValue ReduceLoadWidth(SDNode *N);
353     SDValue ReduceLoadOpStoreWidth(SDNode *N);
354     SDValue TransformFPLoadStorePair(SDNode *N);
355     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
356     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
357
358     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
359
360     /// Walk up chain skipping non-aliasing memory nodes,
361     /// looking for aliasing nodes and adding them to the Aliases vector.
362     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
363                           SmallVectorImpl<SDValue> &Aliases);
364
365     /// Return true if there is any possibility that the two addresses overlap.
366     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
367
368     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
369     /// chain (aliasing node.)
370     SDValue FindBetterChain(SDNode *N, SDValue Chain);
371
372     /// Holds a pointer to an LSBaseSDNode as well as information on where it
373     /// is located in a sequence of memory operations connected by a chain.
374     struct MemOpLink {
375       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
376       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
377       // Ptr to the mem node.
378       LSBaseSDNode *MemNode;
379       // Offset from the base ptr.
380       int64_t OffsetFromBase;
381       // What is the sequence number of this mem node.
382       // Lowest mem operand in the DAG starts at zero.
383       unsigned SequenceNum;
384     };
385
386     /// This is a helper function for MergeConsecutiveStores. When the source
387     /// elements of the consecutive stores are all constants or all extracted
388     /// vector elements, try to merge them into one larger store.
389     /// \return True if a merged store was created.
390     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
391                                          EVT MemVT, unsigned NumElem,
392                                          bool IsConstantSrc, bool UseVector);
393
394     /// Merge consecutive store operations into a wide store.
395     /// This optimization uses wide integers or vectors when possible.
396     /// \return True if some memory operations were changed.
397     bool MergeConsecutiveStores(StoreSDNode *N);
398
399     /// \brief Try to transform a truncation where C is a constant:
400     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
401     ///
402     /// \p N needs to be a truncation and its first operand an AND. Other
403     /// requirements are checked by the function (e.g. that trunc is
404     /// single-use) and if missed an empty SDValue is returned.
405     SDValue distributeTruncateThroughAnd(SDNode *N);
406
407   public:
408     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
409         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
410           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
411       auto *F = DAG.getMachineFunction().getFunction();
412       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
413                     F->hasFnAttribute(Attribute::MinSize);
414     }
415
416     /// Runs the dag combiner on all nodes in the work list
417     void Run(CombineLevel AtLevel);
418
419     SelectionDAG &getDAG() const { return DAG; }
420
421     /// Returns a type large enough to hold any valid shift amount - before type
422     /// legalization these can be huge.
423     EVT getShiftAmountTy(EVT LHSTy) {
424       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
425       if (LHSTy.isVector())
426         return LHSTy;
427       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
428                         : TLI.getPointerTy();
429     }
430
431     /// This method returns true if we are running before type legalization or
432     /// if the specified VT is legal.
433     bool isTypeLegal(const EVT &VT) {
434       if (!LegalTypes) return true;
435       return TLI.isTypeLegal(VT);
436     }
437
438     /// Convenience wrapper around TargetLowering::getSetCCResultType
439     EVT getSetCCResultType(EVT VT) const {
440       return TLI.getSetCCResultType(*DAG.getContext(), VT);
441     }
442   };
443 }
444
445
446 namespace {
447 /// This class is a DAGUpdateListener that removes any deleted
448 /// nodes from the worklist.
449 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
450   DAGCombiner &DC;
451 public:
452   explicit WorklistRemover(DAGCombiner &dc)
453     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
454
455   void NodeDeleted(SDNode *N, SDNode *E) override {
456     DC.removeFromWorklist(N);
457   }
458 };
459 }
460
461 //===----------------------------------------------------------------------===//
462 //  TargetLowering::DAGCombinerInfo implementation
463 //===----------------------------------------------------------------------===//
464
465 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
466   ((DAGCombiner*)DC)->AddToWorklist(N);
467 }
468
469 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
470   ((DAGCombiner*)DC)->removeFromWorklist(N);
471 }
472
473 SDValue TargetLowering::DAGCombinerInfo::
474 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
475   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
476 }
477
478 SDValue TargetLowering::DAGCombinerInfo::
479 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
480   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
481 }
482
483
484 SDValue TargetLowering::DAGCombinerInfo::
485 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
486   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
487 }
488
489 void TargetLowering::DAGCombinerInfo::
490 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
491   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
492 }
493
494 //===----------------------------------------------------------------------===//
495 // Helper Functions
496 //===----------------------------------------------------------------------===//
497
498 void DAGCombiner::deleteAndRecombine(SDNode *N) {
499   removeFromWorklist(N);
500
501   // If the operands of this node are only used by the node, they will now be
502   // dead. Make sure to re-visit them and recursively delete dead nodes.
503   for (const SDValue &Op : N->ops())
504     // For an operand generating multiple values, one of the values may
505     // become dead allowing further simplification (e.g. split index
506     // arithmetic from an indexed load).
507     if (Op->hasOneUse() || Op->getNumValues() > 1)
508       AddToWorklist(Op.getNode());
509
510   DAG.DeleteNode(N);
511 }
512
513 /// Return 1 if we can compute the negated form of the specified expression for
514 /// the same cost as the expression itself, or 2 if we can compute the negated
515 /// form more cheaply than the expression itself.
516 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
517                                const TargetLowering &TLI,
518                                const TargetOptions *Options,
519                                unsigned Depth = 0) {
520   // fneg is removable even if it has multiple uses.
521   if (Op.getOpcode() == ISD::FNEG) return 2;
522
523   // Don't allow anything with multiple uses.
524   if (!Op.hasOneUse()) return 0;
525
526   // Don't recurse exponentially.
527   if (Depth > 6) return 0;
528
529   switch (Op.getOpcode()) {
530   default: return false;
531   case ISD::ConstantFP:
532     // Don't invert constant FP values after legalize.  The negated constant
533     // isn't necessarily legal.
534     return LegalOperations ? 0 : 1;
535   case ISD::FADD:
536     // FIXME: determine better conditions for this xform.
537     if (!Options->UnsafeFPMath) return 0;
538
539     // After operation legalization, it might not be legal to create new FSUBs.
540     if (LegalOperations &&
541         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
542       return 0;
543
544     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
545     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
546                                     Options, Depth + 1))
547       return V;
548     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
549     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
550                               Depth + 1);
551   case ISD::FSUB:
552     // We can't turn -(A-B) into B-A when we honor signed zeros.
553     if (!Options->UnsafeFPMath) return 0;
554
555     // fold (fneg (fsub A, B)) -> (fsub B, A)
556     return 1;
557
558   case ISD::FMUL:
559   case ISD::FDIV:
560     if (Options->HonorSignDependentRoundingFPMath()) return 0;
561
562     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
563     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
564                                     Options, Depth + 1))
565       return V;
566
567     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
568                               Depth + 1);
569
570   case ISD::FP_EXTEND:
571   case ISD::FP_ROUND:
572   case ISD::FSIN:
573     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
574                               Depth + 1);
575   }
576 }
577
578 /// If isNegatibleForFree returns true, return the newly negated expression.
579 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
580                                     bool LegalOperations, unsigned Depth = 0) {
581   const TargetOptions &Options = DAG.getTarget().Options;
582   // fneg is removable even if it has multiple uses.
583   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
584
585   // Don't allow anything with multiple uses.
586   assert(Op.hasOneUse() && "Unknown reuse!");
587
588   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
589   switch (Op.getOpcode()) {
590   default: llvm_unreachable("Unknown code");
591   case ISD::ConstantFP: {
592     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
593     V.changeSign();
594     return DAG.getConstantFP(V, Op.getValueType());
595   }
596   case ISD::FADD:
597     // FIXME: determine better conditions for this xform.
598     assert(Options.UnsafeFPMath);
599
600     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
601     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
602                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
603       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
604                          GetNegatedExpression(Op.getOperand(0), DAG,
605                                               LegalOperations, Depth+1),
606                          Op.getOperand(1));
607     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
608     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
609                        GetNegatedExpression(Op.getOperand(1), DAG,
610                                             LegalOperations, Depth+1),
611                        Op.getOperand(0));
612   case ISD::FSUB:
613     // We can't turn -(A-B) into B-A when we honor signed zeros.
614     assert(Options.UnsafeFPMath);
615
616     // fold (fneg (fsub 0, B)) -> B
617     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
618       if (N0CFP->getValueAPF().isZero())
619         return Op.getOperand(1);
620
621     // fold (fneg (fsub A, B)) -> (fsub B, A)
622     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
623                        Op.getOperand(1), Op.getOperand(0));
624
625   case ISD::FMUL:
626   case ISD::FDIV:
627     assert(!Options.HonorSignDependentRoundingFPMath());
628
629     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
630     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
631                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
632       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
633                          GetNegatedExpression(Op.getOperand(0), DAG,
634                                               LegalOperations, Depth+1),
635                          Op.getOperand(1));
636
637     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
638     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
639                        Op.getOperand(0),
640                        GetNegatedExpression(Op.getOperand(1), DAG,
641                                             LegalOperations, Depth+1));
642
643   case ISD::FP_EXTEND:
644   case ISD::FSIN:
645     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
646                        GetNegatedExpression(Op.getOperand(0), DAG,
647                                             LegalOperations, Depth+1));
648   case ISD::FP_ROUND:
649       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
650                          GetNegatedExpression(Op.getOperand(0), DAG,
651                                               LegalOperations, Depth+1),
652                          Op.getOperand(1));
653   }
654 }
655
656 // Return true if this node is a setcc, or is a select_cc
657 // that selects between the target values used for true and false, making it
658 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
659 // the appropriate nodes based on the type of node we are checking. This
660 // simplifies life a bit for the callers.
661 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
662                                     SDValue &CC) const {
663   if (N.getOpcode() == ISD::SETCC) {
664     LHS = N.getOperand(0);
665     RHS = N.getOperand(1);
666     CC  = N.getOperand(2);
667     return true;
668   }
669
670   if (N.getOpcode() != ISD::SELECT_CC ||
671       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
672       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
673     return false;
674
675   if (TLI.getBooleanContents(N.getValueType()) ==
676       TargetLowering::UndefinedBooleanContent)
677     return false;
678
679   LHS = N.getOperand(0);
680   RHS = N.getOperand(1);
681   CC  = N.getOperand(4);
682   return true;
683 }
684
685 /// Return true if this is a SetCC-equivalent operation with only one use.
686 /// If this is true, it allows the users to invert the operation for free when
687 /// it is profitable to do so.
688 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
689   SDValue N0, N1, N2;
690   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
691     return true;
692   return false;
693 }
694
695 /// Returns true if N is a BUILD_VECTOR node whose
696 /// elements are all the same constant or undefined.
697 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
698   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
699   if (!C)
700     return false;
701
702   APInt SplatUndef;
703   unsigned SplatBitSize;
704   bool HasAnyUndefs;
705   EVT EltVT = N->getValueType(0).getVectorElementType();
706   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
707                              HasAnyUndefs) &&
708           EltVT.getSizeInBits() >= SplatBitSize);
709 }
710
711 // \brief Returns the SDNode if it is a constant integer BuildVector
712 // or constant integer.
713 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
714   if (isa<ConstantSDNode>(N))
715     return N.getNode();
716   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
717     return N.getNode();
718   return nullptr;
719 }
720
721 // \brief Returns the SDNode if it is a constant float BuildVector
722 // or constant float.
723 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
724   if (isa<ConstantFPSDNode>(N))
725     return N.getNode();
726   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
727     return N.getNode();
728   return nullptr;
729 }
730
731 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
732 // int.
733 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
734   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
735     return CN;
736
737   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
738     BitVector UndefElements;
739     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
740
741     // BuildVectors can truncate their operands. Ignore that case here.
742     // FIXME: We blindly ignore splats which include undef which is overly
743     // pessimistic.
744     if (CN && UndefElements.none() &&
745         CN->getValueType(0) == N.getValueType().getScalarType())
746       return CN;
747   }
748
749   return nullptr;
750 }
751
752 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
753 // float.
754 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
755   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
756     return CN;
757
758   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
759     BitVector UndefElements;
760     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
761
762     if (CN && UndefElements.none())
763       return CN;
764   }
765
766   return nullptr;
767 }
768
769 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
770                                     SDValue N0, SDValue N1) {
771   EVT VT = N0.getValueType();
772   if (N0.getOpcode() == Opc) {
773     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
774       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
775         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
776         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
777           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
778         return SDValue();
779       }
780       if (N0.hasOneUse()) {
781         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
782         // use
783         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
784         if (!OpNode.getNode())
785           return SDValue();
786         AddToWorklist(OpNode.getNode());
787         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
788       }
789     }
790   }
791
792   if (N1.getOpcode() == Opc) {
793     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
794       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
795         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
796         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
797           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
798         return SDValue();
799       }
800       if (N1.hasOneUse()) {
801         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
802         // use
803         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
804         if (!OpNode.getNode())
805           return SDValue();
806         AddToWorklist(OpNode.getNode());
807         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
808       }
809     }
810   }
811
812   return SDValue();
813 }
814
815 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
816                                bool AddTo) {
817   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
818   ++NodesCombined;
819   DEBUG(dbgs() << "\nReplacing.1 ";
820         N->dump(&DAG);
821         dbgs() << "\nWith: ";
822         To[0].getNode()->dump(&DAG);
823         dbgs() << " and " << NumTo-1 << " other values\n");
824   for (unsigned i = 0, e = NumTo; i != e; ++i)
825     assert((!To[i].getNode() ||
826             N->getValueType(i) == To[i].getValueType()) &&
827            "Cannot combine value to value of different type!");
828
829   WorklistRemover DeadNodes(*this);
830   DAG.ReplaceAllUsesWith(N, To);
831   if (AddTo) {
832     // Push the new nodes and any users onto the worklist
833     for (unsigned i = 0, e = NumTo; i != e; ++i) {
834       if (To[i].getNode()) {
835         AddToWorklist(To[i].getNode());
836         AddUsersToWorklist(To[i].getNode());
837       }
838     }
839   }
840
841   // Finally, if the node is now dead, remove it from the graph.  The node
842   // may not be dead if the replacement process recursively simplified to
843   // something else needing this node.
844   if (N->use_empty())
845     deleteAndRecombine(N);
846   return SDValue(N, 0);
847 }
848
849 void DAGCombiner::
850 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
851   // Replace all uses.  If any nodes become isomorphic to other nodes and
852   // are deleted, make sure to remove them from our worklist.
853   WorklistRemover DeadNodes(*this);
854   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
855
856   // Push the new node and any (possibly new) users onto the worklist.
857   AddToWorklist(TLO.New.getNode());
858   AddUsersToWorklist(TLO.New.getNode());
859
860   // Finally, if the node is now dead, remove it from the graph.  The node
861   // may not be dead if the replacement process recursively simplified to
862   // something else needing this node.
863   if (TLO.Old.getNode()->use_empty())
864     deleteAndRecombine(TLO.Old.getNode());
865 }
866
867 /// Check the specified integer node value to see if it can be simplified or if
868 /// things it uses can be simplified by bit propagation. If so, return true.
869 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
870   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
871   APInt KnownZero, KnownOne;
872   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
873     return false;
874
875   // Revisit the node.
876   AddToWorklist(Op.getNode());
877
878   // Replace the old value with the new one.
879   ++NodesCombined;
880   DEBUG(dbgs() << "\nReplacing.2 ";
881         TLO.Old.getNode()->dump(&DAG);
882         dbgs() << "\nWith: ";
883         TLO.New.getNode()->dump(&DAG);
884         dbgs() << '\n');
885
886   CommitTargetLoweringOpt(TLO);
887   return true;
888 }
889
890 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
891   SDLoc dl(Load);
892   EVT VT = Load->getValueType(0);
893   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
894
895   DEBUG(dbgs() << "\nReplacing.9 ";
896         Load->dump(&DAG);
897         dbgs() << "\nWith: ";
898         Trunc.getNode()->dump(&DAG);
899         dbgs() << '\n');
900   WorklistRemover DeadNodes(*this);
901   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
902   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
903   deleteAndRecombine(Load);
904   AddToWorklist(Trunc.getNode());
905 }
906
907 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
908   Replace = false;
909   SDLoc dl(Op);
910   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
911     EVT MemVT = LD->getMemoryVT();
912     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
913       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
914                                                        : ISD::EXTLOAD)
915       : LD->getExtensionType();
916     Replace = true;
917     return DAG.getExtLoad(ExtType, dl, PVT,
918                           LD->getChain(), LD->getBasePtr(),
919                           MemVT, LD->getMemOperand());
920   }
921
922   unsigned Opc = Op.getOpcode();
923   switch (Opc) {
924   default: break;
925   case ISD::AssertSext:
926     return DAG.getNode(ISD::AssertSext, dl, PVT,
927                        SExtPromoteOperand(Op.getOperand(0), PVT),
928                        Op.getOperand(1));
929   case ISD::AssertZext:
930     return DAG.getNode(ISD::AssertZext, dl, PVT,
931                        ZExtPromoteOperand(Op.getOperand(0), PVT),
932                        Op.getOperand(1));
933   case ISD::Constant: {
934     unsigned ExtOpc =
935       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
936     return DAG.getNode(ExtOpc, dl, PVT, Op);
937   }
938   }
939
940   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
941     return SDValue();
942   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
943 }
944
945 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
946   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
947     return SDValue();
948   EVT OldVT = Op.getValueType();
949   SDLoc dl(Op);
950   bool Replace = false;
951   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
952   if (!NewOp.getNode())
953     return SDValue();
954   AddToWorklist(NewOp.getNode());
955
956   if (Replace)
957     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
958   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
959                      DAG.getValueType(OldVT));
960 }
961
962 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
963   EVT OldVT = Op.getValueType();
964   SDLoc dl(Op);
965   bool Replace = false;
966   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
967   if (!NewOp.getNode())
968     return SDValue();
969   AddToWorklist(NewOp.getNode());
970
971   if (Replace)
972     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
973   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
974 }
975
976 /// Promote the specified integer binary operation if the target indicates it is
977 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
978 /// i32 since i16 instructions are longer.
979 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
980   if (!LegalOperations)
981     return SDValue();
982
983   EVT VT = Op.getValueType();
984   if (VT.isVector() || !VT.isInteger())
985     return SDValue();
986
987   // If operation type is 'undesirable', e.g. i16 on x86, consider
988   // promoting it.
989   unsigned Opc = Op.getOpcode();
990   if (TLI.isTypeDesirableForOp(Opc, VT))
991     return SDValue();
992
993   EVT PVT = VT;
994   // Consult target whether it is a good idea to promote this operation and
995   // what's the right type to promote it to.
996   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
997     assert(PVT != VT && "Don't know what type to promote to!");
998
999     bool Replace0 = false;
1000     SDValue N0 = Op.getOperand(0);
1001     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1002     if (!NN0.getNode())
1003       return SDValue();
1004
1005     bool Replace1 = false;
1006     SDValue N1 = Op.getOperand(1);
1007     SDValue NN1;
1008     if (N0 == N1)
1009       NN1 = NN0;
1010     else {
1011       NN1 = PromoteOperand(N1, PVT, Replace1);
1012       if (!NN1.getNode())
1013         return SDValue();
1014     }
1015
1016     AddToWorklist(NN0.getNode());
1017     if (NN1.getNode())
1018       AddToWorklist(NN1.getNode());
1019
1020     if (Replace0)
1021       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1022     if (Replace1)
1023       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1024
1025     DEBUG(dbgs() << "\nPromoting ";
1026           Op.getNode()->dump(&DAG));
1027     SDLoc dl(Op);
1028     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1029                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1030   }
1031   return SDValue();
1032 }
1033
1034 /// Promote the specified integer shift operation if the target indicates it is
1035 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1036 /// i32 since i16 instructions are longer.
1037 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1038   if (!LegalOperations)
1039     return SDValue();
1040
1041   EVT VT = Op.getValueType();
1042   if (VT.isVector() || !VT.isInteger())
1043     return SDValue();
1044
1045   // If operation type is 'undesirable', e.g. i16 on x86, consider
1046   // promoting it.
1047   unsigned Opc = Op.getOpcode();
1048   if (TLI.isTypeDesirableForOp(Opc, VT))
1049     return SDValue();
1050
1051   EVT PVT = VT;
1052   // Consult target whether it is a good idea to promote this operation and
1053   // what's the right type to promote it to.
1054   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055     assert(PVT != VT && "Don't know what type to promote to!");
1056
1057     bool Replace = false;
1058     SDValue N0 = Op.getOperand(0);
1059     if (Opc == ISD::SRA)
1060       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1061     else if (Opc == ISD::SRL)
1062       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1063     else
1064       N0 = PromoteOperand(N0, PVT, Replace);
1065     if (!N0.getNode())
1066       return SDValue();
1067
1068     AddToWorklist(N0.getNode());
1069     if (Replace)
1070       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1071
1072     DEBUG(dbgs() << "\nPromoting ";
1073           Op.getNode()->dump(&DAG));
1074     SDLoc dl(Op);
1075     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1076                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1077   }
1078   return SDValue();
1079 }
1080
1081 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1082   if (!LegalOperations)
1083     return SDValue();
1084
1085   EVT VT = Op.getValueType();
1086   if (VT.isVector() || !VT.isInteger())
1087     return SDValue();
1088
1089   // If operation type is 'undesirable', e.g. i16 on x86, consider
1090   // promoting it.
1091   unsigned Opc = Op.getOpcode();
1092   if (TLI.isTypeDesirableForOp(Opc, VT))
1093     return SDValue();
1094
1095   EVT PVT = VT;
1096   // Consult target whether it is a good idea to promote this operation and
1097   // what's the right type to promote it to.
1098   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1099     assert(PVT != VT && "Don't know what type to promote to!");
1100     // fold (aext (aext x)) -> (aext x)
1101     // fold (aext (zext x)) -> (zext x)
1102     // fold (aext (sext x)) -> (sext x)
1103     DEBUG(dbgs() << "\nPromoting ";
1104           Op.getNode()->dump(&DAG));
1105     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1106   }
1107   return SDValue();
1108 }
1109
1110 bool DAGCombiner::PromoteLoad(SDValue Op) {
1111   if (!LegalOperations)
1112     return false;
1113
1114   EVT VT = Op.getValueType();
1115   if (VT.isVector() || !VT.isInteger())
1116     return false;
1117
1118   // If operation type is 'undesirable', e.g. i16 on x86, consider
1119   // promoting it.
1120   unsigned Opc = Op.getOpcode();
1121   if (TLI.isTypeDesirableForOp(Opc, VT))
1122     return false;
1123
1124   EVT PVT = VT;
1125   // Consult target whether it is a good idea to promote this operation and
1126   // what's the right type to promote it to.
1127   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1128     assert(PVT != VT && "Don't know what type to promote to!");
1129
1130     SDLoc dl(Op);
1131     SDNode *N = Op.getNode();
1132     LoadSDNode *LD = cast<LoadSDNode>(N);
1133     EVT MemVT = LD->getMemoryVT();
1134     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1135       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1136                                                        : ISD::EXTLOAD)
1137       : LD->getExtensionType();
1138     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1139                                    LD->getChain(), LD->getBasePtr(),
1140                                    MemVT, LD->getMemOperand());
1141     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1142
1143     DEBUG(dbgs() << "\nPromoting ";
1144           N->dump(&DAG);
1145           dbgs() << "\nTo: ";
1146           Result.getNode()->dump(&DAG);
1147           dbgs() << '\n');
1148     WorklistRemover DeadNodes(*this);
1149     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1150     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1151     deleteAndRecombine(N);
1152     AddToWorklist(Result.getNode());
1153     return true;
1154   }
1155   return false;
1156 }
1157
1158 /// \brief Recursively delete a node which has no uses and any operands for
1159 /// which it is the only use.
1160 ///
1161 /// Note that this both deletes the nodes and removes them from the worklist.
1162 /// It also adds any nodes who have had a user deleted to the worklist as they
1163 /// may now have only one use and subject to other combines.
1164 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1165   if (!N->use_empty())
1166     return false;
1167
1168   SmallSetVector<SDNode *, 16> Nodes;
1169   Nodes.insert(N);
1170   do {
1171     N = Nodes.pop_back_val();
1172     if (!N)
1173       continue;
1174
1175     if (N->use_empty()) {
1176       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1177         Nodes.insert(N->getOperand(i).getNode());
1178
1179       removeFromWorklist(N);
1180       DAG.DeleteNode(N);
1181     } else {
1182       AddToWorklist(N);
1183     }
1184   } while (!Nodes.empty());
1185   return true;
1186 }
1187
1188 //===----------------------------------------------------------------------===//
1189 //  Main DAG Combiner implementation
1190 //===----------------------------------------------------------------------===//
1191
1192 void DAGCombiner::Run(CombineLevel AtLevel) {
1193   // set the instance variables, so that the various visit routines may use it.
1194   Level = AtLevel;
1195   LegalOperations = Level >= AfterLegalizeVectorOps;
1196   LegalTypes = Level >= AfterLegalizeTypes;
1197
1198   // Add all the dag nodes to the worklist.
1199   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1200        E = DAG.allnodes_end(); I != E; ++I)
1201     AddToWorklist(I);
1202
1203   // Create a dummy node (which is not added to allnodes), that adds a reference
1204   // to the root node, preventing it from being deleted, and tracking any
1205   // changes of the root.
1206   HandleSDNode Dummy(DAG.getRoot());
1207
1208   // while the worklist isn't empty, find a node and
1209   // try and combine it.
1210   while (!WorklistMap.empty()) {
1211     SDNode *N;
1212     // The Worklist holds the SDNodes in order, but it may contain null entries.
1213     do {
1214       N = Worklist.pop_back_val();
1215     } while (!N);
1216
1217     bool GoodWorklistEntry = WorklistMap.erase(N);
1218     (void)GoodWorklistEntry;
1219     assert(GoodWorklistEntry &&
1220            "Found a worklist entry without a corresponding map entry!");
1221
1222     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1223     // N is deleted from the DAG, since they too may now be dead or may have a
1224     // reduced number of uses, allowing other xforms.
1225     if (recursivelyDeleteUnusedNodes(N))
1226       continue;
1227
1228     WorklistRemover DeadNodes(*this);
1229
1230     // If this combine is running after legalizing the DAG, re-legalize any
1231     // nodes pulled off the worklist.
1232     if (Level == AfterLegalizeDAG) {
1233       SmallSetVector<SDNode *, 16> UpdatedNodes;
1234       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1235
1236       for (SDNode *LN : UpdatedNodes) {
1237         AddToWorklist(LN);
1238         AddUsersToWorklist(LN);
1239       }
1240       if (!NIsValid)
1241         continue;
1242     }
1243
1244     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1245
1246     // Add any operands of the new node which have not yet been combined to the
1247     // worklist as well. Because the worklist uniques things already, this
1248     // won't repeatedly process the same operand.
1249     CombinedNodes.insert(N);
1250     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1251       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1252         AddToWorklist(N->getOperand(i).getNode());
1253
1254     SDValue RV = combine(N);
1255
1256     if (!RV.getNode())
1257       continue;
1258
1259     ++NodesCombined;
1260
1261     // If we get back the same node we passed in, rather than a new node or
1262     // zero, we know that the node must have defined multiple values and
1263     // CombineTo was used.  Since CombineTo takes care of the worklist
1264     // mechanics for us, we have no work to do in this case.
1265     if (RV.getNode() == N)
1266       continue;
1267
1268     assert(N->getOpcode() != ISD::DELETED_NODE &&
1269            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1270            "Node was deleted but visit returned new node!");
1271
1272     DEBUG(dbgs() << " ... into: ";
1273           RV.getNode()->dump(&DAG));
1274
1275     // Transfer debug value.
1276     DAG.TransferDbgValues(SDValue(N, 0), RV);
1277     if (N->getNumValues() == RV.getNode()->getNumValues())
1278       DAG.ReplaceAllUsesWith(N, RV.getNode());
1279     else {
1280       assert(N->getValueType(0) == RV.getValueType() &&
1281              N->getNumValues() == 1 && "Type mismatch");
1282       SDValue OpV = RV;
1283       DAG.ReplaceAllUsesWith(N, &OpV);
1284     }
1285
1286     // Push the new node and any users onto the worklist
1287     AddToWorklist(RV.getNode());
1288     AddUsersToWorklist(RV.getNode());
1289
1290     // Finally, if the node is now dead, remove it from the graph.  The node
1291     // may not be dead if the replacement process recursively simplified to
1292     // something else needing this node. This will also take care of adding any
1293     // operands which have lost a user to the worklist.
1294     recursivelyDeleteUnusedNodes(N);
1295   }
1296
1297   // If the root changed (e.g. it was a dead load, update the root).
1298   DAG.setRoot(Dummy.getValue());
1299   DAG.RemoveDeadNodes();
1300 }
1301
1302 SDValue DAGCombiner::visit(SDNode *N) {
1303   switch (N->getOpcode()) {
1304   default: break;
1305   case ISD::TokenFactor:        return visitTokenFactor(N);
1306   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1307   case ISD::ADD:                return visitADD(N);
1308   case ISD::SUB:                return visitSUB(N);
1309   case ISD::ADDC:               return visitADDC(N);
1310   case ISD::SUBC:               return visitSUBC(N);
1311   case ISD::ADDE:               return visitADDE(N);
1312   case ISD::SUBE:               return visitSUBE(N);
1313   case ISD::MUL:                return visitMUL(N);
1314   case ISD::SDIV:               return visitSDIV(N);
1315   case ISD::UDIV:               return visitUDIV(N);
1316   case ISD::SREM:               return visitSREM(N);
1317   case ISD::UREM:               return visitUREM(N);
1318   case ISD::MULHU:              return visitMULHU(N);
1319   case ISD::MULHS:              return visitMULHS(N);
1320   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1321   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1322   case ISD::SMULO:              return visitSMULO(N);
1323   case ISD::UMULO:              return visitUMULO(N);
1324   case ISD::SDIVREM:            return visitSDIVREM(N);
1325   case ISD::UDIVREM:            return visitUDIVREM(N);
1326   case ISD::AND:                return visitAND(N);
1327   case ISD::OR:                 return visitOR(N);
1328   case ISD::XOR:                return visitXOR(N);
1329   case ISD::SHL:                return visitSHL(N);
1330   case ISD::SRA:                return visitSRA(N);
1331   case ISD::SRL:                return visitSRL(N);
1332   case ISD::ROTR:
1333   case ISD::ROTL:               return visitRotate(N);
1334   case ISD::CTLZ:               return visitCTLZ(N);
1335   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1336   case ISD::CTTZ:               return visitCTTZ(N);
1337   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1338   case ISD::CTPOP:              return visitCTPOP(N);
1339   case ISD::SELECT:             return visitSELECT(N);
1340   case ISD::VSELECT:            return visitVSELECT(N);
1341   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1342   case ISD::SETCC:              return visitSETCC(N);
1343   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1344   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1345   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1346   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1347   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1348   case ISD::BITCAST:            return visitBITCAST(N);
1349   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1350   case ISD::FADD:               return visitFADD(N);
1351   case ISD::FSUB:               return visitFSUB(N);
1352   case ISD::FMUL:               return visitFMUL(N);
1353   case ISD::FMA:                return visitFMA(N);
1354   case ISD::FDIV:               return visitFDIV(N);
1355   case ISD::FREM:               return visitFREM(N);
1356   case ISD::FSQRT:              return visitFSQRT(N);
1357   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1358   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1359   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1360   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1361   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1362   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1363   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1364   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1365   case ISD::FNEG:               return visitFNEG(N);
1366   case ISD::FABS:               return visitFABS(N);
1367   case ISD::FFLOOR:             return visitFFLOOR(N);
1368   case ISD::FMINNUM:            return visitFMINNUM(N);
1369   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1370   case ISD::FCEIL:              return visitFCEIL(N);
1371   case ISD::FTRUNC:             return visitFTRUNC(N);
1372   case ISD::BRCOND:             return visitBRCOND(N);
1373   case ISD::BR_CC:              return visitBR_CC(N);
1374   case ISD::LOAD:               return visitLOAD(N);
1375   case ISD::STORE:              return visitSTORE(N);
1376   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1377   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1378   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1379   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1380   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1381   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1382   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1383   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1384   case ISD::MLOAD:              return visitMLOAD(N);
1385   case ISD::MSTORE:             return visitMSTORE(N);
1386   }
1387   return SDValue();
1388 }
1389
1390 SDValue DAGCombiner::combine(SDNode *N) {
1391   SDValue RV = visit(N);
1392
1393   // If nothing happened, try a target-specific DAG combine.
1394   if (!RV.getNode()) {
1395     assert(N->getOpcode() != ISD::DELETED_NODE &&
1396            "Node was deleted but visit returned NULL!");
1397
1398     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1399         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1400
1401       // Expose the DAG combiner to the target combiner impls.
1402       TargetLowering::DAGCombinerInfo
1403         DagCombineInfo(DAG, Level, false, this);
1404
1405       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1406     }
1407   }
1408
1409   // If nothing happened still, try promoting the operation.
1410   if (!RV.getNode()) {
1411     switch (N->getOpcode()) {
1412     default: break;
1413     case ISD::ADD:
1414     case ISD::SUB:
1415     case ISD::MUL:
1416     case ISD::AND:
1417     case ISD::OR:
1418     case ISD::XOR:
1419       RV = PromoteIntBinOp(SDValue(N, 0));
1420       break;
1421     case ISD::SHL:
1422     case ISD::SRA:
1423     case ISD::SRL:
1424       RV = PromoteIntShiftOp(SDValue(N, 0));
1425       break;
1426     case ISD::SIGN_EXTEND:
1427     case ISD::ZERO_EXTEND:
1428     case ISD::ANY_EXTEND:
1429       RV = PromoteExtend(SDValue(N, 0));
1430       break;
1431     case ISD::LOAD:
1432       if (PromoteLoad(SDValue(N, 0)))
1433         RV = SDValue(N, 0);
1434       break;
1435     }
1436   }
1437
1438   // If N is a commutative binary node, try commuting it to enable more
1439   // sdisel CSE.
1440   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1441       N->getNumValues() == 1) {
1442     SDValue N0 = N->getOperand(0);
1443     SDValue N1 = N->getOperand(1);
1444
1445     // Constant operands are canonicalized to RHS.
1446     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1447       SDValue Ops[] = {N1, N0};
1448       SDNode *CSENode;
1449       if (const BinaryWithFlagsSDNode *BinNode =
1450               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1451         CSENode = DAG.getNodeIfExists(
1452             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1453             BinNode->hasNoSignedWrap(), BinNode->isExact());
1454       } else {
1455         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1456       }
1457       if (CSENode)
1458         return SDValue(CSENode, 0);
1459     }
1460   }
1461
1462   return RV;
1463 }
1464
1465 /// Given a node, return its input chain if it has one, otherwise return a null
1466 /// sd operand.
1467 static SDValue getInputChainForNode(SDNode *N) {
1468   if (unsigned NumOps = N->getNumOperands()) {
1469     if (N->getOperand(0).getValueType() == MVT::Other)
1470       return N->getOperand(0);
1471     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1472       return N->getOperand(NumOps-1);
1473     for (unsigned i = 1; i < NumOps-1; ++i)
1474       if (N->getOperand(i).getValueType() == MVT::Other)
1475         return N->getOperand(i);
1476   }
1477   return SDValue();
1478 }
1479
1480 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1481   // If N has two operands, where one has an input chain equal to the other,
1482   // the 'other' chain is redundant.
1483   if (N->getNumOperands() == 2) {
1484     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1485       return N->getOperand(0);
1486     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1487       return N->getOperand(1);
1488   }
1489
1490   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1491   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1492   SmallPtrSet<SDNode*, 16> SeenOps;
1493   bool Changed = false;             // If we should replace this token factor.
1494
1495   // Start out with this token factor.
1496   TFs.push_back(N);
1497
1498   // Iterate through token factors.  The TFs grows when new token factors are
1499   // encountered.
1500   for (unsigned i = 0; i < TFs.size(); ++i) {
1501     SDNode *TF = TFs[i];
1502
1503     // Check each of the operands.
1504     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1505       SDValue Op = TF->getOperand(i);
1506
1507       switch (Op.getOpcode()) {
1508       case ISD::EntryToken:
1509         // Entry tokens don't need to be added to the list. They are
1510         // redundant.
1511         Changed = true;
1512         break;
1513
1514       case ISD::TokenFactor:
1515         if (Op.hasOneUse() &&
1516             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1517           // Queue up for processing.
1518           TFs.push_back(Op.getNode());
1519           // Clean up in case the token factor is removed.
1520           AddToWorklist(Op.getNode());
1521           Changed = true;
1522           break;
1523         }
1524         // Fall thru
1525
1526       default:
1527         // Only add if it isn't already in the list.
1528         if (SeenOps.insert(Op.getNode()).second)
1529           Ops.push_back(Op);
1530         else
1531           Changed = true;
1532         break;
1533       }
1534     }
1535   }
1536
1537   SDValue Result;
1538
1539   // If we've changed things around then replace token factor.
1540   if (Changed) {
1541     if (Ops.empty()) {
1542       // The entry token is the only possible outcome.
1543       Result = DAG.getEntryNode();
1544     } else {
1545       // New and improved token factor.
1546       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1547     }
1548
1549     // Add users to worklist if AA is enabled, since it may introduce
1550     // a lot of new chained token factors while removing memory deps.
1551     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1552       : DAG.getSubtarget().useAA();
1553     return CombineTo(N, Result, UseAA /*add to worklist*/);
1554   }
1555
1556   return Result;
1557 }
1558
1559 /// MERGE_VALUES can always be eliminated.
1560 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1561   WorklistRemover DeadNodes(*this);
1562   // Replacing results may cause a different MERGE_VALUES to suddenly
1563   // be CSE'd with N, and carry its uses with it. Iterate until no
1564   // uses remain, to ensure that the node can be safely deleted.
1565   // First add the users of this node to the work list so that they
1566   // can be tried again once they have new operands.
1567   AddUsersToWorklist(N);
1568   do {
1569     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1570       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1571   } while (!N->use_empty());
1572   deleteAndRecombine(N);
1573   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1574 }
1575
1576 SDValue DAGCombiner::visitADD(SDNode *N) {
1577   SDValue N0 = N->getOperand(0);
1578   SDValue N1 = N->getOperand(1);
1579   EVT VT = N0.getValueType();
1580
1581   // fold vector ops
1582   if (VT.isVector()) {
1583     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1584       return FoldedVOp;
1585
1586     // fold (add x, 0) -> x, vector edition
1587     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1588       return N0;
1589     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1590       return N1;
1591   }
1592
1593   // fold (add x, undef) -> undef
1594   if (N0.getOpcode() == ISD::UNDEF)
1595     return N0;
1596   if (N1.getOpcode() == ISD::UNDEF)
1597     return N1;
1598   // fold (add c1, c2) -> c1+c2
1599   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1600   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1601   if (N0C && N1C)
1602     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1603   // canonicalize constant to RHS
1604   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1605      !isConstantIntBuildVectorOrConstantInt(N1))
1606     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1607   // fold (add x, 0) -> x
1608   if (N1C && N1C->isNullValue())
1609     return N0;
1610   // fold (add Sym, c) -> Sym+c
1611   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1612     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1613         GA->getOpcode() == ISD::GlobalAddress)
1614       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1615                                   GA->getOffset() +
1616                                     (uint64_t)N1C->getSExtValue());
1617   // fold ((c1-A)+c2) -> (c1+c2)-A
1618   if (N1C && N0.getOpcode() == ISD::SUB)
1619     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1620       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1621                          DAG.getConstant(N1C->getAPIntValue()+
1622                                          N0C->getAPIntValue(), VT),
1623                          N0.getOperand(1));
1624   // reassociate add
1625   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1626     return RADD;
1627   // fold ((0-A) + B) -> B-A
1628   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1629       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1630     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1631   // fold (A + (0-B)) -> A-B
1632   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1633       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1634     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1635   // fold (A+(B-A)) -> B
1636   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1637     return N1.getOperand(0);
1638   // fold ((B-A)+A) -> B
1639   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1640     return N0.getOperand(0);
1641   // fold (A+(B-(A+C))) to (B-C)
1642   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1643       N0 == N1.getOperand(1).getOperand(0))
1644     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1645                        N1.getOperand(1).getOperand(1));
1646   // fold (A+(B-(C+A))) to (B-C)
1647   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1648       N0 == N1.getOperand(1).getOperand(1))
1649     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1650                        N1.getOperand(1).getOperand(0));
1651   // fold (A+((B-A)+or-C)) to (B+or-C)
1652   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1653       N1.getOperand(0).getOpcode() == ISD::SUB &&
1654       N0 == N1.getOperand(0).getOperand(1))
1655     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1656                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1657
1658   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1659   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1660     SDValue N00 = N0.getOperand(0);
1661     SDValue N01 = N0.getOperand(1);
1662     SDValue N10 = N1.getOperand(0);
1663     SDValue N11 = N1.getOperand(1);
1664
1665     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1666       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1667                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1668                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1669   }
1670
1671   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1672     return SDValue(N, 0);
1673
1674   // fold (a+b) -> (a|b) iff a and b share no bits.
1675   if (VT.isInteger() && !VT.isVector()) {
1676     APInt LHSZero, LHSOne;
1677     APInt RHSZero, RHSOne;
1678     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1679
1680     if (LHSZero.getBoolValue()) {
1681       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1682
1683       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1684       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1685       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1686         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1687           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1688       }
1689     }
1690   }
1691
1692   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1693   if (N1.getOpcode() == ISD::SHL &&
1694       N1.getOperand(0).getOpcode() == ISD::SUB)
1695     if (ConstantSDNode *C =
1696           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1697       if (C->getAPIntValue() == 0)
1698         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1699                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1700                                        N1.getOperand(0).getOperand(1),
1701                                        N1.getOperand(1)));
1702   if (N0.getOpcode() == ISD::SHL &&
1703       N0.getOperand(0).getOpcode() == ISD::SUB)
1704     if (ConstantSDNode *C =
1705           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1706       if (C->getAPIntValue() == 0)
1707         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1708                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1709                                        N0.getOperand(0).getOperand(1),
1710                                        N0.getOperand(1)));
1711
1712   if (N1.getOpcode() == ISD::AND) {
1713     SDValue AndOp0 = N1.getOperand(0);
1714     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1715     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1716     unsigned DestBits = VT.getScalarType().getSizeInBits();
1717
1718     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1719     // and similar xforms where the inner op is either ~0 or 0.
1720     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1721       SDLoc DL(N);
1722       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1723     }
1724   }
1725
1726   // add (sext i1), X -> sub X, (zext i1)
1727   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1728       N0.getOperand(0).getValueType() == MVT::i1 &&
1729       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1730     SDLoc DL(N);
1731     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1732     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1733   }
1734
1735   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1736   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1737     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1738     if (TN->getVT() == MVT::i1) {
1739       SDLoc DL(N);
1740       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1741                                  DAG.getConstant(1, VT));
1742       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1743     }
1744   }
1745
1746   return SDValue();
1747 }
1748
1749 SDValue DAGCombiner::visitADDC(SDNode *N) {
1750   SDValue N0 = N->getOperand(0);
1751   SDValue N1 = N->getOperand(1);
1752   EVT VT = N0.getValueType();
1753
1754   // If the flag result is dead, turn this into an ADD.
1755   if (!N->hasAnyUseOfValue(1))
1756     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1757                      DAG.getNode(ISD::CARRY_FALSE,
1758                                  SDLoc(N), MVT::Glue));
1759
1760   // canonicalize constant to RHS.
1761   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1762   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1763   if (N0C && !N1C)
1764     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1765
1766   // fold (addc x, 0) -> x + no carry out
1767   if (N1C && N1C->isNullValue())
1768     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1769                                         SDLoc(N), MVT::Glue));
1770
1771   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1772   APInt LHSZero, LHSOne;
1773   APInt RHSZero, RHSOne;
1774   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1775
1776   if (LHSZero.getBoolValue()) {
1777     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1778
1779     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1780     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1781     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1782       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1783                        DAG.getNode(ISD::CARRY_FALSE,
1784                                    SDLoc(N), MVT::Glue));
1785   }
1786
1787   return SDValue();
1788 }
1789
1790 SDValue DAGCombiner::visitADDE(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   SDValue CarryIn = N->getOperand(2);
1794
1795   // canonicalize constant to RHS
1796   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1797   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1798   if (N0C && !N1C)
1799     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1800                        N1, N0, CarryIn);
1801
1802   // fold (adde x, y, false) -> (addc x, y)
1803   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1804     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1805
1806   return SDValue();
1807 }
1808
1809 // Since it may not be valid to emit a fold to zero for vector initializers
1810 // check if we can before folding.
1811 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1812                              SelectionDAG &DAG,
1813                              bool LegalOperations, bool LegalTypes) {
1814   if (!VT.isVector())
1815     return DAG.getConstant(0, VT);
1816   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1817     return DAG.getConstant(0, VT);
1818   return SDValue();
1819 }
1820
1821 SDValue DAGCombiner::visitSUB(SDNode *N) {
1822   SDValue N0 = N->getOperand(0);
1823   SDValue N1 = N->getOperand(1);
1824   EVT VT = N0.getValueType();
1825
1826   // fold vector ops
1827   if (VT.isVector()) {
1828     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1829       return FoldedVOp;
1830
1831     // fold (sub x, 0) -> x, vector edition
1832     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1833       return N0;
1834   }
1835
1836   // fold (sub x, x) -> 0
1837   // FIXME: Refactor this and xor and other similar operations together.
1838   if (N0 == N1)
1839     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1840   // fold (sub c1, c2) -> c1-c2
1841   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1842   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1843   if (N0C && N1C)
1844     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1845   // fold (sub x, c) -> (add x, -c)
1846   if (N1C)
1847     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1848                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1849   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1850   if (N0C && N0C->isAllOnesValue())
1851     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1852   // fold A-(A-B) -> B
1853   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1854     return N1.getOperand(1);
1855   // fold (A+B)-A -> B
1856   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1857     return N0.getOperand(1);
1858   // fold (A+B)-B -> A
1859   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1860     return N0.getOperand(0);
1861   // fold C2-(A+C1) -> (C2-C1)-A
1862   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1863     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1864   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1865     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1866                                    VT);
1867     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1868                        N1.getOperand(0));
1869   }
1870   // fold ((A+(B+or-C))-B) -> A+or-C
1871   if (N0.getOpcode() == ISD::ADD &&
1872       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1873        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1874       N0.getOperand(1).getOperand(0) == N1)
1875     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1876                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1877   // fold ((A+(C+B))-B) -> A+C
1878   if (N0.getOpcode() == ISD::ADD &&
1879       N0.getOperand(1).getOpcode() == ISD::ADD &&
1880       N0.getOperand(1).getOperand(1) == N1)
1881     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1882                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1883   // fold ((A-(B-C))-C) -> A-B
1884   if (N0.getOpcode() == ISD::SUB &&
1885       N0.getOperand(1).getOpcode() == ISD::SUB &&
1886       N0.getOperand(1).getOperand(1) == N1)
1887     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1888                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1889
1890   // If either operand of a sub is undef, the result is undef
1891   if (N0.getOpcode() == ISD::UNDEF)
1892     return N0;
1893   if (N1.getOpcode() == ISD::UNDEF)
1894     return N1;
1895
1896   // If the relocation model supports it, consider symbol offsets.
1897   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1898     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1899       // fold (sub Sym, c) -> Sym-c
1900       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1901         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1902                                     GA->getOffset() -
1903                                       (uint64_t)N1C->getSExtValue());
1904       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1905       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1906         if (GA->getGlobal() == GB->getGlobal())
1907           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1908                                  VT);
1909     }
1910
1911   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1912   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1913     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1914     if (TN->getVT() == MVT::i1) {
1915       SDLoc DL(N);
1916       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1917                                  DAG.getConstant(1, VT));
1918       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1919     }
1920   }
1921
1922   return SDValue();
1923 }
1924
1925 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1926   SDValue N0 = N->getOperand(0);
1927   SDValue N1 = N->getOperand(1);
1928   EVT VT = N0.getValueType();
1929
1930   // If the flag result is dead, turn this into an SUB.
1931   if (!N->hasAnyUseOfValue(1))
1932     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1933                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1934                                  MVT::Glue));
1935
1936   // fold (subc x, x) -> 0 + no borrow
1937   if (N0 == N1)
1938     return CombineTo(N, DAG.getConstant(0, VT),
1939                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1940                                  MVT::Glue));
1941
1942   // fold (subc x, 0) -> x + no borrow
1943   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1944   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1945   if (N1C && N1C->isNullValue())
1946     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1947                                         MVT::Glue));
1948
1949   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1950   if (N0C && N0C->isAllOnesValue())
1951     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1952                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1953                                  MVT::Glue));
1954
1955   return SDValue();
1956 }
1957
1958 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1959   SDValue N0 = N->getOperand(0);
1960   SDValue N1 = N->getOperand(1);
1961   SDValue CarryIn = N->getOperand(2);
1962
1963   // fold (sube x, y, false) -> (subc x, y)
1964   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1965     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1966
1967   return SDValue();
1968 }
1969
1970 SDValue DAGCombiner::visitMUL(SDNode *N) {
1971   SDValue N0 = N->getOperand(0);
1972   SDValue N1 = N->getOperand(1);
1973   EVT VT = N0.getValueType();
1974
1975   // fold (mul x, undef) -> 0
1976   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1977     return DAG.getConstant(0, VT);
1978
1979   bool N0IsConst = false;
1980   bool N1IsConst = false;
1981   APInt ConstValue0, ConstValue1;
1982   // fold vector ops
1983   if (VT.isVector()) {
1984     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1985       return FoldedVOp;
1986
1987     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1988     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1989   } else {
1990     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1991     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1992                             : APInt();
1993     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1994     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1995                             : APInt();
1996   }
1997
1998   // fold (mul c1, c2) -> c1*c2
1999   if (N0IsConst && N1IsConst)
2000     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
2001
2002   // canonicalize constant to RHS (vector doesn't have to splat)
2003   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2004      !isConstantIntBuildVectorOrConstantInt(N1))
2005     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2006   // fold (mul x, 0) -> 0
2007   if (N1IsConst && ConstValue1 == 0)
2008     return N1;
2009   // We require a splat of the entire scalar bit width for non-contiguous
2010   // bit patterns.
2011   bool IsFullSplat =
2012     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2013   // fold (mul x, 1) -> x
2014   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2015     return N0;
2016   // fold (mul x, -1) -> 0-x
2017   if (N1IsConst && ConstValue1.isAllOnesValue())
2018     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2019                        DAG.getConstant(0, VT), N0);
2020   // fold (mul x, (1 << c)) -> x << c
2021   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2022     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2023                        DAG.getConstant(ConstValue1.logBase2(),
2024                                        getShiftAmountTy(N0.getValueType())));
2025   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2026   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2027     unsigned Log2Val = (-ConstValue1).logBase2();
2028     // FIXME: If the input is something that is easily negated (e.g. a
2029     // single-use add), we should put the negate there.
2030     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2031                        DAG.getConstant(0, VT),
2032                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2033                             DAG.getConstant(Log2Val,
2034                                       getShiftAmountTy(N0.getValueType()))));
2035   }
2036
2037   APInt Val;
2038   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2039   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2040       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2041                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2042     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2043                              N1, N0.getOperand(1));
2044     AddToWorklist(C3.getNode());
2045     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2046                        N0.getOperand(0), C3);
2047   }
2048
2049   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2050   // use.
2051   {
2052     SDValue Sh(nullptr,0), Y(nullptr,0);
2053     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2054     if (N0.getOpcode() == ISD::SHL &&
2055         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2056                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2057         N0.getNode()->hasOneUse()) {
2058       Sh = N0; Y = N1;
2059     } else if (N1.getOpcode() == ISD::SHL &&
2060                isa<ConstantSDNode>(N1.getOperand(1)) &&
2061                N1.getNode()->hasOneUse()) {
2062       Sh = N1; Y = N0;
2063     }
2064
2065     if (Sh.getNode()) {
2066       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2067                                 Sh.getOperand(0), Y);
2068       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2069                          Mul, Sh.getOperand(1));
2070     }
2071   }
2072
2073   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2074   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2075       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2076                      isa<ConstantSDNode>(N0.getOperand(1))))
2077     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2078                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2079                                    N0.getOperand(0), N1),
2080                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2081                                    N0.getOperand(1), N1));
2082
2083   // reassociate mul
2084   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2085     return RMUL;
2086
2087   return SDValue();
2088 }
2089
2090 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2091   SDValue N0 = N->getOperand(0);
2092   SDValue N1 = N->getOperand(1);
2093   EVT VT = N->getValueType(0);
2094
2095   // fold vector ops
2096   if (VT.isVector())
2097     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2098       return FoldedVOp;
2099
2100   // fold (sdiv c1, c2) -> c1/c2
2101   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2102   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2103   if (N0C && N1C && !N1C->isNullValue())
2104     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2105   // fold (sdiv X, 1) -> X
2106   if (N1C && N1C->getAPIntValue() == 1LL)
2107     return N0;
2108   // fold (sdiv X, -1) -> 0-X
2109   if (N1C && N1C->isAllOnesValue())
2110     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2111                        DAG.getConstant(0, VT), N0);
2112   // If we know the sign bits of both operands are zero, strength reduce to a
2113   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2114   if (!VT.isVector()) {
2115     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2116       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2117                          N0, N1);
2118   }
2119
2120   // fold (sdiv X, pow2) -> simple ops after legalize
2121   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2122                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2123     // If dividing by powers of two is cheap, then don't perform the following
2124     // fold.
2125     if (TLI.isPow2SDivCheap())
2126       return SDValue();
2127
2128     // Target-specific implementation of sdiv x, pow2.
2129     SDValue Res = BuildSDIVPow2(N);
2130     if (Res.getNode())
2131       return Res;
2132
2133     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2134
2135     // Splat the sign bit into the register
2136     SDValue SGN =
2137         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2138                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2139                                     getShiftAmountTy(N0.getValueType())));
2140     AddToWorklist(SGN.getNode());
2141
2142     // Add (N0 < 0) ? abs2 - 1 : 0;
2143     SDValue SRL =
2144         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2145                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2146                                     getShiftAmountTy(SGN.getValueType())));
2147     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2148     AddToWorklist(SRL.getNode());
2149     AddToWorklist(ADD.getNode());    // Divide by pow2
2150     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2151                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2152
2153     // If we're dividing by a positive value, we're done.  Otherwise, we must
2154     // negate the result.
2155     if (N1C->getAPIntValue().isNonNegative())
2156       return SRA;
2157
2158     AddToWorklist(SRA.getNode());
2159     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2160   }
2161
2162   // If integer divide is expensive and we satisfy the requirements, emit an
2163   // alternate sequence.
2164   if (N1C && !TLI.isIntDivCheap()) {
2165     SDValue Op = BuildSDIV(N);
2166     if (Op.getNode()) return Op;
2167   }
2168
2169   // undef / X -> 0
2170   if (N0.getOpcode() == ISD::UNDEF)
2171     return DAG.getConstant(0, VT);
2172   // X / undef -> undef
2173   if (N1.getOpcode() == ISD::UNDEF)
2174     return N1;
2175
2176   return SDValue();
2177 }
2178
2179 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2180   SDValue N0 = N->getOperand(0);
2181   SDValue N1 = N->getOperand(1);
2182   EVT VT = N->getValueType(0);
2183
2184   // fold vector ops
2185   if (VT.isVector())
2186     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2187       return FoldedVOp;
2188
2189   // fold (udiv c1, c2) -> c1/c2
2190   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2191   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2192   if (N0C && N1C && !N1C->isNullValue())
2193     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2194   // fold (udiv x, (1 << c)) -> x >>u c
2195   if (N1C && N1C->getAPIntValue().isPowerOf2())
2196     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2197                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2198                                        getShiftAmountTy(N0.getValueType())));
2199   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2200   if (N1.getOpcode() == ISD::SHL) {
2201     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2202       if (SHC->getAPIntValue().isPowerOf2()) {
2203         EVT ADDVT = N1.getOperand(1).getValueType();
2204         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2205                                   N1.getOperand(1),
2206                                   DAG.getConstant(SHC->getAPIntValue()
2207                                                                   .logBase2(),
2208                                                   ADDVT));
2209         AddToWorklist(Add.getNode());
2210         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2211       }
2212     }
2213   }
2214   // fold (udiv x, c) -> alternate
2215   if (N1C && !TLI.isIntDivCheap()) {
2216     SDValue Op = BuildUDIV(N);
2217     if (Op.getNode()) return Op;
2218   }
2219
2220   // undef / X -> 0
2221   if (N0.getOpcode() == ISD::UNDEF)
2222     return DAG.getConstant(0, VT);
2223   // X / undef -> undef
2224   if (N1.getOpcode() == ISD::UNDEF)
2225     return N1;
2226
2227   return SDValue();
2228 }
2229
2230 SDValue DAGCombiner::visitSREM(SDNode *N) {
2231   SDValue N0 = N->getOperand(0);
2232   SDValue N1 = N->getOperand(1);
2233   EVT VT = N->getValueType(0);
2234
2235   // fold (srem c1, c2) -> c1%c2
2236   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2237   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2238   if (N0C && N1C && !N1C->isNullValue())
2239     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2240   // If we know the sign bits of both operands are zero, strength reduce to a
2241   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2242   if (!VT.isVector()) {
2243     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2244       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2245   }
2246
2247   // If X/C can be simplified by the division-by-constant logic, lower
2248   // X%C to the equivalent of X-X/C*C.
2249   if (N1C && !N1C->isNullValue()) {
2250     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2251     AddToWorklist(Div.getNode());
2252     SDValue OptimizedDiv = combine(Div.getNode());
2253     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2254       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2255                                 OptimizedDiv, N1);
2256       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2257       AddToWorklist(Mul.getNode());
2258       return Sub;
2259     }
2260   }
2261
2262   // undef % X -> 0
2263   if (N0.getOpcode() == ISD::UNDEF)
2264     return DAG.getConstant(0, VT);
2265   // X % undef -> undef
2266   if (N1.getOpcode() == ISD::UNDEF)
2267     return N1;
2268
2269   return SDValue();
2270 }
2271
2272 SDValue DAGCombiner::visitUREM(SDNode *N) {
2273   SDValue N0 = N->getOperand(0);
2274   SDValue N1 = N->getOperand(1);
2275   EVT VT = N->getValueType(0);
2276
2277   // fold (urem c1, c2) -> c1%c2
2278   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2279   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2280   if (N0C && N1C && !N1C->isNullValue())
2281     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2282   // fold (urem x, pow2) -> (and x, pow2-1)
2283   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2284     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2285                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2286   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2287   if (N1.getOpcode() == ISD::SHL) {
2288     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2289       if (SHC->getAPIntValue().isPowerOf2()) {
2290         SDValue Add =
2291           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2292                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2293                                  VT));
2294         AddToWorklist(Add.getNode());
2295         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2296       }
2297     }
2298   }
2299
2300   // If X/C can be simplified by the division-by-constant logic, lower
2301   // X%C to the equivalent of X-X/C*C.
2302   if (N1C && !N1C->isNullValue()) {
2303     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2304     AddToWorklist(Div.getNode());
2305     SDValue OptimizedDiv = combine(Div.getNode());
2306     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2307       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2308                                 OptimizedDiv, N1);
2309       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2310       AddToWorklist(Mul.getNode());
2311       return Sub;
2312     }
2313   }
2314
2315   // undef % X -> 0
2316   if (N0.getOpcode() == ISD::UNDEF)
2317     return DAG.getConstant(0, VT);
2318   // X % undef -> undef
2319   if (N1.getOpcode() == ISD::UNDEF)
2320     return N1;
2321
2322   return SDValue();
2323 }
2324
2325 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2326   SDValue N0 = N->getOperand(0);
2327   SDValue N1 = N->getOperand(1);
2328   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2329   EVT VT = N->getValueType(0);
2330   SDLoc DL(N);
2331
2332   // fold (mulhs x, 0) -> 0
2333   if (N1C && N1C->isNullValue())
2334     return N1;
2335   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2336   if (N1C && N1C->getAPIntValue() == 1)
2337     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2338                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2339                                        getShiftAmountTy(N0.getValueType())));
2340   // fold (mulhs x, undef) -> 0
2341   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2342     return DAG.getConstant(0, VT);
2343
2344   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2345   // plus a shift.
2346   if (VT.isSimple() && !VT.isVector()) {
2347     MVT Simple = VT.getSimpleVT();
2348     unsigned SimpleSize = Simple.getSizeInBits();
2349     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2350     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2351       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2352       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2353       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2354       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2355             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2356       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2357     }
2358   }
2359
2360   return SDValue();
2361 }
2362
2363 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2364   SDValue N0 = N->getOperand(0);
2365   SDValue N1 = N->getOperand(1);
2366   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2367   EVT VT = N->getValueType(0);
2368   SDLoc DL(N);
2369
2370   // fold (mulhu x, 0) -> 0
2371   if (N1C && N1C->isNullValue())
2372     return N1;
2373   // fold (mulhu x, 1) -> 0
2374   if (N1C && N1C->getAPIntValue() == 1)
2375     return DAG.getConstant(0, N0.getValueType());
2376   // fold (mulhu x, undef) -> 0
2377   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2378     return DAG.getConstant(0, VT);
2379
2380   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2381   // plus a shift.
2382   if (VT.isSimple() && !VT.isVector()) {
2383     MVT Simple = VT.getSimpleVT();
2384     unsigned SimpleSize = Simple.getSizeInBits();
2385     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2386     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2387       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2388       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2389       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2390       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2391             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2392       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2393     }
2394   }
2395
2396   return SDValue();
2397 }
2398
2399 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2400 /// give the opcodes for the two computations that are being performed. Return
2401 /// true if a simplification was made.
2402 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2403                                                 unsigned HiOp) {
2404   // If the high half is not needed, just compute the low half.
2405   bool HiExists = N->hasAnyUseOfValue(1);
2406   if (!HiExists &&
2407       (!LegalOperations ||
2408        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2409     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2410     return CombineTo(N, Res, Res);
2411   }
2412
2413   // If the low half is not needed, just compute the high half.
2414   bool LoExists = N->hasAnyUseOfValue(0);
2415   if (!LoExists &&
2416       (!LegalOperations ||
2417        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2418     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2419     return CombineTo(N, Res, Res);
2420   }
2421
2422   // If both halves are used, return as it is.
2423   if (LoExists && HiExists)
2424     return SDValue();
2425
2426   // If the two computed results can be simplified separately, separate them.
2427   if (LoExists) {
2428     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2429     AddToWorklist(Lo.getNode());
2430     SDValue LoOpt = combine(Lo.getNode());
2431     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2432         (!LegalOperations ||
2433          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2434       return CombineTo(N, LoOpt, LoOpt);
2435   }
2436
2437   if (HiExists) {
2438     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2439     AddToWorklist(Hi.getNode());
2440     SDValue HiOpt = combine(Hi.getNode());
2441     if (HiOpt.getNode() && HiOpt != Hi &&
2442         (!LegalOperations ||
2443          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2444       return CombineTo(N, HiOpt, HiOpt);
2445   }
2446
2447   return SDValue();
2448 }
2449
2450 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2451   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2452   if (Res.getNode()) return Res;
2453
2454   EVT VT = N->getValueType(0);
2455   SDLoc DL(N);
2456
2457   // If the type is twice as wide is legal, transform the mulhu to a wider
2458   // multiply plus a shift.
2459   if (VT.isSimple() && !VT.isVector()) {
2460     MVT Simple = VT.getSimpleVT();
2461     unsigned SimpleSize = Simple.getSizeInBits();
2462     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2463     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2464       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2465       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2466       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2467       // Compute the high part as N1.
2468       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2469             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2470       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2471       // Compute the low part as N0.
2472       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2473       return CombineTo(N, Lo, Hi);
2474     }
2475   }
2476
2477   return SDValue();
2478 }
2479
2480 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2481   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2482   if (Res.getNode()) return Res;
2483
2484   EVT VT = N->getValueType(0);
2485   SDLoc DL(N);
2486
2487   // If the type is twice as wide is legal, transform the mulhu to a wider
2488   // multiply plus a shift.
2489   if (VT.isSimple() && !VT.isVector()) {
2490     MVT Simple = VT.getSimpleVT();
2491     unsigned SimpleSize = Simple.getSizeInBits();
2492     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2493     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2494       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2495       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2496       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2497       // Compute the high part as N1.
2498       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2499             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2500       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2501       // Compute the low part as N0.
2502       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2503       return CombineTo(N, Lo, Hi);
2504     }
2505   }
2506
2507   return SDValue();
2508 }
2509
2510 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2511   // (smulo x, 2) -> (saddo x, x)
2512   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2513     if (C2->getAPIntValue() == 2)
2514       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2515                          N->getOperand(0), N->getOperand(0));
2516
2517   return SDValue();
2518 }
2519
2520 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2521   // (umulo x, 2) -> (uaddo x, x)
2522   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2523     if (C2->getAPIntValue() == 2)
2524       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2525                          N->getOperand(0), N->getOperand(0));
2526
2527   return SDValue();
2528 }
2529
2530 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2531   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2532   if (Res.getNode()) return Res;
2533
2534   return SDValue();
2535 }
2536
2537 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2538   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2539   if (Res.getNode()) return Res;
2540
2541   return SDValue();
2542 }
2543
2544 /// If this is a binary operator with two operands of the same opcode, try to
2545 /// simplify it.
2546 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2547   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2548   EVT VT = N0.getValueType();
2549   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2550
2551   // Bail early if none of these transforms apply.
2552   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2553
2554   // For each of OP in AND/OR/XOR:
2555   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2556   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2557   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2558   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2559   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2560   //
2561   // do not sink logical op inside of a vector extend, since it may combine
2562   // into a vsetcc.
2563   EVT Op0VT = N0.getOperand(0).getValueType();
2564   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2565        N0.getOpcode() == ISD::SIGN_EXTEND ||
2566        N0.getOpcode() == ISD::BSWAP ||
2567        // Avoid infinite looping with PromoteIntBinOp.
2568        (N0.getOpcode() == ISD::ANY_EXTEND &&
2569         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2570        (N0.getOpcode() == ISD::TRUNCATE &&
2571         (!TLI.isZExtFree(VT, Op0VT) ||
2572          !TLI.isTruncateFree(Op0VT, VT)) &&
2573         TLI.isTypeLegal(Op0VT))) &&
2574       !VT.isVector() &&
2575       Op0VT == N1.getOperand(0).getValueType() &&
2576       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2577     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2578                                  N0.getOperand(0).getValueType(),
2579                                  N0.getOperand(0), N1.getOperand(0));
2580     AddToWorklist(ORNode.getNode());
2581     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2582   }
2583
2584   // For each of OP in SHL/SRL/SRA/AND...
2585   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2586   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2587   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2588   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2589        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2590       N0.getOperand(1) == N1.getOperand(1)) {
2591     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2592                                  N0.getOperand(0).getValueType(),
2593                                  N0.getOperand(0), N1.getOperand(0));
2594     AddToWorklist(ORNode.getNode());
2595     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2596                        ORNode, N0.getOperand(1));
2597   }
2598
2599   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2600   // Only perform this optimization after type legalization and before
2601   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2602   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2603   // we don't want to undo this promotion.
2604   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2605   // on scalars.
2606   if ((N0.getOpcode() == ISD::BITCAST ||
2607        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2608       Level == AfterLegalizeTypes) {
2609     SDValue In0 = N0.getOperand(0);
2610     SDValue In1 = N1.getOperand(0);
2611     EVT In0Ty = In0.getValueType();
2612     EVT In1Ty = In1.getValueType();
2613     SDLoc DL(N);
2614     // If both incoming values are integers, and the original types are the
2615     // same.
2616     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2617       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2618       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2619       AddToWorklist(Op.getNode());
2620       return BC;
2621     }
2622   }
2623
2624   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2625   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2626   // If both shuffles use the same mask, and both shuffle within a single
2627   // vector, then it is worthwhile to move the swizzle after the operation.
2628   // The type-legalizer generates this pattern when loading illegal
2629   // vector types from memory. In many cases this allows additional shuffle
2630   // optimizations.
2631   // There are other cases where moving the shuffle after the xor/and/or
2632   // is profitable even if shuffles don't perform a swizzle.
2633   // If both shuffles use the same mask, and both shuffles have the same first
2634   // or second operand, then it might still be profitable to move the shuffle
2635   // after the xor/and/or operation.
2636   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2637     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2638     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2639
2640     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2641            "Inputs to shuffles are not the same type");
2642
2643     // Check that both shuffles use the same mask. The masks are known to be of
2644     // the same length because the result vector type is the same.
2645     // Check also that shuffles have only one use to avoid introducing extra
2646     // instructions.
2647     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2648         SVN0->getMask().equals(SVN1->getMask())) {
2649       SDValue ShOp = N0->getOperand(1);
2650
2651       // Don't try to fold this node if it requires introducing a
2652       // build vector of all zeros that might be illegal at this stage.
2653       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2654         if (!LegalTypes)
2655           ShOp = DAG.getConstant(0, VT);
2656         else
2657           ShOp = SDValue();
2658       }
2659
2660       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2661       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2662       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2663       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2664         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2665                                       N0->getOperand(0), N1->getOperand(0));
2666         AddToWorklist(NewNode.getNode());
2667         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2668                                     &SVN0->getMask()[0]);
2669       }
2670
2671       // Don't try to fold this node if it requires introducing a
2672       // build vector of all zeros that might be illegal at this stage.
2673       ShOp = N0->getOperand(0);
2674       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2675         if (!LegalTypes)
2676           ShOp = DAG.getConstant(0, VT);
2677         else
2678           ShOp = SDValue();
2679       }
2680
2681       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2682       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2683       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2684       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2685         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2686                                       N0->getOperand(1), N1->getOperand(1));
2687         AddToWorklist(NewNode.getNode());
2688         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2689                                     &SVN0->getMask()[0]);
2690       }
2691     }
2692   }
2693
2694   return SDValue();
2695 }
2696
2697 /// This contains all DAGCombine rules which reduce two values combined by
2698 /// an And operation to a single value. This makes them reusable in the context
2699 /// of visitSELECT(). Rules involving constants are not included as
2700 /// visitSELECT() already handles those cases.
2701 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2702                                   SDNode *LocReference) {
2703   EVT VT = N1.getValueType();
2704
2705   // fold (and x, undef) -> 0
2706   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2707     return DAG.getConstant(0, VT);
2708   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2709   SDValue LL, LR, RL, RR, CC0, CC1;
2710   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2711     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2712     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2713
2714     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2715         LL.getValueType().isInteger()) {
2716       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2717       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2718         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2719                                      LR.getValueType(), LL, RL);
2720         AddToWorklist(ORNode.getNode());
2721         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2722       }
2723       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2724       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2725         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2726                                       LR.getValueType(), LL, RL);
2727         AddToWorklist(ANDNode.getNode());
2728         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2729       }
2730       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2731       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2732         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2733                                      LR.getValueType(), LL, RL);
2734         AddToWorklist(ORNode.getNode());
2735         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2736       }
2737     }
2738     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2739     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2740         Op0 == Op1 && LL.getValueType().isInteger() &&
2741       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2742                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2743                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2744                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2745       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2746                                     LL, DAG.getConstant(1, LL.getValueType()));
2747       AddToWorklist(ADDNode.getNode());
2748       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2749                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2750     }
2751     // canonicalize equivalent to ll == rl
2752     if (LL == RR && LR == RL) {
2753       Op1 = ISD::getSetCCSwappedOperands(Op1);
2754       std::swap(RL, RR);
2755     }
2756     if (LL == RL && LR == RR) {
2757       bool isInteger = LL.getValueType().isInteger();
2758       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2759       if (Result != ISD::SETCC_INVALID &&
2760           (!LegalOperations ||
2761            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2762             TLI.isOperationLegal(ISD::SETCC,
2763                             getSetCCResultType(N0.getSimpleValueType())))))
2764         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2765                             LL, LR, Result);
2766     }
2767   }
2768
2769   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2770       VT.getSizeInBits() <= 64) {
2771     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2772       APInt ADDC = ADDI->getAPIntValue();
2773       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2774         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2775         // immediate for an add, but it is legal if its top c2 bits are set,
2776         // transform the ADD so the immediate doesn't need to be materialized
2777         // in a register.
2778         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2779           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2780                                              SRLI->getZExtValue());
2781           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2782             ADDC |= Mask;
2783             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2784               SDValue NewAdd =
2785                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2786                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2787               CombineTo(N0.getNode(), NewAdd);
2788               // Return N so it doesn't get rechecked!
2789               return SDValue(LocReference, 0);
2790             }
2791           }
2792         }
2793       }
2794     }
2795   }
2796
2797   return SDValue();
2798 }
2799
2800 SDValue DAGCombiner::visitAND(SDNode *N) {
2801   SDValue N0 = N->getOperand(0);
2802   SDValue N1 = N->getOperand(1);
2803   EVT VT = N1.getValueType();
2804
2805   // fold vector ops
2806   if (VT.isVector()) {
2807     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2808       return FoldedVOp;
2809
2810     // fold (and x, 0) -> 0, vector edition
2811     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2812       // do not return N0, because undef node may exist in N0
2813       return DAG.getConstant(
2814           APInt::getNullValue(
2815               N0.getValueType().getScalarType().getSizeInBits()),
2816           N0.getValueType());
2817     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2818       // do not return N1, because undef node may exist in N1
2819       return DAG.getConstant(
2820           APInt::getNullValue(
2821               N1.getValueType().getScalarType().getSizeInBits()),
2822           N1.getValueType());
2823
2824     // fold (and x, -1) -> x, vector edition
2825     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2826       return N1;
2827     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2828       return N0;
2829   }
2830
2831   // fold (and c1, c2) -> c1&c2
2832   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2833   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2834   if (N0C && N1C)
2835     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2836   // canonicalize constant to RHS
2837   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2838      !isConstantIntBuildVectorOrConstantInt(N1))
2839     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2840   // fold (and x, -1) -> x
2841   if (N1C && N1C->isAllOnesValue())
2842     return N0;
2843   // if (and x, c) is known to be zero, return 0
2844   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2845   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2846                                    APInt::getAllOnesValue(BitWidth)))
2847     return DAG.getConstant(0, VT);
2848   // reassociate and
2849   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2850     return RAND;
2851   // fold (and (or x, C), D) -> D if (C & D) == D
2852   if (N1C && N0.getOpcode() == ISD::OR)
2853     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2854       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2855         return N1;
2856   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2857   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2858     SDValue N0Op0 = N0.getOperand(0);
2859     APInt Mask = ~N1C->getAPIntValue();
2860     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2861     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2862       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2863                                  N0.getValueType(), N0Op0);
2864
2865       // Replace uses of the AND with uses of the Zero extend node.
2866       CombineTo(N, Zext);
2867
2868       // We actually want to replace all uses of the any_extend with the
2869       // zero_extend, to avoid duplicating things.  This will later cause this
2870       // AND to be folded.
2871       CombineTo(N0.getNode(), Zext);
2872       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2873     }
2874   }
2875   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2876   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2877   // already be zero by virtue of the width of the base type of the load.
2878   //
2879   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2880   // more cases.
2881   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2882        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2883       N0.getOpcode() == ISD::LOAD) {
2884     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2885                                          N0 : N0.getOperand(0) );
2886
2887     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2888     // This can be a pure constant or a vector splat, in which case we treat the
2889     // vector as a scalar and use the splat value.
2890     APInt Constant = APInt::getNullValue(1);
2891     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2892       Constant = C->getAPIntValue();
2893     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2894       APInt SplatValue, SplatUndef;
2895       unsigned SplatBitSize;
2896       bool HasAnyUndefs;
2897       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2898                                              SplatBitSize, HasAnyUndefs);
2899       if (IsSplat) {
2900         // Undef bits can contribute to a possible optimisation if set, so
2901         // set them.
2902         SplatValue |= SplatUndef;
2903
2904         // The splat value may be something like "0x00FFFFFF", which means 0 for
2905         // the first vector value and FF for the rest, repeating. We need a mask
2906         // that will apply equally to all members of the vector, so AND all the
2907         // lanes of the constant together.
2908         EVT VT = Vector->getValueType(0);
2909         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2910
2911         // If the splat value has been compressed to a bitlength lower
2912         // than the size of the vector lane, we need to re-expand it to
2913         // the lane size.
2914         if (BitWidth > SplatBitSize)
2915           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2916                SplatBitSize < BitWidth;
2917                SplatBitSize = SplatBitSize * 2)
2918             SplatValue |= SplatValue.shl(SplatBitSize);
2919
2920         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2921         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2922         if (SplatBitSize % BitWidth == 0) {
2923           Constant = APInt::getAllOnesValue(BitWidth);
2924           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2925             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2926         }
2927       }
2928     }
2929
2930     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2931     // actually legal and isn't going to get expanded, else this is a false
2932     // optimisation.
2933     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2934                                                     Load->getValueType(0),
2935                                                     Load->getMemoryVT());
2936
2937     // Resize the constant to the same size as the original memory access before
2938     // extension. If it is still the AllOnesValue then this AND is completely
2939     // unneeded.
2940     Constant =
2941       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2942
2943     bool B;
2944     switch (Load->getExtensionType()) {
2945     default: B = false; break;
2946     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2947     case ISD::ZEXTLOAD:
2948     case ISD::NON_EXTLOAD: B = true; break;
2949     }
2950
2951     if (B && Constant.isAllOnesValue()) {
2952       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2953       // preserve semantics once we get rid of the AND.
2954       SDValue NewLoad(Load, 0);
2955       if (Load->getExtensionType() == ISD::EXTLOAD) {
2956         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2957                               Load->getValueType(0), SDLoc(Load),
2958                               Load->getChain(), Load->getBasePtr(),
2959                               Load->getOffset(), Load->getMemoryVT(),
2960                               Load->getMemOperand());
2961         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2962         if (Load->getNumValues() == 3) {
2963           // PRE/POST_INC loads have 3 values.
2964           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2965                            NewLoad.getValue(2) };
2966           CombineTo(Load, To, 3, true);
2967         } else {
2968           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2969         }
2970       }
2971
2972       // Fold the AND away, taking care not to fold to the old load node if we
2973       // replaced it.
2974       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2975
2976       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2977     }
2978   }
2979
2980   // fold (and (load x), 255) -> (zextload x, i8)
2981   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2982   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2983   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2984               (N0.getOpcode() == ISD::ANY_EXTEND &&
2985                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2986     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2987     LoadSDNode *LN0 = HasAnyExt
2988       ? cast<LoadSDNode>(N0.getOperand(0))
2989       : cast<LoadSDNode>(N0);
2990     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2991         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2992       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2993       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2994         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2995         EVT LoadedVT = LN0->getMemoryVT();
2996         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2997
2998         if (ExtVT == LoadedVT &&
2999             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3000                                                     ExtVT))) {
3001
3002           SDValue NewLoad =
3003             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3004                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3005                            LN0->getMemOperand());
3006           AddToWorklist(N);
3007           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3008           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3009         }
3010
3011         // Do not change the width of a volatile load.
3012         // Do not generate loads of non-round integer types since these can
3013         // be expensive (and would be wrong if the type is not byte sized).
3014         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3015             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3016                                                     ExtVT))) {
3017           EVT PtrType = LN0->getOperand(1).getValueType();
3018
3019           unsigned Alignment = LN0->getAlignment();
3020           SDValue NewPtr = LN0->getBasePtr();
3021
3022           // For big endian targets, we need to add an offset to the pointer
3023           // to load the correct bytes.  For little endian systems, we merely
3024           // need to read fewer bytes from the same pointer.
3025           if (TLI.isBigEndian()) {
3026             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3027             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3028             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3029             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3030                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3031             Alignment = MinAlign(Alignment, PtrOff);
3032           }
3033
3034           AddToWorklist(NewPtr.getNode());
3035
3036           SDValue Load =
3037             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3038                            LN0->getChain(), NewPtr,
3039                            LN0->getPointerInfo(),
3040                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3041                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3042           AddToWorklist(N);
3043           CombineTo(LN0, Load, Load.getValue(1));
3044           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3045         }
3046       }
3047     }
3048   }
3049
3050   if (SDValue Combined = visitANDLike(N0, N1, N))
3051     return Combined;
3052
3053   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3054   if (N0.getOpcode() == N1.getOpcode()) {
3055     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3056     if (Tmp.getNode()) return Tmp;
3057   }
3058
3059   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3060   // fold (and (sra)) -> (and (srl)) when possible.
3061   if (!VT.isVector() &&
3062       SimplifyDemandedBits(SDValue(N, 0)))
3063     return SDValue(N, 0);
3064
3065   // fold (zext_inreg (extload x)) -> (zextload x)
3066   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3067     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3068     EVT MemVT = LN0->getMemoryVT();
3069     // If we zero all the possible extended bits, then we can turn this into
3070     // a zextload if we are running before legalize or the operation is legal.
3071     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3072     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3073                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3074         ((!LegalOperations && !LN0->isVolatile()) ||
3075          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3076       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3077                                        LN0->getChain(), LN0->getBasePtr(),
3078                                        MemVT, LN0->getMemOperand());
3079       AddToWorklist(N);
3080       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3081       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3082     }
3083   }
3084   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3085   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3086       N0.hasOneUse()) {
3087     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3088     EVT MemVT = LN0->getMemoryVT();
3089     // If we zero all the possible extended bits, then we can turn this into
3090     // a zextload if we are running before legalize or the operation is legal.
3091     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3092     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3093                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3094         ((!LegalOperations && !LN0->isVolatile()) ||
3095          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3096       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3097                                        LN0->getChain(), LN0->getBasePtr(),
3098                                        MemVT, LN0->getMemOperand());
3099       AddToWorklist(N);
3100       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3101       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3102     }
3103   }
3104   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3105   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3106     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3107                                        N0.getOperand(1), false);
3108     if (BSwap.getNode())
3109       return BSwap;
3110   }
3111
3112   return SDValue();
3113 }
3114
3115 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3116 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3117                                         bool DemandHighBits) {
3118   if (!LegalOperations)
3119     return SDValue();
3120
3121   EVT VT = N->getValueType(0);
3122   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3123     return SDValue();
3124   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3125     return SDValue();
3126
3127   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3128   bool LookPassAnd0 = false;
3129   bool LookPassAnd1 = false;
3130   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3131       std::swap(N0, N1);
3132   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3133       std::swap(N0, N1);
3134   if (N0.getOpcode() == ISD::AND) {
3135     if (!N0.getNode()->hasOneUse())
3136       return SDValue();
3137     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3138     if (!N01C || N01C->getZExtValue() != 0xFF00)
3139       return SDValue();
3140     N0 = N0.getOperand(0);
3141     LookPassAnd0 = true;
3142   }
3143
3144   if (N1.getOpcode() == ISD::AND) {
3145     if (!N1.getNode()->hasOneUse())
3146       return SDValue();
3147     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3148     if (!N11C || N11C->getZExtValue() != 0xFF)
3149       return SDValue();
3150     N1 = N1.getOperand(0);
3151     LookPassAnd1 = true;
3152   }
3153
3154   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3155     std::swap(N0, N1);
3156   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3157     return SDValue();
3158   if (!N0.getNode()->hasOneUse() ||
3159       !N1.getNode()->hasOneUse())
3160     return SDValue();
3161
3162   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3163   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3164   if (!N01C || !N11C)
3165     return SDValue();
3166   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3167     return SDValue();
3168
3169   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3170   SDValue N00 = N0->getOperand(0);
3171   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3172     if (!N00.getNode()->hasOneUse())
3173       return SDValue();
3174     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3175     if (!N001C || N001C->getZExtValue() != 0xFF)
3176       return SDValue();
3177     N00 = N00.getOperand(0);
3178     LookPassAnd0 = true;
3179   }
3180
3181   SDValue N10 = N1->getOperand(0);
3182   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3183     if (!N10.getNode()->hasOneUse())
3184       return SDValue();
3185     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3186     if (!N101C || N101C->getZExtValue() != 0xFF00)
3187       return SDValue();
3188     N10 = N10.getOperand(0);
3189     LookPassAnd1 = true;
3190   }
3191
3192   if (N00 != N10)
3193     return SDValue();
3194
3195   // Make sure everything beyond the low halfword gets set to zero since the SRL
3196   // 16 will clear the top bits.
3197   unsigned OpSizeInBits = VT.getSizeInBits();
3198   if (DemandHighBits && OpSizeInBits > 16) {
3199     // If the left-shift isn't masked out then the only way this is a bswap is
3200     // if all bits beyond the low 8 are 0. In that case the entire pattern
3201     // reduces to a left shift anyway: leave it for other parts of the combiner.
3202     if (!LookPassAnd0)
3203       return SDValue();
3204
3205     // However, if the right shift isn't masked out then it might be because
3206     // it's not needed. See if we can spot that too.
3207     if (!LookPassAnd1 &&
3208         !DAG.MaskedValueIsZero(
3209             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3210       return SDValue();
3211   }
3212
3213   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3214   if (OpSizeInBits > 16)
3215     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3216                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3217   return Res;
3218 }
3219
3220 /// Return true if the specified node is an element that makes up a 32-bit
3221 /// packed halfword byteswap.
3222 /// ((x & 0x000000ff) << 8) |
3223 /// ((x & 0x0000ff00) >> 8) |
3224 /// ((x & 0x00ff0000) << 8) |
3225 /// ((x & 0xff000000) >> 8)
3226 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3227   if (!N.getNode()->hasOneUse())
3228     return false;
3229
3230   unsigned Opc = N.getOpcode();
3231   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3232     return false;
3233
3234   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3235   if (!N1C)
3236     return false;
3237
3238   unsigned Num;
3239   switch (N1C->getZExtValue()) {
3240   default:
3241     return false;
3242   case 0xFF:       Num = 0; break;
3243   case 0xFF00:     Num = 1; break;
3244   case 0xFF0000:   Num = 2; break;
3245   case 0xFF000000: Num = 3; break;
3246   }
3247
3248   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3249   SDValue N0 = N.getOperand(0);
3250   if (Opc == ISD::AND) {
3251     if (Num == 0 || Num == 2) {
3252       // (x >> 8) & 0xff
3253       // (x >> 8) & 0xff0000
3254       if (N0.getOpcode() != ISD::SRL)
3255         return false;
3256       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3257       if (!C || C->getZExtValue() != 8)
3258         return false;
3259     } else {
3260       // (x << 8) & 0xff00
3261       // (x << 8) & 0xff000000
3262       if (N0.getOpcode() != ISD::SHL)
3263         return false;
3264       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3265       if (!C || C->getZExtValue() != 8)
3266         return false;
3267     }
3268   } else if (Opc == ISD::SHL) {
3269     // (x & 0xff) << 8
3270     // (x & 0xff0000) << 8
3271     if (Num != 0 && Num != 2)
3272       return false;
3273     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3274     if (!C || C->getZExtValue() != 8)
3275       return false;
3276   } else { // Opc == ISD::SRL
3277     // (x & 0xff00) >> 8
3278     // (x & 0xff000000) >> 8
3279     if (Num != 1 && Num != 3)
3280       return false;
3281     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3282     if (!C || C->getZExtValue() != 8)
3283       return false;
3284   }
3285
3286   if (Parts[Num])
3287     return false;
3288
3289   Parts[Num] = N0.getOperand(0).getNode();
3290   return true;
3291 }
3292
3293 /// Match a 32-bit packed halfword bswap. That is
3294 /// ((x & 0x000000ff) << 8) |
3295 /// ((x & 0x0000ff00) >> 8) |
3296 /// ((x & 0x00ff0000) << 8) |
3297 /// ((x & 0xff000000) >> 8)
3298 /// => (rotl (bswap x), 16)
3299 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3300   if (!LegalOperations)
3301     return SDValue();
3302
3303   EVT VT = N->getValueType(0);
3304   if (VT != MVT::i32)
3305     return SDValue();
3306   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3307     return SDValue();
3308
3309   // Look for either
3310   // (or (or (and), (and)), (or (and), (and)))
3311   // (or (or (or (and), (and)), (and)), (and))
3312   if (N0.getOpcode() != ISD::OR)
3313     return SDValue();
3314   SDValue N00 = N0.getOperand(0);
3315   SDValue N01 = N0.getOperand(1);
3316   SDNode *Parts[4] = {};
3317
3318   if (N1.getOpcode() == ISD::OR &&
3319       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3320     // (or (or (and), (and)), (or (and), (and)))
3321     SDValue N000 = N00.getOperand(0);
3322     if (!isBSwapHWordElement(N000, Parts))
3323       return SDValue();
3324
3325     SDValue N001 = N00.getOperand(1);
3326     if (!isBSwapHWordElement(N001, Parts))
3327       return SDValue();
3328     SDValue N010 = N01.getOperand(0);
3329     if (!isBSwapHWordElement(N010, Parts))
3330       return SDValue();
3331     SDValue N011 = N01.getOperand(1);
3332     if (!isBSwapHWordElement(N011, Parts))
3333       return SDValue();
3334   } else {
3335     // (or (or (or (and), (and)), (and)), (and))
3336     if (!isBSwapHWordElement(N1, Parts))
3337       return SDValue();
3338     if (!isBSwapHWordElement(N01, Parts))
3339       return SDValue();
3340     if (N00.getOpcode() != ISD::OR)
3341       return SDValue();
3342     SDValue N000 = N00.getOperand(0);
3343     if (!isBSwapHWordElement(N000, Parts))
3344       return SDValue();
3345     SDValue N001 = N00.getOperand(1);
3346     if (!isBSwapHWordElement(N001, Parts))
3347       return SDValue();
3348   }
3349
3350   // Make sure the parts are all coming from the same node.
3351   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3352     return SDValue();
3353
3354   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3355                               SDValue(Parts[0],0));
3356
3357   // Result of the bswap should be rotated by 16. If it's not legal, then
3358   // do  (x << 16) | (x >> 16).
3359   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3360   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3361     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3362   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3363     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3364   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3365                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3366                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3367 }
3368
3369 /// This contains all DAGCombine rules which reduce two values combined by
3370 /// an Or operation to a single value \see visitANDLike().
3371 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3372   EVT VT = N1.getValueType();
3373   // fold (or x, undef) -> -1
3374   if (!LegalOperations &&
3375       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3376     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3377     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3378   }
3379   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3380   SDValue LL, LR, RL, RR, CC0, CC1;
3381   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3382     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3383     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3384
3385     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3386         LL.getValueType().isInteger()) {
3387       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3388       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3389       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3390           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3391         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3392                                      LR.getValueType(), LL, RL);
3393         AddToWorklist(ORNode.getNode());
3394         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3395       }
3396       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3397       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3398       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3399           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3400         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3401                                       LR.getValueType(), LL, RL);
3402         AddToWorklist(ANDNode.getNode());
3403         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3404       }
3405     }
3406     // canonicalize equivalent to ll == rl
3407     if (LL == RR && LR == RL) {
3408       Op1 = ISD::getSetCCSwappedOperands(Op1);
3409       std::swap(RL, RR);
3410     }
3411     if (LL == RL && LR == RR) {
3412       bool isInteger = LL.getValueType().isInteger();
3413       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3414       if (Result != ISD::SETCC_INVALID &&
3415           (!LegalOperations ||
3416            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3417             TLI.isOperationLegal(ISD::SETCC,
3418               getSetCCResultType(N0.getValueType())))))
3419         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3420                             LL, LR, Result);
3421     }
3422   }
3423
3424   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3425   if (N0.getOpcode() == ISD::AND &&
3426       N1.getOpcode() == ISD::AND &&
3427       N0.getOperand(1).getOpcode() == ISD::Constant &&
3428       N1.getOperand(1).getOpcode() == ISD::Constant &&
3429       // Don't increase # computations.
3430       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3431     // We can only do this xform if we know that bits from X that are set in C2
3432     // but not in C1 are already zero.  Likewise for Y.
3433     const APInt &LHSMask =
3434       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3435     const APInt &RHSMask =
3436       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3437
3438     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3439         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3440       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3441                               N0.getOperand(0), N1.getOperand(0));
3442       return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3443                          DAG.getConstant(LHSMask | RHSMask, VT));
3444     }
3445   }
3446
3447   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3448   if (N0.getOpcode() == ISD::AND &&
3449       N1.getOpcode() == ISD::AND &&
3450       N0.getOperand(0) == N1.getOperand(0) &&
3451       // Don't increase # computations.
3452       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3453     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3454                             N0.getOperand(1), N1.getOperand(1));
3455     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3456   }
3457
3458   return SDValue();
3459 }
3460
3461 SDValue DAGCombiner::visitOR(SDNode *N) {
3462   SDValue N0 = N->getOperand(0);
3463   SDValue N1 = N->getOperand(1);
3464   EVT VT = N1.getValueType();
3465
3466   // fold vector ops
3467   if (VT.isVector()) {
3468     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3469       return FoldedVOp;
3470
3471     // fold (or x, 0) -> x, vector edition
3472     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3473       return N1;
3474     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3475       return N0;
3476
3477     // fold (or x, -1) -> -1, vector edition
3478     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3479       // do not return N0, because undef node may exist in N0
3480       return DAG.getConstant(
3481           APInt::getAllOnesValue(
3482               N0.getValueType().getScalarType().getSizeInBits()),
3483           N0.getValueType());
3484     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3485       // do not return N1, because undef node may exist in N1
3486       return DAG.getConstant(
3487           APInt::getAllOnesValue(
3488               N1.getValueType().getScalarType().getSizeInBits()),
3489           N1.getValueType());
3490
3491     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3492     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3493     // Do this only if the resulting shuffle is legal.
3494     if (isa<ShuffleVectorSDNode>(N0) &&
3495         isa<ShuffleVectorSDNode>(N1) &&
3496         // Avoid folding a node with illegal type.
3497         TLI.isTypeLegal(VT) &&
3498         N0->getOperand(1) == N1->getOperand(1) &&
3499         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3500       bool CanFold = true;
3501       unsigned NumElts = VT.getVectorNumElements();
3502       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3503       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3504       // We construct two shuffle masks:
3505       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3506       // and N1 as the second operand.
3507       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3508       // and N0 as the second operand.
3509       // We do this because OR is commutable and therefore there might be
3510       // two ways to fold this node into a shuffle.
3511       SmallVector<int,4> Mask1;
3512       SmallVector<int,4> Mask2;
3513
3514       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3515         int M0 = SV0->getMaskElt(i);
3516         int M1 = SV1->getMaskElt(i);
3517
3518         // Both shuffle indexes are undef. Propagate Undef.
3519         if (M0 < 0 && M1 < 0) {
3520           Mask1.push_back(M0);
3521           Mask2.push_back(M0);
3522           continue;
3523         }
3524
3525         if (M0 < 0 || M1 < 0 ||
3526             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3527             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3528           CanFold = false;
3529           break;
3530         }
3531
3532         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3533         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3534       }
3535
3536       if (CanFold) {
3537         // Fold this sequence only if the resulting shuffle is 'legal'.
3538         if (TLI.isShuffleMaskLegal(Mask1, VT))
3539           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3540                                       N1->getOperand(0), &Mask1[0]);
3541         if (TLI.isShuffleMaskLegal(Mask2, VT))
3542           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3543                                       N0->getOperand(0), &Mask2[0]);
3544       }
3545     }
3546   }
3547
3548   // fold (or c1, c2) -> c1|c2
3549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3551   if (N0C && N1C)
3552     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3553   // canonicalize constant to RHS
3554   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3555      !isConstantIntBuildVectorOrConstantInt(N1))
3556     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3557   // fold (or x, 0) -> x
3558   if (N1C && N1C->isNullValue())
3559     return N0;
3560   // fold (or x, -1) -> -1
3561   if (N1C && N1C->isAllOnesValue())
3562     return N1;
3563   // fold (or x, c) -> c iff (x & ~c) == 0
3564   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3565     return N1;
3566
3567   if (SDValue Combined = visitORLike(N0, N1, N))
3568     return Combined;
3569
3570   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3571   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3572   if (BSwap.getNode())
3573     return BSwap;
3574   BSwap = MatchBSwapHWordLow(N, N0, N1);
3575   if (BSwap.getNode())
3576     return BSwap;
3577
3578   // reassociate or
3579   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3580     return ROR;
3581   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3582   // iff (c1 & c2) == 0.
3583   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3584              isa<ConstantSDNode>(N0.getOperand(1))) {
3585     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3586     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3587       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3588         return DAG.getNode(
3589             ISD::AND, SDLoc(N), VT,
3590             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3591       return SDValue();
3592     }
3593   }
3594   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3595   if (N0.getOpcode() == N1.getOpcode()) {
3596     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3597     if (Tmp.getNode()) return Tmp;
3598   }
3599
3600   // See if this is some rotate idiom.
3601   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3602     return SDValue(Rot, 0);
3603
3604   // Simplify the operands using demanded-bits information.
3605   if (!VT.isVector() &&
3606       SimplifyDemandedBits(SDValue(N, 0)))
3607     return SDValue(N, 0);
3608
3609   return SDValue();
3610 }
3611
3612 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3613 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3614   if (Op.getOpcode() == ISD::AND) {
3615     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3616       Mask = Op.getOperand(1);
3617       Op = Op.getOperand(0);
3618     } else {
3619       return false;
3620     }
3621   }
3622
3623   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3624     Shift = Op;
3625     return true;
3626   }
3627
3628   return false;
3629 }
3630
3631 // Return true if we can prove that, whenever Neg and Pos are both in the
3632 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3633 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3634 //
3635 //     (or (shift1 X, Neg), (shift2 X, Pos))
3636 //
3637 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3638 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3639 // to consider shift amounts with defined behavior.
3640 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3641   // If OpSize is a power of 2 then:
3642   //
3643   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3644   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3645   //
3646   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3647   // for the stronger condition:
3648   //
3649   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3650   //
3651   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3652   // we can just replace Neg with Neg' for the rest of the function.
3653   //
3654   // In other cases we check for the even stronger condition:
3655   //
3656   //     Neg == OpSize - Pos                                    [B]
3657   //
3658   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3659   // behavior if Pos == 0 (and consequently Neg == OpSize).
3660   //
3661   // We could actually use [A] whenever OpSize is a power of 2, but the
3662   // only extra cases that it would match are those uninteresting ones
3663   // where Neg and Pos are never in range at the same time.  E.g. for
3664   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3665   // as well as (sub 32, Pos), but:
3666   //
3667   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3668   //
3669   // always invokes undefined behavior for 32-bit X.
3670   //
3671   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3672   unsigned MaskLoBits = 0;
3673   if (Neg.getOpcode() == ISD::AND &&
3674       isPowerOf2_64(OpSize) &&
3675       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3676       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3677     Neg = Neg.getOperand(0);
3678     MaskLoBits = Log2_64(OpSize);
3679   }
3680
3681   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3682   if (Neg.getOpcode() != ISD::SUB)
3683     return 0;
3684   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3685   if (!NegC)
3686     return 0;
3687   SDValue NegOp1 = Neg.getOperand(1);
3688
3689   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3690   // Pos'.  The truncation is redundant for the purpose of the equality.
3691   if (MaskLoBits &&
3692       Pos.getOpcode() == ISD::AND &&
3693       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3694       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3695     Pos = Pos.getOperand(0);
3696
3697   // The condition we need is now:
3698   //
3699   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3700   //
3701   // If NegOp1 == Pos then we need:
3702   //
3703   //              OpSize & Mask == NegC & Mask
3704   //
3705   // (because "x & Mask" is a truncation and distributes through subtraction).
3706   APInt Width;
3707   if (Pos == NegOp1)
3708     Width = NegC->getAPIntValue();
3709   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3710   // Then the condition we want to prove becomes:
3711   //
3712   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3713   //
3714   // which, again because "x & Mask" is a truncation, becomes:
3715   //
3716   //                NegC & Mask == (OpSize - PosC) & Mask
3717   //              OpSize & Mask == (NegC + PosC) & Mask
3718   else if (Pos.getOpcode() == ISD::ADD &&
3719            Pos.getOperand(0) == NegOp1 &&
3720            Pos.getOperand(1).getOpcode() == ISD::Constant)
3721     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3722              NegC->getAPIntValue());
3723   else
3724     return false;
3725
3726   // Now we just need to check that OpSize & Mask == Width & Mask.
3727   if (MaskLoBits)
3728     // Opsize & Mask is 0 since Mask is Opsize - 1.
3729     return Width.getLoBits(MaskLoBits) == 0;
3730   return Width == OpSize;
3731 }
3732
3733 // A subroutine of MatchRotate used once we have found an OR of two opposite
3734 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3735 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3736 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3737 // Neg with outer conversions stripped away.
3738 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3739                                        SDValue Neg, SDValue InnerPos,
3740                                        SDValue InnerNeg, unsigned PosOpcode,
3741                                        unsigned NegOpcode, SDLoc DL) {
3742   // fold (or (shl x, (*ext y)),
3743   //          (srl x, (*ext (sub 32, y)))) ->
3744   //   (rotl x, y) or (rotr x, (sub 32, y))
3745   //
3746   // fold (or (shl x, (*ext (sub 32, y))),
3747   //          (srl x, (*ext y))) ->
3748   //   (rotr x, y) or (rotl x, (sub 32, y))
3749   EVT VT = Shifted.getValueType();
3750   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3751     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3752     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3753                        HasPos ? Pos : Neg).getNode();
3754   }
3755
3756   return nullptr;
3757 }
3758
3759 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3760 // idioms for rotate, and if the target supports rotation instructions, generate
3761 // a rot[lr].
3762 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3763   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3764   EVT VT = LHS.getValueType();
3765   if (!TLI.isTypeLegal(VT)) return nullptr;
3766
3767   // The target must have at least one rotate flavor.
3768   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3769   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3770   if (!HasROTL && !HasROTR) return nullptr;
3771
3772   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3773   SDValue LHSShift;   // The shift.
3774   SDValue LHSMask;    // AND value if any.
3775   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3776     return nullptr; // Not part of a rotate.
3777
3778   SDValue RHSShift;   // The shift.
3779   SDValue RHSMask;    // AND value if any.
3780   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3781     return nullptr; // Not part of a rotate.
3782
3783   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3784     return nullptr;   // Not shifting the same value.
3785
3786   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3787     return nullptr;   // Shifts must disagree.
3788
3789   // Canonicalize shl to left side in a shl/srl pair.
3790   if (RHSShift.getOpcode() == ISD::SHL) {
3791     std::swap(LHS, RHS);
3792     std::swap(LHSShift, RHSShift);
3793     std::swap(LHSMask , RHSMask );
3794   }
3795
3796   unsigned OpSizeInBits = VT.getSizeInBits();
3797   SDValue LHSShiftArg = LHSShift.getOperand(0);
3798   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3799   SDValue RHSShiftArg = RHSShift.getOperand(0);
3800   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3801
3802   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3803   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3804   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3805       RHSShiftAmt.getOpcode() == ISD::Constant) {
3806     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3807     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3808     if ((LShVal + RShVal) != OpSizeInBits)
3809       return nullptr;
3810
3811     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3812                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3813
3814     // If there is an AND of either shifted operand, apply it to the result.
3815     if (LHSMask.getNode() || RHSMask.getNode()) {
3816       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3817
3818       if (LHSMask.getNode()) {
3819         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3820         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3821       }
3822       if (RHSMask.getNode()) {
3823         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3824         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3825       }
3826
3827       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3828     }
3829
3830     return Rot.getNode();
3831   }
3832
3833   // If there is a mask here, and we have a variable shift, we can't be sure
3834   // that we're masking out the right stuff.
3835   if (LHSMask.getNode() || RHSMask.getNode())
3836     return nullptr;
3837
3838   // If the shift amount is sign/zext/any-extended just peel it off.
3839   SDValue LExtOp0 = LHSShiftAmt;
3840   SDValue RExtOp0 = RHSShiftAmt;
3841   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3842        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3843        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3844        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3845       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3846        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3847        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3848        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3849     LExtOp0 = LHSShiftAmt.getOperand(0);
3850     RExtOp0 = RHSShiftAmt.getOperand(0);
3851   }
3852
3853   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3854                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3855   if (TryL)
3856     return TryL;
3857
3858   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3859                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3860   if (TryR)
3861     return TryR;
3862
3863   return nullptr;
3864 }
3865
3866 SDValue DAGCombiner::visitXOR(SDNode *N) {
3867   SDValue N0 = N->getOperand(0);
3868   SDValue N1 = N->getOperand(1);
3869   EVT VT = N0.getValueType();
3870
3871   // fold vector ops
3872   if (VT.isVector()) {
3873     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3874       return FoldedVOp;
3875
3876     // fold (xor x, 0) -> x, vector edition
3877     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3878       return N1;
3879     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3880       return N0;
3881   }
3882
3883   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3884   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3885     return DAG.getConstant(0, VT);
3886   // fold (xor x, undef) -> undef
3887   if (N0.getOpcode() == ISD::UNDEF)
3888     return N0;
3889   if (N1.getOpcode() == ISD::UNDEF)
3890     return N1;
3891   // fold (xor c1, c2) -> c1^c2
3892   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3893   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3894   if (N0C && N1C)
3895     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3896   // canonicalize constant to RHS
3897   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3898      !isConstantIntBuildVectorOrConstantInt(N1))
3899     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3900   // fold (xor x, 0) -> x
3901   if (N1C && N1C->isNullValue())
3902     return N0;
3903   // reassociate xor
3904   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3905     return RXOR;
3906
3907   // fold !(x cc y) -> (x !cc y)
3908   SDValue LHS, RHS, CC;
3909   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3910     bool isInt = LHS.getValueType().isInteger();
3911     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3912                                                isInt);
3913
3914     if (!LegalOperations ||
3915         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3916       switch (N0.getOpcode()) {
3917       default:
3918         llvm_unreachable("Unhandled SetCC Equivalent!");
3919       case ISD::SETCC:
3920         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3921       case ISD::SELECT_CC:
3922         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3923                                N0.getOperand(3), NotCC);
3924       }
3925     }
3926   }
3927
3928   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3929   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3930       N0.getNode()->hasOneUse() &&
3931       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3932     SDValue V = N0.getOperand(0);
3933     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3934                     DAG.getConstant(1, V.getValueType()));
3935     AddToWorklist(V.getNode());
3936     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3937   }
3938
3939   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3940   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3941       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3942     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3943     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3944       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3945       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3946       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3947       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3948       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3949     }
3950   }
3951   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3952   if (N1C && N1C->isAllOnesValue() &&
3953       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3954     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3955     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3956       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3957       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3958       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3959       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3960       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3961     }
3962   }
3963   // fold (xor (and x, y), y) -> (and (not x), y)
3964   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3965       N0->getOperand(1) == N1) {
3966     SDValue X = N0->getOperand(0);
3967     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3968     AddToWorklist(NotX.getNode());
3969     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3970   }
3971   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3972   if (N1C && N0.getOpcode() == ISD::XOR) {
3973     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3974     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3975     if (N00C)
3976       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3977                          DAG.getConstant(N1C->getAPIntValue() ^
3978                                          N00C->getAPIntValue(), VT));
3979     if (N01C)
3980       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3981                          DAG.getConstant(N1C->getAPIntValue() ^
3982                                          N01C->getAPIntValue(), VT));
3983   }
3984   // fold (xor x, x) -> 0
3985   if (N0 == N1)
3986     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3987
3988   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3989   // Here is a concrete example of this equivalence:
3990   // i16   x ==  14
3991   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
3992   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3993   //
3994   // =>
3995   //
3996   // i16     ~1      == 0b1111111111111110
3997   // i16 rol(~1, 14) == 0b1011111111111111
3998   //
3999   // Some additional tips to help conceptualize this transform:
4000   // - Try to see the operation as placing a single zero in a value of all ones.
4001   // - There exists no value for x which would allow the result to contain zero.
4002   // - Values of x larger than the bitwidth are undefined and do not require a
4003   //   consistent result.
4004   // - Pushing the zero left requires shifting one bits in from the right.
4005   // A rotate left of ~1 is a nice way of achieving the desired result.
4006   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4007     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4008       if (N0.getOpcode() == ISD::SHL)
4009         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4010           if (N1C->isAllOnesValue() && ShlLHS->isOne())
4011             return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4012                                N0.getOperand(1));
4013
4014   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4015   if (N0.getOpcode() == N1.getOpcode()) {
4016     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4017     if (Tmp.getNode()) return Tmp;
4018   }
4019
4020   // Simplify the expression using non-local knowledge.
4021   if (!VT.isVector() &&
4022       SimplifyDemandedBits(SDValue(N, 0)))
4023     return SDValue(N, 0);
4024
4025   return SDValue();
4026 }
4027
4028 /// Handle transforms common to the three shifts, when the shift amount is a
4029 /// constant.
4030 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4031   // We can't and shouldn't fold opaque constants.
4032   if (Amt->isOpaque())
4033     return SDValue();
4034
4035   SDNode *LHS = N->getOperand(0).getNode();
4036   if (!LHS->hasOneUse()) return SDValue();
4037
4038   // We want to pull some binops through shifts, so that we have (and (shift))
4039   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4040   // thing happens with address calculations, so it's important to canonicalize
4041   // it.
4042   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4043
4044   switch (LHS->getOpcode()) {
4045   default: return SDValue();
4046   case ISD::OR:
4047   case ISD::XOR:
4048     HighBitSet = false; // We can only transform sra if the high bit is clear.
4049     break;
4050   case ISD::AND:
4051     HighBitSet = true;  // We can only transform sra if the high bit is set.
4052     break;
4053   case ISD::ADD:
4054     if (N->getOpcode() != ISD::SHL)
4055       return SDValue(); // only shl(add) not sr[al](add).
4056     HighBitSet = false; // We can only transform sra if the high bit is clear.
4057     break;
4058   }
4059
4060   // We require the RHS of the binop to be a constant and not opaque as well.
4061   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4062   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4063
4064   // FIXME: disable this unless the input to the binop is a shift by a constant.
4065   // If it is not a shift, it pessimizes some common cases like:
4066   //
4067   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4068   //    int bar(int *X, int i) { return X[i & 255]; }
4069   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4070   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4071        BinOpLHSVal->getOpcode() != ISD::SRA &&
4072        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4073       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4074     return SDValue();
4075
4076   EVT VT = N->getValueType(0);
4077
4078   // If this is a signed shift right, and the high bit is modified by the
4079   // logical operation, do not perform the transformation. The highBitSet
4080   // boolean indicates the value of the high bit of the constant which would
4081   // cause it to be modified for this operation.
4082   if (N->getOpcode() == ISD::SRA) {
4083     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4084     if (BinOpRHSSignSet != HighBitSet)
4085       return SDValue();
4086   }
4087
4088   if (!TLI.isDesirableToCommuteWithShift(LHS))
4089     return SDValue();
4090
4091   // Fold the constants, shifting the binop RHS by the shift amount.
4092   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4093                                N->getValueType(0),
4094                                LHS->getOperand(1), N->getOperand(1));
4095   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4096
4097   // Create the new shift.
4098   SDValue NewShift = DAG.getNode(N->getOpcode(),
4099                                  SDLoc(LHS->getOperand(0)),
4100                                  VT, LHS->getOperand(0), N->getOperand(1));
4101
4102   // Create the new binop.
4103   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4104 }
4105
4106 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4107   assert(N->getOpcode() == ISD::TRUNCATE);
4108   assert(N->getOperand(0).getOpcode() == ISD::AND);
4109
4110   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4111   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4112     SDValue N01 = N->getOperand(0).getOperand(1);
4113
4114     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4115       EVT TruncVT = N->getValueType(0);
4116       SDValue N00 = N->getOperand(0).getOperand(0);
4117       APInt TruncC = N01C->getAPIntValue();
4118       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4119
4120       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4121                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4122                          DAG.getConstant(TruncC, TruncVT));
4123     }
4124   }
4125
4126   return SDValue();
4127 }
4128
4129 SDValue DAGCombiner::visitRotate(SDNode *N) {
4130   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4131   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4132       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4133     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4134     if (NewOp1.getNode())
4135       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4136                          N->getOperand(0), NewOp1);
4137   }
4138   return SDValue();
4139 }
4140
4141 SDValue DAGCombiner::visitSHL(SDNode *N) {
4142   SDValue N0 = N->getOperand(0);
4143   SDValue N1 = N->getOperand(1);
4144   EVT VT = N0.getValueType();
4145   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4146
4147   // fold vector ops
4148   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4149   if (VT.isVector()) {
4150     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4151       return FoldedVOp;
4152
4153     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4154     // If setcc produces all-one true value then:
4155     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4156     if (N1CV && N1CV->isConstant()) {
4157       if (N0.getOpcode() == ISD::AND) {
4158         SDValue N00 = N0->getOperand(0);
4159         SDValue N01 = N0->getOperand(1);
4160         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4161
4162         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4163             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4164                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4165           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4166             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4167         }
4168       } else {
4169         N1C = isConstOrConstSplat(N1);
4170       }
4171     }
4172   }
4173
4174   // fold (shl c1, c2) -> c1<<c2
4175   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4176   if (N0C && N1C)
4177     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4178   // fold (shl 0, x) -> 0
4179   if (N0C && N0C->isNullValue())
4180     return N0;
4181   // fold (shl x, c >= size(x)) -> undef
4182   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4183     return DAG.getUNDEF(VT);
4184   // fold (shl x, 0) -> x
4185   if (N1C && N1C->isNullValue())
4186     return N0;
4187   // fold (shl undef, x) -> 0
4188   if (N0.getOpcode() == ISD::UNDEF)
4189     return DAG.getConstant(0, VT);
4190   // if (shl x, c) is known to be zero, return 0
4191   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4192                             APInt::getAllOnesValue(OpSizeInBits)))
4193     return DAG.getConstant(0, VT);
4194   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4195   if (N1.getOpcode() == ISD::TRUNCATE &&
4196       N1.getOperand(0).getOpcode() == ISD::AND) {
4197     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4198     if (NewOp1.getNode())
4199       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4200   }
4201
4202   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4203     return SDValue(N, 0);
4204
4205   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4206   if (N1C && N0.getOpcode() == ISD::SHL) {
4207     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4208       uint64_t c1 = N0C1->getZExtValue();
4209       uint64_t c2 = N1C->getZExtValue();
4210       if (c1 + c2 >= OpSizeInBits)
4211         return DAG.getConstant(0, VT);
4212       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4213                          DAG.getConstant(c1 + c2, N1.getValueType()));
4214     }
4215   }
4216
4217   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4218   // For this to be valid, the second form must not preserve any of the bits
4219   // that are shifted out by the inner shift in the first form.  This means
4220   // the outer shift size must be >= the number of bits added by the ext.
4221   // As a corollary, we don't care what kind of ext it is.
4222   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4223               N0.getOpcode() == ISD::ANY_EXTEND ||
4224               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4225       N0.getOperand(0).getOpcode() == ISD::SHL) {
4226     SDValue N0Op0 = N0.getOperand(0);
4227     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4228       uint64_t c1 = N0Op0C1->getZExtValue();
4229       uint64_t c2 = N1C->getZExtValue();
4230       EVT InnerShiftVT = N0Op0.getValueType();
4231       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4232       if (c2 >= OpSizeInBits - InnerShiftSize) {
4233         if (c1 + c2 >= OpSizeInBits)
4234           return DAG.getConstant(0, VT);
4235         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4236                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4237                                        N0Op0->getOperand(0)),
4238                            DAG.getConstant(c1 + c2, N1.getValueType()));
4239       }
4240     }
4241   }
4242
4243   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4244   // Only fold this if the inner zext has no other uses to avoid increasing
4245   // the total number of instructions.
4246   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4247       N0.getOperand(0).getOpcode() == ISD::SRL) {
4248     SDValue N0Op0 = N0.getOperand(0);
4249     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4250       uint64_t c1 = N0Op0C1->getZExtValue();
4251       if (c1 < VT.getScalarSizeInBits()) {
4252         uint64_t c2 = N1C->getZExtValue();
4253         if (c1 == c2) {
4254           SDValue NewOp0 = N0.getOperand(0);
4255           EVT CountVT = NewOp0.getOperand(1).getValueType();
4256           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4257                                        NewOp0, DAG.getConstant(c2, CountVT));
4258           AddToWorklist(NewSHL.getNode());
4259           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4260         }
4261       }
4262     }
4263   }
4264
4265   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4266   //                               (and (srl x, (sub c1, c2), MASK)
4267   // Only fold this if the inner shift has no other uses -- if it does, folding
4268   // this will increase the total number of instructions.
4269   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4270     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4271       uint64_t c1 = N0C1->getZExtValue();
4272       if (c1 < OpSizeInBits) {
4273         uint64_t c2 = N1C->getZExtValue();
4274         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4275         SDValue Shift;
4276         if (c2 > c1) {
4277           Mask = Mask.shl(c2 - c1);
4278           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4279                               DAG.getConstant(c2 - c1, N1.getValueType()));
4280         } else {
4281           Mask = Mask.lshr(c1 - c2);
4282           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4283                               DAG.getConstant(c1 - c2, N1.getValueType()));
4284         }
4285         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4286                            DAG.getConstant(Mask, VT));
4287       }
4288     }
4289   }
4290   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4291   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4292     unsigned BitSize = VT.getScalarSizeInBits();
4293     SDValue HiBitsMask =
4294       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4295                                             BitSize - N1C->getZExtValue()), VT);
4296     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4297                        HiBitsMask);
4298   }
4299
4300   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4301   // Variant of version done on multiply, except mul by a power of 2 is turned
4302   // into a shift.
4303   APInt Val;
4304   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4305       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4306        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4307     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4308     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4309     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4310   }
4311
4312   if (N1C) {
4313     SDValue NewSHL = visitShiftByConstant(N, N1C);
4314     if (NewSHL.getNode())
4315       return NewSHL;
4316   }
4317
4318   return SDValue();
4319 }
4320
4321 SDValue DAGCombiner::visitSRA(SDNode *N) {
4322   SDValue N0 = N->getOperand(0);
4323   SDValue N1 = N->getOperand(1);
4324   EVT VT = N0.getValueType();
4325   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4326
4327   // fold vector ops
4328   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4329   if (VT.isVector()) {
4330     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4331       return FoldedVOp;
4332
4333     N1C = isConstOrConstSplat(N1);
4334   }
4335
4336   // fold (sra c1, c2) -> (sra c1, c2)
4337   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4338   if (N0C && N1C)
4339     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4340   // fold (sra 0, x) -> 0
4341   if (N0C && N0C->isNullValue())
4342     return N0;
4343   // fold (sra -1, x) -> -1
4344   if (N0C && N0C->isAllOnesValue())
4345     return N0;
4346   // fold (sra x, (setge c, size(x))) -> undef
4347   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4348     return DAG.getUNDEF(VT);
4349   // fold (sra x, 0) -> x
4350   if (N1C && N1C->isNullValue())
4351     return N0;
4352   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4353   // sext_inreg.
4354   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4355     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4356     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4357     if (VT.isVector())
4358       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4359                                ExtVT, VT.getVectorNumElements());
4360     if ((!LegalOperations ||
4361          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4362       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4363                          N0.getOperand(0), DAG.getValueType(ExtVT));
4364   }
4365
4366   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4367   if (N1C && N0.getOpcode() == ISD::SRA) {
4368     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4369       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4370       if (Sum >= OpSizeInBits)
4371         Sum = OpSizeInBits - 1;
4372       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4373                          DAG.getConstant(Sum, N1.getValueType()));
4374     }
4375   }
4376
4377   // fold (sra (shl X, m), (sub result_size, n))
4378   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4379   // result_size - n != m.
4380   // If truncate is free for the target sext(shl) is likely to result in better
4381   // code.
4382   if (N0.getOpcode() == ISD::SHL && N1C) {
4383     // Get the two constanst of the shifts, CN0 = m, CN = n.
4384     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4385     if (N01C) {
4386       LLVMContext &Ctx = *DAG.getContext();
4387       // Determine what the truncate's result bitsize and type would be.
4388       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4389
4390       if (VT.isVector())
4391         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4392
4393       // Determine the residual right-shift amount.
4394       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4395
4396       // If the shift is not a no-op (in which case this should be just a sign
4397       // extend already), the truncated to type is legal, sign_extend is legal
4398       // on that type, and the truncate to that type is both legal and free,
4399       // perform the transform.
4400       if ((ShiftAmt > 0) &&
4401           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4402           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4403           TLI.isTruncateFree(VT, TruncVT)) {
4404
4405           SDValue Amt = DAG.getConstant(ShiftAmt,
4406               getShiftAmountTy(N0.getOperand(0).getValueType()));
4407           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4408                                       N0.getOperand(0), Amt);
4409           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4410                                       Shift);
4411           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4412                              N->getValueType(0), Trunc);
4413       }
4414     }
4415   }
4416
4417   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4418   if (N1.getOpcode() == ISD::TRUNCATE &&
4419       N1.getOperand(0).getOpcode() == ISD::AND) {
4420     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4421     if (NewOp1.getNode())
4422       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4423   }
4424
4425   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4426   //      if c1 is equal to the number of bits the trunc removes
4427   if (N0.getOpcode() == ISD::TRUNCATE &&
4428       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4429        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4430       N0.getOperand(0).hasOneUse() &&
4431       N0.getOperand(0).getOperand(1).hasOneUse() &&
4432       N1C) {
4433     SDValue N0Op0 = N0.getOperand(0);
4434     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4435       unsigned LargeShiftVal = LargeShift->getZExtValue();
4436       EVT LargeVT = N0Op0.getValueType();
4437
4438       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4439         SDValue Amt =
4440           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4441                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4442         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4443                                   N0Op0.getOperand(0), Amt);
4444         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4445       }
4446     }
4447   }
4448
4449   // Simplify, based on bits shifted out of the LHS.
4450   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4451     return SDValue(N, 0);
4452
4453
4454   // If the sign bit is known to be zero, switch this to a SRL.
4455   if (DAG.SignBitIsZero(N0))
4456     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4457
4458   if (N1C) {
4459     SDValue NewSRA = visitShiftByConstant(N, N1C);
4460     if (NewSRA.getNode())
4461       return NewSRA;
4462   }
4463
4464   return SDValue();
4465 }
4466
4467 SDValue DAGCombiner::visitSRL(SDNode *N) {
4468   SDValue N0 = N->getOperand(0);
4469   SDValue N1 = N->getOperand(1);
4470   EVT VT = N0.getValueType();
4471   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4472
4473   // fold vector ops
4474   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4475   if (VT.isVector()) {
4476     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4477       return FoldedVOp;
4478
4479     N1C = isConstOrConstSplat(N1);
4480   }
4481
4482   // fold (srl c1, c2) -> c1 >>u c2
4483   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4484   if (N0C && N1C)
4485     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4486   // fold (srl 0, x) -> 0
4487   if (N0C && N0C->isNullValue())
4488     return N0;
4489   // fold (srl x, c >= size(x)) -> undef
4490   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4491     return DAG.getUNDEF(VT);
4492   // fold (srl x, 0) -> x
4493   if (N1C && N1C->isNullValue())
4494     return N0;
4495   // if (srl x, c) is known to be zero, return 0
4496   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4497                                    APInt::getAllOnesValue(OpSizeInBits)))
4498     return DAG.getConstant(0, VT);
4499
4500   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4501   if (N1C && N0.getOpcode() == ISD::SRL) {
4502     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4503       uint64_t c1 = N01C->getZExtValue();
4504       uint64_t c2 = N1C->getZExtValue();
4505       if (c1 + c2 >= OpSizeInBits)
4506         return DAG.getConstant(0, VT);
4507       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4508                          DAG.getConstant(c1 + c2, N1.getValueType()));
4509     }
4510   }
4511
4512   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4513   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4514       N0.getOperand(0).getOpcode() == ISD::SRL &&
4515       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4516     uint64_t c1 =
4517       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4518     uint64_t c2 = N1C->getZExtValue();
4519     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4520     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4521     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4522     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4523     if (c1 + OpSizeInBits == InnerShiftSize) {
4524       if (c1 + c2 >= InnerShiftSize)
4525         return DAG.getConstant(0, VT);
4526       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4527                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4528                                      N0.getOperand(0)->getOperand(0),
4529                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4530     }
4531   }
4532
4533   // fold (srl (shl x, c), c) -> (and x, cst2)
4534   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4535     unsigned BitSize = N0.getScalarValueSizeInBits();
4536     if (BitSize <= 64) {
4537       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4538       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4539                          DAG.getConstant(~0ULL >> ShAmt, VT));
4540     }
4541   }
4542
4543   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4544   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4545     // Shifting in all undef bits?
4546     EVT SmallVT = N0.getOperand(0).getValueType();
4547     unsigned BitSize = SmallVT.getScalarSizeInBits();
4548     if (N1C->getZExtValue() >= BitSize)
4549       return DAG.getUNDEF(VT);
4550
4551     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4552       uint64_t ShiftAmt = N1C->getZExtValue();
4553       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4554                                        N0.getOperand(0),
4555                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4556       AddToWorklist(SmallShift.getNode());
4557       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4558       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4559                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4560                          DAG.getConstant(Mask, VT));
4561     }
4562   }
4563
4564   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4565   // bit, which is unmodified by sra.
4566   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4567     if (N0.getOpcode() == ISD::SRA)
4568       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4569   }
4570
4571   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4572   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4573       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4574     APInt KnownZero, KnownOne;
4575     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4576
4577     // If any of the input bits are KnownOne, then the input couldn't be all
4578     // zeros, thus the result of the srl will always be zero.
4579     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4580
4581     // If all of the bits input the to ctlz node are known to be zero, then
4582     // the result of the ctlz is "32" and the result of the shift is one.
4583     APInt UnknownBits = ~KnownZero;
4584     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4585
4586     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4587     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4588       // Okay, we know that only that the single bit specified by UnknownBits
4589       // could be set on input to the CTLZ node. If this bit is set, the SRL
4590       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4591       // to an SRL/XOR pair, which is likely to simplify more.
4592       unsigned ShAmt = UnknownBits.countTrailingZeros();
4593       SDValue Op = N0.getOperand(0);
4594
4595       if (ShAmt) {
4596         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4597                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4598         AddToWorklist(Op.getNode());
4599       }
4600
4601       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4602                          Op, DAG.getConstant(1, VT));
4603     }
4604   }
4605
4606   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4607   if (N1.getOpcode() == ISD::TRUNCATE &&
4608       N1.getOperand(0).getOpcode() == ISD::AND) {
4609     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4610     if (NewOp1.getNode())
4611       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4612   }
4613
4614   // fold operands of srl based on knowledge that the low bits are not
4615   // demanded.
4616   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4617     return SDValue(N, 0);
4618
4619   if (N1C) {
4620     SDValue NewSRL = visitShiftByConstant(N, N1C);
4621     if (NewSRL.getNode())
4622       return NewSRL;
4623   }
4624
4625   // Attempt to convert a srl of a load into a narrower zero-extending load.
4626   SDValue NarrowLoad = ReduceLoadWidth(N);
4627   if (NarrowLoad.getNode())
4628     return NarrowLoad;
4629
4630   // Here is a common situation. We want to optimize:
4631   //
4632   //   %a = ...
4633   //   %b = and i32 %a, 2
4634   //   %c = srl i32 %b, 1
4635   //   brcond i32 %c ...
4636   //
4637   // into
4638   //
4639   //   %a = ...
4640   //   %b = and %a, 2
4641   //   %c = setcc eq %b, 0
4642   //   brcond %c ...
4643   //
4644   // However when after the source operand of SRL is optimized into AND, the SRL
4645   // itself may not be optimized further. Look for it and add the BRCOND into
4646   // the worklist.
4647   if (N->hasOneUse()) {
4648     SDNode *Use = *N->use_begin();
4649     if (Use->getOpcode() == ISD::BRCOND)
4650       AddToWorklist(Use);
4651     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4652       // Also look pass the truncate.
4653       Use = *Use->use_begin();
4654       if (Use->getOpcode() == ISD::BRCOND)
4655         AddToWorklist(Use);
4656     }
4657   }
4658
4659   return SDValue();
4660 }
4661
4662 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4663   SDValue N0 = N->getOperand(0);
4664   EVT VT = N->getValueType(0);
4665
4666   // fold (ctlz c1) -> c2
4667   if (isa<ConstantSDNode>(N0))
4668     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4669   return SDValue();
4670 }
4671
4672 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4673   SDValue N0 = N->getOperand(0);
4674   EVT VT = N->getValueType(0);
4675
4676   // fold (ctlz_zero_undef c1) -> c2
4677   if (isa<ConstantSDNode>(N0))
4678     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4679   return SDValue();
4680 }
4681
4682 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4683   SDValue N0 = N->getOperand(0);
4684   EVT VT = N->getValueType(0);
4685
4686   // fold (cttz c1) -> c2
4687   if (isa<ConstantSDNode>(N0))
4688     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4689   return SDValue();
4690 }
4691
4692 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4693   SDValue N0 = N->getOperand(0);
4694   EVT VT = N->getValueType(0);
4695
4696   // fold (cttz_zero_undef c1) -> c2
4697   if (isa<ConstantSDNode>(N0))
4698     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4699   return SDValue();
4700 }
4701
4702 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4703   SDValue N0 = N->getOperand(0);
4704   EVT VT = N->getValueType(0);
4705
4706   // fold (ctpop c1) -> c2
4707   if (isa<ConstantSDNode>(N0))
4708     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4709   return SDValue();
4710 }
4711
4712
4713 /// \brief Generate Min/Max node
4714 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4715                                    SDValue True, SDValue False,
4716                                    ISD::CondCode CC, const TargetLowering &TLI,
4717                                    SelectionDAG &DAG) {
4718   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4719     return SDValue();
4720
4721   switch (CC) {
4722   case ISD::SETOLT:
4723   case ISD::SETOLE:
4724   case ISD::SETLT:
4725   case ISD::SETLE:
4726   case ISD::SETULT:
4727   case ISD::SETULE: {
4728     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4729     if (TLI.isOperationLegal(Opcode, VT))
4730       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4731     return SDValue();
4732   }
4733   case ISD::SETOGT:
4734   case ISD::SETOGE:
4735   case ISD::SETGT:
4736   case ISD::SETGE:
4737   case ISD::SETUGT:
4738   case ISD::SETUGE: {
4739     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4740     if (TLI.isOperationLegal(Opcode, VT))
4741       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4742     return SDValue();
4743   }
4744   default:
4745     return SDValue();
4746   }
4747 }
4748
4749 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4750   SDValue N0 = N->getOperand(0);
4751   SDValue N1 = N->getOperand(1);
4752   SDValue N2 = N->getOperand(2);
4753   EVT VT = N->getValueType(0);
4754   EVT VT0 = N0.getValueType();
4755
4756   // fold (select C, X, X) -> X
4757   if (N1 == N2)
4758     return N1;
4759   // fold (select true, X, Y) -> X
4760   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4761   if (N0C && !N0C->isNullValue())
4762     return N1;
4763   // fold (select false, X, Y) -> Y
4764   if (N0C && N0C->isNullValue())
4765     return N2;
4766   // fold (select C, 1, X) -> (or C, X)
4767   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4768   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4769     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4770   // fold (select C, 0, 1) -> (xor C, 1)
4771   // We can't do this reliably if integer based booleans have different contents
4772   // to floating point based booleans. This is because we can't tell whether we
4773   // have an integer-based boolean or a floating-point-based boolean unless we
4774   // can find the SETCC that produced it and inspect its operands. This is
4775   // fairly easy if C is the SETCC node, but it can potentially be
4776   // undiscoverable (or not reasonably discoverable). For example, it could be
4777   // in another basic block or it could require searching a complicated
4778   // expression.
4779   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4780   if (VT.isInteger() &&
4781       (VT0 == MVT::i1 || (VT0.isInteger() &&
4782                           TLI.getBooleanContents(false, false) ==
4783                               TLI.getBooleanContents(false, true) &&
4784                           TLI.getBooleanContents(false, false) ==
4785                               TargetLowering::ZeroOrOneBooleanContent)) &&
4786       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4787     SDValue XORNode;
4788     if (VT == VT0)
4789       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4790                          N0, DAG.getConstant(1, VT0));
4791     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4792                           N0, DAG.getConstant(1, VT0));
4793     AddToWorklist(XORNode.getNode());
4794     if (VT.bitsGT(VT0))
4795       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4796     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4797   }
4798   // fold (select C, 0, X) -> (and (not C), X)
4799   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4800     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4801     AddToWorklist(NOTNode.getNode());
4802     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4803   }
4804   // fold (select C, X, 1) -> (or (not C), X)
4805   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4806     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4807     AddToWorklist(NOTNode.getNode());
4808     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4809   }
4810   // fold (select C, X, 0) -> (and C, X)
4811   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4812     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4813   // fold (select X, X, Y) -> (or X, Y)
4814   // fold (select X, 1, Y) -> (or X, Y)
4815   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4816     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4817   // fold (select X, Y, X) -> (and X, Y)
4818   // fold (select X, Y, 0) -> (and X, Y)
4819   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4820     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4821
4822   // If we can fold this based on the true/false value, do so.
4823   if (SimplifySelectOps(N, N1, N2))
4824     return SDValue(N, 0);  // Don't revisit N.
4825
4826   // fold selects based on a setcc into other things, such as min/max/abs
4827   if (N0.getOpcode() == ISD::SETCC) {
4828     // select x, y (fcmp lt x, y) -> fminnum x, y
4829     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4830     //
4831     // This is OK if we don't care about what happens if either operand is a
4832     // NaN.
4833     //
4834
4835     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4836     // no signed zeros as well as no nans.
4837     const TargetOptions &Options = DAG.getTarget().Options;
4838     if (Options.UnsafeFPMath &&
4839         VT.isFloatingPoint() && N0.hasOneUse() &&
4840         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4841       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4842
4843       SDValue FMinMax =
4844           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4845                               N1, N2, CC, TLI, DAG);
4846       if (FMinMax)
4847         return FMinMax;
4848     }
4849
4850     if ((!LegalOperations &&
4851          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4852         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4853       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4854                          N0.getOperand(0), N0.getOperand(1),
4855                          N1, N2, N0.getOperand(2));
4856     return SimplifySelect(SDLoc(N), N0, N1, N2);
4857   }
4858
4859   if (VT0 == MVT::i1) {
4860     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4861       // select (and Cond0, Cond1), X, Y
4862       //   -> select Cond0, (select Cond1, X, Y), Y
4863       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4864         SDValue Cond0 = N0->getOperand(0);
4865         SDValue Cond1 = N0->getOperand(1);
4866         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4867                                           N1.getValueType(), Cond1, N1, N2);
4868         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4869                            InnerSelect, N2);
4870       }
4871       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4872       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4873         SDValue Cond0 = N0->getOperand(0);
4874         SDValue Cond1 = N0->getOperand(1);
4875         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4876                                           N1.getValueType(), Cond1, N1, N2);
4877         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4878                            InnerSelect);
4879       }
4880     }
4881
4882     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4883     if (N1->getOpcode() == ISD::SELECT) {
4884       SDValue N1_0 = N1->getOperand(0);
4885       SDValue N1_1 = N1->getOperand(1);
4886       SDValue N1_2 = N1->getOperand(2);
4887       if (N1_2 == N2) {
4888         // Create the actual and node if we can generate good code for it.
4889         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4890           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4891                                     N0, N1_0);
4892           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4893                              N1_1, N2);
4894         }
4895         // Otherwise see if we can optimize the "and" to a better pattern.
4896         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4897           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4898                              N1_1, N2);
4899       }
4900     }
4901     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4902     if (N2->getOpcode() == ISD::SELECT) {
4903       SDValue N2_0 = N2->getOperand(0);
4904       SDValue N2_1 = N2->getOperand(1);
4905       SDValue N2_2 = N2->getOperand(2);
4906       if (N2_1 == N1) {
4907         // Create the actual or node if we can generate good code for it.
4908         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4909           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4910                                    N0, N2_0);
4911           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4912                              N1, N2_2);
4913         }
4914         // Otherwise see if we can optimize to a better pattern.
4915         if (SDValue Combined = visitORLike(N0, N2_0, N))
4916           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4917                              N1, N2_2);
4918       }
4919     }
4920   }
4921
4922   return SDValue();
4923 }
4924
4925 static
4926 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4927   SDLoc DL(N);
4928   EVT LoVT, HiVT;
4929   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4930
4931   // Split the inputs.
4932   SDValue Lo, Hi, LL, LH, RL, RH;
4933   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4934   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4935
4936   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4937   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4938
4939   return std::make_pair(Lo, Hi);
4940 }
4941
4942 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4943 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4944 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4945   SDLoc dl(N);
4946   SDValue Cond = N->getOperand(0);
4947   SDValue LHS = N->getOperand(1);
4948   SDValue RHS = N->getOperand(2);
4949   EVT VT = N->getValueType(0);
4950   int NumElems = VT.getVectorNumElements();
4951   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4952          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4953          Cond.getOpcode() == ISD::BUILD_VECTOR);
4954
4955   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4956   // binary ones here.
4957   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4958     return SDValue();
4959
4960   // We're sure we have an even number of elements due to the
4961   // concat_vectors we have as arguments to vselect.
4962   // Skip BV elements until we find one that's not an UNDEF
4963   // After we find an UNDEF element, keep looping until we get to half the
4964   // length of the BV and see if all the non-undef nodes are the same.
4965   ConstantSDNode *BottomHalf = nullptr;
4966   for (int i = 0; i < NumElems / 2; ++i) {
4967     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4968       continue;
4969
4970     if (BottomHalf == nullptr)
4971       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4972     else if (Cond->getOperand(i).getNode() != BottomHalf)
4973       return SDValue();
4974   }
4975
4976   // Do the same for the second half of the BuildVector
4977   ConstantSDNode *TopHalf = nullptr;
4978   for (int i = NumElems / 2; i < NumElems; ++i) {
4979     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4980       continue;
4981
4982     if (TopHalf == nullptr)
4983       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4984     else if (Cond->getOperand(i).getNode() != TopHalf)
4985       return SDValue();
4986   }
4987
4988   assert(TopHalf && BottomHalf &&
4989          "One half of the selector was all UNDEFs and the other was all the "
4990          "same value. This should have been addressed before this function.");
4991   return DAG.getNode(
4992       ISD::CONCAT_VECTORS, dl, VT,
4993       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4994       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4995 }
4996
4997 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4998
4999   if (Level >= AfterLegalizeTypes)
5000     return SDValue();
5001
5002   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5003   SDValue Mask = MST->getMask();
5004   SDValue Data  = MST->getValue();
5005   SDLoc DL(N);
5006
5007   // If the MSTORE data type requires splitting and the mask is provided by a
5008   // SETCC, then split both nodes and its operands before legalization. This
5009   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5010   // and enables future optimizations (e.g. min/max pattern matching on X86).
5011   if (Mask.getOpcode() == ISD::SETCC) {
5012
5013     // Check if any splitting is required.
5014     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5015         TargetLowering::TypeSplitVector)
5016       return SDValue();
5017
5018     SDValue MaskLo, MaskHi, Lo, Hi;
5019     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5020
5021     EVT LoVT, HiVT;
5022     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5023
5024     SDValue Chain = MST->getChain();
5025     SDValue Ptr   = MST->getBasePtr();
5026
5027     EVT MemoryVT = MST->getMemoryVT();
5028     unsigned Alignment = MST->getOriginalAlignment();
5029
5030     // if Alignment is equal to the vector size,
5031     // take the half of it for the second part
5032     unsigned SecondHalfAlignment =
5033       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5034          Alignment/2 : Alignment;
5035
5036     EVT LoMemVT, HiMemVT;
5037     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5038
5039     SDValue DataLo, DataHi;
5040     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5041
5042     MachineMemOperand *MMO = DAG.getMachineFunction().
5043       getMachineMemOperand(MST->getPointerInfo(),
5044                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5045                            Alignment, MST->getAAInfo(), MST->getRanges());
5046
5047     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5048                             MST->isTruncatingStore());
5049
5050     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5051     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5052                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5053
5054     MMO = DAG.getMachineFunction().
5055       getMachineMemOperand(MST->getPointerInfo(),
5056                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5057                            SecondHalfAlignment, MST->getAAInfo(),
5058                            MST->getRanges());
5059
5060     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5061                             MST->isTruncatingStore());
5062
5063     AddToWorklist(Lo.getNode());
5064     AddToWorklist(Hi.getNode());
5065
5066     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5067   }
5068   return SDValue();
5069 }
5070
5071 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5072
5073   if (Level >= AfterLegalizeTypes)
5074     return SDValue();
5075
5076   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5077   SDValue Mask = MLD->getMask();
5078   SDLoc DL(N);
5079
5080   // If the MLOAD result requires splitting and the mask is provided by a
5081   // SETCC, then split both nodes and its operands before legalization. This
5082   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5083   // and enables future optimizations (e.g. min/max pattern matching on X86).
5084
5085   if (Mask.getOpcode() == ISD::SETCC) {
5086     EVT VT = N->getValueType(0);
5087
5088     // Check if any splitting is required.
5089     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5090         TargetLowering::TypeSplitVector)
5091       return SDValue();
5092
5093     SDValue MaskLo, MaskHi, Lo, Hi;
5094     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5095
5096     SDValue Src0 = MLD->getSrc0();
5097     SDValue Src0Lo, Src0Hi;
5098     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5099
5100     EVT LoVT, HiVT;
5101     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5102
5103     SDValue Chain = MLD->getChain();
5104     SDValue Ptr   = MLD->getBasePtr();
5105     EVT MemoryVT = MLD->getMemoryVT();
5106     unsigned Alignment = MLD->getOriginalAlignment();
5107
5108     // if Alignment is equal to the vector size,
5109     // take the half of it for the second part
5110     unsigned SecondHalfAlignment =
5111       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5112          Alignment/2 : Alignment;
5113
5114     EVT LoMemVT, HiMemVT;
5115     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5116
5117     MachineMemOperand *MMO = DAG.getMachineFunction().
5118     getMachineMemOperand(MLD->getPointerInfo(),
5119                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5120                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5121
5122     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5123                            ISD::NON_EXTLOAD);
5124
5125     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5126     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5127                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5128
5129     MMO = DAG.getMachineFunction().
5130     getMachineMemOperand(MLD->getPointerInfo(),
5131                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5132                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5133
5134     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5135                            ISD::NON_EXTLOAD);
5136
5137     AddToWorklist(Lo.getNode());
5138     AddToWorklist(Hi.getNode());
5139
5140     // Build a factor node to remember that this load is independent of the
5141     // other one.
5142     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5143                         Hi.getValue(1));
5144
5145     // Legalized the chain result - switch anything that used the old chain to
5146     // use the new one.
5147     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5148
5149     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5150
5151     SDValue RetOps[] = { LoadRes, Chain };
5152     return DAG.getMergeValues(RetOps, DL);
5153   }
5154   return SDValue();
5155 }
5156
5157 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5158   SDValue N0 = N->getOperand(0);
5159   SDValue N1 = N->getOperand(1);
5160   SDValue N2 = N->getOperand(2);
5161   SDLoc DL(N);
5162
5163   // Canonicalize integer abs.
5164   // vselect (setg[te] X,  0),  X, -X ->
5165   // vselect (setgt    X, -1),  X, -X ->
5166   // vselect (setl[te] X,  0), -X,  X ->
5167   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5168   if (N0.getOpcode() == ISD::SETCC) {
5169     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5170     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5171     bool isAbs = false;
5172     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5173
5174     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5175          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5176         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5177       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5178     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5179              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5180       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5181
5182     if (isAbs) {
5183       EVT VT = LHS.getValueType();
5184       SDValue Shift = DAG.getNode(
5185           ISD::SRA, DL, VT, LHS,
5186           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5187       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5188       AddToWorklist(Shift.getNode());
5189       AddToWorklist(Add.getNode());
5190       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5191     }
5192   }
5193
5194   // If the VSELECT result requires splitting and the mask is provided by a
5195   // SETCC, then split both nodes and its operands before legalization. This
5196   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5197   // and enables future optimizations (e.g. min/max pattern matching on X86).
5198   if (N0.getOpcode() == ISD::SETCC) {
5199     EVT VT = N->getValueType(0);
5200
5201     // Check if any splitting is required.
5202     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5203         TargetLowering::TypeSplitVector)
5204       return SDValue();
5205
5206     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5207     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5208     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5209     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5210
5211     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5212     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5213
5214     // Add the new VSELECT nodes to the work list in case they need to be split
5215     // again.
5216     AddToWorklist(Lo.getNode());
5217     AddToWorklist(Hi.getNode());
5218
5219     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5220   }
5221
5222   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5223   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5224     return N1;
5225   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5226   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5227     return N2;
5228
5229   // The ConvertSelectToConcatVector function is assuming both the above
5230   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5231   // and addressed.
5232   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5233       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5234       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5235     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5236     if (CV.getNode())
5237       return CV;
5238   }
5239
5240   return SDValue();
5241 }
5242
5243 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5244   SDValue N0 = N->getOperand(0);
5245   SDValue N1 = N->getOperand(1);
5246   SDValue N2 = N->getOperand(2);
5247   SDValue N3 = N->getOperand(3);
5248   SDValue N4 = N->getOperand(4);
5249   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5250
5251   // fold select_cc lhs, rhs, x, x, cc -> x
5252   if (N2 == N3)
5253     return N2;
5254
5255   // Determine if the condition we're dealing with is constant
5256   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5257                               N0, N1, CC, SDLoc(N), false);
5258   if (SCC.getNode()) {
5259     AddToWorklist(SCC.getNode());
5260
5261     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5262       if (!SCCC->isNullValue())
5263         return N2;    // cond always true -> true val
5264       else
5265         return N3;    // cond always false -> false val
5266     } else if (SCC->getOpcode() == ISD::UNDEF) {
5267       // When the condition is UNDEF, just return the first operand. This is
5268       // coherent the DAG creation, no setcc node is created in this case
5269       return N2;
5270     } else if (SCC.getOpcode() == ISD::SETCC) {
5271       // Fold to a simpler select_cc
5272       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5273                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5274                          SCC.getOperand(2));
5275     }
5276   }
5277
5278   // If we can fold this based on the true/false value, do so.
5279   if (SimplifySelectOps(N, N2, N3))
5280     return SDValue(N, 0);  // Don't revisit N.
5281
5282   // fold select_cc into other things, such as min/max/abs
5283   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5284 }
5285
5286 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5287   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5288                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5289                        SDLoc(N));
5290 }
5291
5292 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5293 // dag node into a ConstantSDNode or a build_vector of constants.
5294 // This function is called by the DAGCombiner when visiting sext/zext/aext
5295 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5296 // Vector extends are not folded if operations are legal; this is to
5297 // avoid introducing illegal build_vector dag nodes.
5298 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5299                                          SelectionDAG &DAG, bool LegalTypes,
5300                                          bool LegalOperations) {
5301   unsigned Opcode = N->getOpcode();
5302   SDValue N0 = N->getOperand(0);
5303   EVT VT = N->getValueType(0);
5304
5305   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5306          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5307
5308   // fold (sext c1) -> c1
5309   // fold (zext c1) -> c1
5310   // fold (aext c1) -> c1
5311   if (isa<ConstantSDNode>(N0))
5312     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5313
5314   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5315   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5316   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5317   EVT SVT = VT.getScalarType();
5318   if (!(VT.isVector() &&
5319       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5320       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5321     return nullptr;
5322
5323   // We can fold this node into a build_vector.
5324   unsigned VTBits = SVT.getSizeInBits();
5325   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5326   unsigned ShAmt = VTBits - EVTBits;
5327   SmallVector<SDValue, 8> Elts;
5328   unsigned NumElts = N0->getNumOperands();
5329   SDLoc DL(N);
5330
5331   for (unsigned i=0; i != NumElts; ++i) {
5332     SDValue Op = N0->getOperand(i);
5333     if (Op->getOpcode() == ISD::UNDEF) {
5334       Elts.push_back(DAG.getUNDEF(SVT));
5335       continue;
5336     }
5337
5338     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5339     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5340     if (Opcode == ISD::SIGN_EXTEND)
5341       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5342                                      SVT));
5343     else
5344       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5345                                      SVT));
5346   }
5347
5348   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5349 }
5350
5351 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5352 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5353 // transformation. Returns true if extension are possible and the above
5354 // mentioned transformation is profitable.
5355 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5356                                     unsigned ExtOpc,
5357                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5358                                     const TargetLowering &TLI) {
5359   bool HasCopyToRegUses = false;
5360   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5361   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5362                             UE = N0.getNode()->use_end();
5363        UI != UE; ++UI) {
5364     SDNode *User = *UI;
5365     if (User == N)
5366       continue;
5367     if (UI.getUse().getResNo() != N0.getResNo())
5368       continue;
5369     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5370     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5371       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5372       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5373         // Sign bits will be lost after a zext.
5374         return false;
5375       bool Add = false;
5376       for (unsigned i = 0; i != 2; ++i) {
5377         SDValue UseOp = User->getOperand(i);
5378         if (UseOp == N0)
5379           continue;
5380         if (!isa<ConstantSDNode>(UseOp))
5381           return false;
5382         Add = true;
5383       }
5384       if (Add)
5385         ExtendNodes.push_back(User);
5386       continue;
5387     }
5388     // If truncates aren't free and there are users we can't
5389     // extend, it isn't worthwhile.
5390     if (!isTruncFree)
5391       return false;
5392     // Remember if this value is live-out.
5393     if (User->getOpcode() == ISD::CopyToReg)
5394       HasCopyToRegUses = true;
5395   }
5396
5397   if (HasCopyToRegUses) {
5398     bool BothLiveOut = false;
5399     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5400          UI != UE; ++UI) {
5401       SDUse &Use = UI.getUse();
5402       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5403         BothLiveOut = true;
5404         break;
5405       }
5406     }
5407     if (BothLiveOut)
5408       // Both unextended and extended values are live out. There had better be
5409       // a good reason for the transformation.
5410       return ExtendNodes.size();
5411   }
5412   return true;
5413 }
5414
5415 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5416                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5417                                   ISD::NodeType ExtType) {
5418   // Extend SetCC uses if necessary.
5419   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5420     SDNode *SetCC = SetCCs[i];
5421     SmallVector<SDValue, 4> Ops;
5422
5423     for (unsigned j = 0; j != 2; ++j) {
5424       SDValue SOp = SetCC->getOperand(j);
5425       if (SOp == Trunc)
5426         Ops.push_back(ExtLoad);
5427       else
5428         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5429     }
5430
5431     Ops.push_back(SetCC->getOperand(2));
5432     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5433   }
5434 }
5435
5436 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5437 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5438   SDValue N0 = N->getOperand(0);
5439   EVT DstVT = N->getValueType(0);
5440   EVT SrcVT = N0.getValueType();
5441
5442   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5443           N->getOpcode() == ISD::ZERO_EXTEND) &&
5444          "Unexpected node type (not an extend)!");
5445
5446   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5447   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5448   //   (v8i32 (sext (v8i16 (load x))))
5449   // into:
5450   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5451   //                          (v4i32 (sextload (x + 16)))))
5452   // Where uses of the original load, i.e.:
5453   //   (v8i16 (load x))
5454   // are replaced with:
5455   //   (v8i16 (truncate
5456   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5457   //                            (v4i32 (sextload (x + 16)))))))
5458   //
5459   // This combine is only applicable to illegal, but splittable, vectors.
5460   // All legal types, and illegal non-vector types, are handled elsewhere.
5461   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5462   //
5463   if (N0->getOpcode() != ISD::LOAD)
5464     return SDValue();
5465
5466   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5467
5468   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5469       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5470       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5471     return SDValue();
5472
5473   SmallVector<SDNode *, 4> SetCCs;
5474   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5475     return SDValue();
5476
5477   ISD::LoadExtType ExtType =
5478       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5479
5480   // Try to split the vector types to get down to legal types.
5481   EVT SplitSrcVT = SrcVT;
5482   EVT SplitDstVT = DstVT;
5483   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5484          SplitSrcVT.getVectorNumElements() > 1) {
5485     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5486     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5487   }
5488
5489   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5490     return SDValue();
5491
5492   SDLoc DL(N);
5493   const unsigned NumSplits =
5494       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5495   const unsigned Stride = SplitSrcVT.getStoreSize();
5496   SmallVector<SDValue, 4> Loads;
5497   SmallVector<SDValue, 4> Chains;
5498
5499   SDValue BasePtr = LN0->getBasePtr();
5500   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5501     const unsigned Offset = Idx * Stride;
5502     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5503
5504     SDValue SplitLoad = DAG.getExtLoad(
5505         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5506         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5507         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5508         Align, LN0->getAAInfo());
5509
5510     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5511                           DAG.getConstant(Stride, BasePtr.getValueType()));
5512
5513     Loads.push_back(SplitLoad.getValue(0));
5514     Chains.push_back(SplitLoad.getValue(1));
5515   }
5516
5517   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5518   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5519
5520   CombineTo(N, NewValue);
5521
5522   // Replace uses of the original load (before extension)
5523   // with a truncate of the concatenated sextloaded vectors.
5524   SDValue Trunc =
5525       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5526   CombineTo(N0.getNode(), Trunc, NewChain);
5527   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5528                   (ISD::NodeType)N->getOpcode());
5529   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5530 }
5531
5532 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5533   SDValue N0 = N->getOperand(0);
5534   EVT VT = N->getValueType(0);
5535
5536   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5537                                               LegalOperations))
5538     return SDValue(Res, 0);
5539
5540   // fold (sext (sext x)) -> (sext x)
5541   // fold (sext (aext x)) -> (sext x)
5542   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5543     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5544                        N0.getOperand(0));
5545
5546   if (N0.getOpcode() == ISD::TRUNCATE) {
5547     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5548     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5549     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5550     if (NarrowLoad.getNode()) {
5551       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5552       if (NarrowLoad.getNode() != N0.getNode()) {
5553         CombineTo(N0.getNode(), NarrowLoad);
5554         // CombineTo deleted the truncate, if needed, but not what's under it.
5555         AddToWorklist(oye);
5556       }
5557       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5558     }
5559
5560     // See if the value being truncated is already sign extended.  If so, just
5561     // eliminate the trunc/sext pair.
5562     SDValue Op = N0.getOperand(0);
5563     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5564     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5565     unsigned DestBits = VT.getScalarType().getSizeInBits();
5566     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5567
5568     if (OpBits == DestBits) {
5569       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5570       // bits, it is already ready.
5571       if (NumSignBits > DestBits-MidBits)
5572         return Op;
5573     } else if (OpBits < DestBits) {
5574       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5575       // bits, just sext from i32.
5576       if (NumSignBits > OpBits-MidBits)
5577         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5578     } else {
5579       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5580       // bits, just truncate to i32.
5581       if (NumSignBits > OpBits-MidBits)
5582         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5583     }
5584
5585     // fold (sext (truncate x)) -> (sextinreg x).
5586     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5587                                                  N0.getValueType())) {
5588       if (OpBits < DestBits)
5589         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5590       else if (OpBits > DestBits)
5591         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5592       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5593                          DAG.getValueType(N0.getValueType()));
5594     }
5595   }
5596
5597   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5598   // Only generate vector extloads when 1) they're legal, and 2) they are
5599   // deemed desirable by the target.
5600   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5601       ((!LegalOperations && !VT.isVector() &&
5602         !cast<LoadSDNode>(N0)->isVolatile()) ||
5603        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5604     bool DoXform = true;
5605     SmallVector<SDNode*, 4> SetCCs;
5606     if (!N0.hasOneUse())
5607       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5608     if (VT.isVector())
5609       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5610     if (DoXform) {
5611       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5612       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5613                                        LN0->getChain(),
5614                                        LN0->getBasePtr(), N0.getValueType(),
5615                                        LN0->getMemOperand());
5616       CombineTo(N, ExtLoad);
5617       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5618                                   N0.getValueType(), ExtLoad);
5619       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5620       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5621                       ISD::SIGN_EXTEND);
5622       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5623     }
5624   }
5625
5626   // fold (sext (load x)) to multiple smaller sextloads.
5627   // Only on illegal but splittable vectors.
5628   if (SDValue ExtLoad = CombineExtLoad(N))
5629     return ExtLoad;
5630
5631   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5632   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5633   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5634       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5635     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5636     EVT MemVT = LN0->getMemoryVT();
5637     if ((!LegalOperations && !LN0->isVolatile()) ||
5638         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5639       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5640                                        LN0->getChain(),
5641                                        LN0->getBasePtr(), MemVT,
5642                                        LN0->getMemOperand());
5643       CombineTo(N, ExtLoad);
5644       CombineTo(N0.getNode(),
5645                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5646                             N0.getValueType(), ExtLoad),
5647                 ExtLoad.getValue(1));
5648       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5649     }
5650   }
5651
5652   // fold (sext (and/or/xor (load x), cst)) ->
5653   //      (and/or/xor (sextload x), (sext cst))
5654   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5655        N0.getOpcode() == ISD::XOR) &&
5656       isa<LoadSDNode>(N0.getOperand(0)) &&
5657       N0.getOperand(1).getOpcode() == ISD::Constant &&
5658       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5659       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5660     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5661     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5662       bool DoXform = true;
5663       SmallVector<SDNode*, 4> SetCCs;
5664       if (!N0.hasOneUse())
5665         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5666                                           SetCCs, TLI);
5667       if (DoXform) {
5668         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5669                                          LN0->getChain(), LN0->getBasePtr(),
5670                                          LN0->getMemoryVT(),
5671                                          LN0->getMemOperand());
5672         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5673         Mask = Mask.sext(VT.getSizeInBits());
5674         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5675                                   ExtLoad, DAG.getConstant(Mask, VT));
5676         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5677                                     SDLoc(N0.getOperand(0)),
5678                                     N0.getOperand(0).getValueType(), ExtLoad);
5679         CombineTo(N, And);
5680         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5681         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5682                         ISD::SIGN_EXTEND);
5683         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5684       }
5685     }
5686   }
5687
5688   if (N0.getOpcode() == ISD::SETCC) {
5689     EVT N0VT = N0.getOperand(0).getValueType();
5690     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5691     // Only do this before legalize for now.
5692     if (VT.isVector() && !LegalOperations &&
5693         TLI.getBooleanContents(N0VT) ==
5694             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5695       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5696       // of the same size as the compared operands. Only optimize sext(setcc())
5697       // if this is the case.
5698       EVT SVT = getSetCCResultType(N0VT);
5699
5700       // We know that the # elements of the results is the same as the
5701       // # elements of the compare (and the # elements of the compare result
5702       // for that matter).  Check to see that they are the same size.  If so,
5703       // we know that the element size of the sext'd result matches the
5704       // element size of the compare operands.
5705       if (VT.getSizeInBits() == SVT.getSizeInBits())
5706         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5707                              N0.getOperand(1),
5708                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5709
5710       // If the desired elements are smaller or larger than the source
5711       // elements we can use a matching integer vector type and then
5712       // truncate/sign extend
5713       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5714       if (SVT == MatchingVectorType) {
5715         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5716                                N0.getOperand(0), N0.getOperand(1),
5717                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5718         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5719       }
5720     }
5721
5722     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5723     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5724     SDValue NegOne =
5725       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5726     SDValue SCC =
5727       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5728                        NegOne, DAG.getConstant(0, VT),
5729                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5730     if (SCC.getNode()) return SCC;
5731
5732     if (!VT.isVector()) {
5733       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5734       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5735         SDLoc DL(N);
5736         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5737         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5738                                      N0.getOperand(0), N0.getOperand(1), CC);
5739         return DAG.getSelect(DL, VT, SetCC,
5740                              NegOne, DAG.getConstant(0, VT));
5741       }
5742     }
5743   }
5744
5745   // fold (sext x) -> (zext x) if the sign bit is known zero.
5746   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5747       DAG.SignBitIsZero(N0))
5748     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5749
5750   return SDValue();
5751 }
5752
5753 // isTruncateOf - If N is a truncate of some other value, return true, record
5754 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5755 // This function computes KnownZero to avoid a duplicated call to
5756 // computeKnownBits in the caller.
5757 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5758                          APInt &KnownZero) {
5759   APInt KnownOne;
5760   if (N->getOpcode() == ISD::TRUNCATE) {
5761     Op = N->getOperand(0);
5762     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5763     return true;
5764   }
5765
5766   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5767       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5768     return false;
5769
5770   SDValue Op0 = N->getOperand(0);
5771   SDValue Op1 = N->getOperand(1);
5772   assert(Op0.getValueType() == Op1.getValueType());
5773
5774   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5775   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5776   if (COp0 && COp0->isNullValue())
5777     Op = Op1;
5778   else if (COp1 && COp1->isNullValue())
5779     Op = Op0;
5780   else
5781     return false;
5782
5783   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5784
5785   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5786     return false;
5787
5788   return true;
5789 }
5790
5791 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5792   SDValue N0 = N->getOperand(0);
5793   EVT VT = N->getValueType(0);
5794
5795   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5796                                               LegalOperations))
5797     return SDValue(Res, 0);
5798
5799   // fold (zext (zext x)) -> (zext x)
5800   // fold (zext (aext x)) -> (zext x)
5801   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5802     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5803                        N0.getOperand(0));
5804
5805   // fold (zext (truncate x)) -> (zext x) or
5806   //      (zext (truncate x)) -> (truncate x)
5807   // This is valid when the truncated bits of x are already zero.
5808   // FIXME: We should extend this to work for vectors too.
5809   SDValue Op;
5810   APInt KnownZero;
5811   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5812     APInt TruncatedBits =
5813       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5814       APInt(Op.getValueSizeInBits(), 0) :
5815       APInt::getBitsSet(Op.getValueSizeInBits(),
5816                         N0.getValueSizeInBits(),
5817                         std::min(Op.getValueSizeInBits(),
5818                                  VT.getSizeInBits()));
5819     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5820       if (VT.bitsGT(Op.getValueType()))
5821         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5822       if (VT.bitsLT(Op.getValueType()))
5823         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5824
5825       return Op;
5826     }
5827   }
5828
5829   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5830   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5831   if (N0.getOpcode() == ISD::TRUNCATE) {
5832     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5833     if (NarrowLoad.getNode()) {
5834       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5835       if (NarrowLoad.getNode() != N0.getNode()) {
5836         CombineTo(N0.getNode(), NarrowLoad);
5837         // CombineTo deleted the truncate, if needed, but not what's under it.
5838         AddToWorklist(oye);
5839       }
5840       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5841     }
5842   }
5843
5844   // fold (zext (truncate x)) -> (and x, mask)
5845   if (N0.getOpcode() == ISD::TRUNCATE &&
5846       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5847
5848     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5849     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5850     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5851     if (NarrowLoad.getNode()) {
5852       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5853       if (NarrowLoad.getNode() != N0.getNode()) {
5854         CombineTo(N0.getNode(), NarrowLoad);
5855         // CombineTo deleted the truncate, if needed, but not what's under it.
5856         AddToWorklist(oye);
5857       }
5858       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5859     }
5860
5861     SDValue Op = N0.getOperand(0);
5862     if (Op.getValueType().bitsLT(VT)) {
5863       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5864       AddToWorklist(Op.getNode());
5865     } else if (Op.getValueType().bitsGT(VT)) {
5866       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5867       AddToWorklist(Op.getNode());
5868     }
5869     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5870                                   N0.getValueType().getScalarType());
5871   }
5872
5873   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5874   // if either of the casts is not free.
5875   if (N0.getOpcode() == ISD::AND &&
5876       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5877       N0.getOperand(1).getOpcode() == ISD::Constant &&
5878       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5879                            N0.getValueType()) ||
5880        !TLI.isZExtFree(N0.getValueType(), VT))) {
5881     SDValue X = N0.getOperand(0).getOperand(0);
5882     if (X.getValueType().bitsLT(VT)) {
5883       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5884     } else if (X.getValueType().bitsGT(VT)) {
5885       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5886     }
5887     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5888     Mask = Mask.zext(VT.getSizeInBits());
5889     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5890                        X, DAG.getConstant(Mask, VT));
5891   }
5892
5893   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5894   // Only generate vector extloads when 1) they're legal, and 2) they are
5895   // deemed desirable by the target.
5896   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5897       ((!LegalOperations && !VT.isVector() &&
5898         !cast<LoadSDNode>(N0)->isVolatile()) ||
5899        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5900     bool DoXform = true;
5901     SmallVector<SDNode*, 4> SetCCs;
5902     if (!N0.hasOneUse())
5903       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5904     if (VT.isVector())
5905       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5906     if (DoXform) {
5907       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5908       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5909                                        LN0->getChain(),
5910                                        LN0->getBasePtr(), N0.getValueType(),
5911                                        LN0->getMemOperand());
5912       CombineTo(N, ExtLoad);
5913       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5914                                   N0.getValueType(), ExtLoad);
5915       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5916
5917       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5918                       ISD::ZERO_EXTEND);
5919       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5920     }
5921   }
5922
5923   // fold (zext (load x)) to multiple smaller zextloads.
5924   // Only on illegal but splittable vectors.
5925   if (SDValue ExtLoad = CombineExtLoad(N))
5926     return ExtLoad;
5927
5928   // fold (zext (and/or/xor (load x), cst)) ->
5929   //      (and/or/xor (zextload x), (zext cst))
5930   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5931        N0.getOpcode() == ISD::XOR) &&
5932       isa<LoadSDNode>(N0.getOperand(0)) &&
5933       N0.getOperand(1).getOpcode() == ISD::Constant &&
5934       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5935       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5936     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5937     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5938       bool DoXform = true;
5939       SmallVector<SDNode*, 4> SetCCs;
5940       if (!N0.hasOneUse())
5941         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5942                                           SetCCs, TLI);
5943       if (DoXform) {
5944         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5945                                          LN0->getChain(), LN0->getBasePtr(),
5946                                          LN0->getMemoryVT(),
5947                                          LN0->getMemOperand());
5948         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5949         Mask = Mask.zext(VT.getSizeInBits());
5950         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5951                                   ExtLoad, DAG.getConstant(Mask, VT));
5952         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5953                                     SDLoc(N0.getOperand(0)),
5954                                     N0.getOperand(0).getValueType(), ExtLoad);
5955         CombineTo(N, And);
5956         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5957         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5958                         ISD::ZERO_EXTEND);
5959         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5960       }
5961     }
5962   }
5963
5964   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5965   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5966   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5967       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5968     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5969     EVT MemVT = LN0->getMemoryVT();
5970     if ((!LegalOperations && !LN0->isVolatile()) ||
5971         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5972       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5973                                        LN0->getChain(),
5974                                        LN0->getBasePtr(), MemVT,
5975                                        LN0->getMemOperand());
5976       CombineTo(N, ExtLoad);
5977       CombineTo(N0.getNode(),
5978                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5979                             ExtLoad),
5980                 ExtLoad.getValue(1));
5981       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5982     }
5983   }
5984
5985   if (N0.getOpcode() == ISD::SETCC) {
5986     if (!LegalOperations && VT.isVector() &&
5987         N0.getValueType().getVectorElementType() == MVT::i1) {
5988       EVT N0VT = N0.getOperand(0).getValueType();
5989       if (getSetCCResultType(N0VT) == N0.getValueType())
5990         return SDValue();
5991
5992       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5993       // Only do this before legalize for now.
5994       EVT EltVT = VT.getVectorElementType();
5995       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5996                                     DAG.getConstant(1, EltVT));
5997       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5998         // We know that the # elements of the results is the same as the
5999         // # elements of the compare (and the # elements of the compare result
6000         // for that matter).  Check to see that they are the same size.  If so,
6001         // we know that the element size of the sext'd result matches the
6002         // element size of the compare operands.
6003         return DAG.getNode(ISD::AND, SDLoc(N), VT,
6004                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6005                                          N0.getOperand(1),
6006                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6007                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
6008                                        OneOps));
6009
6010       // If the desired elements are smaller or larger than the source
6011       // elements we can use a matching integer vector type and then
6012       // truncate/sign extend
6013       EVT MatchingElementType =
6014         EVT::getIntegerVT(*DAG.getContext(),
6015                           N0VT.getScalarType().getSizeInBits());
6016       EVT MatchingVectorType =
6017         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6018                          N0VT.getVectorNumElements());
6019       SDValue VsetCC =
6020         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6021                       N0.getOperand(1),
6022                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6023       return DAG.getNode(ISD::AND, SDLoc(N), VT,
6024                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
6025                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
6026     }
6027
6028     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6029     SDValue SCC =
6030       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6031                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6032                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6033     if (SCC.getNode()) return SCC;
6034   }
6035
6036   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6037   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6038       isa<ConstantSDNode>(N0.getOperand(1)) &&
6039       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6040       N0.hasOneUse()) {
6041     SDValue ShAmt = N0.getOperand(1);
6042     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6043     if (N0.getOpcode() == ISD::SHL) {
6044       SDValue InnerZExt = N0.getOperand(0);
6045       // If the original shl may be shifting out bits, do not perform this
6046       // transformation.
6047       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6048         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6049       if (ShAmtVal > KnownZeroBits)
6050         return SDValue();
6051     }
6052
6053     SDLoc DL(N);
6054
6055     // Ensure that the shift amount is wide enough for the shifted value.
6056     if (VT.getSizeInBits() >= 256)
6057       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6058
6059     return DAG.getNode(N0.getOpcode(), DL, VT,
6060                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6061                        ShAmt);
6062   }
6063
6064   return SDValue();
6065 }
6066
6067 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6068   SDValue N0 = N->getOperand(0);
6069   EVT VT = N->getValueType(0);
6070
6071   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6072                                               LegalOperations))
6073     return SDValue(Res, 0);
6074
6075   // fold (aext (aext x)) -> (aext x)
6076   // fold (aext (zext x)) -> (zext x)
6077   // fold (aext (sext x)) -> (sext x)
6078   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6079       N0.getOpcode() == ISD::ZERO_EXTEND ||
6080       N0.getOpcode() == ISD::SIGN_EXTEND)
6081     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6082
6083   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6084   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6085   if (N0.getOpcode() == ISD::TRUNCATE) {
6086     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6087     if (NarrowLoad.getNode()) {
6088       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6089       if (NarrowLoad.getNode() != N0.getNode()) {
6090         CombineTo(N0.getNode(), NarrowLoad);
6091         // CombineTo deleted the truncate, if needed, but not what's under it.
6092         AddToWorklist(oye);
6093       }
6094       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6095     }
6096   }
6097
6098   // fold (aext (truncate x))
6099   if (N0.getOpcode() == ISD::TRUNCATE) {
6100     SDValue TruncOp = N0.getOperand(0);
6101     if (TruncOp.getValueType() == VT)
6102       return TruncOp; // x iff x size == zext size.
6103     if (TruncOp.getValueType().bitsGT(VT))
6104       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6105     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6106   }
6107
6108   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6109   // if the trunc is not free.
6110   if (N0.getOpcode() == ISD::AND &&
6111       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6112       N0.getOperand(1).getOpcode() == ISD::Constant &&
6113       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6114                           N0.getValueType())) {
6115     SDValue X = N0.getOperand(0).getOperand(0);
6116     if (X.getValueType().bitsLT(VT)) {
6117       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6118     } else if (X.getValueType().bitsGT(VT)) {
6119       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6120     }
6121     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6122     Mask = Mask.zext(VT.getSizeInBits());
6123     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6124                        X, DAG.getConstant(Mask, VT));
6125   }
6126
6127   // fold (aext (load x)) -> (aext (truncate (extload x)))
6128   // None of the supported targets knows how to perform load and any_ext
6129   // on vectors in one instruction.  We only perform this transformation on
6130   // scalars.
6131   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6132       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6133       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6134     bool DoXform = true;
6135     SmallVector<SDNode*, 4> SetCCs;
6136     if (!N0.hasOneUse())
6137       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6138     if (DoXform) {
6139       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6140       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6141                                        LN0->getChain(),
6142                                        LN0->getBasePtr(), N0.getValueType(),
6143                                        LN0->getMemOperand());
6144       CombineTo(N, ExtLoad);
6145       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6146                                   N0.getValueType(), ExtLoad);
6147       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6148       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6149                       ISD::ANY_EXTEND);
6150       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6151     }
6152   }
6153
6154   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6155   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6156   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6157   if (N0.getOpcode() == ISD::LOAD &&
6158       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6159       N0.hasOneUse()) {
6160     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6161     ISD::LoadExtType ExtType = LN0->getExtensionType();
6162     EVT MemVT = LN0->getMemoryVT();
6163     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6164       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6165                                        VT, LN0->getChain(), LN0->getBasePtr(),
6166                                        MemVT, LN0->getMemOperand());
6167       CombineTo(N, ExtLoad);
6168       CombineTo(N0.getNode(),
6169                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6170                             N0.getValueType(), ExtLoad),
6171                 ExtLoad.getValue(1));
6172       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6173     }
6174   }
6175
6176   if (N0.getOpcode() == ISD::SETCC) {
6177     // For vectors:
6178     // aext(setcc) -> vsetcc
6179     // aext(setcc) -> truncate(vsetcc)
6180     // aext(setcc) -> aext(vsetcc)
6181     // Only do this before legalize for now.
6182     if (VT.isVector() && !LegalOperations) {
6183       EVT N0VT = N0.getOperand(0).getValueType();
6184         // We know that the # elements of the results is the same as the
6185         // # elements of the compare (and the # elements of the compare result
6186         // for that matter).  Check to see that they are the same size.  If so,
6187         // we know that the element size of the sext'd result matches the
6188         // element size of the compare operands.
6189       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6190         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6191                              N0.getOperand(1),
6192                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6193       // If the desired elements are smaller or larger than the source
6194       // elements we can use a matching integer vector type and then
6195       // truncate/any extend
6196       else {
6197         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6198         SDValue VsetCC =
6199           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6200                         N0.getOperand(1),
6201                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6202         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6203       }
6204     }
6205
6206     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6207     SDValue SCC =
6208       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6209                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6210                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6211     if (SCC.getNode())
6212       return SCC;
6213   }
6214
6215   return SDValue();
6216 }
6217
6218 /// See if the specified operand can be simplified with the knowledge that only
6219 /// the bits specified by Mask are used.  If so, return the simpler operand,
6220 /// otherwise return a null SDValue.
6221 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6222   switch (V.getOpcode()) {
6223   default: break;
6224   case ISD::Constant: {
6225     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6226     assert(CV && "Const value should be ConstSDNode.");
6227     const APInt &CVal = CV->getAPIntValue();
6228     APInt NewVal = CVal & Mask;
6229     if (NewVal != CVal)
6230       return DAG.getConstant(NewVal, V.getValueType());
6231     break;
6232   }
6233   case ISD::OR:
6234   case ISD::XOR:
6235     // If the LHS or RHS don't contribute bits to the or, drop them.
6236     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6237       return V.getOperand(1);
6238     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6239       return V.getOperand(0);
6240     break;
6241   case ISD::SRL:
6242     // Only look at single-use SRLs.
6243     if (!V.getNode()->hasOneUse())
6244       break;
6245     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6246       // See if we can recursively simplify the LHS.
6247       unsigned Amt = RHSC->getZExtValue();
6248
6249       // Watch out for shift count overflow though.
6250       if (Amt >= Mask.getBitWidth()) break;
6251       APInt NewMask = Mask << Amt;
6252       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6253       if (SimplifyLHS.getNode())
6254         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6255                            SimplifyLHS, V.getOperand(1));
6256     }
6257   }
6258   return SDValue();
6259 }
6260
6261 /// If the result of a wider load is shifted to right of N  bits and then
6262 /// truncated to a narrower type and where N is a multiple of number of bits of
6263 /// the narrower type, transform it to a narrower load from address + N / num of
6264 /// bits of new type. If the result is to be extended, also fold the extension
6265 /// to form a extending load.
6266 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6267   unsigned Opc = N->getOpcode();
6268
6269   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6270   SDValue N0 = N->getOperand(0);
6271   EVT VT = N->getValueType(0);
6272   EVT ExtVT = VT;
6273
6274   // This transformation isn't valid for vector loads.
6275   if (VT.isVector())
6276     return SDValue();
6277
6278   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6279   // extended to VT.
6280   if (Opc == ISD::SIGN_EXTEND_INREG) {
6281     ExtType = ISD::SEXTLOAD;
6282     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6283   } else if (Opc == ISD::SRL) {
6284     // Another special-case: SRL is basically zero-extending a narrower value.
6285     ExtType = ISD::ZEXTLOAD;
6286     N0 = SDValue(N, 0);
6287     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6288     if (!N01) return SDValue();
6289     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6290                               VT.getSizeInBits() - N01->getZExtValue());
6291   }
6292   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6293     return SDValue();
6294
6295   unsigned EVTBits = ExtVT.getSizeInBits();
6296
6297   // Do not generate loads of non-round integer types since these can
6298   // be expensive (and would be wrong if the type is not byte sized).
6299   if (!ExtVT.isRound())
6300     return SDValue();
6301
6302   unsigned ShAmt = 0;
6303   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6304     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6305       ShAmt = N01->getZExtValue();
6306       // Is the shift amount a multiple of size of VT?
6307       if ((ShAmt & (EVTBits-1)) == 0) {
6308         N0 = N0.getOperand(0);
6309         // Is the load width a multiple of size of VT?
6310         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6311           return SDValue();
6312       }
6313
6314       // At this point, we must have a load or else we can't do the transform.
6315       if (!isa<LoadSDNode>(N0)) return SDValue();
6316
6317       // Because a SRL must be assumed to *need* to zero-extend the high bits
6318       // (as opposed to anyext the high bits), we can't combine the zextload
6319       // lowering of SRL and an sextload.
6320       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6321         return SDValue();
6322
6323       // If the shift amount is larger than the input type then we're not
6324       // accessing any of the loaded bytes.  If the load was a zextload/extload
6325       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6326       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6327         return SDValue();
6328     }
6329   }
6330
6331   // If the load is shifted left (and the result isn't shifted back right),
6332   // we can fold the truncate through the shift.
6333   unsigned ShLeftAmt = 0;
6334   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6335       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6336     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6337       ShLeftAmt = N01->getZExtValue();
6338       N0 = N0.getOperand(0);
6339     }
6340   }
6341
6342   // If we haven't found a load, we can't narrow it.  Don't transform one with
6343   // multiple uses, this would require adding a new load.
6344   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6345     return SDValue();
6346
6347   // Don't change the width of a volatile load.
6348   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6349   if (LN0->isVolatile())
6350     return SDValue();
6351
6352   // Verify that we are actually reducing a load width here.
6353   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6354     return SDValue();
6355
6356   // For the transform to be legal, the load must produce only two values
6357   // (the value loaded and the chain).  Don't transform a pre-increment
6358   // load, for example, which produces an extra value.  Otherwise the
6359   // transformation is not equivalent, and the downstream logic to replace
6360   // uses gets things wrong.
6361   if (LN0->getNumValues() > 2)
6362     return SDValue();
6363
6364   // If the load that we're shrinking is an extload and we're not just
6365   // discarding the extension we can't simply shrink the load. Bail.
6366   // TODO: It would be possible to merge the extensions in some cases.
6367   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6368       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6369     return SDValue();
6370
6371   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6372     return SDValue();
6373
6374   EVT PtrType = N0.getOperand(1).getValueType();
6375
6376   if (PtrType == MVT::Untyped || PtrType.isExtended())
6377     // It's not possible to generate a constant of extended or untyped type.
6378     return SDValue();
6379
6380   // For big endian targets, we need to adjust the offset to the pointer to
6381   // load the correct bytes.
6382   if (TLI.isBigEndian()) {
6383     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6384     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6385     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6386   }
6387
6388   uint64_t PtrOff = ShAmt / 8;
6389   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6390   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6391                                PtrType, LN0->getBasePtr(),
6392                                DAG.getConstant(PtrOff, PtrType));
6393   AddToWorklist(NewPtr.getNode());
6394
6395   SDValue Load;
6396   if (ExtType == ISD::NON_EXTLOAD)
6397     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6398                         LN0->getPointerInfo().getWithOffset(PtrOff),
6399                         LN0->isVolatile(), LN0->isNonTemporal(),
6400                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6401   else
6402     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6403                           LN0->getPointerInfo().getWithOffset(PtrOff),
6404                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6405                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6406
6407   // Replace the old load's chain with the new load's chain.
6408   WorklistRemover DeadNodes(*this);
6409   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6410
6411   // Shift the result left, if we've swallowed a left shift.
6412   SDValue Result = Load;
6413   if (ShLeftAmt != 0) {
6414     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6415     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6416       ShImmTy = VT;
6417     // If the shift amount is as large as the result size (but, presumably,
6418     // no larger than the source) then the useful bits of the result are
6419     // zero; we can't simply return the shortened shift, because the result
6420     // of that operation is undefined.
6421     if (ShLeftAmt >= VT.getSizeInBits())
6422       Result = DAG.getConstant(0, VT);
6423     else
6424       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6425                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6426   }
6427
6428   // Return the new loaded value.
6429   return Result;
6430 }
6431
6432 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6433   SDValue N0 = N->getOperand(0);
6434   SDValue N1 = N->getOperand(1);
6435   EVT VT = N->getValueType(0);
6436   EVT EVT = cast<VTSDNode>(N1)->getVT();
6437   unsigned VTBits = VT.getScalarType().getSizeInBits();
6438   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6439
6440   // fold (sext_in_reg c1) -> c1
6441   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6442     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6443
6444   // If the input is already sign extended, just drop the extension.
6445   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6446     return N0;
6447
6448   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6449   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6450       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6451     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6452                        N0.getOperand(0), N1);
6453
6454   // fold (sext_in_reg (sext x)) -> (sext x)
6455   // fold (sext_in_reg (aext x)) -> (sext x)
6456   // if x is small enough.
6457   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6458     SDValue N00 = N0.getOperand(0);
6459     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6460         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6461       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6462   }
6463
6464   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6465   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6466     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6467
6468   // fold operands of sext_in_reg based on knowledge that the top bits are not
6469   // demanded.
6470   if (SimplifyDemandedBits(SDValue(N, 0)))
6471     return SDValue(N, 0);
6472
6473   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6474   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6475   SDValue NarrowLoad = ReduceLoadWidth(N);
6476   if (NarrowLoad.getNode())
6477     return NarrowLoad;
6478
6479   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6480   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6481   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6482   if (N0.getOpcode() == ISD::SRL) {
6483     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6484       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6485         // We can turn this into an SRA iff the input to the SRL is already sign
6486         // extended enough.
6487         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6488         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6489           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6490                              N0.getOperand(0), N0.getOperand(1));
6491       }
6492   }
6493
6494   // fold (sext_inreg (extload x)) -> (sextload x)
6495   if (ISD::isEXTLoad(N0.getNode()) &&
6496       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6497       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6498       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6499        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6500     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6501     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6502                                      LN0->getChain(),
6503                                      LN0->getBasePtr(), EVT,
6504                                      LN0->getMemOperand());
6505     CombineTo(N, ExtLoad);
6506     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6507     AddToWorklist(ExtLoad.getNode());
6508     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6509   }
6510   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6511   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6512       N0.hasOneUse() &&
6513       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6514       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6515        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6516     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6517     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6518                                      LN0->getChain(),
6519                                      LN0->getBasePtr(), EVT,
6520                                      LN0->getMemOperand());
6521     CombineTo(N, ExtLoad);
6522     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6523     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6524   }
6525
6526   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6527   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6528     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6529                                        N0.getOperand(1), false);
6530     if (BSwap.getNode())
6531       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6532                          BSwap, N1);
6533   }
6534
6535   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6536   // into a build_vector.
6537   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6538     SmallVector<SDValue, 8> Elts;
6539     unsigned NumElts = N0->getNumOperands();
6540     unsigned ShAmt = VTBits - EVTBits;
6541
6542     for (unsigned i = 0; i != NumElts; ++i) {
6543       SDValue Op = N0->getOperand(i);
6544       if (Op->getOpcode() == ISD::UNDEF) {
6545         Elts.push_back(Op);
6546         continue;
6547       }
6548
6549       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6550       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6551       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6552                                      Op.getValueType()));
6553     }
6554
6555     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6556   }
6557
6558   return SDValue();
6559 }
6560
6561 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6562   SDValue N0 = N->getOperand(0);
6563   EVT VT = N->getValueType(0);
6564   bool isLE = TLI.isLittleEndian();
6565
6566   // noop truncate
6567   if (N0.getValueType() == N->getValueType(0))
6568     return N0;
6569   // fold (truncate c1) -> c1
6570   if (isConstantIntBuildVectorOrConstantInt(N0))
6571     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6572   // fold (truncate (truncate x)) -> (truncate x)
6573   if (N0.getOpcode() == ISD::TRUNCATE)
6574     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6575   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6576   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6577       N0.getOpcode() == ISD::SIGN_EXTEND ||
6578       N0.getOpcode() == ISD::ANY_EXTEND) {
6579     if (N0.getOperand(0).getValueType().bitsLT(VT))
6580       // if the source is smaller than the dest, we still need an extend
6581       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6582                          N0.getOperand(0));
6583     if (N0.getOperand(0).getValueType().bitsGT(VT))
6584       // if the source is larger than the dest, than we just need the truncate
6585       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6586     // if the source and dest are the same type, we can drop both the extend
6587     // and the truncate.
6588     return N0.getOperand(0);
6589   }
6590
6591   // Fold extract-and-trunc into a narrow extract. For example:
6592   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6593   //   i32 y = TRUNCATE(i64 x)
6594   //        -- becomes --
6595   //   v16i8 b = BITCAST (v2i64 val)
6596   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6597   //
6598   // Note: We only run this optimization after type legalization (which often
6599   // creates this pattern) and before operation legalization after which
6600   // we need to be more careful about the vector instructions that we generate.
6601   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6602       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6603
6604     EVT VecTy = N0.getOperand(0).getValueType();
6605     EVT ExTy = N0.getValueType();
6606     EVT TrTy = N->getValueType(0);
6607
6608     unsigned NumElem = VecTy.getVectorNumElements();
6609     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6610
6611     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6612     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6613
6614     SDValue EltNo = N0->getOperand(1);
6615     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6616       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6617       EVT IndexTy = TLI.getVectorIdxTy();
6618       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6619
6620       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6621                               NVT, N0.getOperand(0));
6622
6623       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6624                          SDLoc(N), TrTy, V,
6625                          DAG.getConstant(Index, IndexTy));
6626     }
6627   }
6628
6629   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6630   if (N0.getOpcode() == ISD::SELECT) {
6631     EVT SrcVT = N0.getValueType();
6632     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6633         TLI.isTruncateFree(SrcVT, VT)) {
6634       SDLoc SL(N0);
6635       SDValue Cond = N0.getOperand(0);
6636       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6637       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6638       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6639     }
6640   }
6641
6642   // Fold a series of buildvector, bitcast, and truncate if possible.
6643   // For example fold
6644   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6645   //   (2xi32 (buildvector x, y)).
6646   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6647       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6648       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6649       N0.getOperand(0).hasOneUse()) {
6650
6651     SDValue BuildVect = N0.getOperand(0);
6652     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6653     EVT TruncVecEltTy = VT.getVectorElementType();
6654
6655     // Check that the element types match.
6656     if (BuildVectEltTy == TruncVecEltTy) {
6657       // Now we only need to compute the offset of the truncated elements.
6658       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6659       unsigned TruncVecNumElts = VT.getVectorNumElements();
6660       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6661
6662       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6663              "Invalid number of elements");
6664
6665       SmallVector<SDValue, 8> Opnds;
6666       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6667         Opnds.push_back(BuildVect.getOperand(i));
6668
6669       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6670     }
6671   }
6672
6673   // See if we can simplify the input to this truncate through knowledge that
6674   // only the low bits are being used.
6675   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6676   // Currently we only perform this optimization on scalars because vectors
6677   // may have different active low bits.
6678   if (!VT.isVector()) {
6679     SDValue Shorter =
6680       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6681                                                VT.getSizeInBits()));
6682     if (Shorter.getNode())
6683       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6684   }
6685   // fold (truncate (load x)) -> (smaller load x)
6686   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6687   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6688     SDValue Reduced = ReduceLoadWidth(N);
6689     if (Reduced.getNode())
6690       return Reduced;
6691     // Handle the case where the load remains an extending load even
6692     // after truncation.
6693     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6694       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6695       if (!LN0->isVolatile() &&
6696           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6697         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6698                                          VT, LN0->getChain(), LN0->getBasePtr(),
6699                                          LN0->getMemoryVT(),
6700                                          LN0->getMemOperand());
6701         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6702         return NewLoad;
6703       }
6704     }
6705   }
6706   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6707   // where ... are all 'undef'.
6708   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6709     SmallVector<EVT, 8> VTs;
6710     SDValue V;
6711     unsigned Idx = 0;
6712     unsigned NumDefs = 0;
6713
6714     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6715       SDValue X = N0.getOperand(i);
6716       if (X.getOpcode() != ISD::UNDEF) {
6717         V = X;
6718         Idx = i;
6719         NumDefs++;
6720       }
6721       // Stop if more than one members are non-undef.
6722       if (NumDefs > 1)
6723         break;
6724       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6725                                      VT.getVectorElementType(),
6726                                      X.getValueType().getVectorNumElements()));
6727     }
6728
6729     if (NumDefs == 0)
6730       return DAG.getUNDEF(VT);
6731
6732     if (NumDefs == 1) {
6733       assert(V.getNode() && "The single defined operand is empty!");
6734       SmallVector<SDValue, 8> Opnds;
6735       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6736         if (i != Idx) {
6737           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6738           continue;
6739         }
6740         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6741         AddToWorklist(NV.getNode());
6742         Opnds.push_back(NV);
6743       }
6744       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6745     }
6746   }
6747
6748   // Simplify the operands using demanded-bits information.
6749   if (!VT.isVector() &&
6750       SimplifyDemandedBits(SDValue(N, 0)))
6751     return SDValue(N, 0);
6752
6753   return SDValue();
6754 }
6755
6756 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6757   SDValue Elt = N->getOperand(i);
6758   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6759     return Elt.getNode();
6760   return Elt.getOperand(Elt.getResNo()).getNode();
6761 }
6762
6763 /// build_pair (load, load) -> load
6764 /// if load locations are consecutive.
6765 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6766   assert(N->getOpcode() == ISD::BUILD_PAIR);
6767
6768   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6769   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6770   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6771       LD1->getAddressSpace() != LD2->getAddressSpace())
6772     return SDValue();
6773   EVT LD1VT = LD1->getValueType(0);
6774
6775   if (ISD::isNON_EXTLoad(LD2) &&
6776       LD2->hasOneUse() &&
6777       // If both are volatile this would reduce the number of volatile loads.
6778       // If one is volatile it might be ok, but play conservative and bail out.
6779       !LD1->isVolatile() &&
6780       !LD2->isVolatile() &&
6781       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6782     unsigned Align = LD1->getAlignment();
6783     unsigned NewAlign = TLI.getDataLayout()->
6784       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6785
6786     if (NewAlign <= Align &&
6787         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6788       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6789                          LD1->getBasePtr(), LD1->getPointerInfo(),
6790                          false, false, false, Align);
6791   }
6792
6793   return SDValue();
6794 }
6795
6796 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6797   SDValue N0 = N->getOperand(0);
6798   EVT VT = N->getValueType(0);
6799
6800   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6801   // Only do this before legalize, since afterward the target may be depending
6802   // on the bitconvert.
6803   // First check to see if this is all constant.
6804   if (!LegalTypes &&
6805       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6806       VT.isVector()) {
6807     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6808
6809     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6810     assert(!DestEltVT.isVector() &&
6811            "Element type of vector ValueType must not be vector!");
6812     if (isSimple)
6813       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6814   }
6815
6816   // If the input is a constant, let getNode fold it.
6817   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6818     // If we can't allow illegal operations, we need to check that this is just
6819     // a fp -> int or int -> conversion and that the resulting operation will
6820     // be legal.
6821     if (!LegalOperations ||
6822         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6823          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6824         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6825          TLI.isOperationLegal(ISD::Constant, VT)))
6826       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6827   }
6828
6829   // (conv (conv x, t1), t2) -> (conv x, t2)
6830   if (N0.getOpcode() == ISD::BITCAST)
6831     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6832                        N0.getOperand(0));
6833
6834   // fold (conv (load x)) -> (load (conv*)x)
6835   // If the resultant load doesn't need a higher alignment than the original!
6836   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6837       // Do not change the width of a volatile load.
6838       !cast<LoadSDNode>(N0)->isVolatile() &&
6839       // Do not remove the cast if the types differ in endian layout.
6840       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6841       TLI.hasBigEndianPartOrdering(VT) &&
6842       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6843       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6844     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6845     unsigned Align = TLI.getDataLayout()->
6846       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6847     unsigned OrigAlign = LN0->getAlignment();
6848
6849     if (Align <= OrigAlign) {
6850       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6851                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6852                                  LN0->isVolatile(), LN0->isNonTemporal(),
6853                                  LN0->isInvariant(), OrigAlign,
6854                                  LN0->getAAInfo());
6855       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6856       return Load;
6857     }
6858   }
6859
6860   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6861   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6862   // This often reduces constant pool loads.
6863   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6864        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6865       N0.getNode()->hasOneUse() && VT.isInteger() &&
6866       !VT.isVector() && !N0.getValueType().isVector()) {
6867     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6868                                   N0.getOperand(0));
6869     AddToWorklist(NewConv.getNode());
6870
6871     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6872     if (N0.getOpcode() == ISD::FNEG)
6873       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6874                          NewConv, DAG.getConstant(SignBit, VT));
6875     assert(N0.getOpcode() == ISD::FABS);
6876     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6877                        NewConv, DAG.getConstant(~SignBit, VT));
6878   }
6879
6880   // fold (bitconvert (fcopysign cst, x)) ->
6881   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6882   // Note that we don't handle (copysign x, cst) because this can always be
6883   // folded to an fneg or fabs.
6884   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6885       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6886       VT.isInteger() && !VT.isVector()) {
6887     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6888     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6889     if (isTypeLegal(IntXVT)) {
6890       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6891                               IntXVT, N0.getOperand(1));
6892       AddToWorklist(X.getNode());
6893
6894       // If X has a different width than the result/lhs, sext it or truncate it.
6895       unsigned VTWidth = VT.getSizeInBits();
6896       if (OrigXWidth < VTWidth) {
6897         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6898         AddToWorklist(X.getNode());
6899       } else if (OrigXWidth > VTWidth) {
6900         // To get the sign bit in the right place, we have to shift it right
6901         // before truncating.
6902         X = DAG.getNode(ISD::SRL, SDLoc(X),
6903                         X.getValueType(), X,
6904                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6905         AddToWorklist(X.getNode());
6906         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6907         AddToWorklist(X.getNode());
6908       }
6909
6910       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6911       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6912                       X, DAG.getConstant(SignBit, VT));
6913       AddToWorklist(X.getNode());
6914
6915       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6916                                 VT, N0.getOperand(0));
6917       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6918                         Cst, DAG.getConstant(~SignBit, VT));
6919       AddToWorklist(Cst.getNode());
6920
6921       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6922     }
6923   }
6924
6925   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6926   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6927     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6928     if (CombineLD.getNode())
6929       return CombineLD;
6930   }
6931
6932   return SDValue();
6933 }
6934
6935 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6936   EVT VT = N->getValueType(0);
6937   return CombineConsecutiveLoads(N, VT);
6938 }
6939
6940 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6941 /// operands. DstEltVT indicates the destination element value type.
6942 SDValue DAGCombiner::
6943 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6944   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6945
6946   // If this is already the right type, we're done.
6947   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6948
6949   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6950   unsigned DstBitSize = DstEltVT.getSizeInBits();
6951
6952   // If this is a conversion of N elements of one type to N elements of another
6953   // type, convert each element.  This handles FP<->INT cases.
6954   if (SrcBitSize == DstBitSize) {
6955     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6956                               BV->getValueType(0).getVectorNumElements());
6957
6958     // Due to the FP element handling below calling this routine recursively,
6959     // we can end up with a scalar-to-vector node here.
6960     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6961       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6962                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6963                                      DstEltVT, BV->getOperand(0)));
6964
6965     SmallVector<SDValue, 8> Ops;
6966     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6967       SDValue Op = BV->getOperand(i);
6968       // If the vector element type is not legal, the BUILD_VECTOR operands
6969       // are promoted and implicitly truncated.  Make that explicit here.
6970       if (Op.getValueType() != SrcEltVT)
6971         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6972       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6973                                 DstEltVT, Op));
6974       AddToWorklist(Ops.back().getNode());
6975     }
6976     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6977   }
6978
6979   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6980   // handle annoying details of growing/shrinking FP values, we convert them to
6981   // int first.
6982   if (SrcEltVT.isFloatingPoint()) {
6983     // Convert the input float vector to a int vector where the elements are the
6984     // same sizes.
6985     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6986     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6987     SrcEltVT = IntVT;
6988   }
6989
6990   // Now we know the input is an integer vector.  If the output is a FP type,
6991   // convert to integer first, then to FP of the right size.
6992   if (DstEltVT.isFloatingPoint()) {
6993     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6994     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6995
6996     // Next, convert to FP elements of the same size.
6997     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6998   }
6999
7000   // Okay, we know the src/dst types are both integers of differing types.
7001   // Handling growing first.
7002   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7003   if (SrcBitSize < DstBitSize) {
7004     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7005
7006     SmallVector<SDValue, 8> Ops;
7007     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7008          i += NumInputsPerOutput) {
7009       bool isLE = TLI.isLittleEndian();
7010       APInt NewBits = APInt(DstBitSize, 0);
7011       bool EltIsUndef = true;
7012       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7013         // Shift the previously computed bits over.
7014         NewBits <<= SrcBitSize;
7015         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7016         if (Op.getOpcode() == ISD::UNDEF) continue;
7017         EltIsUndef = false;
7018
7019         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7020                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7021       }
7022
7023       if (EltIsUndef)
7024         Ops.push_back(DAG.getUNDEF(DstEltVT));
7025       else
7026         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7027     }
7028
7029     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7030     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7031   }
7032
7033   // Finally, this must be the case where we are shrinking elements: each input
7034   // turns into multiple outputs.
7035   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7036   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7037                             NumOutputsPerInput*BV->getNumOperands());
7038   SmallVector<SDValue, 8> Ops;
7039
7040   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7041     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7042       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7043       continue;
7044     }
7045
7046     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7047                   getAPIntValue().zextOrTrunc(SrcBitSize);
7048
7049     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7050       APInt ThisVal = OpVal.trunc(DstBitSize);
7051       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7052       OpVal = OpVal.lshr(DstBitSize);
7053     }
7054
7055     // For big endian targets, swap the order of the pieces of each element.
7056     if (TLI.isBigEndian())
7057       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7058   }
7059
7060   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7061 }
7062
7063 /// Try to perform FMA combining on a given FADD node.
7064 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7065   SDValue N0 = N->getOperand(0);
7066   SDValue N1 = N->getOperand(1);
7067   EVT VT = N->getValueType(0);
7068   SDLoc SL(N);
7069
7070   const TargetOptions &Options = DAG.getTarget().Options;
7071   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7072                        Options.UnsafeFPMath);
7073
7074   // Floating-point multiply-add with intermediate rounding.
7075   bool HasFMAD = (LegalOperations &&
7076                   TLI.isOperationLegal(ISD::FMAD, VT));
7077
7078   // Floating-point multiply-add without intermediate rounding.
7079   bool HasFMA = ((!LegalOperations ||
7080                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7081                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7082                  UnsafeFPMath);
7083
7084   // No valid opcode, do not combine.
7085   if (!HasFMAD && !HasFMA)
7086     return SDValue();
7087
7088   // Always prefer FMAD to FMA for precision.
7089   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7090   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7091   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7092
7093   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7094   if (N0.getOpcode() == ISD::FMUL &&
7095       (Aggressive || N0->hasOneUse())) {
7096     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7097                        N0.getOperand(0), N0.getOperand(1), N1);
7098   }
7099
7100   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7101   // Note: Commutes FADD operands.
7102   if (N1.getOpcode() == ISD::FMUL &&
7103       (Aggressive || N1->hasOneUse())) {
7104     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7105                        N1.getOperand(0), N1.getOperand(1), N0);
7106   }
7107
7108   // Look through FP_EXTEND nodes to do more combining.
7109   if (UnsafeFPMath && LookThroughFPExt) {
7110     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7111     if (N0.getOpcode() == ISD::FP_EXTEND) {
7112       SDValue N00 = N0.getOperand(0);
7113       if (N00.getOpcode() == ISD::FMUL)
7114         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7115                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7116                                        N00.getOperand(0)),
7117                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7118                                        N00.getOperand(1)), N1);
7119     }
7120
7121     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7122     // Note: Commutes FADD operands.
7123     if (N1.getOpcode() == ISD::FP_EXTEND) {
7124       SDValue N10 = N1.getOperand(0);
7125       if (N10.getOpcode() == ISD::FMUL)
7126         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7127                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7128                                        N10.getOperand(0)),
7129                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7130                                        N10.getOperand(1)), N0);
7131     }
7132   }
7133
7134   // More folding opportunities when target permits.
7135   if (UnsafeFPMath && Aggressive) {
7136     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7137     if (N0.getOpcode() == PreferredFusedOpcode &&
7138         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7139       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7140                          N0.getOperand(0), N0.getOperand(1),
7141                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7142                                      N0.getOperand(2).getOperand(0),
7143                                      N0.getOperand(2).getOperand(1),
7144                                      N1));
7145     }
7146
7147     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7148     if (N1->getOpcode() == PreferredFusedOpcode &&
7149         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7150       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7151                          N1.getOperand(0), N1.getOperand(1),
7152                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7153                                      N1.getOperand(2).getOperand(0),
7154                                      N1.getOperand(2).getOperand(1),
7155                                      N0));
7156     }
7157
7158     if (LookThroughFPExt) {
7159       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7160       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7161       auto FoldFAddFMAFPExtFMul = [&] (
7162           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7163         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7164                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7165                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7166                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7167                                        Z));
7168       };
7169       if (N0.getOpcode() == PreferredFusedOpcode) {
7170         SDValue N02 = N0.getOperand(2);
7171         if (N02.getOpcode() == ISD::FP_EXTEND) {
7172           SDValue N020 = N02.getOperand(0);
7173           if (N020.getOpcode() == ISD::FMUL)
7174             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7175                                         N020.getOperand(0), N020.getOperand(1),
7176                                         N1);
7177         }
7178       }
7179
7180       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7181       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7182       // FIXME: This turns two single-precision and one double-precision
7183       // operation into two double-precision operations, which might not be
7184       // interesting for all targets, especially GPUs.
7185       auto FoldFAddFPExtFMAFMul = [&] (
7186           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7187         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7188                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7189                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7190                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7191                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7192                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7193                                        Z));
7194       };
7195       if (N0.getOpcode() == ISD::FP_EXTEND) {
7196         SDValue N00 = N0.getOperand(0);
7197         if (N00.getOpcode() == PreferredFusedOpcode) {
7198           SDValue N002 = N00.getOperand(2);
7199           if (N002.getOpcode() == ISD::FMUL)
7200             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7201                                         N002.getOperand(0), N002.getOperand(1),
7202                                         N1);
7203         }
7204       }
7205
7206       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7207       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7208       if (N1.getOpcode() == PreferredFusedOpcode) {
7209         SDValue N12 = N1.getOperand(2);
7210         if (N12.getOpcode() == ISD::FP_EXTEND) {
7211           SDValue N120 = N12.getOperand(0);
7212           if (N120.getOpcode() == ISD::FMUL)
7213             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7214                                         N120.getOperand(0), N120.getOperand(1),
7215                                         N0);
7216         }
7217       }
7218
7219       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7220       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7221       // FIXME: This turns two single-precision and one double-precision
7222       // operation into two double-precision operations, which might not be
7223       // interesting for all targets, especially GPUs.
7224       if (N1.getOpcode() == ISD::FP_EXTEND) {
7225         SDValue N10 = N1.getOperand(0);
7226         if (N10.getOpcode() == PreferredFusedOpcode) {
7227           SDValue N102 = N10.getOperand(2);
7228           if (N102.getOpcode() == ISD::FMUL)
7229             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7230                                         N102.getOperand(0), N102.getOperand(1),
7231                                         N0);
7232         }
7233       }
7234     }
7235   }
7236
7237   return SDValue();
7238 }
7239
7240 /// Try to perform FMA combining on a given FSUB node.
7241 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7242   SDValue N0 = N->getOperand(0);
7243   SDValue N1 = N->getOperand(1);
7244   EVT VT = N->getValueType(0);
7245   SDLoc SL(N);
7246
7247   const TargetOptions &Options = DAG.getTarget().Options;
7248   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7249                        Options.UnsafeFPMath);
7250
7251   // Floating-point multiply-add with intermediate rounding.
7252   bool HasFMAD = (LegalOperations &&
7253                   TLI.isOperationLegal(ISD::FMAD, VT));
7254
7255   // Floating-point multiply-add without intermediate rounding.
7256   bool HasFMA = ((!LegalOperations ||
7257                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7258                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7259                  UnsafeFPMath);
7260
7261   // No valid opcode, do not combine.
7262   if (!HasFMAD && !HasFMA)
7263     return SDValue();
7264
7265   // Always prefer FMAD to FMA for precision.
7266   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7267   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7268   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7269
7270   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7271   if (N0.getOpcode() == ISD::FMUL &&
7272       (Aggressive || N0->hasOneUse())) {
7273     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7274                        N0.getOperand(0), N0.getOperand(1),
7275                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7276   }
7277
7278   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7279   // Note: Commutes FSUB operands.
7280   if (N1.getOpcode() == ISD::FMUL &&
7281       (Aggressive || N1->hasOneUse()))
7282     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7283                        DAG.getNode(ISD::FNEG, SL, VT,
7284                                    N1.getOperand(0)),
7285                        N1.getOperand(1), N0);
7286
7287   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7288   if (N0.getOpcode() == ISD::FNEG &&
7289       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7290       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7291     SDValue N00 = N0.getOperand(0).getOperand(0);
7292     SDValue N01 = N0.getOperand(0).getOperand(1);
7293     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7294                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7295                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7296   }
7297
7298   // Look through FP_EXTEND nodes to do more combining.
7299   if (UnsafeFPMath && LookThroughFPExt) {
7300     // fold (fsub (fpext (fmul x, y)), z)
7301     //   -> (fma (fpext x), (fpext y), (fneg z))
7302     if (N0.getOpcode() == ISD::FP_EXTEND) {
7303       SDValue N00 = N0.getOperand(0);
7304       if (N00.getOpcode() == ISD::FMUL)
7305         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7306                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7307                                        N00.getOperand(0)),
7308                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7309                                        N00.getOperand(1)),
7310                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7311     }
7312
7313     // fold (fsub x, (fpext (fmul y, z)))
7314     //   -> (fma (fneg (fpext y)), (fpext z), x)
7315     // Note: Commutes FSUB operands.
7316     if (N1.getOpcode() == ISD::FP_EXTEND) {
7317       SDValue N10 = N1.getOperand(0);
7318       if (N10.getOpcode() == ISD::FMUL)
7319         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7320                            DAG.getNode(ISD::FNEG, SL, VT,
7321                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7322                                                    N10.getOperand(0))),
7323                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7324                                        N10.getOperand(1)),
7325                            N0);
7326     }
7327
7328     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7329     //   -> (fneg (fma (fpext x), (fpext y), z))
7330     // Note: This could be removed with appropriate canonicalization of the
7331     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7332     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7333     // from implementing the canonicalization in visitFSUB.
7334     if (N0.getOpcode() == ISD::FP_EXTEND) {
7335       SDValue N00 = N0.getOperand(0);
7336       if (N00.getOpcode() == ISD::FNEG) {
7337         SDValue N000 = N00.getOperand(0);
7338         if (N000.getOpcode() == ISD::FMUL) {
7339           return DAG.getNode(ISD::FNEG, SL, VT,
7340                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7341                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7342                                                      N000.getOperand(0)),
7343                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7344                                                      N000.getOperand(1)),
7345                                          N1));
7346         }
7347       }
7348     }
7349
7350     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7351     //   -> (fneg (fma (fpext x)), (fpext y), z)
7352     // Note: This could be removed with appropriate canonicalization of the
7353     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7354     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7355     // from implementing the canonicalization in visitFSUB.
7356     if (N0.getOpcode() == ISD::FNEG) {
7357       SDValue N00 = N0.getOperand(0);
7358       if (N00.getOpcode() == ISD::FP_EXTEND) {
7359         SDValue N000 = N00.getOperand(0);
7360         if (N000.getOpcode() == ISD::FMUL) {
7361           return DAG.getNode(ISD::FNEG, SL, VT,
7362                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7363                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7364                                                      N000.getOperand(0)),
7365                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7366                                                      N000.getOperand(1)),
7367                                          N1));
7368         }
7369       }
7370     }
7371
7372   }
7373
7374   // More folding opportunities when target permits.
7375   if (UnsafeFPMath && Aggressive) {
7376     // fold (fsub (fma x, y, (fmul u, v)), z)
7377     //   -> (fma x, y (fma u, v, (fneg z)))
7378     if (N0.getOpcode() == PreferredFusedOpcode &&
7379         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7380       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7381                          N0.getOperand(0), N0.getOperand(1),
7382                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7383                                      N0.getOperand(2).getOperand(0),
7384                                      N0.getOperand(2).getOperand(1),
7385                                      DAG.getNode(ISD::FNEG, SL, VT,
7386                                                  N1)));
7387     }
7388
7389     // fold (fsub x, (fma y, z, (fmul u, v)))
7390     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7391     if (N1.getOpcode() == PreferredFusedOpcode &&
7392         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7393       SDValue N20 = N1.getOperand(2).getOperand(0);
7394       SDValue N21 = N1.getOperand(2).getOperand(1);
7395       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7396                          DAG.getNode(ISD::FNEG, SL, VT,
7397                                      N1.getOperand(0)),
7398                          N1.getOperand(1),
7399                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7400                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7401                                      N21, N0));
7402     }
7403
7404     if (LookThroughFPExt) {
7405       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7406       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7407       if (N0.getOpcode() == PreferredFusedOpcode) {
7408         SDValue N02 = N0.getOperand(2);
7409         if (N02.getOpcode() == ISD::FP_EXTEND) {
7410           SDValue N020 = N02.getOperand(0);
7411           if (N020.getOpcode() == ISD::FMUL)
7412             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7413                                N0.getOperand(0), N0.getOperand(1),
7414                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7415                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7416                                                        N020.getOperand(0)),
7417                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7418                                                        N020.getOperand(1)),
7419                                            DAG.getNode(ISD::FNEG, SL, VT,
7420                                                        N1)));
7421         }
7422       }
7423
7424       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7425       //   -> (fma (fpext x), (fpext y),
7426       //           (fma (fpext u), (fpext v), (fneg z)))
7427       // FIXME: This turns two single-precision and one double-precision
7428       // operation into two double-precision operations, which might not be
7429       // interesting for all targets, especially GPUs.
7430       if (N0.getOpcode() == ISD::FP_EXTEND) {
7431         SDValue N00 = N0.getOperand(0);
7432         if (N00.getOpcode() == PreferredFusedOpcode) {
7433           SDValue N002 = N00.getOperand(2);
7434           if (N002.getOpcode() == ISD::FMUL)
7435             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7436                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7437                                            N00.getOperand(0)),
7438                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7439                                            N00.getOperand(1)),
7440                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7441                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7442                                                        N002.getOperand(0)),
7443                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7444                                                        N002.getOperand(1)),
7445                                            DAG.getNode(ISD::FNEG, SL, VT,
7446                                                        N1)));
7447         }
7448       }
7449
7450       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7451       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7452       if (N1.getOpcode() == PreferredFusedOpcode &&
7453         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7454         SDValue N120 = N1.getOperand(2).getOperand(0);
7455         if (N120.getOpcode() == ISD::FMUL) {
7456           SDValue N1200 = N120.getOperand(0);
7457           SDValue N1201 = N120.getOperand(1);
7458           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7459                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7460                              N1.getOperand(1),
7461                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7462                                          DAG.getNode(ISD::FNEG, SL, VT,
7463                                              DAG.getNode(ISD::FP_EXTEND, SL,
7464                                                          VT, N1200)),
7465                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7466                                                      N1201),
7467                                          N0));
7468         }
7469       }
7470
7471       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7472       //   -> (fma (fneg (fpext y)), (fpext z),
7473       //           (fma (fneg (fpext u)), (fpext v), x))
7474       // FIXME: This turns two single-precision and one double-precision
7475       // operation into two double-precision operations, which might not be
7476       // interesting for all targets, especially GPUs.
7477       if (N1.getOpcode() == ISD::FP_EXTEND &&
7478         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7479         SDValue N100 = N1.getOperand(0).getOperand(0);
7480         SDValue N101 = N1.getOperand(0).getOperand(1);
7481         SDValue N102 = N1.getOperand(0).getOperand(2);
7482         if (N102.getOpcode() == ISD::FMUL) {
7483           SDValue N1020 = N102.getOperand(0);
7484           SDValue N1021 = N102.getOperand(1);
7485           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7486                              DAG.getNode(ISD::FNEG, SL, VT,
7487                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7488                                                      N100)),
7489                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7490                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7491                                          DAG.getNode(ISD::FNEG, SL, VT,
7492                                              DAG.getNode(ISD::FP_EXTEND, SL,
7493                                                          VT, N1020)),
7494                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7495                                                      N1021),
7496                                          N0));
7497         }
7498       }
7499     }
7500   }
7501
7502   return SDValue();
7503 }
7504
7505 SDValue DAGCombiner::visitFADD(SDNode *N) {
7506   SDValue N0 = N->getOperand(0);
7507   SDValue N1 = N->getOperand(1);
7508   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7509   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7510   EVT VT = N->getValueType(0);
7511   const TargetOptions &Options = DAG.getTarget().Options;
7512
7513   // fold vector ops
7514   if (VT.isVector())
7515     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7516       return FoldedVOp;
7517
7518   // fold (fadd c1, c2) -> c1 + c2
7519   if (N0CFP && N1CFP)
7520     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7521
7522   // canonicalize constant to RHS
7523   if (N0CFP && !N1CFP)
7524     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7525
7526   // fold (fadd A, (fneg B)) -> (fsub A, B)
7527   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7528       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7529     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7530                        GetNegatedExpression(N1, DAG, LegalOperations));
7531
7532   // fold (fadd (fneg A), B) -> (fsub B, A)
7533   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7534       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7535     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7536                        GetNegatedExpression(N0, DAG, LegalOperations));
7537
7538   // If 'unsafe math' is enabled, fold lots of things.
7539   if (Options.UnsafeFPMath) {
7540     // No FP constant should be created after legalization as Instruction
7541     // Selection pass has a hard time dealing with FP constants.
7542     bool AllowNewConst = (Level < AfterLegalizeDAG);
7543
7544     // fold (fadd A, 0) -> A
7545     if (N1CFP && N1CFP->getValueAPF().isZero())
7546       return N0;
7547
7548     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7549     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7550         isa<ConstantFPSDNode>(N0.getOperand(1)))
7551       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7552                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7553                                      N0.getOperand(1), N1));
7554
7555     // If allowed, fold (fadd (fneg x), x) -> 0.0
7556     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7557       return DAG.getConstantFP(0.0, VT);
7558
7559     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7560     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7561       return DAG.getConstantFP(0.0, VT);
7562
7563     // We can fold chains of FADD's of the same value into multiplications.
7564     // This transform is not safe in general because we are reducing the number
7565     // of rounding steps.
7566     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7567       if (N0.getOpcode() == ISD::FMUL) {
7568         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7569         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7570
7571         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7572         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7573           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7574                                        SDValue(CFP01, 0),
7575                                        DAG.getConstantFP(1.0, VT));
7576           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7577         }
7578
7579         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7580         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7581             N1.getOperand(0) == N1.getOperand(1) &&
7582             N0.getOperand(0) == N1.getOperand(0)) {
7583           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7584                                        SDValue(CFP01, 0),
7585                                        DAG.getConstantFP(2.0, VT));
7586           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7587                              N0.getOperand(0), NewCFP);
7588         }
7589       }
7590
7591       if (N1.getOpcode() == ISD::FMUL) {
7592         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7593         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7594
7595         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7596         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7597           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7598                                        SDValue(CFP11, 0),
7599                                        DAG.getConstantFP(1.0, VT));
7600           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7601         }
7602
7603         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7604         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7605             N0.getOperand(0) == N0.getOperand(1) &&
7606             N1.getOperand(0) == N0.getOperand(0)) {
7607           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7608                                        SDValue(CFP11, 0),
7609                                        DAG.getConstantFP(2.0, VT));
7610           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7611         }
7612       }
7613
7614       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7615         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7616         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7617         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7618             (N0.getOperand(0) == N1))
7619           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7620                              N1, DAG.getConstantFP(3.0, VT));
7621       }
7622
7623       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7624         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7625         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7626         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7627             N1.getOperand(0) == N0)
7628           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7629                              N0, DAG.getConstantFP(3.0, VT));
7630       }
7631
7632       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7633       if (AllowNewConst &&
7634           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7635           N0.getOperand(0) == N0.getOperand(1) &&
7636           N1.getOperand(0) == N1.getOperand(1) &&
7637           N0.getOperand(0) == N1.getOperand(0))
7638         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7639                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7640     }
7641   } // enable-unsafe-fp-math
7642
7643   // FADD -> FMA combines:
7644   SDValue Fused = visitFADDForFMACombine(N);
7645   if (Fused) {
7646     AddToWorklist(Fused.getNode());
7647     return Fused;
7648   }
7649
7650   return SDValue();
7651 }
7652
7653 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7654   SDValue N0 = N->getOperand(0);
7655   SDValue N1 = N->getOperand(1);
7656   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7657   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7658   EVT VT = N->getValueType(0);
7659   SDLoc dl(N);
7660   const TargetOptions &Options = DAG.getTarget().Options;
7661
7662   // fold vector ops
7663   if (VT.isVector())
7664     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7665       return FoldedVOp;
7666
7667   // fold (fsub c1, c2) -> c1-c2
7668   if (N0CFP && N1CFP)
7669     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7670
7671   // fold (fsub A, (fneg B)) -> (fadd A, B)
7672   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7673     return DAG.getNode(ISD::FADD, dl, VT, N0,
7674                        GetNegatedExpression(N1, DAG, LegalOperations));
7675
7676   // If 'unsafe math' is enabled, fold lots of things.
7677   if (Options.UnsafeFPMath) {
7678     // (fsub A, 0) -> A
7679     if (N1CFP && N1CFP->getValueAPF().isZero())
7680       return N0;
7681
7682     // (fsub 0, B) -> -B
7683     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7684       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7685         return GetNegatedExpression(N1, DAG, LegalOperations);
7686       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7687         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7688     }
7689
7690     // (fsub x, x) -> 0.0
7691     if (N0 == N1)
7692       return DAG.getConstantFP(0.0f, VT);
7693
7694     // (fsub x, (fadd x, y)) -> (fneg y)
7695     // (fsub x, (fadd y, x)) -> (fneg y)
7696     if (N1.getOpcode() == ISD::FADD) {
7697       SDValue N10 = N1->getOperand(0);
7698       SDValue N11 = N1->getOperand(1);
7699
7700       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7701         return GetNegatedExpression(N11, DAG, LegalOperations);
7702
7703       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7704         return GetNegatedExpression(N10, DAG, LegalOperations);
7705     }
7706   }
7707
7708   // FSUB -> FMA combines:
7709   SDValue Fused = visitFSUBForFMACombine(N);
7710   if (Fused) {
7711     AddToWorklist(Fused.getNode());
7712     return Fused;
7713   }
7714
7715   return SDValue();
7716 }
7717
7718 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7719   SDValue N0 = N->getOperand(0);
7720   SDValue N1 = N->getOperand(1);
7721   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7722   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7723   EVT VT = N->getValueType(0);
7724   const TargetOptions &Options = DAG.getTarget().Options;
7725
7726   // fold vector ops
7727   if (VT.isVector()) {
7728     // This just handles C1 * C2 for vectors. Other vector folds are below.
7729     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7730       return FoldedVOp;
7731   }
7732
7733   // fold (fmul c1, c2) -> c1*c2
7734   if (N0CFP && N1CFP)
7735     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7736
7737   // canonicalize constant to RHS
7738   if (isConstantFPBuildVectorOrConstantFP(N0) &&
7739      !isConstantFPBuildVectorOrConstantFP(N1))
7740     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7741
7742   // fold (fmul A, 1.0) -> A
7743   if (N1CFP && N1CFP->isExactlyValue(1.0))
7744     return N0;
7745
7746   if (Options.UnsafeFPMath) {
7747     // fold (fmul A, 0) -> 0
7748     if (N1CFP && N1CFP->getValueAPF().isZero())
7749       return N1;
7750
7751     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7752     if (N0.getOpcode() == ISD::FMUL) {
7753       // Fold scalars or any vector constants (not just splats).
7754       // This fold is done in general by InstCombine, but extra fmul insts
7755       // may have been generated during lowering.
7756       SDValue N00 = N0.getOperand(0);
7757       SDValue N01 = N0.getOperand(1);
7758       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7759       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7760       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7761       
7762       // Check 1: Make sure that the first operand of the inner multiply is NOT
7763       // a constant. Otherwise, we may induce infinite looping.
7764       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7765         // Check 2: Make sure that the second operand of the inner multiply and
7766         // the second operand of the outer multiply are constants.
7767         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7768             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7769           SDLoc SL(N);
7770           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7771           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7772         }
7773       }
7774     }
7775
7776     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7777     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7778     // during an early run of DAGCombiner can prevent folding with fmuls
7779     // inserted during lowering.
7780     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7781       SDLoc SL(N);
7782       const SDValue Two = DAG.getConstantFP(2.0, VT);
7783       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7784       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7785     }
7786   }
7787
7788   // fold (fmul X, 2.0) -> (fadd X, X)
7789   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7790     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7791
7792   // fold (fmul X, -1.0) -> (fneg X)
7793   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7794     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7795       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7796
7797   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7798   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7799     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7800       // Both can be negated for free, check to see if at least one is cheaper
7801       // negated.
7802       if (LHSNeg == 2 || RHSNeg == 2)
7803         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7804                            GetNegatedExpression(N0, DAG, LegalOperations),
7805                            GetNegatedExpression(N1, DAG, LegalOperations));
7806     }
7807   }
7808
7809   return SDValue();
7810 }
7811
7812 SDValue DAGCombiner::visitFMA(SDNode *N) {
7813   SDValue N0 = N->getOperand(0);
7814   SDValue N1 = N->getOperand(1);
7815   SDValue N2 = N->getOperand(2);
7816   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7817   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7818   EVT VT = N->getValueType(0);
7819   SDLoc dl(N);
7820   const TargetOptions &Options = DAG.getTarget().Options;
7821
7822   // Constant fold FMA.
7823   if (isa<ConstantFPSDNode>(N0) &&
7824       isa<ConstantFPSDNode>(N1) &&
7825       isa<ConstantFPSDNode>(N2)) {
7826     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7827   }
7828
7829   if (Options.UnsafeFPMath) {
7830     if (N0CFP && N0CFP->isZero())
7831       return N2;
7832     if (N1CFP && N1CFP->isZero())
7833       return N2;
7834   }
7835   if (N0CFP && N0CFP->isExactlyValue(1.0))
7836     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7837   if (N1CFP && N1CFP->isExactlyValue(1.0))
7838     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7839
7840   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7841   if (N0CFP && !N1CFP)
7842     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7843
7844   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7845   if (Options.UnsafeFPMath && N1CFP &&
7846       N2.getOpcode() == ISD::FMUL &&
7847       N0 == N2.getOperand(0) &&
7848       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7849     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7850                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7851   }
7852
7853
7854   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7855   if (Options.UnsafeFPMath &&
7856       N0.getOpcode() == ISD::FMUL && N1CFP &&
7857       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7858     return DAG.getNode(ISD::FMA, dl, VT,
7859                        N0.getOperand(0),
7860                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7861                        N2);
7862   }
7863
7864   // (fma x, 1, y) -> (fadd x, y)
7865   // (fma x, -1, y) -> (fadd (fneg x), y)
7866   if (N1CFP) {
7867     if (N1CFP->isExactlyValue(1.0))
7868       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7869
7870     if (N1CFP->isExactlyValue(-1.0) &&
7871         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7872       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7873       AddToWorklist(RHSNeg.getNode());
7874       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7875     }
7876   }
7877
7878   // (fma x, c, x) -> (fmul x, (c+1))
7879   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7880     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7881                        DAG.getNode(ISD::FADD, dl, VT,
7882                                    N1, DAG.getConstantFP(1.0, VT)));
7883
7884   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7885   if (Options.UnsafeFPMath && N1CFP &&
7886       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7887     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7888                        DAG.getNode(ISD::FADD, dl, VT,
7889                                    N1, DAG.getConstantFP(-1.0, VT)));
7890
7891
7892   return SDValue();
7893 }
7894
7895 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7896   SDValue N0 = N->getOperand(0);
7897   SDValue N1 = N->getOperand(1);
7898   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7899   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7900   EVT VT = N->getValueType(0);
7901   SDLoc DL(N);
7902   const TargetOptions &Options = DAG.getTarget().Options;
7903
7904   // fold vector ops
7905   if (VT.isVector())
7906     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7907       return FoldedVOp;
7908
7909   // fold (fdiv c1, c2) -> c1/c2
7910   if (N0CFP && N1CFP)
7911     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7912
7913   if (Options.UnsafeFPMath) {
7914     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7915     if (N1CFP) {
7916       // Compute the reciprocal 1.0 / c2.
7917       APFloat N1APF = N1CFP->getValueAPF();
7918       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7919       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7920       // Only do the transform if the reciprocal is a legal fp immediate that
7921       // isn't too nasty (eg NaN, denormal, ...).
7922       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7923           (!LegalOperations ||
7924            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7925            // backend)... we should handle this gracefully after Legalize.
7926            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7927            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7928            TLI.isFPImmLegal(Recip, VT)))
7929         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7930                            DAG.getConstantFP(Recip, VT));
7931     }
7932
7933     // If this FDIV is part of a reciprocal square root, it may be folded
7934     // into a target-specific square root estimate instruction.
7935     if (N1.getOpcode() == ISD::FSQRT) {
7936       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7937         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7938       }
7939     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7940                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7941       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7942         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7943         AddToWorklist(RV.getNode());
7944         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7945       }
7946     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7947                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7948       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7949         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7950         AddToWorklist(RV.getNode());
7951         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7952       }
7953     } else if (N1.getOpcode() == ISD::FMUL) {
7954       // Look through an FMUL. Even though this won't remove the FDIV directly,
7955       // it's still worthwhile to get rid of the FSQRT if possible.
7956       SDValue SqrtOp;
7957       SDValue OtherOp;
7958       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7959         SqrtOp = N1.getOperand(0);
7960         OtherOp = N1.getOperand(1);
7961       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7962         SqrtOp = N1.getOperand(1);
7963         OtherOp = N1.getOperand(0);
7964       }
7965       if (SqrtOp.getNode()) {
7966         // We found a FSQRT, so try to make this fold:
7967         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7968         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7969           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7970           AddToWorklist(RV.getNode());
7971           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7972         }
7973       }
7974     }
7975
7976     // Fold into a reciprocal estimate and multiply instead of a real divide.
7977     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7978       AddToWorklist(RV.getNode());
7979       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7980     }
7981   }
7982
7983   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7984   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7985     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7986       // Both can be negated for free, check to see if at least one is cheaper
7987       // negated.
7988       if (LHSNeg == 2 || RHSNeg == 2)
7989         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7990                            GetNegatedExpression(N0, DAG, LegalOperations),
7991                            GetNegatedExpression(N1, DAG, LegalOperations));
7992     }
7993   }
7994
7995   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7996   // reciprocal.
7997   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7998   // Notice that this is not always beneficial. One reason is different target
7999   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8000   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8001   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8002   if (Options.UnsafeFPMath) {
8003     // Skip if current node is a reciprocal.
8004     if (N0CFP && N0CFP->isExactlyValue(1.0))
8005       return SDValue();
8006
8007     SmallVector<SDNode *, 4> Users;
8008     // Find all FDIV users of the same divisor.
8009     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8010                               UE = N1.getNode()->use_end();
8011          UI != UE; ++UI) {
8012       SDNode *User = UI.getUse().getUser();
8013       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8014         Users.push_back(User);
8015     }
8016
8017     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8018       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
8019       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
8020
8021       // Dividend / Divisor -> Dividend * Reciprocal
8022       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8023         if ((*I)->getOperand(0) != FPOne) {
8024           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8025                                         (*I)->getOperand(0), Reciprocal);
8026           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8027         }
8028       }
8029       return SDValue();
8030     }
8031   }
8032
8033   return SDValue();
8034 }
8035
8036 SDValue DAGCombiner::visitFREM(SDNode *N) {
8037   SDValue N0 = N->getOperand(0);
8038   SDValue N1 = N->getOperand(1);
8039   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8040   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8041   EVT VT = N->getValueType(0);
8042
8043   // fold (frem c1, c2) -> fmod(c1,c2)
8044   if (N0CFP && N1CFP)
8045     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8046
8047   return SDValue();
8048 }
8049
8050 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8051   if (DAG.getTarget().Options.UnsafeFPMath &&
8052       !TLI.isFsqrtCheap()) {
8053     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8054     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8055       EVT VT = RV.getValueType();
8056       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
8057       AddToWorklist(RV.getNode());
8058
8059       // Unfortunately, RV is now NaN if the input was exactly 0.
8060       // Select out this case and force the answer to 0.
8061       SDValue Zero = DAG.getConstantFP(0.0, VT);
8062       SDValue ZeroCmp =
8063         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
8064                      N->getOperand(0), Zero, ISD::SETEQ);
8065       AddToWorklist(ZeroCmp.getNode());
8066       AddToWorklist(RV.getNode());
8067
8068       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8069                        SDLoc(N), VT, ZeroCmp, Zero, RV);
8070       return RV;
8071     }
8072   }
8073   return SDValue();
8074 }
8075
8076 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8077   SDValue N0 = N->getOperand(0);
8078   SDValue N1 = N->getOperand(1);
8079   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8080   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8081   EVT VT = N->getValueType(0);
8082
8083   if (N0CFP && N1CFP)  // Constant fold
8084     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8085
8086   if (N1CFP) {
8087     const APFloat& V = N1CFP->getValueAPF();
8088     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8089     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8090     if (!V.isNegative()) {
8091       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8092         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8093     } else {
8094       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8095         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8096                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8097     }
8098   }
8099
8100   // copysign(fabs(x), y) -> copysign(x, y)
8101   // copysign(fneg(x), y) -> copysign(x, y)
8102   // copysign(copysign(x,z), y) -> copysign(x, y)
8103   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8104       N0.getOpcode() == ISD::FCOPYSIGN)
8105     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8106                        N0.getOperand(0), N1);
8107
8108   // copysign(x, abs(y)) -> abs(x)
8109   if (N1.getOpcode() == ISD::FABS)
8110     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8111
8112   // copysign(x, copysign(y,z)) -> copysign(x, z)
8113   if (N1.getOpcode() == ISD::FCOPYSIGN)
8114     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8115                        N0, N1.getOperand(1));
8116
8117   // copysign(x, fp_extend(y)) -> copysign(x, y)
8118   // copysign(x, fp_round(y)) -> copysign(x, y)
8119   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8120     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8121                        N0, N1.getOperand(0));
8122
8123   return SDValue();
8124 }
8125
8126 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8127   SDValue N0 = N->getOperand(0);
8128   EVT VT = N->getValueType(0);
8129   EVT OpVT = N0.getValueType();
8130
8131   // fold (sint_to_fp c1) -> c1fp
8132   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8133       // ...but only if the target supports immediate floating-point values
8134       (!LegalOperations ||
8135        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8136     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8137
8138   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8139   // but UINT_TO_FP is legal on this target, try to convert.
8140   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8141       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8142     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8143     if (DAG.SignBitIsZero(N0))
8144       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8145   }
8146
8147   // The next optimizations are desirable only if SELECT_CC can be lowered.
8148   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8149     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8150     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8151         !VT.isVector() &&
8152         (!LegalOperations ||
8153          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8154       SDValue Ops[] =
8155         { N0.getOperand(0), N0.getOperand(1),
8156           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
8157           N0.getOperand(2) };
8158       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8159     }
8160
8161     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8162     //      (select_cc x, y, 1.0, 0.0,, cc)
8163     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8164         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8165         (!LegalOperations ||
8166          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8167       SDValue Ops[] =
8168         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8169           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
8170           N0.getOperand(0).getOperand(2) };
8171       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8172     }
8173   }
8174
8175   return SDValue();
8176 }
8177
8178 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8179   SDValue N0 = N->getOperand(0);
8180   EVT VT = N->getValueType(0);
8181   EVT OpVT = N0.getValueType();
8182
8183   // fold (uint_to_fp c1) -> c1fp
8184   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8185       // ...but only if the target supports immediate floating-point values
8186       (!LegalOperations ||
8187        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8188     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8189
8190   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8191   // but SINT_TO_FP is legal on this target, try to convert.
8192   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8193       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8194     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8195     if (DAG.SignBitIsZero(N0))
8196       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8197   }
8198
8199   // The next optimizations are desirable only if SELECT_CC can be lowered.
8200   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8201     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8202
8203     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8204         (!LegalOperations ||
8205          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8206       SDValue Ops[] =
8207         { N0.getOperand(0), N0.getOperand(1),
8208           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
8209           N0.getOperand(2) };
8210       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8211     }
8212   }
8213
8214   return SDValue();
8215 }
8216
8217 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8218 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8219   SDValue N0 = N->getOperand(0);
8220   EVT VT = N->getValueType(0);
8221
8222   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8223     return SDValue();
8224
8225   SDValue Src = N0.getOperand(0);
8226   EVT SrcVT = Src.getValueType();
8227   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8228   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8229
8230   // We can safely assume the conversion won't overflow the output range,
8231   // because (for example) (uint8_t)18293.f is undefined behavior.
8232
8233   // Since we can assume the conversion won't overflow, our decision as to
8234   // whether the input will fit in the float should depend on the minimum
8235   // of the input range and output range.
8236
8237   // This means this is also safe for a signed input and unsigned output, since
8238   // a negative input would lead to undefined behavior.
8239   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8240   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8241   unsigned ActualSize = std::min(InputSize, OutputSize);
8242   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8243
8244   // We can only fold away the float conversion if the input range can be
8245   // represented exactly in the float range.
8246   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8247     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8248       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8249                                                        : ISD::ZERO_EXTEND;
8250       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8251     }
8252     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8253       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8254     if (SrcVT == VT)
8255       return Src;
8256     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8257   }
8258   return SDValue();
8259 }
8260
8261 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8262   SDValue N0 = N->getOperand(0);
8263   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8264   EVT VT = N->getValueType(0);
8265
8266   // fold (fp_to_sint c1fp) -> c1
8267   if (N0CFP)
8268     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8269
8270   return FoldIntToFPToInt(N, DAG);
8271 }
8272
8273 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8274   SDValue N0 = N->getOperand(0);
8275   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8276   EVT VT = N->getValueType(0);
8277
8278   // fold (fp_to_uint c1fp) -> c1
8279   if (N0CFP)
8280     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8281
8282   return FoldIntToFPToInt(N, DAG);
8283 }
8284
8285 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8286   SDValue N0 = N->getOperand(0);
8287   SDValue N1 = N->getOperand(1);
8288   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8289   EVT VT = N->getValueType(0);
8290
8291   // fold (fp_round c1fp) -> c1fp
8292   if (N0CFP)
8293     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8294
8295   // fold (fp_round (fp_extend x)) -> x
8296   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8297     return N0.getOperand(0);
8298
8299   // fold (fp_round (fp_round x)) -> (fp_round x)
8300   if (N0.getOpcode() == ISD::FP_ROUND) {
8301     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8302     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8303     // If the first fp_round isn't a value preserving truncation, it might
8304     // introduce a tie in the second fp_round, that wouldn't occur in the
8305     // single-step fp_round we want to fold to.
8306     // In other words, double rounding isn't the same as rounding.
8307     // Also, this is a value preserving truncation iff both fp_round's are.
8308     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8309       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8310                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8311   }
8312
8313   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8314   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8315     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8316                               N0.getOperand(0), N1);
8317     AddToWorklist(Tmp.getNode());
8318     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8319                        Tmp, N0.getOperand(1));
8320   }
8321
8322   return SDValue();
8323 }
8324
8325 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8326   SDValue N0 = N->getOperand(0);
8327   EVT VT = N->getValueType(0);
8328   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8329   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8330
8331   // fold (fp_round_inreg c1fp) -> c1fp
8332   if (N0CFP && isTypeLegal(EVT)) {
8333     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8334     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8335   }
8336
8337   return SDValue();
8338 }
8339
8340 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8341   SDValue N0 = N->getOperand(0);
8342   EVT VT = N->getValueType(0);
8343
8344   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8345   if (N->hasOneUse() &&
8346       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8347     return SDValue();
8348
8349   // fold (fp_extend c1fp) -> c1fp
8350   if (isConstantFPBuildVectorOrConstantFP(N0))
8351     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8352
8353   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8354   // value of X.
8355   if (N0.getOpcode() == ISD::FP_ROUND
8356       && N0.getNode()->getConstantOperandVal(1) == 1) {
8357     SDValue In = N0.getOperand(0);
8358     if (In.getValueType() == VT) return In;
8359     if (VT.bitsLT(In.getValueType()))
8360       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8361                          In, N0.getOperand(1));
8362     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8363   }
8364
8365   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8366   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8367        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8368     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8369     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8370                                      LN0->getChain(),
8371                                      LN0->getBasePtr(), N0.getValueType(),
8372                                      LN0->getMemOperand());
8373     CombineTo(N, ExtLoad);
8374     CombineTo(N0.getNode(),
8375               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8376                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8377               ExtLoad.getValue(1));
8378     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8379   }
8380
8381   return SDValue();
8382 }
8383
8384 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8385   SDValue N0 = N->getOperand(0);
8386   EVT VT = N->getValueType(0);
8387
8388   // fold (fceil c1) -> fceil(c1)
8389   if (isConstantFPBuildVectorOrConstantFP(N0))
8390     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8391
8392   return SDValue();
8393 }
8394
8395 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8396   SDValue N0 = N->getOperand(0);
8397   EVT VT = N->getValueType(0);
8398
8399   // fold (ftrunc c1) -> ftrunc(c1)
8400   if (isConstantFPBuildVectorOrConstantFP(N0))
8401     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8402
8403   return SDValue();
8404 }
8405
8406 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8407   SDValue N0 = N->getOperand(0);
8408   EVT VT = N->getValueType(0);
8409
8410   // fold (ffloor c1) -> ffloor(c1)
8411   if (isConstantFPBuildVectorOrConstantFP(N0))
8412     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8413
8414   return SDValue();
8415 }
8416
8417 // FIXME: FNEG and FABS have a lot in common; refactor.
8418 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8419   SDValue N0 = N->getOperand(0);
8420   EVT VT = N->getValueType(0);
8421
8422   // Constant fold FNEG.
8423   if (isConstantFPBuildVectorOrConstantFP(N0))
8424     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8425
8426   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8427                          &DAG.getTarget().Options))
8428     return GetNegatedExpression(N0, DAG, LegalOperations);
8429
8430   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8431   // constant pool values.
8432   if (!TLI.isFNegFree(VT) &&
8433       N0.getOpcode() == ISD::BITCAST &&
8434       N0.getNode()->hasOneUse()) {
8435     SDValue Int = N0.getOperand(0);
8436     EVT IntVT = Int.getValueType();
8437     if (IntVT.isInteger() && !IntVT.isVector()) {
8438       APInt SignMask;
8439       if (N0.getValueType().isVector()) {
8440         // For a vector, get a mask such as 0x80... per scalar element
8441         // and splat it.
8442         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8443         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8444       } else {
8445         // For a scalar, just generate 0x80...
8446         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8447       }
8448       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8449                         DAG.getConstant(SignMask, IntVT));
8450       AddToWorklist(Int.getNode());
8451       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8452     }
8453   }
8454
8455   // (fneg (fmul c, x)) -> (fmul -c, x)
8456   if (N0.getOpcode() == ISD::FMUL) {
8457     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8458     if (CFP1) {
8459       APFloat CVal = CFP1->getValueAPF();
8460       CVal.changeSign();
8461       if (Level >= AfterLegalizeDAG &&
8462           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8463            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8464         return DAG.getNode(
8465             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8466             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8467     }
8468   }
8469
8470   return SDValue();
8471 }
8472
8473 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8474   SDValue N0 = N->getOperand(0);
8475   SDValue N1 = N->getOperand(1);
8476   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8477   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8478
8479   if (N0CFP && N1CFP) {
8480     const APFloat &C0 = N0CFP->getValueAPF();
8481     const APFloat &C1 = N1CFP->getValueAPF();
8482     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8483   }
8484
8485   if (N0CFP) {
8486     EVT VT = N->getValueType(0);
8487     // Canonicalize to constant on RHS.
8488     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8489   }
8490
8491   return SDValue();
8492 }
8493
8494 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8495   SDValue N0 = N->getOperand(0);
8496   SDValue N1 = N->getOperand(1);
8497   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8498   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8499
8500   if (N0CFP && N1CFP) {
8501     const APFloat &C0 = N0CFP->getValueAPF();
8502     const APFloat &C1 = N1CFP->getValueAPF();
8503     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8504   }
8505
8506   if (N0CFP) {
8507     EVT VT = N->getValueType(0);
8508     // Canonicalize to constant on RHS.
8509     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8510   }
8511
8512   return SDValue();
8513 }
8514
8515 SDValue DAGCombiner::visitFABS(SDNode *N) {
8516   SDValue N0 = N->getOperand(0);
8517   EVT VT = N->getValueType(0);
8518
8519   // fold (fabs c1) -> fabs(c1)
8520   if (isConstantFPBuildVectorOrConstantFP(N0))
8521     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8522
8523   // fold (fabs (fabs x)) -> (fabs x)
8524   if (N0.getOpcode() == ISD::FABS)
8525     return N->getOperand(0);
8526
8527   // fold (fabs (fneg x)) -> (fabs x)
8528   // fold (fabs (fcopysign x, y)) -> (fabs x)
8529   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8530     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8531
8532   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8533   // constant pool values.
8534   if (!TLI.isFAbsFree(VT) &&
8535       N0.getOpcode() == ISD::BITCAST &&
8536       N0.getNode()->hasOneUse()) {
8537     SDValue Int = N0.getOperand(0);
8538     EVT IntVT = Int.getValueType();
8539     if (IntVT.isInteger() && !IntVT.isVector()) {
8540       APInt SignMask;
8541       if (N0.getValueType().isVector()) {
8542         // For a vector, get a mask such as 0x7f... per scalar element
8543         // and splat it.
8544         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8545         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8546       } else {
8547         // For a scalar, just generate 0x7f...
8548         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8549       }
8550       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8551                         DAG.getConstant(SignMask, IntVT));
8552       AddToWorklist(Int.getNode());
8553       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8554     }
8555   }
8556
8557   return SDValue();
8558 }
8559
8560 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8561   SDValue Chain = N->getOperand(0);
8562   SDValue N1 = N->getOperand(1);
8563   SDValue N2 = N->getOperand(2);
8564
8565   // If N is a constant we could fold this into a fallthrough or unconditional
8566   // branch. However that doesn't happen very often in normal code, because
8567   // Instcombine/SimplifyCFG should have handled the available opportunities.
8568   // If we did this folding here, it would be necessary to update the
8569   // MachineBasicBlock CFG, which is awkward.
8570
8571   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8572   // on the target.
8573   if (N1.getOpcode() == ISD::SETCC &&
8574       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8575                                    N1.getOperand(0).getValueType())) {
8576     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8577                        Chain, N1.getOperand(2),
8578                        N1.getOperand(0), N1.getOperand(1), N2);
8579   }
8580
8581   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8582       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8583        (N1.getOperand(0).hasOneUse() &&
8584         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8585     SDNode *Trunc = nullptr;
8586     if (N1.getOpcode() == ISD::TRUNCATE) {
8587       // Look pass the truncate.
8588       Trunc = N1.getNode();
8589       N1 = N1.getOperand(0);
8590     }
8591
8592     // Match this pattern so that we can generate simpler code:
8593     //
8594     //   %a = ...
8595     //   %b = and i32 %a, 2
8596     //   %c = srl i32 %b, 1
8597     //   brcond i32 %c ...
8598     //
8599     // into
8600     //
8601     //   %a = ...
8602     //   %b = and i32 %a, 2
8603     //   %c = setcc eq %b, 0
8604     //   brcond %c ...
8605     //
8606     // This applies only when the AND constant value has one bit set and the
8607     // SRL constant is equal to the log2 of the AND constant. The back-end is
8608     // smart enough to convert the result into a TEST/JMP sequence.
8609     SDValue Op0 = N1.getOperand(0);
8610     SDValue Op1 = N1.getOperand(1);
8611
8612     if (Op0.getOpcode() == ISD::AND &&
8613         Op1.getOpcode() == ISD::Constant) {
8614       SDValue AndOp1 = Op0.getOperand(1);
8615
8616       if (AndOp1.getOpcode() == ISD::Constant) {
8617         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8618
8619         if (AndConst.isPowerOf2() &&
8620             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8621           SDValue SetCC =
8622             DAG.getSetCC(SDLoc(N),
8623                          getSetCCResultType(Op0.getValueType()),
8624                          Op0, DAG.getConstant(0, Op0.getValueType()),
8625                          ISD::SETNE);
8626
8627           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8628                                           MVT::Other, Chain, SetCC, N2);
8629           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8630           // will convert it back to (X & C1) >> C2.
8631           CombineTo(N, NewBRCond, false);
8632           // Truncate is dead.
8633           if (Trunc)
8634             deleteAndRecombine(Trunc);
8635           // Replace the uses of SRL with SETCC
8636           WorklistRemover DeadNodes(*this);
8637           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8638           deleteAndRecombine(N1.getNode());
8639           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8640         }
8641       }
8642     }
8643
8644     if (Trunc)
8645       // Restore N1 if the above transformation doesn't match.
8646       N1 = N->getOperand(1);
8647   }
8648
8649   // Transform br(xor(x, y)) -> br(x != y)
8650   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8651   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8652     SDNode *TheXor = N1.getNode();
8653     SDValue Op0 = TheXor->getOperand(0);
8654     SDValue Op1 = TheXor->getOperand(1);
8655     if (Op0.getOpcode() == Op1.getOpcode()) {
8656       // Avoid missing important xor optimizations.
8657       SDValue Tmp = visitXOR(TheXor);
8658       if (Tmp.getNode()) {
8659         if (Tmp.getNode() != TheXor) {
8660           DEBUG(dbgs() << "\nReplacing.8 ";
8661                 TheXor->dump(&DAG);
8662                 dbgs() << "\nWith: ";
8663                 Tmp.getNode()->dump(&DAG);
8664                 dbgs() << '\n');
8665           WorklistRemover DeadNodes(*this);
8666           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8667           deleteAndRecombine(TheXor);
8668           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8669                              MVT::Other, Chain, Tmp, N2);
8670         }
8671
8672         // visitXOR has changed XOR's operands or replaced the XOR completely,
8673         // bail out.
8674         return SDValue(N, 0);
8675       }
8676     }
8677
8678     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8679       bool Equal = false;
8680       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8681         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8682             Op0.getOpcode() == ISD::XOR) {
8683           TheXor = Op0.getNode();
8684           Equal = true;
8685         }
8686
8687       EVT SetCCVT = N1.getValueType();
8688       if (LegalTypes)
8689         SetCCVT = getSetCCResultType(SetCCVT);
8690       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8691                                    SetCCVT,
8692                                    Op0, Op1,
8693                                    Equal ? ISD::SETEQ : ISD::SETNE);
8694       // Replace the uses of XOR with SETCC
8695       WorklistRemover DeadNodes(*this);
8696       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8697       deleteAndRecombine(N1.getNode());
8698       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8699                          MVT::Other, Chain, SetCC, N2);
8700     }
8701   }
8702
8703   return SDValue();
8704 }
8705
8706 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8707 //
8708 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8709   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8710   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8711
8712   // If N is a constant we could fold this into a fallthrough or unconditional
8713   // branch. However that doesn't happen very often in normal code, because
8714   // Instcombine/SimplifyCFG should have handled the available opportunities.
8715   // If we did this folding here, it would be necessary to update the
8716   // MachineBasicBlock CFG, which is awkward.
8717
8718   // Use SimplifySetCC to simplify SETCC's.
8719   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8720                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8721                                false);
8722   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8723
8724   // fold to a simpler setcc
8725   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8726     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8727                        N->getOperand(0), Simp.getOperand(2),
8728                        Simp.getOperand(0), Simp.getOperand(1),
8729                        N->getOperand(4));
8730
8731   return SDValue();
8732 }
8733
8734 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8735 /// and that N may be folded in the load / store addressing mode.
8736 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8737                                     SelectionDAG &DAG,
8738                                     const TargetLowering &TLI) {
8739   EVT VT;
8740   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8741     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8742       return false;
8743     VT = Use->getValueType(0);
8744   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8745     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8746       return false;
8747     VT = ST->getValue().getValueType();
8748   } else
8749     return false;
8750
8751   TargetLowering::AddrMode AM;
8752   if (N->getOpcode() == ISD::ADD) {
8753     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8754     if (Offset)
8755       // [reg +/- imm]
8756       AM.BaseOffs = Offset->getSExtValue();
8757     else
8758       // [reg +/- reg]
8759       AM.Scale = 1;
8760   } else if (N->getOpcode() == ISD::SUB) {
8761     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8762     if (Offset)
8763       // [reg +/- imm]
8764       AM.BaseOffs = -Offset->getSExtValue();
8765     else
8766       // [reg +/- reg]
8767       AM.Scale = 1;
8768   } else
8769     return false;
8770
8771   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8772 }
8773
8774 /// Try turning a load/store into a pre-indexed load/store when the base
8775 /// pointer is an add or subtract and it has other uses besides the load/store.
8776 /// After the transformation, the new indexed load/store has effectively folded
8777 /// the add/subtract in and all of its other uses are redirected to the
8778 /// new load/store.
8779 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8780   if (Level < AfterLegalizeDAG)
8781     return false;
8782
8783   bool isLoad = true;
8784   SDValue Ptr;
8785   EVT VT;
8786   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8787     if (LD->isIndexed())
8788       return false;
8789     VT = LD->getMemoryVT();
8790     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8791         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8792       return false;
8793     Ptr = LD->getBasePtr();
8794   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8795     if (ST->isIndexed())
8796       return false;
8797     VT = ST->getMemoryVT();
8798     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8799         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8800       return false;
8801     Ptr = ST->getBasePtr();
8802     isLoad = false;
8803   } else {
8804     return false;
8805   }
8806
8807   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8808   // out.  There is no reason to make this a preinc/predec.
8809   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8810       Ptr.getNode()->hasOneUse())
8811     return false;
8812
8813   // Ask the target to do addressing mode selection.
8814   SDValue BasePtr;
8815   SDValue Offset;
8816   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8817   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8818     return false;
8819
8820   // Backends without true r+i pre-indexed forms may need to pass a
8821   // constant base with a variable offset so that constant coercion
8822   // will work with the patterns in canonical form.
8823   bool Swapped = false;
8824   if (isa<ConstantSDNode>(BasePtr)) {
8825     std::swap(BasePtr, Offset);
8826     Swapped = true;
8827   }
8828
8829   // Don't create a indexed load / store with zero offset.
8830   if (isa<ConstantSDNode>(Offset) &&
8831       cast<ConstantSDNode>(Offset)->isNullValue())
8832     return false;
8833
8834   // Try turning it into a pre-indexed load / store except when:
8835   // 1) The new base ptr is a frame index.
8836   // 2) If N is a store and the new base ptr is either the same as or is a
8837   //    predecessor of the value being stored.
8838   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8839   //    that would create a cycle.
8840   // 4) All uses are load / store ops that use it as old base ptr.
8841
8842   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8843   // (plus the implicit offset) to a register to preinc anyway.
8844   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8845     return false;
8846
8847   // Check #2.
8848   if (!isLoad) {
8849     SDValue Val = cast<StoreSDNode>(N)->getValue();
8850     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8851       return false;
8852   }
8853
8854   // If the offset is a constant, there may be other adds of constants that
8855   // can be folded with this one. We should do this to avoid having to keep
8856   // a copy of the original base pointer.
8857   SmallVector<SDNode *, 16> OtherUses;
8858   if (isa<ConstantSDNode>(Offset))
8859     for (SDNode *Use : BasePtr.getNode()->uses()) {
8860       if (Use == Ptr.getNode())
8861         continue;
8862
8863       if (Use->isPredecessorOf(N))
8864         continue;
8865
8866       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8867         OtherUses.clear();
8868         break;
8869       }
8870
8871       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8872       if (Op1.getNode() == BasePtr.getNode())
8873         std::swap(Op0, Op1);
8874       assert(Op0.getNode() == BasePtr.getNode() &&
8875              "Use of ADD/SUB but not an operand");
8876
8877       if (!isa<ConstantSDNode>(Op1)) {
8878         OtherUses.clear();
8879         break;
8880       }
8881
8882       // FIXME: In some cases, we can be smarter about this.
8883       if (Op1.getValueType() != Offset.getValueType()) {
8884         OtherUses.clear();
8885         break;
8886       }
8887
8888       OtherUses.push_back(Use);
8889     }
8890
8891   if (Swapped)
8892     std::swap(BasePtr, Offset);
8893
8894   // Now check for #3 and #4.
8895   bool RealUse = false;
8896
8897   // Caches for hasPredecessorHelper
8898   SmallPtrSet<const SDNode *, 32> Visited;
8899   SmallVector<const SDNode *, 16> Worklist;
8900
8901   for (SDNode *Use : Ptr.getNode()->uses()) {
8902     if (Use == N)
8903       continue;
8904     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8905       return false;
8906
8907     // If Ptr may be folded in addressing mode of other use, then it's
8908     // not profitable to do this transformation.
8909     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8910       RealUse = true;
8911   }
8912
8913   if (!RealUse)
8914     return false;
8915
8916   SDValue Result;
8917   if (isLoad)
8918     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8919                                 BasePtr, Offset, AM);
8920   else
8921     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8922                                  BasePtr, Offset, AM);
8923   ++PreIndexedNodes;
8924   ++NodesCombined;
8925   DEBUG(dbgs() << "\nReplacing.4 ";
8926         N->dump(&DAG);
8927         dbgs() << "\nWith: ";
8928         Result.getNode()->dump(&DAG);
8929         dbgs() << '\n');
8930   WorklistRemover DeadNodes(*this);
8931   if (isLoad) {
8932     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8933     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8934   } else {
8935     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8936   }
8937
8938   // Finally, since the node is now dead, remove it from the graph.
8939   deleteAndRecombine(N);
8940
8941   if (Swapped)
8942     std::swap(BasePtr, Offset);
8943
8944   // Replace other uses of BasePtr that can be updated to use Ptr
8945   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8946     unsigned OffsetIdx = 1;
8947     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8948       OffsetIdx = 0;
8949     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8950            BasePtr.getNode() && "Expected BasePtr operand");
8951
8952     // We need to replace ptr0 in the following expression:
8953     //   x0 * offset0 + y0 * ptr0 = t0
8954     // knowing that
8955     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8956     //
8957     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8958     // indexed load/store and the expresion that needs to be re-written.
8959     //
8960     // Therefore, we have:
8961     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8962
8963     ConstantSDNode *CN =
8964       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8965     int X0, X1, Y0, Y1;
8966     APInt Offset0 = CN->getAPIntValue();
8967     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8968
8969     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8970     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8971     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8972     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8973
8974     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8975
8976     APInt CNV = Offset0;
8977     if (X0 < 0) CNV = -CNV;
8978     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8979     else CNV = CNV - Offset1;
8980
8981     // We can now generate the new expression.
8982     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8983     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8984
8985     SDValue NewUse = DAG.getNode(Opcode,
8986                                  SDLoc(OtherUses[i]),
8987                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8988     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8989     deleteAndRecombine(OtherUses[i]);
8990   }
8991
8992   // Replace the uses of Ptr with uses of the updated base value.
8993   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8994   deleteAndRecombine(Ptr.getNode());
8995
8996   return true;
8997 }
8998
8999 /// Try to combine a load/store with a add/sub of the base pointer node into a
9000 /// post-indexed load/store. The transformation folded the add/subtract into the
9001 /// new indexed load/store effectively and all of its uses are redirected to the
9002 /// new load/store.
9003 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9004   if (Level < AfterLegalizeDAG)
9005     return false;
9006
9007   bool isLoad = true;
9008   SDValue Ptr;
9009   EVT VT;
9010   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9011     if (LD->isIndexed())
9012       return false;
9013     VT = LD->getMemoryVT();
9014     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9015         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9016       return false;
9017     Ptr = LD->getBasePtr();
9018   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9019     if (ST->isIndexed())
9020       return false;
9021     VT = ST->getMemoryVT();
9022     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9023         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9024       return false;
9025     Ptr = ST->getBasePtr();
9026     isLoad = false;
9027   } else {
9028     return false;
9029   }
9030
9031   if (Ptr.getNode()->hasOneUse())
9032     return false;
9033
9034   for (SDNode *Op : Ptr.getNode()->uses()) {
9035     if (Op == N ||
9036         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9037       continue;
9038
9039     SDValue BasePtr;
9040     SDValue Offset;
9041     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9042     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9043       // Don't create a indexed load / store with zero offset.
9044       if (isa<ConstantSDNode>(Offset) &&
9045           cast<ConstantSDNode>(Offset)->isNullValue())
9046         continue;
9047
9048       // Try turning it into a post-indexed load / store except when
9049       // 1) All uses are load / store ops that use it as base ptr (and
9050       //    it may be folded as addressing mmode).
9051       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9052       //    nor a successor of N. Otherwise, if Op is folded that would
9053       //    create a cycle.
9054
9055       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9056         continue;
9057
9058       // Check for #1.
9059       bool TryNext = false;
9060       for (SDNode *Use : BasePtr.getNode()->uses()) {
9061         if (Use == Ptr.getNode())
9062           continue;
9063
9064         // If all the uses are load / store addresses, then don't do the
9065         // transformation.
9066         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9067           bool RealUse = false;
9068           for (SDNode *UseUse : Use->uses()) {
9069             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9070               RealUse = true;
9071           }
9072
9073           if (!RealUse) {
9074             TryNext = true;
9075             break;
9076           }
9077         }
9078       }
9079
9080       if (TryNext)
9081         continue;
9082
9083       // Check for #2
9084       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9085         SDValue Result = isLoad
9086           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9087                                BasePtr, Offset, AM)
9088           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9089                                 BasePtr, Offset, AM);
9090         ++PostIndexedNodes;
9091         ++NodesCombined;
9092         DEBUG(dbgs() << "\nReplacing.5 ";
9093               N->dump(&DAG);
9094               dbgs() << "\nWith: ";
9095               Result.getNode()->dump(&DAG);
9096               dbgs() << '\n');
9097         WorklistRemover DeadNodes(*this);
9098         if (isLoad) {
9099           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9100           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9101         } else {
9102           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9103         }
9104
9105         // Finally, since the node is now dead, remove it from the graph.
9106         deleteAndRecombine(N);
9107
9108         // Replace the uses of Use with uses of the updated base value.
9109         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9110                                       Result.getValue(isLoad ? 1 : 0));
9111         deleteAndRecombine(Op);
9112         return true;
9113       }
9114     }
9115   }
9116
9117   return false;
9118 }
9119
9120 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9121 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9122   ISD::MemIndexedMode AM = LD->getAddressingMode();
9123   assert(AM != ISD::UNINDEXED);
9124   SDValue BP = LD->getOperand(1);
9125   SDValue Inc = LD->getOperand(2);
9126
9127   // Some backends use TargetConstants for load offsets, but don't expect
9128   // TargetConstants in general ADD nodes. We can convert these constants into
9129   // regular Constants (if the constant is not opaque).
9130   assert((Inc.getOpcode() != ISD::TargetConstant ||
9131           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9132          "Cannot split out indexing using opaque target constants");
9133   if (Inc.getOpcode() == ISD::TargetConstant) {
9134     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9135     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
9136                           ConstInc->getValueType(0));
9137   }
9138
9139   unsigned Opc =
9140       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9141   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9142 }
9143
9144 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9145   LoadSDNode *LD  = cast<LoadSDNode>(N);
9146   SDValue Chain = LD->getChain();
9147   SDValue Ptr   = LD->getBasePtr();
9148
9149   // If load is not volatile and there are no uses of the loaded value (and
9150   // the updated indexed value in case of indexed loads), change uses of the
9151   // chain value into uses of the chain input (i.e. delete the dead load).
9152   if (!LD->isVolatile()) {
9153     if (N->getValueType(1) == MVT::Other) {
9154       // Unindexed loads.
9155       if (!N->hasAnyUseOfValue(0)) {
9156         // It's not safe to use the two value CombineTo variant here. e.g.
9157         // v1, chain2 = load chain1, loc
9158         // v2, chain3 = load chain2, loc
9159         // v3         = add v2, c
9160         // Now we replace use of chain2 with chain1.  This makes the second load
9161         // isomorphic to the one we are deleting, and thus makes this load live.
9162         DEBUG(dbgs() << "\nReplacing.6 ";
9163               N->dump(&DAG);
9164               dbgs() << "\nWith chain: ";
9165               Chain.getNode()->dump(&DAG);
9166               dbgs() << "\n");
9167         WorklistRemover DeadNodes(*this);
9168         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9169
9170         if (N->use_empty())
9171           deleteAndRecombine(N);
9172
9173         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9174       }
9175     } else {
9176       // Indexed loads.
9177       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9178
9179       // If this load has an opaque TargetConstant offset, then we cannot split
9180       // the indexing into an add/sub directly (that TargetConstant may not be
9181       // valid for a different type of node, and we cannot convert an opaque
9182       // target constant into a regular constant).
9183       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9184                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9185
9186       if (!N->hasAnyUseOfValue(0) &&
9187           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9188         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9189         SDValue Index;
9190         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9191           Index = SplitIndexingFromLoad(LD);
9192           // Try to fold the base pointer arithmetic into subsequent loads and
9193           // stores.
9194           AddUsersToWorklist(N);
9195         } else
9196           Index = DAG.getUNDEF(N->getValueType(1));
9197         DEBUG(dbgs() << "\nReplacing.7 ";
9198               N->dump(&DAG);
9199               dbgs() << "\nWith: ";
9200               Undef.getNode()->dump(&DAG);
9201               dbgs() << " and 2 other values\n");
9202         WorklistRemover DeadNodes(*this);
9203         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9204         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9205         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9206         deleteAndRecombine(N);
9207         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9208       }
9209     }
9210   }
9211
9212   // If this load is directly stored, replace the load value with the stored
9213   // value.
9214   // TODO: Handle store large -> read small portion.
9215   // TODO: Handle TRUNCSTORE/LOADEXT
9216   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9217     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9218       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9219       if (PrevST->getBasePtr() == Ptr &&
9220           PrevST->getValue().getValueType() == N->getValueType(0))
9221       return CombineTo(N, Chain.getOperand(1), Chain);
9222     }
9223   }
9224
9225   // Try to infer better alignment information than the load already has.
9226   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9227     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9228       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9229         SDValue NewLoad =
9230                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9231                               LD->getValueType(0),
9232                               Chain, Ptr, LD->getPointerInfo(),
9233                               LD->getMemoryVT(),
9234                               LD->isVolatile(), LD->isNonTemporal(),
9235                               LD->isInvariant(), Align, LD->getAAInfo());
9236         if (NewLoad.getNode() != N)
9237           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9238       }
9239     }
9240   }
9241
9242   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9243                                                   : DAG.getSubtarget().useAA();
9244 #ifndef NDEBUG
9245   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9246       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9247     UseAA = false;
9248 #endif
9249   if (UseAA && LD->isUnindexed()) {
9250     // Walk up chain skipping non-aliasing memory nodes.
9251     SDValue BetterChain = FindBetterChain(N, Chain);
9252
9253     // If there is a better chain.
9254     if (Chain != BetterChain) {
9255       SDValue ReplLoad;
9256
9257       // Replace the chain to void dependency.
9258       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9259         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9260                                BetterChain, Ptr, LD->getMemOperand());
9261       } else {
9262         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9263                                   LD->getValueType(0),
9264                                   BetterChain, Ptr, LD->getMemoryVT(),
9265                                   LD->getMemOperand());
9266       }
9267
9268       // Create token factor to keep old chain connected.
9269       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9270                                   MVT::Other, Chain, ReplLoad.getValue(1));
9271
9272       // Make sure the new and old chains are cleaned up.
9273       AddToWorklist(Token.getNode());
9274
9275       // Replace uses with load result and token factor. Don't add users
9276       // to work list.
9277       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9278     }
9279   }
9280
9281   // Try transforming N to an indexed load.
9282   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9283     return SDValue(N, 0);
9284
9285   // Try to slice up N to more direct loads if the slices are mapped to
9286   // different register banks or pairing can take place.
9287   if (SliceUpLoad(N))
9288     return SDValue(N, 0);
9289
9290   return SDValue();
9291 }
9292
9293 namespace {
9294 /// \brief Helper structure used to slice a load in smaller loads.
9295 /// Basically a slice is obtained from the following sequence:
9296 /// Origin = load Ty1, Base
9297 /// Shift = srl Ty1 Origin, CstTy Amount
9298 /// Inst = trunc Shift to Ty2
9299 ///
9300 /// Then, it will be rewriten into:
9301 /// Slice = load SliceTy, Base + SliceOffset
9302 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9303 ///
9304 /// SliceTy is deduced from the number of bits that are actually used to
9305 /// build Inst.
9306 struct LoadedSlice {
9307   /// \brief Helper structure used to compute the cost of a slice.
9308   struct Cost {
9309     /// Are we optimizing for code size.
9310     bool ForCodeSize;
9311     /// Various cost.
9312     unsigned Loads;
9313     unsigned Truncates;
9314     unsigned CrossRegisterBanksCopies;
9315     unsigned ZExts;
9316     unsigned Shift;
9317
9318     Cost(bool ForCodeSize = false)
9319         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9320           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9321
9322     /// \brief Get the cost of one isolated slice.
9323     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9324         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9325           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9326       EVT TruncType = LS.Inst->getValueType(0);
9327       EVT LoadedType = LS.getLoadedType();
9328       if (TruncType != LoadedType &&
9329           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9330         ZExts = 1;
9331     }
9332
9333     /// \brief Account for slicing gain in the current cost.
9334     /// Slicing provide a few gains like removing a shift or a
9335     /// truncate. This method allows to grow the cost of the original
9336     /// load with the gain from this slice.
9337     void addSliceGain(const LoadedSlice &LS) {
9338       // Each slice saves a truncate.
9339       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9340       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9341                               LS.Inst->getOperand(0).getValueType()))
9342         ++Truncates;
9343       // If there is a shift amount, this slice gets rid of it.
9344       if (LS.Shift)
9345         ++Shift;
9346       // If this slice can merge a cross register bank copy, account for it.
9347       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9348         ++CrossRegisterBanksCopies;
9349     }
9350
9351     Cost &operator+=(const Cost &RHS) {
9352       Loads += RHS.Loads;
9353       Truncates += RHS.Truncates;
9354       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9355       ZExts += RHS.ZExts;
9356       Shift += RHS.Shift;
9357       return *this;
9358     }
9359
9360     bool operator==(const Cost &RHS) const {
9361       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9362              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9363              ZExts == RHS.ZExts && Shift == RHS.Shift;
9364     }
9365
9366     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9367
9368     bool operator<(const Cost &RHS) const {
9369       // Assume cross register banks copies are as expensive as loads.
9370       // FIXME: Do we want some more target hooks?
9371       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9372       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9373       // Unless we are optimizing for code size, consider the
9374       // expensive operation first.
9375       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9376         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9377       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9378              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9379     }
9380
9381     bool operator>(const Cost &RHS) const { return RHS < *this; }
9382
9383     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9384
9385     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9386   };
9387   // The last instruction that represent the slice. This should be a
9388   // truncate instruction.
9389   SDNode *Inst;
9390   // The original load instruction.
9391   LoadSDNode *Origin;
9392   // The right shift amount in bits from the original load.
9393   unsigned Shift;
9394   // The DAG from which Origin came from.
9395   // This is used to get some contextual information about legal types, etc.
9396   SelectionDAG *DAG;
9397
9398   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9399               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9400       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9401
9402   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9403   /// \return Result is \p BitWidth and has used bits set to 1 and
9404   ///         not used bits set to 0.
9405   APInt getUsedBits() const {
9406     // Reproduce the trunc(lshr) sequence:
9407     // - Start from the truncated value.
9408     // - Zero extend to the desired bit width.
9409     // - Shift left.
9410     assert(Origin && "No original load to compare against.");
9411     unsigned BitWidth = Origin->getValueSizeInBits(0);
9412     assert(Inst && "This slice is not bound to an instruction");
9413     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9414            "Extracted slice is bigger than the whole type!");
9415     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9416     UsedBits.setAllBits();
9417     UsedBits = UsedBits.zext(BitWidth);
9418     UsedBits <<= Shift;
9419     return UsedBits;
9420   }
9421
9422   /// \brief Get the size of the slice to be loaded in bytes.
9423   unsigned getLoadedSize() const {
9424     unsigned SliceSize = getUsedBits().countPopulation();
9425     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9426     return SliceSize / 8;
9427   }
9428
9429   /// \brief Get the type that will be loaded for this slice.
9430   /// Note: This may not be the final type for the slice.
9431   EVT getLoadedType() const {
9432     assert(DAG && "Missing context");
9433     LLVMContext &Ctxt = *DAG->getContext();
9434     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9435   }
9436
9437   /// \brief Get the alignment of the load used for this slice.
9438   unsigned getAlignment() const {
9439     unsigned Alignment = Origin->getAlignment();
9440     unsigned Offset = getOffsetFromBase();
9441     if (Offset != 0)
9442       Alignment = MinAlign(Alignment, Alignment + Offset);
9443     return Alignment;
9444   }
9445
9446   /// \brief Check if this slice can be rewritten with legal operations.
9447   bool isLegal() const {
9448     // An invalid slice is not legal.
9449     if (!Origin || !Inst || !DAG)
9450       return false;
9451
9452     // Offsets are for indexed load only, we do not handle that.
9453     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9454       return false;
9455
9456     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9457
9458     // Check that the type is legal.
9459     EVT SliceType = getLoadedType();
9460     if (!TLI.isTypeLegal(SliceType))
9461       return false;
9462
9463     // Check that the load is legal for this type.
9464     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9465       return false;
9466
9467     // Check that the offset can be computed.
9468     // 1. Check its type.
9469     EVT PtrType = Origin->getBasePtr().getValueType();
9470     if (PtrType == MVT::Untyped || PtrType.isExtended())
9471       return false;
9472
9473     // 2. Check that it fits in the immediate.
9474     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9475       return false;
9476
9477     // 3. Check that the computation is legal.
9478     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9479       return false;
9480
9481     // Check that the zext is legal if it needs one.
9482     EVT TruncateType = Inst->getValueType(0);
9483     if (TruncateType != SliceType &&
9484         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9485       return false;
9486
9487     return true;
9488   }
9489
9490   /// \brief Get the offset in bytes of this slice in the original chunk of
9491   /// bits.
9492   /// \pre DAG != nullptr.
9493   uint64_t getOffsetFromBase() const {
9494     assert(DAG && "Missing context.");
9495     bool IsBigEndian =
9496         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9497     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9498     uint64_t Offset = Shift / 8;
9499     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9500     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9501            "The size of the original loaded type is not a multiple of a"
9502            " byte.");
9503     // If Offset is bigger than TySizeInBytes, it means we are loading all
9504     // zeros. This should have been optimized before in the process.
9505     assert(TySizeInBytes > Offset &&
9506            "Invalid shift amount for given loaded size");
9507     if (IsBigEndian)
9508       Offset = TySizeInBytes - Offset - getLoadedSize();
9509     return Offset;
9510   }
9511
9512   /// \brief Generate the sequence of instructions to load the slice
9513   /// represented by this object and redirect the uses of this slice to
9514   /// this new sequence of instructions.
9515   /// \pre this->Inst && this->Origin are valid Instructions and this
9516   /// object passed the legal check: LoadedSlice::isLegal returned true.
9517   /// \return The last instruction of the sequence used to load the slice.
9518   SDValue loadSlice() const {
9519     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9520     const SDValue &OldBaseAddr = Origin->getBasePtr();
9521     SDValue BaseAddr = OldBaseAddr;
9522     // Get the offset in that chunk of bytes w.r.t. the endianess.
9523     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9524     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9525     if (Offset) {
9526       // BaseAddr = BaseAddr + Offset.
9527       EVT ArithType = BaseAddr.getValueType();
9528       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9529                               DAG->getConstant(Offset, ArithType));
9530     }
9531
9532     // Create the type of the loaded slice according to its size.
9533     EVT SliceType = getLoadedType();
9534
9535     // Create the load for the slice.
9536     SDValue LastInst = DAG->getLoad(
9537         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9538         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9539         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9540     // If the final type is not the same as the loaded type, this means that
9541     // we have to pad with zero. Create a zero extend for that.
9542     EVT FinalType = Inst->getValueType(0);
9543     if (SliceType != FinalType)
9544       LastInst =
9545           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9546     return LastInst;
9547   }
9548
9549   /// \brief Check if this slice can be merged with an expensive cross register
9550   /// bank copy. E.g.,
9551   /// i = load i32
9552   /// f = bitcast i32 i to float
9553   bool canMergeExpensiveCrossRegisterBankCopy() const {
9554     if (!Inst || !Inst->hasOneUse())
9555       return false;
9556     SDNode *Use = *Inst->use_begin();
9557     if (Use->getOpcode() != ISD::BITCAST)
9558       return false;
9559     assert(DAG && "Missing context");
9560     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9561     EVT ResVT = Use->getValueType(0);
9562     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9563     const TargetRegisterClass *ArgRC =
9564         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9565     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9566       return false;
9567
9568     // At this point, we know that we perform a cross-register-bank copy.
9569     // Check if it is expensive.
9570     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9571     // Assume bitcasts are cheap, unless both register classes do not
9572     // explicitly share a common sub class.
9573     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9574       return false;
9575
9576     // Check if it will be merged with the load.
9577     // 1. Check the alignment constraint.
9578     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9579         ResVT.getTypeForEVT(*DAG->getContext()));
9580
9581     if (RequiredAlignment > getAlignment())
9582       return false;
9583
9584     // 2. Check that the load is a legal operation for that type.
9585     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9586       return false;
9587
9588     // 3. Check that we do not have a zext in the way.
9589     if (Inst->getValueType(0) != getLoadedType())
9590       return false;
9591
9592     return true;
9593   }
9594 };
9595 }
9596
9597 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9598 /// \p UsedBits looks like 0..0 1..1 0..0.
9599 static bool areUsedBitsDense(const APInt &UsedBits) {
9600   // If all the bits are one, this is dense!
9601   if (UsedBits.isAllOnesValue())
9602     return true;
9603
9604   // Get rid of the unused bits on the right.
9605   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9606   // Get rid of the unused bits on the left.
9607   if (NarrowedUsedBits.countLeadingZeros())
9608     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9609   // Check that the chunk of bits is completely used.
9610   return NarrowedUsedBits.isAllOnesValue();
9611 }
9612
9613 /// \brief Check whether or not \p First and \p Second are next to each other
9614 /// in memory. This means that there is no hole between the bits loaded
9615 /// by \p First and the bits loaded by \p Second.
9616 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9617                                      const LoadedSlice &Second) {
9618   assert(First.Origin == Second.Origin && First.Origin &&
9619          "Unable to match different memory origins.");
9620   APInt UsedBits = First.getUsedBits();
9621   assert((UsedBits & Second.getUsedBits()) == 0 &&
9622          "Slices are not supposed to overlap.");
9623   UsedBits |= Second.getUsedBits();
9624   return areUsedBitsDense(UsedBits);
9625 }
9626
9627 /// \brief Adjust the \p GlobalLSCost according to the target
9628 /// paring capabilities and the layout of the slices.
9629 /// \pre \p GlobalLSCost should account for at least as many loads as
9630 /// there is in the slices in \p LoadedSlices.
9631 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9632                                  LoadedSlice::Cost &GlobalLSCost) {
9633   unsigned NumberOfSlices = LoadedSlices.size();
9634   // If there is less than 2 elements, no pairing is possible.
9635   if (NumberOfSlices < 2)
9636     return;
9637
9638   // Sort the slices so that elements that are likely to be next to each
9639   // other in memory are next to each other in the list.
9640   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9641             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9642     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9643     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9644   });
9645   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9646   // First (resp. Second) is the first (resp. Second) potentially candidate
9647   // to be placed in a paired load.
9648   const LoadedSlice *First = nullptr;
9649   const LoadedSlice *Second = nullptr;
9650   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9651                 // Set the beginning of the pair.
9652                                                            First = Second) {
9653
9654     Second = &LoadedSlices[CurrSlice];
9655
9656     // If First is NULL, it means we start a new pair.
9657     // Get to the next slice.
9658     if (!First)
9659       continue;
9660
9661     EVT LoadedType = First->getLoadedType();
9662
9663     // If the types of the slices are different, we cannot pair them.
9664     if (LoadedType != Second->getLoadedType())
9665       continue;
9666
9667     // Check if the target supplies paired loads for this type.
9668     unsigned RequiredAlignment = 0;
9669     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9670       // move to the next pair, this type is hopeless.
9671       Second = nullptr;
9672       continue;
9673     }
9674     // Check if we meet the alignment requirement.
9675     if (RequiredAlignment > First->getAlignment())
9676       continue;
9677
9678     // Check that both loads are next to each other in memory.
9679     if (!areSlicesNextToEachOther(*First, *Second))
9680       continue;
9681
9682     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9683     --GlobalLSCost.Loads;
9684     // Move to the next pair.
9685     Second = nullptr;
9686   }
9687 }
9688
9689 /// \brief Check the profitability of all involved LoadedSlice.
9690 /// Currently, it is considered profitable if there is exactly two
9691 /// involved slices (1) which are (2) next to each other in memory, and
9692 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9693 ///
9694 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9695 /// the elements themselves.
9696 ///
9697 /// FIXME: When the cost model will be mature enough, we can relax
9698 /// constraints (1) and (2).
9699 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9700                                 const APInt &UsedBits, bool ForCodeSize) {
9701   unsigned NumberOfSlices = LoadedSlices.size();
9702   if (StressLoadSlicing)
9703     return NumberOfSlices > 1;
9704
9705   // Check (1).
9706   if (NumberOfSlices != 2)
9707     return false;
9708
9709   // Check (2).
9710   if (!areUsedBitsDense(UsedBits))
9711     return false;
9712
9713   // Check (3).
9714   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9715   // The original code has one big load.
9716   OrigCost.Loads = 1;
9717   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9718     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9719     // Accumulate the cost of all the slices.
9720     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9721     GlobalSlicingCost += SliceCost;
9722
9723     // Account as cost in the original configuration the gain obtained
9724     // with the current slices.
9725     OrigCost.addSliceGain(LS);
9726   }
9727
9728   // If the target supports paired load, adjust the cost accordingly.
9729   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9730   return OrigCost > GlobalSlicingCost;
9731 }
9732
9733 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9734 /// operations, split it in the various pieces being extracted.
9735 ///
9736 /// This sort of thing is introduced by SROA.
9737 /// This slicing takes care not to insert overlapping loads.
9738 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9739 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9740   if (Level < AfterLegalizeDAG)
9741     return false;
9742
9743   LoadSDNode *LD = cast<LoadSDNode>(N);
9744   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9745       !LD->getValueType(0).isInteger())
9746     return false;
9747
9748   // Keep track of already used bits to detect overlapping values.
9749   // In that case, we will just abort the transformation.
9750   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9751
9752   SmallVector<LoadedSlice, 4> LoadedSlices;
9753
9754   // Check if this load is used as several smaller chunks of bits.
9755   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9756   // of computation for each trunc.
9757   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9758        UI != UIEnd; ++UI) {
9759     // Skip the uses of the chain.
9760     if (UI.getUse().getResNo() != 0)
9761       continue;
9762
9763     SDNode *User = *UI;
9764     unsigned Shift = 0;
9765
9766     // Check if this is a trunc(lshr).
9767     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9768         isa<ConstantSDNode>(User->getOperand(1))) {
9769       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9770       User = *User->use_begin();
9771     }
9772
9773     // At this point, User is a Truncate, iff we encountered, trunc or
9774     // trunc(lshr).
9775     if (User->getOpcode() != ISD::TRUNCATE)
9776       return false;
9777
9778     // The width of the type must be a power of 2 and greater than 8-bits.
9779     // Otherwise the load cannot be represented in LLVM IR.
9780     // Moreover, if we shifted with a non-8-bits multiple, the slice
9781     // will be across several bytes. We do not support that.
9782     unsigned Width = User->getValueSizeInBits(0);
9783     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9784       return 0;
9785
9786     // Build the slice for this chain of computations.
9787     LoadedSlice LS(User, LD, Shift, &DAG);
9788     APInt CurrentUsedBits = LS.getUsedBits();
9789
9790     // Check if this slice overlaps with another.
9791     if ((CurrentUsedBits & UsedBits) != 0)
9792       return false;
9793     // Update the bits used globally.
9794     UsedBits |= CurrentUsedBits;
9795
9796     // Check if the new slice would be legal.
9797     if (!LS.isLegal())
9798       return false;
9799
9800     // Record the slice.
9801     LoadedSlices.push_back(LS);
9802   }
9803
9804   // Abort slicing if it does not seem to be profitable.
9805   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9806     return false;
9807
9808   ++SlicedLoads;
9809
9810   // Rewrite each chain to use an independent load.
9811   // By construction, each chain can be represented by a unique load.
9812
9813   // Prepare the argument for the new token factor for all the slices.
9814   SmallVector<SDValue, 8> ArgChains;
9815   for (SmallVectorImpl<LoadedSlice>::const_iterator
9816            LSIt = LoadedSlices.begin(),
9817            LSItEnd = LoadedSlices.end();
9818        LSIt != LSItEnd; ++LSIt) {
9819     SDValue SliceInst = LSIt->loadSlice();
9820     CombineTo(LSIt->Inst, SliceInst, true);
9821     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9822       SliceInst = SliceInst.getOperand(0);
9823     assert(SliceInst->getOpcode() == ISD::LOAD &&
9824            "It takes more than a zext to get to the loaded slice!!");
9825     ArgChains.push_back(SliceInst.getValue(1));
9826   }
9827
9828   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9829                               ArgChains);
9830   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9831   return true;
9832 }
9833
9834 /// Check to see if V is (and load (ptr), imm), where the load is having
9835 /// specific bytes cleared out.  If so, return the byte size being masked out
9836 /// and the shift amount.
9837 static std::pair<unsigned, unsigned>
9838 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9839   std::pair<unsigned, unsigned> Result(0, 0);
9840
9841   // Check for the structure we're looking for.
9842   if (V->getOpcode() != ISD::AND ||
9843       !isa<ConstantSDNode>(V->getOperand(1)) ||
9844       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9845     return Result;
9846
9847   // Check the chain and pointer.
9848   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9849   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9850
9851   // The store should be chained directly to the load or be an operand of a
9852   // tokenfactor.
9853   if (LD == Chain.getNode())
9854     ; // ok.
9855   else if (Chain->getOpcode() != ISD::TokenFactor)
9856     return Result; // Fail.
9857   else {
9858     bool isOk = false;
9859     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9860       if (Chain->getOperand(i).getNode() == LD) {
9861         isOk = true;
9862         break;
9863       }
9864     if (!isOk) return Result;
9865   }
9866
9867   // This only handles simple types.
9868   if (V.getValueType() != MVT::i16 &&
9869       V.getValueType() != MVT::i32 &&
9870       V.getValueType() != MVT::i64)
9871     return Result;
9872
9873   // Check the constant mask.  Invert it so that the bits being masked out are
9874   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9875   // follow the sign bit for uniformity.
9876   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9877   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9878   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9879   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9880   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9881   if (NotMaskLZ == 64) return Result;  // All zero mask.
9882
9883   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9884   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9885     return Result;
9886
9887   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9888   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9889     NotMaskLZ -= 64-V.getValueSizeInBits();
9890
9891   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9892   switch (MaskedBytes) {
9893   case 1:
9894   case 2:
9895   case 4: break;
9896   default: return Result; // All one mask, or 5-byte mask.
9897   }
9898
9899   // Verify that the first bit starts at a multiple of mask so that the access
9900   // is aligned the same as the access width.
9901   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9902
9903   Result.first = MaskedBytes;
9904   Result.second = NotMaskTZ/8;
9905   return Result;
9906 }
9907
9908
9909 /// Check to see if IVal is something that provides a value as specified by
9910 /// MaskInfo. If so, replace the specified store with a narrower store of
9911 /// truncated IVal.
9912 static SDNode *
9913 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9914                                 SDValue IVal, StoreSDNode *St,
9915                                 DAGCombiner *DC) {
9916   unsigned NumBytes = MaskInfo.first;
9917   unsigned ByteShift = MaskInfo.second;
9918   SelectionDAG &DAG = DC->getDAG();
9919
9920   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9921   // that uses this.  If not, this is not a replacement.
9922   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9923                                   ByteShift*8, (ByteShift+NumBytes)*8);
9924   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9925
9926   // Check that it is legal on the target to do this.  It is legal if the new
9927   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9928   // legalization.
9929   MVT VT = MVT::getIntegerVT(NumBytes*8);
9930   if (!DC->isTypeLegal(VT))
9931     return nullptr;
9932
9933   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9934   // shifted by ByteShift and truncated down to NumBytes.
9935   if (ByteShift)
9936     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9937                        DAG.getConstant(ByteShift*8,
9938                                     DC->getShiftAmountTy(IVal.getValueType())));
9939
9940   // Figure out the offset for the store and the alignment of the access.
9941   unsigned StOffset;
9942   unsigned NewAlign = St->getAlignment();
9943
9944   if (DAG.getTargetLoweringInfo().isLittleEndian())
9945     StOffset = ByteShift;
9946   else
9947     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9948
9949   SDValue Ptr = St->getBasePtr();
9950   if (StOffset) {
9951     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9952                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9953     NewAlign = MinAlign(NewAlign, StOffset);
9954   }
9955
9956   // Truncate down to the new size.
9957   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9958
9959   ++OpsNarrowed;
9960   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9961                       St->getPointerInfo().getWithOffset(StOffset),
9962                       false, false, NewAlign).getNode();
9963 }
9964
9965
9966 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9967 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9968 /// narrowing the load and store if it would end up being a win for performance
9969 /// or code size.
9970 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9971   StoreSDNode *ST  = cast<StoreSDNode>(N);
9972   if (ST->isVolatile())
9973     return SDValue();
9974
9975   SDValue Chain = ST->getChain();
9976   SDValue Value = ST->getValue();
9977   SDValue Ptr   = ST->getBasePtr();
9978   EVT VT = Value.getValueType();
9979
9980   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9981     return SDValue();
9982
9983   unsigned Opc = Value.getOpcode();
9984
9985   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9986   // is a byte mask indicating a consecutive number of bytes, check to see if
9987   // Y is known to provide just those bytes.  If so, we try to replace the
9988   // load + replace + store sequence with a single (narrower) store, which makes
9989   // the load dead.
9990   if (Opc == ISD::OR) {
9991     std::pair<unsigned, unsigned> MaskedLoad;
9992     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9993     if (MaskedLoad.first)
9994       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9995                                                   Value.getOperand(1), ST,this))
9996         return SDValue(NewST, 0);
9997
9998     // Or is commutative, so try swapping X and Y.
9999     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10000     if (MaskedLoad.first)
10001       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10002                                                   Value.getOperand(0), ST,this))
10003         return SDValue(NewST, 0);
10004   }
10005
10006   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10007       Value.getOperand(1).getOpcode() != ISD::Constant)
10008     return SDValue();
10009
10010   SDValue N0 = Value.getOperand(0);
10011   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10012       Chain == SDValue(N0.getNode(), 1)) {
10013     LoadSDNode *LD = cast<LoadSDNode>(N0);
10014     if (LD->getBasePtr() != Ptr ||
10015         LD->getPointerInfo().getAddrSpace() !=
10016         ST->getPointerInfo().getAddrSpace())
10017       return SDValue();
10018
10019     // Find the type to narrow it the load / op / store to.
10020     SDValue N1 = Value.getOperand(1);
10021     unsigned BitWidth = N1.getValueSizeInBits();
10022     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10023     if (Opc == ISD::AND)
10024       Imm ^= APInt::getAllOnesValue(BitWidth);
10025     if (Imm == 0 || Imm.isAllOnesValue())
10026       return SDValue();
10027     unsigned ShAmt = Imm.countTrailingZeros();
10028     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10029     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10030     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10031     // The narrowing should be profitable, the load/store operation should be
10032     // legal (or custom) and the store size should be equal to the NewVT width.
10033     while (NewBW < BitWidth &&
10034            (NewVT.getStoreSizeInBits() != NewBW ||
10035             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10036             !TLI.isNarrowingProfitable(VT, NewVT))) {
10037       NewBW = NextPowerOf2(NewBW);
10038       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10039     }
10040     if (NewBW >= BitWidth)
10041       return SDValue();
10042
10043     // If the lsb changed does not start at the type bitwidth boundary,
10044     // start at the previous one.
10045     if (ShAmt % NewBW)
10046       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10047     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10048                                    std::min(BitWidth, ShAmt + NewBW));
10049     if ((Imm & Mask) == Imm) {
10050       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10051       if (Opc == ISD::AND)
10052         NewImm ^= APInt::getAllOnesValue(NewBW);
10053       uint64_t PtrOff = ShAmt / 8;
10054       // For big endian targets, we need to adjust the offset to the pointer to
10055       // load the correct bytes.
10056       if (TLI.isBigEndian())
10057         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10058
10059       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10060       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10061       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10062         return SDValue();
10063
10064       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10065                                    Ptr.getValueType(), Ptr,
10066                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
10067       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10068                                   LD->getChain(), NewPtr,
10069                                   LD->getPointerInfo().getWithOffset(PtrOff),
10070                                   LD->isVolatile(), LD->isNonTemporal(),
10071                                   LD->isInvariant(), NewAlign,
10072                                   LD->getAAInfo());
10073       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10074                                    DAG.getConstant(NewImm, NewVT));
10075       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10076                                    NewVal, NewPtr,
10077                                    ST->getPointerInfo().getWithOffset(PtrOff),
10078                                    false, false, NewAlign);
10079
10080       AddToWorklist(NewPtr.getNode());
10081       AddToWorklist(NewLD.getNode());
10082       AddToWorklist(NewVal.getNode());
10083       WorklistRemover DeadNodes(*this);
10084       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10085       ++OpsNarrowed;
10086       return NewST;
10087     }
10088   }
10089
10090   return SDValue();
10091 }
10092
10093 /// For a given floating point load / store pair, if the load value isn't used
10094 /// by any other operations, then consider transforming the pair to integer
10095 /// load / store operations if the target deems the transformation profitable.
10096 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10097   StoreSDNode *ST  = cast<StoreSDNode>(N);
10098   SDValue Chain = ST->getChain();
10099   SDValue Value = ST->getValue();
10100   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10101       Value.hasOneUse() &&
10102       Chain == SDValue(Value.getNode(), 1)) {
10103     LoadSDNode *LD = cast<LoadSDNode>(Value);
10104     EVT VT = LD->getMemoryVT();
10105     if (!VT.isFloatingPoint() ||
10106         VT != ST->getMemoryVT() ||
10107         LD->isNonTemporal() ||
10108         ST->isNonTemporal() ||
10109         LD->getPointerInfo().getAddrSpace() != 0 ||
10110         ST->getPointerInfo().getAddrSpace() != 0)
10111       return SDValue();
10112
10113     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10114     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10115         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10116         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10117         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10118       return SDValue();
10119
10120     unsigned LDAlign = LD->getAlignment();
10121     unsigned STAlign = ST->getAlignment();
10122     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10123     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10124     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10125       return SDValue();
10126
10127     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10128                                 LD->getChain(), LD->getBasePtr(),
10129                                 LD->getPointerInfo(),
10130                                 false, false, false, LDAlign);
10131
10132     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10133                                  NewLD, ST->getBasePtr(),
10134                                  ST->getPointerInfo(),
10135                                  false, false, STAlign);
10136
10137     AddToWorklist(NewLD.getNode());
10138     AddToWorklist(NewST.getNode());
10139     WorklistRemover DeadNodes(*this);
10140     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10141     ++LdStFP2Int;
10142     return NewST;
10143   }
10144
10145   return SDValue();
10146 }
10147
10148 namespace {
10149 /// Helper struct to parse and store a memory address as base + index + offset.
10150 /// We ignore sign extensions when it is safe to do so.
10151 /// The following two expressions are not equivalent. To differentiate we need
10152 /// to store whether there was a sign extension involved in the index
10153 /// computation.
10154 ///  (load (i64 add (i64 copyfromreg %c)
10155 ///                 (i64 signextend (add (i8 load %index)
10156 ///                                      (i8 1))))
10157 /// vs
10158 ///
10159 /// (load (i64 add (i64 copyfromreg %c)
10160 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10161 ///                                         (i32 1)))))
10162 struct BaseIndexOffset {
10163   SDValue Base;
10164   SDValue Index;
10165   int64_t Offset;
10166   bool IsIndexSignExt;
10167
10168   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10169
10170   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10171                   bool IsIndexSignExt) :
10172     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10173
10174   bool equalBaseIndex(const BaseIndexOffset &Other) {
10175     return Other.Base == Base && Other.Index == Index &&
10176       Other.IsIndexSignExt == IsIndexSignExt;
10177   }
10178
10179   /// Parses tree in Ptr for base, index, offset addresses.
10180   static BaseIndexOffset match(SDValue Ptr) {
10181     bool IsIndexSignExt = false;
10182
10183     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10184     // instruction, then it could be just the BASE or everything else we don't
10185     // know how to handle. Just use Ptr as BASE and give up.
10186     if (Ptr->getOpcode() != ISD::ADD)
10187       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10188
10189     // We know that we have at least an ADD instruction. Try to pattern match
10190     // the simple case of BASE + OFFSET.
10191     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10192       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10193       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10194                               IsIndexSignExt);
10195     }
10196
10197     // Inside a loop the current BASE pointer is calculated using an ADD and a
10198     // MUL instruction. In this case Ptr is the actual BASE pointer.
10199     // (i64 add (i64 %array_ptr)
10200     //          (i64 mul (i64 %induction_var)
10201     //                   (i64 %element_size)))
10202     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10203       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10204
10205     // Look at Base + Index + Offset cases.
10206     SDValue Base = Ptr->getOperand(0);
10207     SDValue IndexOffset = Ptr->getOperand(1);
10208
10209     // Skip signextends.
10210     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10211       IndexOffset = IndexOffset->getOperand(0);
10212       IsIndexSignExt = true;
10213     }
10214
10215     // Either the case of Base + Index (no offset) or something else.
10216     if (IndexOffset->getOpcode() != ISD::ADD)
10217       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10218
10219     // Now we have the case of Base + Index + offset.
10220     SDValue Index = IndexOffset->getOperand(0);
10221     SDValue Offset = IndexOffset->getOperand(1);
10222
10223     if (!isa<ConstantSDNode>(Offset))
10224       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10225
10226     // Ignore signextends.
10227     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10228       Index = Index->getOperand(0);
10229       IsIndexSignExt = true;
10230     } else IsIndexSignExt = false;
10231
10232     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10233     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10234   }
10235 };
10236 } // namespace
10237
10238 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10239                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10240                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10241   // Make sure we have something to merge.
10242   if (NumElem < 2)
10243     return false;
10244
10245   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10246   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10247   unsigned LatestNodeUsed = 0;
10248
10249   for (unsigned i=0; i < NumElem; ++i) {
10250     // Find a chain for the new wide-store operand. Notice that some
10251     // of the store nodes that we found may not be selected for inclusion
10252     // in the wide store. The chain we use needs to be the chain of the
10253     // latest store node which is *used* and replaced by the wide store.
10254     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10255       LatestNodeUsed = i;
10256   }
10257
10258   // The latest Node in the DAG.
10259   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10260   SDLoc DL(StoreNodes[0].MemNode);
10261
10262   SDValue StoredVal;
10263   if (UseVector) {
10264     // Find a legal type for the vector store.
10265     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10266     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10267     if (IsConstantSrc) {
10268       // A vector store with a constant source implies that the constant is
10269       // zero; we only handle merging stores of constant zeros because the zero
10270       // can be materialized without a load.
10271       // It may be beneficial to loosen this restriction to allow non-zero
10272       // store merging.
10273       StoredVal = DAG.getConstant(0, Ty);
10274     } else {
10275       SmallVector<SDValue, 8> Ops;
10276       for (unsigned i = 0; i < NumElem ; ++i) {
10277         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10278         SDValue Val = St->getValue();
10279         // All of the operands of a BUILD_VECTOR must have the same type.
10280         if (Val.getValueType() != MemVT)
10281           return false;
10282         Ops.push_back(Val);
10283       }
10284
10285       // Build the extracted vector elements back into a vector.
10286       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10287     }
10288   } else {
10289     // We should always use a vector store when merging extracted vector
10290     // elements, so this path implies a store of constants.
10291     assert(IsConstantSrc && "Merged vector elements should use vector store");
10292
10293     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10294     APInt StoreInt(StoreBW, 0);
10295
10296     // Construct a single integer constant which is made of the smaller
10297     // constant inputs.
10298     bool IsLE = TLI.isLittleEndian();
10299     for (unsigned i = 0; i < NumElem ; ++i) {
10300       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10301       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10302       SDValue Val = St->getValue();
10303       StoreInt <<= ElementSizeBytes*8;
10304       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10305         StoreInt |= C->getAPIntValue().zext(StoreBW);
10306       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10307         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10308       } else {
10309         llvm_unreachable("Invalid constant element type");
10310       }
10311     }
10312
10313     // Create the new Load and Store operations.
10314     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10315     StoredVal = DAG.getConstant(StoreInt, StoreTy);
10316   }
10317
10318   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10319                                   FirstInChain->getBasePtr(),
10320                                   FirstInChain->getPointerInfo(),
10321                                   false, false,
10322                                   FirstInChain->getAlignment());
10323
10324   // Replace the last store with the new store
10325   CombineTo(LatestOp, NewStore);
10326   // Erase all other stores.
10327   for (unsigned i = 0; i < NumElem ; ++i) {
10328     if (StoreNodes[i].MemNode == LatestOp)
10329       continue;
10330     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10331     // ReplaceAllUsesWith will replace all uses that existed when it was
10332     // called, but graph optimizations may cause new ones to appear. For
10333     // example, the case in pr14333 looks like
10334     //
10335     //  St's chain -> St -> another store -> X
10336     //
10337     // And the only difference from St to the other store is the chain.
10338     // When we change it's chain to be St's chain they become identical,
10339     // get CSEed and the net result is that X is now a use of St.
10340     // Since we know that St is redundant, just iterate.
10341     while (!St->use_empty())
10342       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10343     deleteAndRecombine(St);
10344   }
10345
10346   return true;
10347 }
10348
10349 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10350   if (OptLevel == CodeGenOpt::None)
10351     return false;
10352
10353   EVT MemVT = St->getMemoryVT();
10354   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10355   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10356       Attribute::NoImplicitFloat);
10357
10358   // Don't merge vectors into wider inputs.
10359   if (MemVT.isVector() || !MemVT.isSimple())
10360     return false;
10361
10362   // Perform an early exit check. Do not bother looking at stored values that
10363   // are not constants, loads, or extracted vector elements.
10364   SDValue StoredVal = St->getValue();
10365   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10366   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10367                        isa<ConstantFPSDNode>(StoredVal);
10368   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10369
10370   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10371     return false;
10372
10373   // Only look at ends of store sequences.
10374   SDValue Chain = SDValue(St, 0);
10375   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10376     return false;
10377
10378   // This holds the base pointer, index, and the offset in bytes from the base
10379   // pointer.
10380   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10381
10382   // We must have a base and an offset.
10383   if (!BasePtr.Base.getNode())
10384     return false;
10385
10386   // Do not handle stores to undef base pointers.
10387   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10388     return false;
10389
10390   // Save the LoadSDNodes that we find in the chain.
10391   // We need to make sure that these nodes do not interfere with
10392   // any of the store nodes.
10393   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10394
10395   // Save the StoreSDNodes that we find in the chain.
10396   SmallVector<MemOpLink, 8> StoreNodes;
10397
10398   // Walk up the chain and look for nodes with offsets from the same
10399   // base pointer. Stop when reaching an instruction with a different kind
10400   // or instruction which has a different base pointer.
10401   unsigned Seq = 0;
10402   StoreSDNode *Index = St;
10403   while (Index) {
10404     // If the chain has more than one use, then we can't reorder the mem ops.
10405     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10406       break;
10407
10408     // Find the base pointer and offset for this memory node.
10409     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10410
10411     // Check that the base pointer is the same as the original one.
10412     if (!Ptr.equalBaseIndex(BasePtr))
10413       break;
10414
10415     // Check that the alignment is the same.
10416     if (Index->getAlignment() != St->getAlignment())
10417       break;
10418
10419     // The memory operands must not be volatile.
10420     if (Index->isVolatile() || Index->isIndexed())
10421       break;
10422
10423     // No truncation.
10424     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10425       if (St->isTruncatingStore())
10426         break;
10427
10428     // The stored memory type must be the same.
10429     if (Index->getMemoryVT() != MemVT)
10430       break;
10431
10432     // We do not allow unaligned stores because we want to prevent overriding
10433     // stores.
10434     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10435       break;
10436
10437     // We found a potential memory operand to merge.
10438     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10439
10440     // Find the next memory operand in the chain. If the next operand in the
10441     // chain is a store then move up and continue the scan with the next
10442     // memory operand. If the next operand is a load save it and use alias
10443     // information to check if it interferes with anything.
10444     SDNode *NextInChain = Index->getChain().getNode();
10445     while (1) {
10446       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10447         // We found a store node. Use it for the next iteration.
10448         Index = STn;
10449         break;
10450       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10451         if (Ldn->isVolatile()) {
10452           Index = nullptr;
10453           break;
10454         }
10455
10456         // Save the load node for later. Continue the scan.
10457         AliasLoadNodes.push_back(Ldn);
10458         NextInChain = Ldn->getChain().getNode();
10459         continue;
10460       } else {
10461         Index = nullptr;
10462         break;
10463       }
10464     }
10465   }
10466
10467   // Check if there is anything to merge.
10468   if (StoreNodes.size() < 2)
10469     return false;
10470
10471   // Sort the memory operands according to their distance from the base pointer.
10472   std::sort(StoreNodes.begin(), StoreNodes.end(),
10473             [](MemOpLink LHS, MemOpLink RHS) {
10474     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10475            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10476             LHS.SequenceNum > RHS.SequenceNum);
10477   });
10478
10479   // Scan the memory operations on the chain and find the first non-consecutive
10480   // store memory address.
10481   unsigned LastConsecutiveStore = 0;
10482   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10483   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10484
10485     // Check that the addresses are consecutive starting from the second
10486     // element in the list of stores.
10487     if (i > 0) {
10488       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10489       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10490         break;
10491     }
10492
10493     bool Alias = false;
10494     // Check if this store interferes with any of the loads that we found.
10495     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10496       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10497         Alias = true;
10498         break;
10499       }
10500     // We found a load that alias with this store. Stop the sequence.
10501     if (Alias)
10502       break;
10503
10504     // Mark this node as useful.
10505     LastConsecutiveStore = i;
10506   }
10507
10508   // The node with the lowest store address.
10509   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10510
10511   // Store the constants into memory as one consecutive store.
10512   if (IsConstantSrc) {
10513     unsigned LastLegalType = 0;
10514     unsigned LastLegalVectorType = 0;
10515     bool NonZero = false;
10516     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10517       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10518       SDValue StoredVal = St->getValue();
10519
10520       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10521         NonZero |= !C->isNullValue();
10522       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10523         NonZero |= !C->getConstantFPValue()->isNullValue();
10524       } else {
10525         // Non-constant.
10526         break;
10527       }
10528
10529       // Find a legal type for the constant store.
10530       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10531       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10532       if (TLI.isTypeLegal(StoreTy))
10533         LastLegalType = i+1;
10534       // Or check whether a truncstore is legal.
10535       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10536                TargetLowering::TypePromoteInteger) {
10537         EVT LegalizedStoredValueTy =
10538           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10539         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10540           LastLegalType = i+1;
10541       }
10542
10543       // Find a legal type for the vector store.
10544       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10545       if (TLI.isTypeLegal(Ty))
10546         LastLegalVectorType = i + 1;
10547     }
10548
10549     // We only use vectors if the constant is known to be zero and the
10550     // function is not marked with the noimplicitfloat attribute.
10551     if (NonZero || NoVectors)
10552       LastLegalVectorType = 0;
10553
10554     // Check if we found a legal integer type to store.
10555     if (LastLegalType == 0 && LastLegalVectorType == 0)
10556       return false;
10557
10558     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10559     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10560
10561     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10562                                            true, UseVector);
10563   }
10564
10565   // When extracting multiple vector elements, try to store them
10566   // in one vector store rather than a sequence of scalar stores.
10567   if (IsExtractVecEltSrc) {
10568     unsigned NumElem = 0;
10569     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10570       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10571       SDValue StoredVal = St->getValue();
10572       // This restriction could be loosened.
10573       // Bail out if any stored values are not elements extracted from a vector.
10574       // It should be possible to handle mixed sources, but load sources need
10575       // more careful handling (see the block of code below that handles
10576       // consecutive loads).
10577       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10578         return false;
10579
10580       // Find a legal type for the vector store.
10581       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10582       if (TLI.isTypeLegal(Ty))
10583         NumElem = i + 1;
10584     }
10585
10586     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10587                                            false, true);
10588   }
10589
10590   // Below we handle the case of multiple consecutive stores that
10591   // come from multiple consecutive loads. We merge them into a single
10592   // wide load and a single wide store.
10593
10594   // Look for load nodes which are used by the stored values.
10595   SmallVector<MemOpLink, 8> LoadNodes;
10596
10597   // Find acceptable loads. Loads need to have the same chain (token factor),
10598   // must not be zext, volatile, indexed, and they must be consecutive.
10599   BaseIndexOffset LdBasePtr;
10600   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10601     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10602     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10603     if (!Ld) break;
10604
10605     // Loads must only have one use.
10606     if (!Ld->hasNUsesOfValue(1, 0))
10607       break;
10608
10609     // Check that the alignment is the same as the stores.
10610     if (Ld->getAlignment() != St->getAlignment())
10611       break;
10612
10613     // The memory operands must not be volatile.
10614     if (Ld->isVolatile() || Ld->isIndexed())
10615       break;
10616
10617     // We do not accept ext loads.
10618     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10619       break;
10620
10621     // The stored memory type must be the same.
10622     if (Ld->getMemoryVT() != MemVT)
10623       break;
10624
10625     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10626     // If this is not the first ptr that we check.
10627     if (LdBasePtr.Base.getNode()) {
10628       // The base ptr must be the same.
10629       if (!LdPtr.equalBaseIndex(LdBasePtr))
10630         break;
10631     } else {
10632       // Check that all other base pointers are the same as this one.
10633       LdBasePtr = LdPtr;
10634     }
10635
10636     // We found a potential memory operand to merge.
10637     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10638   }
10639
10640   if (LoadNodes.size() < 2)
10641     return false;
10642
10643   // If we have load/store pair instructions and we only have two values,
10644   // don't bother.
10645   unsigned RequiredAlignment;
10646   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10647       St->getAlignment() >= RequiredAlignment)
10648     return false;
10649
10650   // Scan the memory operations on the chain and find the first non-consecutive
10651   // load memory address. These variables hold the index in the store node
10652   // array.
10653   unsigned LastConsecutiveLoad = 0;
10654   // This variable refers to the size and not index in the array.
10655   unsigned LastLegalVectorType = 0;
10656   unsigned LastLegalIntegerType = 0;
10657   StartAddress = LoadNodes[0].OffsetFromBase;
10658   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10659   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10660     // All loads much share the same chain.
10661     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10662       break;
10663
10664     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10665     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10666       break;
10667     LastConsecutiveLoad = i;
10668
10669     // Find a legal type for the vector store.
10670     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10671     if (TLI.isTypeLegal(StoreTy))
10672       LastLegalVectorType = i + 1;
10673
10674     // Find a legal type for the integer store.
10675     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10676     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10677     if (TLI.isTypeLegal(StoreTy))
10678       LastLegalIntegerType = i + 1;
10679     // Or check whether a truncstore and extload is legal.
10680     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10681              TargetLowering::TypePromoteInteger) {
10682       EVT LegalizedStoredValueTy =
10683         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10684       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10685           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10686           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10687           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10688         LastLegalIntegerType = i+1;
10689     }
10690   }
10691
10692   // Only use vector types if the vector type is larger than the integer type.
10693   // If they are the same, use integers.
10694   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10695   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10696
10697   // We add +1 here because the LastXXX variables refer to location while
10698   // the NumElem refers to array/index size.
10699   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10700   NumElem = std::min(LastLegalType, NumElem);
10701
10702   if (NumElem < 2)
10703     return false;
10704
10705   // The latest Node in the DAG.
10706   unsigned LatestNodeUsed = 0;
10707   for (unsigned i=1; i<NumElem; ++i) {
10708     // Find a chain for the new wide-store operand. Notice that some
10709     // of the store nodes that we found may not be selected for inclusion
10710     // in the wide store. The chain we use needs to be the chain of the
10711     // latest store node which is *used* and replaced by the wide store.
10712     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10713       LatestNodeUsed = i;
10714   }
10715
10716   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10717
10718   // Find if it is better to use vectors or integers to load and store
10719   // to memory.
10720   EVT JointMemOpVT;
10721   if (UseVectorTy) {
10722     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10723   } else {
10724     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10725     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10726   }
10727
10728   SDLoc LoadDL(LoadNodes[0].MemNode);
10729   SDLoc StoreDL(StoreNodes[0].MemNode);
10730
10731   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10732   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10733                                 FirstLoad->getChain(),
10734                                 FirstLoad->getBasePtr(),
10735                                 FirstLoad->getPointerInfo(),
10736                                 false, false, false,
10737                                 FirstLoad->getAlignment());
10738
10739   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10740                                   FirstInChain->getBasePtr(),
10741                                   FirstInChain->getPointerInfo(), false, false,
10742                                   FirstInChain->getAlignment());
10743
10744   // Replace one of the loads with the new load.
10745   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10746   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10747                                 SDValue(NewLoad.getNode(), 1));
10748
10749   // Remove the rest of the load chains.
10750   for (unsigned i = 1; i < NumElem ; ++i) {
10751     // Replace all chain users of the old load nodes with the chain of the new
10752     // load node.
10753     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10754     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10755   }
10756
10757   // Replace the last store with the new store.
10758   CombineTo(LatestOp, NewStore);
10759   // Erase all other stores.
10760   for (unsigned i = 0; i < NumElem ; ++i) {
10761     // Remove all Store nodes.
10762     if (StoreNodes[i].MemNode == LatestOp)
10763       continue;
10764     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10765     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10766     deleteAndRecombine(St);
10767   }
10768
10769   return true;
10770 }
10771
10772 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10773   StoreSDNode *ST  = cast<StoreSDNode>(N);
10774   SDValue Chain = ST->getChain();
10775   SDValue Value = ST->getValue();
10776   SDValue Ptr   = ST->getBasePtr();
10777
10778   // If this is a store of a bit convert, store the input value if the
10779   // resultant store does not need a higher alignment than the original.
10780   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10781       ST->isUnindexed()) {
10782     unsigned OrigAlign = ST->getAlignment();
10783     EVT SVT = Value.getOperand(0).getValueType();
10784     unsigned Align = TLI.getDataLayout()->
10785       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10786     if (Align <= OrigAlign &&
10787         ((!LegalOperations && !ST->isVolatile()) ||
10788          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10789       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10790                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10791                           ST->isNonTemporal(), OrigAlign,
10792                           ST->getAAInfo());
10793   }
10794
10795   // Turn 'store undef, Ptr' -> nothing.
10796   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10797     return Chain;
10798
10799   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10800   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10801     // NOTE: If the original store is volatile, this transform must not increase
10802     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10803     // processor operation but an i64 (which is not legal) requires two.  So the
10804     // transform should not be done in this case.
10805     if (Value.getOpcode() != ISD::TargetConstantFP) {
10806       SDValue Tmp;
10807       switch (CFP->getSimpleValueType(0).SimpleTy) {
10808       default: llvm_unreachable("Unknown FP type");
10809       case MVT::f16:    // We don't do this for these yet.
10810       case MVT::f80:
10811       case MVT::f128:
10812       case MVT::ppcf128:
10813         break;
10814       case MVT::f32:
10815         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10816             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10817           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10818                               bitcastToAPInt().getZExtValue(), MVT::i32);
10819           return DAG.getStore(Chain, SDLoc(N), Tmp,
10820                               Ptr, ST->getMemOperand());
10821         }
10822         break;
10823       case MVT::f64:
10824         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10825              !ST->isVolatile()) ||
10826             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10827           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10828                                 getZExtValue(), MVT::i64);
10829           return DAG.getStore(Chain, SDLoc(N), Tmp,
10830                               Ptr, ST->getMemOperand());
10831         }
10832
10833         if (!ST->isVolatile() &&
10834             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10835           // Many FP stores are not made apparent until after legalize, e.g. for
10836           // argument passing.  Since this is so common, custom legalize the
10837           // 64-bit integer store into two 32-bit stores.
10838           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10839           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10840           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10841           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10842
10843           unsigned Alignment = ST->getAlignment();
10844           bool isVolatile = ST->isVolatile();
10845           bool isNonTemporal = ST->isNonTemporal();
10846           AAMDNodes AAInfo = ST->getAAInfo();
10847
10848           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10849                                      Ptr, ST->getPointerInfo(),
10850                                      isVolatile, isNonTemporal,
10851                                      ST->getAlignment(), AAInfo);
10852           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10853                             DAG.getConstant(4, Ptr.getValueType()));
10854           Alignment = MinAlign(Alignment, 4U);
10855           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10856                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10857                                      isVolatile, isNonTemporal,
10858                                      Alignment, AAInfo);
10859           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10860                              St0, St1);
10861         }
10862
10863         break;
10864       }
10865     }
10866   }
10867
10868   // Try to infer better alignment information than the store already has.
10869   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10870     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10871       if (Align > ST->getAlignment()) {
10872         SDValue NewStore =
10873                DAG.getTruncStore(Chain, SDLoc(N), Value,
10874                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10875                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10876                                  ST->getAAInfo());
10877         if (NewStore.getNode() != N)
10878           return CombineTo(ST, NewStore, true);
10879       }
10880     }
10881   }
10882
10883   // Try transforming a pair floating point load / store ops to integer
10884   // load / store ops.
10885   SDValue NewST = TransformFPLoadStorePair(N);
10886   if (NewST.getNode())
10887     return NewST;
10888
10889   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10890                                                   : DAG.getSubtarget().useAA();
10891 #ifndef NDEBUG
10892   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10893       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10894     UseAA = false;
10895 #endif
10896   if (UseAA && ST->isUnindexed()) {
10897     // Walk up chain skipping non-aliasing memory nodes.
10898     SDValue BetterChain = FindBetterChain(N, Chain);
10899
10900     // If there is a better chain.
10901     if (Chain != BetterChain) {
10902       SDValue ReplStore;
10903
10904       // Replace the chain to avoid dependency.
10905       if (ST->isTruncatingStore()) {
10906         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10907                                       ST->getMemoryVT(), ST->getMemOperand());
10908       } else {
10909         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10910                                  ST->getMemOperand());
10911       }
10912
10913       // Create token to keep both nodes around.
10914       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10915                                   MVT::Other, Chain, ReplStore);
10916
10917       // Make sure the new and old chains are cleaned up.
10918       AddToWorklist(Token.getNode());
10919
10920       // Don't add users to work list.
10921       return CombineTo(N, Token, false);
10922     }
10923   }
10924
10925   // Try transforming N to an indexed store.
10926   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10927     return SDValue(N, 0);
10928
10929   // FIXME: is there such a thing as a truncating indexed store?
10930   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10931       Value.getValueType().isInteger()) {
10932     // See if we can simplify the input to this truncstore with knowledge that
10933     // only the low bits are being used.  For example:
10934     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10935     SDValue Shorter =
10936       GetDemandedBits(Value,
10937                       APInt::getLowBitsSet(
10938                         Value.getValueType().getScalarType().getSizeInBits(),
10939                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10940     AddToWorklist(Value.getNode());
10941     if (Shorter.getNode())
10942       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10943                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10944
10945     // Otherwise, see if we can simplify the operation with
10946     // SimplifyDemandedBits, which only works if the value has a single use.
10947     if (SimplifyDemandedBits(Value,
10948                         APInt::getLowBitsSet(
10949                           Value.getValueType().getScalarType().getSizeInBits(),
10950                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10951       return SDValue(N, 0);
10952   }
10953
10954   // If this is a load followed by a store to the same location, then the store
10955   // is dead/noop.
10956   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10957     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10958         ST->isUnindexed() && !ST->isVolatile() &&
10959         // There can't be any side effects between the load and store, such as
10960         // a call or store.
10961         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10962       // The store is dead, remove it.
10963       return Chain;
10964     }
10965   }
10966
10967   // If this is a store followed by a store with the same value to the same
10968   // location, then the store is dead/noop.
10969   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10970     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10971         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10972         ST1->isUnindexed() && !ST1->isVolatile()) {
10973       // The store is dead, remove it.
10974       return Chain;
10975     }
10976   }
10977
10978   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10979   // truncating store.  We can do this even if this is already a truncstore.
10980   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10981       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10982       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10983                             ST->getMemoryVT())) {
10984     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10985                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10986   }
10987
10988   // Only perform this optimization before the types are legal, because we
10989   // don't want to perform this optimization on every DAGCombine invocation.
10990   if (!LegalTypes) {
10991     bool EverChanged = false;
10992
10993     do {
10994       // There can be multiple store sequences on the same chain.
10995       // Keep trying to merge store sequences until we are unable to do so
10996       // or until we merge the last store on the chain.
10997       bool Changed = MergeConsecutiveStores(ST);
10998       EverChanged |= Changed;
10999       if (!Changed) break;
11000     } while (ST->getOpcode() != ISD::DELETED_NODE);
11001
11002     if (EverChanged)
11003       return SDValue(N, 0);
11004   }
11005
11006   return ReduceLoadOpStoreWidth(N);
11007 }
11008
11009 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11010   SDValue InVec = N->getOperand(0);
11011   SDValue InVal = N->getOperand(1);
11012   SDValue EltNo = N->getOperand(2);
11013   SDLoc dl(N);
11014
11015   // If the inserted element is an UNDEF, just use the input vector.
11016   if (InVal.getOpcode() == ISD::UNDEF)
11017     return InVec;
11018
11019   EVT VT = InVec.getValueType();
11020
11021   // If we can't generate a legal BUILD_VECTOR, exit
11022   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11023     return SDValue();
11024
11025   // Check that we know which element is being inserted
11026   if (!isa<ConstantSDNode>(EltNo))
11027     return SDValue();
11028   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11029
11030   // Canonicalize insert_vector_elt dag nodes.
11031   // Example:
11032   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11033   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11034   //
11035   // Do this only if the child insert_vector node has one use; also
11036   // do this only if indices are both constants and Idx1 < Idx0.
11037   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11038       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11039     unsigned OtherElt =
11040       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11041     if (Elt < OtherElt) {
11042       // Swap nodes.
11043       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11044                                   InVec.getOperand(0), InVal, EltNo);
11045       AddToWorklist(NewOp.getNode());
11046       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11047                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11048     }
11049   }
11050
11051   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11052   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11053   // vector elements.
11054   SmallVector<SDValue, 8> Ops;
11055   // Do not combine these two vectors if the output vector will not replace
11056   // the input vector.
11057   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11058     Ops.append(InVec.getNode()->op_begin(),
11059                InVec.getNode()->op_end());
11060   } else if (InVec.getOpcode() == ISD::UNDEF) {
11061     unsigned NElts = VT.getVectorNumElements();
11062     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11063   } else {
11064     return SDValue();
11065   }
11066
11067   // Insert the element
11068   if (Elt < Ops.size()) {
11069     // All the operands of BUILD_VECTOR must have the same type;
11070     // we enforce that here.
11071     EVT OpVT = Ops[0].getValueType();
11072     if (InVal.getValueType() != OpVT)
11073       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11074                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11075                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11076     Ops[Elt] = InVal;
11077   }
11078
11079   // Return the new vector
11080   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11081 }
11082
11083 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11084     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11085   EVT ResultVT = EVE->getValueType(0);
11086   EVT VecEltVT = InVecVT.getVectorElementType();
11087   unsigned Align = OriginalLoad->getAlignment();
11088   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11089       VecEltVT.getTypeForEVT(*DAG.getContext()));
11090
11091   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11092     return SDValue();
11093
11094   Align = NewAlign;
11095
11096   SDValue NewPtr = OriginalLoad->getBasePtr();
11097   SDValue Offset;
11098   EVT PtrType = NewPtr.getValueType();
11099   MachinePointerInfo MPI;
11100   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11101     int Elt = ConstEltNo->getZExtValue();
11102     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11103     if (TLI.isBigEndian())
11104       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11105     Offset = DAG.getConstant(PtrOff, PtrType);
11106     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11107   } else {
11108     Offset = DAG.getNode(
11109         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
11110         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
11111     if (TLI.isBigEndian())
11112       Offset = DAG.getNode(
11113           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
11114           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
11115     MPI = OriginalLoad->getPointerInfo();
11116   }
11117   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
11118
11119   // The replacement we need to do here is a little tricky: we need to
11120   // replace an extractelement of a load with a load.
11121   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11122   // Note that this replacement assumes that the extractvalue is the only
11123   // use of the load; that's okay because we don't want to perform this
11124   // transformation in other cases anyway.
11125   SDValue Load;
11126   SDValue Chain;
11127   if (ResultVT.bitsGT(VecEltVT)) {
11128     // If the result type of vextract is wider than the load, then issue an
11129     // extending load instead.
11130     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11131                                                   VecEltVT)
11132                                    ? ISD::ZEXTLOAD
11133                                    : ISD::EXTLOAD;
11134     Load = DAG.getExtLoad(
11135         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11136         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11137         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11138     Chain = Load.getValue(1);
11139   } else {
11140     Load = DAG.getLoad(
11141         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11142         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11143         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11144     Chain = Load.getValue(1);
11145     if (ResultVT.bitsLT(VecEltVT))
11146       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11147     else
11148       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11149   }
11150   WorklistRemover DeadNodes(*this);
11151   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11152   SDValue To[] = { Load, Chain };
11153   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11154   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11155   // worklist explicitly as well.
11156   AddToWorklist(Load.getNode());
11157   AddUsersToWorklist(Load.getNode()); // Add users too
11158   // Make sure to revisit this node to clean it up; it will usually be dead.
11159   AddToWorklist(EVE);
11160   ++OpsNarrowed;
11161   return SDValue(EVE, 0);
11162 }
11163
11164 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11165   // (vextract (scalar_to_vector val, 0) -> val
11166   SDValue InVec = N->getOperand(0);
11167   EVT VT = InVec.getValueType();
11168   EVT NVT = N->getValueType(0);
11169
11170   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11171     // Check if the result type doesn't match the inserted element type. A
11172     // SCALAR_TO_VECTOR may truncate the inserted element and the
11173     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11174     SDValue InOp = InVec.getOperand(0);
11175     if (InOp.getValueType() != NVT) {
11176       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11177       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11178     }
11179     return InOp;
11180   }
11181
11182   SDValue EltNo = N->getOperand(1);
11183   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11184
11185   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11186   // We only perform this optimization before the op legalization phase because
11187   // we may introduce new vector instructions which are not backed by TD
11188   // patterns. For example on AVX, extracting elements from a wide vector
11189   // without using extract_subvector. However, if we can find an underlying
11190   // scalar value, then we can always use that.
11191   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11192       && ConstEltNo) {
11193     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11194     int NumElem = VT.getVectorNumElements();
11195     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11196     // Find the new index to extract from.
11197     int OrigElt = SVOp->getMaskElt(Elt);
11198
11199     // Extracting an undef index is undef.
11200     if (OrigElt == -1)
11201       return DAG.getUNDEF(NVT);
11202
11203     // Select the right vector half to extract from.
11204     SDValue SVInVec;
11205     if (OrigElt < NumElem) {
11206       SVInVec = InVec->getOperand(0);
11207     } else {
11208       SVInVec = InVec->getOperand(1);
11209       OrigElt -= NumElem;
11210     }
11211
11212     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11213       SDValue InOp = SVInVec.getOperand(OrigElt);
11214       if (InOp.getValueType() != NVT) {
11215         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11216         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11217       }
11218
11219       return InOp;
11220     }
11221
11222     // FIXME: We should handle recursing on other vector shuffles and
11223     // scalar_to_vector here as well.
11224
11225     if (!LegalOperations) {
11226       EVT IndexTy = TLI.getVectorIdxTy();
11227       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11228                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
11229     }
11230   }
11231
11232   bool BCNumEltsChanged = false;
11233   EVT ExtVT = VT.getVectorElementType();
11234   EVT LVT = ExtVT;
11235
11236   // If the result of load has to be truncated, then it's not necessarily
11237   // profitable.
11238   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11239     return SDValue();
11240
11241   if (InVec.getOpcode() == ISD::BITCAST) {
11242     // Don't duplicate a load with other uses.
11243     if (!InVec.hasOneUse())
11244       return SDValue();
11245
11246     EVT BCVT = InVec.getOperand(0).getValueType();
11247     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11248       return SDValue();
11249     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11250       BCNumEltsChanged = true;
11251     InVec = InVec.getOperand(0);
11252     ExtVT = BCVT.getVectorElementType();
11253   }
11254
11255   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11256   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11257       ISD::isNormalLoad(InVec.getNode()) &&
11258       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11259     SDValue Index = N->getOperand(1);
11260     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11261       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11262                                                            OrigLoad);
11263   }
11264
11265   // Perform only after legalization to ensure build_vector / vector_shuffle
11266   // optimizations have already been done.
11267   if (!LegalOperations) return SDValue();
11268
11269   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11270   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11271   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11272
11273   if (ConstEltNo) {
11274     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11275
11276     LoadSDNode *LN0 = nullptr;
11277     const ShuffleVectorSDNode *SVN = nullptr;
11278     if (ISD::isNormalLoad(InVec.getNode())) {
11279       LN0 = cast<LoadSDNode>(InVec);
11280     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11281                InVec.getOperand(0).getValueType() == ExtVT &&
11282                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11283       // Don't duplicate a load with other uses.
11284       if (!InVec.hasOneUse())
11285         return SDValue();
11286
11287       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11288     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11289       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11290       // =>
11291       // (load $addr+1*size)
11292
11293       // Don't duplicate a load with other uses.
11294       if (!InVec.hasOneUse())
11295         return SDValue();
11296
11297       // If the bit convert changed the number of elements, it is unsafe
11298       // to examine the mask.
11299       if (BCNumEltsChanged)
11300         return SDValue();
11301
11302       // Select the input vector, guarding against out of range extract vector.
11303       unsigned NumElems = VT.getVectorNumElements();
11304       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11305       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11306
11307       if (InVec.getOpcode() == ISD::BITCAST) {
11308         // Don't duplicate a load with other uses.
11309         if (!InVec.hasOneUse())
11310           return SDValue();
11311
11312         InVec = InVec.getOperand(0);
11313       }
11314       if (ISD::isNormalLoad(InVec.getNode())) {
11315         LN0 = cast<LoadSDNode>(InVec);
11316         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11317         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11318       }
11319     }
11320
11321     // Make sure we found a non-volatile load and the extractelement is
11322     // the only use.
11323     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11324       return SDValue();
11325
11326     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11327     if (Elt == -1)
11328       return DAG.getUNDEF(LVT);
11329
11330     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11331   }
11332
11333   return SDValue();
11334 }
11335
11336 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11337 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11338   // We perform this optimization post type-legalization because
11339   // the type-legalizer often scalarizes integer-promoted vectors.
11340   // Performing this optimization before may create bit-casts which
11341   // will be type-legalized to complex code sequences.
11342   // We perform this optimization only before the operation legalizer because we
11343   // may introduce illegal operations.
11344   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11345     return SDValue();
11346
11347   unsigned NumInScalars = N->getNumOperands();
11348   SDLoc dl(N);
11349   EVT VT = N->getValueType(0);
11350
11351   // Check to see if this is a BUILD_VECTOR of a bunch of values
11352   // which come from any_extend or zero_extend nodes. If so, we can create
11353   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11354   // optimizations. We do not handle sign-extend because we can't fill the sign
11355   // using shuffles.
11356   EVT SourceType = MVT::Other;
11357   bool AllAnyExt = true;
11358
11359   for (unsigned i = 0; i != NumInScalars; ++i) {
11360     SDValue In = N->getOperand(i);
11361     // Ignore undef inputs.
11362     if (In.getOpcode() == ISD::UNDEF) continue;
11363
11364     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11365     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11366
11367     // Abort if the element is not an extension.
11368     if (!ZeroExt && !AnyExt) {
11369       SourceType = MVT::Other;
11370       break;
11371     }
11372
11373     // The input is a ZeroExt or AnyExt. Check the original type.
11374     EVT InTy = In.getOperand(0).getValueType();
11375
11376     // Check that all of the widened source types are the same.
11377     if (SourceType == MVT::Other)
11378       // First time.
11379       SourceType = InTy;
11380     else if (InTy != SourceType) {
11381       // Multiple income types. Abort.
11382       SourceType = MVT::Other;
11383       break;
11384     }
11385
11386     // Check if all of the extends are ANY_EXTENDs.
11387     AllAnyExt &= AnyExt;
11388   }
11389
11390   // In order to have valid types, all of the inputs must be extended from the
11391   // same source type and all of the inputs must be any or zero extend.
11392   // Scalar sizes must be a power of two.
11393   EVT OutScalarTy = VT.getScalarType();
11394   bool ValidTypes = SourceType != MVT::Other &&
11395                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11396                  isPowerOf2_32(SourceType.getSizeInBits());
11397
11398   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11399   // turn into a single shuffle instruction.
11400   if (!ValidTypes)
11401     return SDValue();
11402
11403   bool isLE = TLI.isLittleEndian();
11404   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11405   assert(ElemRatio > 1 && "Invalid element size ratio");
11406   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11407                                DAG.getConstant(0, SourceType);
11408
11409   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11410   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11411
11412   // Populate the new build_vector
11413   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11414     SDValue Cast = N->getOperand(i);
11415     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11416             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11417             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11418     SDValue In;
11419     if (Cast.getOpcode() == ISD::UNDEF)
11420       In = DAG.getUNDEF(SourceType);
11421     else
11422       In = Cast->getOperand(0);
11423     unsigned Index = isLE ? (i * ElemRatio) :
11424                             (i * ElemRatio + (ElemRatio - 1));
11425
11426     assert(Index < Ops.size() && "Invalid index");
11427     Ops[Index] = In;
11428   }
11429
11430   // The type of the new BUILD_VECTOR node.
11431   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11432   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11433          "Invalid vector size");
11434   // Check if the new vector type is legal.
11435   if (!isTypeLegal(VecVT)) return SDValue();
11436
11437   // Make the new BUILD_VECTOR.
11438   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11439
11440   // The new BUILD_VECTOR node has the potential to be further optimized.
11441   AddToWorklist(BV.getNode());
11442   // Bitcast to the desired type.
11443   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11444 }
11445
11446 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11447   EVT VT = N->getValueType(0);
11448
11449   unsigned NumInScalars = N->getNumOperands();
11450   SDLoc dl(N);
11451
11452   EVT SrcVT = MVT::Other;
11453   unsigned Opcode = ISD::DELETED_NODE;
11454   unsigned NumDefs = 0;
11455
11456   for (unsigned i = 0; i != NumInScalars; ++i) {
11457     SDValue In = N->getOperand(i);
11458     unsigned Opc = In.getOpcode();
11459
11460     if (Opc == ISD::UNDEF)
11461       continue;
11462
11463     // If all scalar values are floats and converted from integers.
11464     if (Opcode == ISD::DELETED_NODE &&
11465         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11466       Opcode = Opc;
11467     }
11468
11469     if (Opc != Opcode)
11470       return SDValue();
11471
11472     EVT InVT = In.getOperand(0).getValueType();
11473
11474     // If all scalar values are typed differently, bail out. It's chosen to
11475     // simplify BUILD_VECTOR of integer types.
11476     if (SrcVT == MVT::Other)
11477       SrcVT = InVT;
11478     if (SrcVT != InVT)
11479       return SDValue();
11480     NumDefs++;
11481   }
11482
11483   // If the vector has just one element defined, it's not worth to fold it into
11484   // a vectorized one.
11485   if (NumDefs < 2)
11486     return SDValue();
11487
11488   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11489          && "Should only handle conversion from integer to float.");
11490   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11491
11492   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11493
11494   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11495     return SDValue();
11496
11497   // Just because the floating-point vector type is legal does not necessarily
11498   // mean that the corresponding integer vector type is.
11499   if (!isTypeLegal(NVT))
11500     return SDValue();
11501
11502   SmallVector<SDValue, 8> Opnds;
11503   for (unsigned i = 0; i != NumInScalars; ++i) {
11504     SDValue In = N->getOperand(i);
11505
11506     if (In.getOpcode() == ISD::UNDEF)
11507       Opnds.push_back(DAG.getUNDEF(SrcVT));
11508     else
11509       Opnds.push_back(In.getOperand(0));
11510   }
11511   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11512   AddToWorklist(BV.getNode());
11513
11514   return DAG.getNode(Opcode, dl, VT, BV);
11515 }
11516
11517 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11518   unsigned NumInScalars = N->getNumOperands();
11519   SDLoc dl(N);
11520   EVT VT = N->getValueType(0);
11521
11522   // A vector built entirely of undefs is undef.
11523   if (ISD::allOperandsUndef(N))
11524     return DAG.getUNDEF(VT);
11525
11526   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11527     return V;
11528
11529   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11530     return V;
11531
11532   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11533   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11534   // at most two distinct vectors, turn this into a shuffle node.
11535
11536   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11537   if (!isTypeLegal(VT))
11538     return SDValue();
11539
11540   // May only combine to shuffle after legalize if shuffle is legal.
11541   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11542     return SDValue();
11543
11544   SDValue VecIn1, VecIn2;
11545   bool UsesZeroVector = false;
11546   for (unsigned i = 0; i != NumInScalars; ++i) {
11547     SDValue Op = N->getOperand(i);
11548     // Ignore undef inputs.
11549     if (Op.getOpcode() == ISD::UNDEF) continue;
11550
11551     // See if we can combine this build_vector into a blend with a zero vector.
11552     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11553         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11554         (Op.getOpcode() == ISD::ConstantFP &&
11555         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11556       UsesZeroVector = true;
11557       continue;
11558     }
11559
11560     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11561     // constant index, bail out.
11562     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11563         !isa<ConstantSDNode>(Op.getOperand(1))) {
11564       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11565       break;
11566     }
11567
11568     // We allow up to two distinct input vectors.
11569     SDValue ExtractedFromVec = Op.getOperand(0);
11570     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11571       continue;
11572
11573     if (!VecIn1.getNode()) {
11574       VecIn1 = ExtractedFromVec;
11575     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11576       VecIn2 = ExtractedFromVec;
11577     } else {
11578       // Too many inputs.
11579       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11580       break;
11581     }
11582   }
11583
11584   // If everything is good, we can make a shuffle operation.
11585   if (VecIn1.getNode()) {
11586     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11587     SmallVector<int, 8> Mask;
11588     for (unsigned i = 0; i != NumInScalars; ++i) {
11589       unsigned Opcode = N->getOperand(i).getOpcode();
11590       if (Opcode == ISD::UNDEF) {
11591         Mask.push_back(-1);
11592         continue;
11593       }
11594
11595       // Operands can also be zero.
11596       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11597         assert(UsesZeroVector &&
11598                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11599                "Unexpected node found!");
11600         Mask.push_back(NumInScalars+i);
11601         continue;
11602       }
11603
11604       // If extracting from the first vector, just use the index directly.
11605       SDValue Extract = N->getOperand(i);
11606       SDValue ExtVal = Extract.getOperand(1);
11607       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11608       if (Extract.getOperand(0) == VecIn1) {
11609         Mask.push_back(ExtIndex);
11610         continue;
11611       }
11612
11613       // Otherwise, use InIdx + InputVecSize
11614       Mask.push_back(InNumElements + ExtIndex);
11615     }
11616
11617     // Avoid introducing illegal shuffles with zero.
11618     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11619       return SDValue();
11620
11621     // We can't generate a shuffle node with mismatched input and output types.
11622     // Attempt to transform a single input vector to the correct type.
11623     if ((VT != VecIn1.getValueType())) {
11624       // If the input vector type has a different base type to the output
11625       // vector type, bail out.
11626       EVT VTElemType = VT.getVectorElementType();
11627       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11628           (VecIn2.getNode() &&
11629            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11630         return SDValue();
11631
11632       // If the input vector is too small, widen it.
11633       // We only support widening of vectors which are half the size of the
11634       // output registers. For example XMM->YMM widening on X86 with AVX.
11635       EVT VecInT = VecIn1.getValueType();
11636       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11637         // If we only have one small input, widen it by adding undef values.
11638         if (!VecIn2.getNode())
11639           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11640                                DAG.getUNDEF(VecIn1.getValueType()));
11641         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11642           // If we have two small inputs of the same type, try to concat them.
11643           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11644           VecIn2 = SDValue(nullptr, 0);
11645         } else
11646           return SDValue();
11647       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11648         // If the input vector is too large, try to split it.
11649         // We don't support having two input vectors that are too large.
11650         // If the zero vector was used, we can not split the vector,
11651         // since we'd need 3 inputs.
11652         if (UsesZeroVector || VecIn2.getNode())
11653           return SDValue();
11654
11655         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11656           return SDValue();
11657
11658         // Try to replace VecIn1 with two extract_subvectors
11659         // No need to update the masks, they should still be correct.
11660         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11661           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11662         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11663           DAG.getConstant(0, TLI.getVectorIdxTy()));
11664       } else
11665         return SDValue();
11666     }
11667
11668     if (UsesZeroVector)
11669       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11670                                 DAG.getConstantFP(0.0, VT);
11671     else
11672       // If VecIn2 is unused then change it to undef.
11673       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11674
11675     // Check that we were able to transform all incoming values to the same
11676     // type.
11677     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11678         VecIn1.getValueType() != VT)
11679           return SDValue();
11680
11681     // Return the new VECTOR_SHUFFLE node.
11682     SDValue Ops[2];
11683     Ops[0] = VecIn1;
11684     Ops[1] = VecIn2;
11685     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11686   }
11687
11688   return SDValue();
11689 }
11690
11691 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11692   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11693   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11694   // inputs come from at most two distinct vectors, turn this into a shuffle
11695   // node.
11696
11697   // If we only have one input vector, we don't need to do any concatenation.
11698   if (N->getNumOperands() == 1)
11699     return N->getOperand(0);
11700
11701   // Check if all of the operands are undefs.
11702   EVT VT = N->getValueType(0);
11703   if (ISD::allOperandsUndef(N))
11704     return DAG.getUNDEF(VT);
11705
11706   // Optimize concat_vectors where one of the vectors is undef.
11707   if (N->getNumOperands() == 2 &&
11708       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11709     SDValue In = N->getOperand(0);
11710     assert(In.getValueType().isVector() && "Must concat vectors");
11711
11712     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11713     if (In->getOpcode() == ISD::BITCAST &&
11714         !In->getOperand(0)->getValueType(0).isVector()) {
11715       SDValue Scalar = In->getOperand(0);
11716       EVT SclTy = Scalar->getValueType(0);
11717
11718       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11719         return SDValue();
11720
11721       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11722                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11723       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11724         return SDValue();
11725
11726       SDLoc dl = SDLoc(N);
11727       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11728       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11729     }
11730   }
11731
11732   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11733   // We have already tested above for an UNDEF only concatenation.
11734   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11735   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11736   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11737     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11738   };
11739   bool AllBuildVectorsOrUndefs =
11740       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11741   if (AllBuildVectorsOrUndefs) {
11742     SmallVector<SDValue, 8> Opnds;
11743     EVT SVT = VT.getScalarType();
11744
11745     EVT MinVT = SVT;
11746     if (!SVT.isFloatingPoint()) {
11747       // If BUILD_VECTOR are from built from integer, they may have different
11748       // operand types. Get the smallest type and truncate all operands to it.
11749       bool FoundMinVT = false;
11750       for (const SDValue &Op : N->ops())
11751         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11752           EVT OpSVT = Op.getOperand(0)->getValueType(0);
11753           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11754           FoundMinVT = true;
11755         }
11756       assert(FoundMinVT && "Concat vector type mismatch");
11757     }
11758
11759     for (const SDValue &Op : N->ops()) {
11760       EVT OpVT = Op.getValueType();
11761       unsigned NumElts = OpVT.getVectorNumElements();
11762
11763       if (ISD::UNDEF == Op.getOpcode())
11764         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11765
11766       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11767         if (SVT.isFloatingPoint()) {
11768           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11769           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11770         } else {
11771           for (unsigned i = 0; i != NumElts; ++i)
11772             Opnds.push_back(
11773                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11774         }
11775       }
11776     }
11777
11778     assert(VT.getVectorNumElements() == Opnds.size() &&
11779            "Concat vector type mismatch");
11780     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11781   }
11782
11783   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11784   // nodes often generate nop CONCAT_VECTOR nodes.
11785   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11786   // place the incoming vectors at the exact same location.
11787   SDValue SingleSource = SDValue();
11788   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11789
11790   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11791     SDValue Op = N->getOperand(i);
11792
11793     if (Op.getOpcode() == ISD::UNDEF)
11794       continue;
11795
11796     // Check if this is the identity extract:
11797     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11798       return SDValue();
11799
11800     // Find the single incoming vector for the extract_subvector.
11801     if (SingleSource.getNode()) {
11802       if (Op.getOperand(0) != SingleSource)
11803         return SDValue();
11804     } else {
11805       SingleSource = Op.getOperand(0);
11806
11807       // Check the source type is the same as the type of the result.
11808       // If not, this concat may extend the vector, so we can not
11809       // optimize it away.
11810       if (SingleSource.getValueType() != N->getValueType(0))
11811         return SDValue();
11812     }
11813
11814     unsigned IdentityIndex = i * PartNumElem;
11815     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11816     // The extract index must be constant.
11817     if (!CS)
11818       return SDValue();
11819
11820     // Check that we are reading from the identity index.
11821     if (CS->getZExtValue() != IdentityIndex)
11822       return SDValue();
11823   }
11824
11825   if (SingleSource.getNode())
11826     return SingleSource;
11827
11828   return SDValue();
11829 }
11830
11831 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11832   EVT NVT = N->getValueType(0);
11833   SDValue V = N->getOperand(0);
11834
11835   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11836     // Combine:
11837     //    (extract_subvec (concat V1, V2, ...), i)
11838     // Into:
11839     //    Vi if possible
11840     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11841     // type.
11842     if (V->getOperand(0).getValueType() != NVT)
11843       return SDValue();
11844     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11845     unsigned NumElems = NVT.getVectorNumElements();
11846     assert((Idx % NumElems) == 0 &&
11847            "IDX in concat is not a multiple of the result vector length.");
11848     return V->getOperand(Idx / NumElems);
11849   }
11850
11851   // Skip bitcasting
11852   if (V->getOpcode() == ISD::BITCAST)
11853     V = V.getOperand(0);
11854
11855   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11856     SDLoc dl(N);
11857     // Handle only simple case where vector being inserted and vector
11858     // being extracted are of same type, and are half size of larger vectors.
11859     EVT BigVT = V->getOperand(0).getValueType();
11860     EVT SmallVT = V->getOperand(1).getValueType();
11861     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11862       return SDValue();
11863
11864     // Only handle cases where both indexes are constants with the same type.
11865     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11866     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11867
11868     if (InsIdx && ExtIdx &&
11869         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11870         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11871       // Combine:
11872       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11873       // Into:
11874       //    indices are equal or bit offsets are equal => V1
11875       //    otherwise => (extract_subvec V1, ExtIdx)
11876       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11877           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11878         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11879       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11880                          DAG.getNode(ISD::BITCAST, dl,
11881                                      N->getOperand(0).getValueType(),
11882                                      V->getOperand(0)), N->getOperand(1));
11883     }
11884   }
11885
11886   return SDValue();
11887 }
11888
11889 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11890                                                  SDValue V, SelectionDAG &DAG) {
11891   SDLoc DL(V);
11892   EVT VT = V.getValueType();
11893
11894   switch (V.getOpcode()) {
11895   default:
11896     return V;
11897
11898   case ISD::CONCAT_VECTORS: {
11899     EVT OpVT = V->getOperand(0).getValueType();
11900     int OpSize = OpVT.getVectorNumElements();
11901     SmallBitVector OpUsedElements(OpSize, false);
11902     bool FoundSimplification = false;
11903     SmallVector<SDValue, 4> NewOps;
11904     NewOps.reserve(V->getNumOperands());
11905     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11906       SDValue Op = V->getOperand(i);
11907       bool OpUsed = false;
11908       for (int j = 0; j < OpSize; ++j)
11909         if (UsedElements[i * OpSize + j]) {
11910           OpUsedElements[j] = true;
11911           OpUsed = true;
11912         }
11913       NewOps.push_back(
11914           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11915                  : DAG.getUNDEF(OpVT));
11916       FoundSimplification |= Op == NewOps.back();
11917       OpUsedElements.reset();
11918     }
11919     if (FoundSimplification)
11920       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11921     return V;
11922   }
11923
11924   case ISD::INSERT_SUBVECTOR: {
11925     SDValue BaseV = V->getOperand(0);
11926     SDValue SubV = V->getOperand(1);
11927     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11928     if (!IdxN)
11929       return V;
11930
11931     int SubSize = SubV.getValueType().getVectorNumElements();
11932     int Idx = IdxN->getZExtValue();
11933     bool SubVectorUsed = false;
11934     SmallBitVector SubUsedElements(SubSize, false);
11935     for (int i = 0; i < SubSize; ++i)
11936       if (UsedElements[i + Idx]) {
11937         SubVectorUsed = true;
11938         SubUsedElements[i] = true;
11939         UsedElements[i + Idx] = false;
11940       }
11941
11942     // Now recurse on both the base and sub vectors.
11943     SDValue SimplifiedSubV =
11944         SubVectorUsed
11945             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11946             : DAG.getUNDEF(SubV.getValueType());
11947     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11948     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11949       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11950                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11951     return V;
11952   }
11953   }
11954 }
11955
11956 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11957                                        SDValue N1, SelectionDAG &DAG) {
11958   EVT VT = SVN->getValueType(0);
11959   int NumElts = VT.getVectorNumElements();
11960   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11961   for (int M : SVN->getMask())
11962     if (M >= 0 && M < NumElts)
11963       N0UsedElements[M] = true;
11964     else if (M >= NumElts)
11965       N1UsedElements[M - NumElts] = true;
11966
11967   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11968   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11969   if (S0 == N0 && S1 == N1)
11970     return SDValue();
11971
11972   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11973 }
11974
11975 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11976 // or turn a shuffle of a single concat into simpler shuffle then concat.
11977 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11978   EVT VT = N->getValueType(0);
11979   unsigned NumElts = VT.getVectorNumElements();
11980
11981   SDValue N0 = N->getOperand(0);
11982   SDValue N1 = N->getOperand(1);
11983   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11984
11985   SmallVector<SDValue, 4> Ops;
11986   EVT ConcatVT = N0.getOperand(0).getValueType();
11987   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11988   unsigned NumConcats = NumElts / NumElemsPerConcat;
11989
11990   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11991   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11992   // half vector elements.
11993   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11994       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11995                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11996     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11997                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11998     N1 = DAG.getUNDEF(ConcatVT);
11999     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12000   }
12001
12002   // Look at every vector that's inserted. We're looking for exact
12003   // subvector-sized copies from a concatenated vector
12004   for (unsigned I = 0; I != NumConcats; ++I) {
12005     // Make sure we're dealing with a copy.
12006     unsigned Begin = I * NumElemsPerConcat;
12007     bool AllUndef = true, NoUndef = true;
12008     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12009       if (SVN->getMaskElt(J) >= 0)
12010         AllUndef = false;
12011       else
12012         NoUndef = false;
12013     }
12014
12015     if (NoUndef) {
12016       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12017         return SDValue();
12018
12019       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12020         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12021           return SDValue();
12022
12023       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12024       if (FirstElt < N0.getNumOperands())
12025         Ops.push_back(N0.getOperand(FirstElt));
12026       else
12027         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12028
12029     } else if (AllUndef) {
12030       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12031     } else { // Mixed with general masks and undefs, can't do optimization.
12032       return SDValue();
12033     }
12034   }
12035
12036   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12037 }
12038
12039 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12040   EVT VT = N->getValueType(0);
12041   unsigned NumElts = VT.getVectorNumElements();
12042
12043   SDValue N0 = N->getOperand(0);
12044   SDValue N1 = N->getOperand(1);
12045
12046   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12047
12048   // Canonicalize shuffle undef, undef -> undef
12049   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12050     return DAG.getUNDEF(VT);
12051
12052   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12053
12054   // Canonicalize shuffle v, v -> v, undef
12055   if (N0 == N1) {
12056     SmallVector<int, 8> NewMask;
12057     for (unsigned i = 0; i != NumElts; ++i) {
12058       int Idx = SVN->getMaskElt(i);
12059       if (Idx >= (int)NumElts) Idx -= NumElts;
12060       NewMask.push_back(Idx);
12061     }
12062     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12063                                 &NewMask[0]);
12064   }
12065
12066   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12067   if (N0.getOpcode() == ISD::UNDEF) {
12068     SmallVector<int, 8> NewMask;
12069     for (unsigned i = 0; i != NumElts; ++i) {
12070       int Idx = SVN->getMaskElt(i);
12071       if (Idx >= 0) {
12072         if (Idx >= (int)NumElts)
12073           Idx -= NumElts;
12074         else
12075           Idx = -1; // remove reference to lhs
12076       }
12077       NewMask.push_back(Idx);
12078     }
12079     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12080                                 &NewMask[0]);
12081   }
12082
12083   // Remove references to rhs if it is undef
12084   if (N1.getOpcode() == ISD::UNDEF) {
12085     bool Changed = false;
12086     SmallVector<int, 8> NewMask;
12087     for (unsigned i = 0; i != NumElts; ++i) {
12088       int Idx = SVN->getMaskElt(i);
12089       if (Idx >= (int)NumElts) {
12090         Idx = -1;
12091         Changed = true;
12092       }
12093       NewMask.push_back(Idx);
12094     }
12095     if (Changed)
12096       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12097   }
12098
12099   // If it is a splat, check if the argument vector is another splat or a
12100   // build_vector.
12101   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12102     SDNode *V = N0.getNode();
12103
12104     // If this is a bit convert that changes the element type of the vector but
12105     // not the number of vector elements, look through it.  Be careful not to
12106     // look though conversions that change things like v4f32 to v2f64.
12107     if (V->getOpcode() == ISD::BITCAST) {
12108       SDValue ConvInput = V->getOperand(0);
12109       if (ConvInput.getValueType().isVector() &&
12110           ConvInput.getValueType().getVectorNumElements() == NumElts)
12111         V = ConvInput.getNode();
12112     }
12113
12114     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12115       assert(V->getNumOperands() == NumElts &&
12116              "BUILD_VECTOR has wrong number of operands");
12117       SDValue Base;
12118       bool AllSame = true;
12119       for (unsigned i = 0; i != NumElts; ++i) {
12120         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12121           Base = V->getOperand(i);
12122           break;
12123         }
12124       }
12125       // Splat of <u, u, u, u>, return <u, u, u, u>
12126       if (!Base.getNode())
12127         return N0;
12128       for (unsigned i = 0; i != NumElts; ++i) {
12129         if (V->getOperand(i) != Base) {
12130           AllSame = false;
12131           break;
12132         }
12133       }
12134       // Splat of <x, x, x, x>, return <x, x, x, x>
12135       if (AllSame)
12136         return N0;
12137
12138       // Canonicalize any other splat as a build_vector.
12139       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12140       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12141       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12142                                   V->getValueType(0), Ops);
12143
12144       // We may have jumped through bitcasts, so the type of the
12145       // BUILD_VECTOR may not match the type of the shuffle.
12146       if (V->getValueType(0) != VT)
12147         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12148       return NewBV;
12149     }
12150   }
12151
12152   // There are various patterns used to build up a vector from smaller vectors,
12153   // subvectors, or elements. Scan chains of these and replace unused insertions
12154   // or components with undef.
12155   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12156     return S;
12157
12158   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12159       Level < AfterLegalizeVectorOps &&
12160       (N1.getOpcode() == ISD::UNDEF ||
12161       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12162        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12163     SDValue V = partitionShuffleOfConcats(N, DAG);
12164
12165     if (V.getNode())
12166       return V;
12167   }
12168
12169   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12170   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12171   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12172     SmallVector<SDValue, 8> Ops;
12173     for (int M : SVN->getMask()) {
12174       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12175       if (M >= 0) {
12176         int Idx = M % NumElts;
12177         SDValue &S = (M < (int)NumElts ? N0 : N1);
12178         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12179           Op = S.getOperand(Idx);
12180         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12181           if (Idx == 0)
12182             Op = S.getOperand(0);
12183         } else {
12184           // Operand can't be combined - bail out.
12185           break;
12186         }
12187       }
12188       Ops.push_back(Op);
12189     }
12190     if (Ops.size() == VT.getVectorNumElements()) {
12191       // BUILD_VECTOR requires all inputs to be of the same type, find the
12192       // maximum type and extend them all.
12193       EVT SVT = VT.getScalarType();
12194       if (SVT.isInteger())
12195         for (SDValue &Op : Ops)
12196           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12197       if (SVT != VT.getScalarType())
12198         for (SDValue &Op : Ops)
12199           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12200                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12201                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12202       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12203     }
12204   }
12205
12206   // If this shuffle only has a single input that is a bitcasted shuffle,
12207   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12208   // back to their original types.
12209   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12210       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12211       TLI.isTypeLegal(VT)) {
12212
12213     // Peek through the bitcast only if there is one user.
12214     SDValue BC0 = N0;
12215     while (BC0.getOpcode() == ISD::BITCAST) {
12216       if (!BC0.hasOneUse())
12217         break;
12218       BC0 = BC0.getOperand(0);
12219     }
12220
12221     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12222       if (Scale == 1)
12223         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12224
12225       SmallVector<int, 8> NewMask;
12226       for (int M : Mask)
12227         for (int s = 0; s != Scale; ++s)
12228           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12229       return NewMask;
12230     };
12231
12232     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12233       EVT SVT = VT.getScalarType();
12234       EVT InnerVT = BC0->getValueType(0);
12235       EVT InnerSVT = InnerVT.getScalarType();
12236
12237       // Determine which shuffle works with the smaller scalar type.
12238       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12239       EVT ScaleSVT = ScaleVT.getScalarType();
12240
12241       if (TLI.isTypeLegal(ScaleVT) &&
12242           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12243           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12244
12245         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12246         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12247
12248         // Scale the shuffle masks to the smaller scalar type.
12249         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12250         SmallVector<int, 8> InnerMask =
12251             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12252         SmallVector<int, 8> OuterMask =
12253             ScaleShuffleMask(SVN->getMask(), OuterScale);
12254
12255         // Merge the shuffle masks.
12256         SmallVector<int, 8> NewMask;
12257         for (int M : OuterMask)
12258           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12259
12260         // Test for shuffle mask legality over both commutations.
12261         SDValue SV0 = BC0->getOperand(0);
12262         SDValue SV1 = BC0->getOperand(1);
12263         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12264         if (!LegalMask) {
12265           std::swap(SV0, SV1);
12266           ShuffleVectorSDNode::commuteMask(NewMask);
12267           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12268         }
12269
12270         if (LegalMask) {
12271           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12272           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12273           return DAG.getNode(
12274               ISD::BITCAST, SDLoc(N), VT,
12275               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12276         }
12277       }
12278     }
12279   }
12280
12281   // Canonicalize shuffles according to rules:
12282   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12283   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12284   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12285   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12286       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12287       TLI.isTypeLegal(VT)) {
12288     // The incoming shuffle must be of the same type as the result of the
12289     // current shuffle.
12290     assert(N1->getOperand(0).getValueType() == VT &&
12291            "Shuffle types don't match");
12292
12293     SDValue SV0 = N1->getOperand(0);
12294     SDValue SV1 = N1->getOperand(1);
12295     bool HasSameOp0 = N0 == SV0;
12296     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12297     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12298       // Commute the operands of this shuffle so that next rule
12299       // will trigger.
12300       return DAG.getCommutedVectorShuffle(*SVN);
12301   }
12302
12303   // Try to fold according to rules:
12304   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12305   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12306   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12307   // Don't try to fold shuffles with illegal type.
12308   // Only fold if this shuffle is the only user of the other shuffle.
12309   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12310       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12311     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12312
12313     // The incoming shuffle must be of the same type as the result of the
12314     // current shuffle.
12315     assert(OtherSV->getOperand(0).getValueType() == VT &&
12316            "Shuffle types don't match");
12317
12318     SDValue SV0, SV1;
12319     SmallVector<int, 4> Mask;
12320     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12321     // operand, and SV1 as the second operand.
12322     for (unsigned i = 0; i != NumElts; ++i) {
12323       int Idx = SVN->getMaskElt(i);
12324       if (Idx < 0) {
12325         // Propagate Undef.
12326         Mask.push_back(Idx);
12327         continue;
12328       }
12329
12330       SDValue CurrentVec;
12331       if (Idx < (int)NumElts) {
12332         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12333         // shuffle mask to identify which vector is actually referenced.
12334         Idx = OtherSV->getMaskElt(Idx);
12335         if (Idx < 0) {
12336           // Propagate Undef.
12337           Mask.push_back(Idx);
12338           continue;
12339         }
12340
12341         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12342                                            : OtherSV->getOperand(1);
12343       } else {
12344         // This shuffle index references an element within N1.
12345         CurrentVec = N1;
12346       }
12347
12348       // Simple case where 'CurrentVec' is UNDEF.
12349       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12350         Mask.push_back(-1);
12351         continue;
12352       }
12353
12354       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12355       // will be the first or second operand of the combined shuffle.
12356       Idx = Idx % NumElts;
12357       if (!SV0.getNode() || SV0 == CurrentVec) {
12358         // Ok. CurrentVec is the left hand side.
12359         // Update the mask accordingly.
12360         SV0 = CurrentVec;
12361         Mask.push_back(Idx);
12362         continue;
12363       }
12364
12365       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12366       if (SV1.getNode() && SV1 != CurrentVec)
12367         return SDValue();
12368
12369       // Ok. CurrentVec is the right hand side.
12370       // Update the mask accordingly.
12371       SV1 = CurrentVec;
12372       Mask.push_back(Idx + NumElts);
12373     }
12374
12375     // Check if all indices in Mask are Undef. In case, propagate Undef.
12376     bool isUndefMask = true;
12377     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12378       isUndefMask &= Mask[i] < 0;
12379
12380     if (isUndefMask)
12381       return DAG.getUNDEF(VT);
12382
12383     if (!SV0.getNode())
12384       SV0 = DAG.getUNDEF(VT);
12385     if (!SV1.getNode())
12386       SV1 = DAG.getUNDEF(VT);
12387
12388     // Avoid introducing shuffles with illegal mask.
12389     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12390       ShuffleVectorSDNode::commuteMask(Mask);
12391
12392       if (!TLI.isShuffleMaskLegal(Mask, VT))
12393         return SDValue();
12394
12395       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12396       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12397       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12398       std::swap(SV0, SV1);
12399     }
12400
12401     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12402     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12403     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12404     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12405   }
12406
12407   return SDValue();
12408 }
12409
12410 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12411   SDValue InVal = N->getOperand(0);
12412   EVT VT = N->getValueType(0);
12413
12414   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12415   // with a VECTOR_SHUFFLE.
12416   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12417     SDValue InVec = InVal->getOperand(0);
12418     SDValue EltNo = InVal->getOperand(1);
12419
12420     // FIXME: We could support implicit truncation if the shuffle can be
12421     // scaled to a smaller vector scalar type.
12422     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12423     if (C0 && VT == InVec.getValueType() &&
12424         VT.getScalarType() == InVal.getValueType()) {
12425       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12426       int Elt = C0->getZExtValue();
12427       NewMask[0] = Elt;
12428
12429       if (TLI.isShuffleMaskLegal(NewMask, VT))
12430         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12431                                     NewMask);
12432     }
12433   }
12434
12435   return SDValue();
12436 }
12437
12438 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12439   SDValue N0 = N->getOperand(0);
12440   SDValue N2 = N->getOperand(2);
12441
12442   // If the input vector is a concatenation, and the insert replaces
12443   // one of the halves, we can optimize into a single concat_vectors.
12444   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12445       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12446     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12447     EVT VT = N->getValueType(0);
12448
12449     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12450     // (concat_vectors Z, Y)
12451     if (InsIdx == 0)
12452       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12453                          N->getOperand(1), N0.getOperand(1));
12454
12455     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12456     // (concat_vectors X, Z)
12457     if (InsIdx == VT.getVectorNumElements()/2)
12458       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12459                          N0.getOperand(0), N->getOperand(1));
12460   }
12461
12462   return SDValue();
12463 }
12464
12465 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12466 /// with the destination vector and a zero vector.
12467 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12468 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12469 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12470   EVT VT = N->getValueType(0);
12471   SDValue LHS = N->getOperand(0);
12472   SDValue RHS = N->getOperand(1);
12473   SDLoc dl(N);
12474
12475   // Make sure we're not running after operation legalization where it 
12476   // may have custom lowered the vector shuffles.
12477   if (LegalOperations)
12478     return SDValue();
12479
12480   if (N->getOpcode() != ISD::AND)
12481     return SDValue();
12482
12483   if (RHS.getOpcode() == ISD::BITCAST)
12484     RHS = RHS.getOperand(0);
12485
12486   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12487     SmallVector<int, 8> Indices;
12488     unsigned NumElts = RHS.getNumOperands();
12489
12490     for (unsigned i = 0; i != NumElts; ++i) {
12491       SDValue Elt = RHS.getOperand(i);
12492       if (!isa<ConstantSDNode>(Elt))
12493         return SDValue();
12494
12495       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12496         Indices.push_back(i);
12497       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12498         Indices.push_back(NumElts+i);
12499       else
12500         return SDValue();
12501     }
12502
12503     // Let's see if the target supports this vector_shuffle.
12504     EVT RVT = RHS.getValueType();
12505     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12506       return SDValue();
12507
12508     // Return the new VECTOR_SHUFFLE node.
12509     EVT EltVT = RVT.getVectorElementType();
12510     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12511                                    DAG.getConstant(0, EltVT));
12512     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12513     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12514     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12515     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12516   }
12517
12518   return SDValue();
12519 }
12520
12521 /// Visit a binary vector operation, like ADD.
12522 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12523   assert(N->getValueType(0).isVector() &&
12524          "SimplifyVBinOp only works on vectors!");
12525
12526   SDValue LHS = N->getOperand(0);
12527   SDValue RHS = N->getOperand(1);
12528
12529   if (SDValue Shuffle = XformToShuffleWithZero(N))
12530     return Shuffle;
12531
12532   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12533   // this operation.
12534   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12535       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12536     // Check if both vectors are constants. If not bail out.
12537     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12538           cast<BuildVectorSDNode>(RHS)->isConstant()))
12539       return SDValue();
12540
12541     SmallVector<SDValue, 8> Ops;
12542     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12543       SDValue LHSOp = LHS.getOperand(i);
12544       SDValue RHSOp = RHS.getOperand(i);
12545
12546       // Can't fold divide by zero.
12547       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12548           N->getOpcode() == ISD::FDIV) {
12549         if ((RHSOp.getOpcode() == ISD::Constant &&
12550              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12551             (RHSOp.getOpcode() == ISD::ConstantFP &&
12552              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12553           break;
12554       }
12555
12556       EVT VT = LHSOp.getValueType();
12557       EVT RVT = RHSOp.getValueType();
12558       if (RVT != VT) {
12559         // Integer BUILD_VECTOR operands may have types larger than the element
12560         // size (e.g., when the element type is not legal).  Prior to type
12561         // legalization, the types may not match between the two BUILD_VECTORS.
12562         // Truncate one of the operands to make them match.
12563         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12564           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12565         } else {
12566           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12567           VT = RVT;
12568         }
12569       }
12570       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12571                                    LHSOp, RHSOp);
12572       if (FoldOp.getOpcode() != ISD::UNDEF &&
12573           FoldOp.getOpcode() != ISD::Constant &&
12574           FoldOp.getOpcode() != ISD::ConstantFP)
12575         break;
12576       Ops.push_back(FoldOp);
12577       AddToWorklist(FoldOp.getNode());
12578     }
12579
12580     if (Ops.size() == LHS.getNumOperands())
12581       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12582   }
12583
12584   // Type legalization might introduce new shuffles in the DAG.
12585   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12586   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12587   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12588       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12589       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12590       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12591     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12592     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12593
12594     if (SVN0->getMask().equals(SVN1->getMask())) {
12595       EVT VT = N->getValueType(0);
12596       SDValue UndefVector = LHS.getOperand(1);
12597       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12598                                      LHS.getOperand(0), RHS.getOperand(0));
12599       AddUsersToWorklist(N);
12600       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12601                                   &SVN0->getMask()[0]);
12602     }
12603   }
12604
12605   return SDValue();
12606 }
12607
12608 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12609                                     SDValue N1, SDValue N2){
12610   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12611
12612   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12613                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12614
12615   // If we got a simplified select_cc node back from SimplifySelectCC, then
12616   // break it down into a new SETCC node, and a new SELECT node, and then return
12617   // the SELECT node, since we were called with a SELECT node.
12618   if (SCC.getNode()) {
12619     // Check to see if we got a select_cc back (to turn into setcc/select).
12620     // Otherwise, just return whatever node we got back, like fabs.
12621     if (SCC.getOpcode() == ISD::SELECT_CC) {
12622       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12623                                   N0.getValueType(),
12624                                   SCC.getOperand(0), SCC.getOperand(1),
12625                                   SCC.getOperand(4));
12626       AddToWorklist(SETCC.getNode());
12627       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12628                            SCC.getOperand(2), SCC.getOperand(3));
12629     }
12630
12631     return SCC;
12632   }
12633   return SDValue();
12634 }
12635
12636 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12637 /// being selected between, see if we can simplify the select.  Callers of this
12638 /// should assume that TheSelect is deleted if this returns true.  As such, they
12639 /// should return the appropriate thing (e.g. the node) back to the top-level of
12640 /// the DAG combiner loop to avoid it being looked at.
12641 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12642                                     SDValue RHS) {
12643
12644   // Cannot simplify select with vector condition
12645   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12646
12647   // If this is a select from two identical things, try to pull the operation
12648   // through the select.
12649   if (LHS.getOpcode() != RHS.getOpcode() ||
12650       !LHS.hasOneUse() || !RHS.hasOneUse())
12651     return false;
12652
12653   // If this is a load and the token chain is identical, replace the select
12654   // of two loads with a load through a select of the address to load from.
12655   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12656   // constants have been dropped into the constant pool.
12657   if (LHS.getOpcode() == ISD::LOAD) {
12658     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12659     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12660
12661     // Token chains must be identical.
12662     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12663         // Do not let this transformation reduce the number of volatile loads.
12664         LLD->isVolatile() || RLD->isVolatile() ||
12665         // If this is an EXTLOAD, the VT's must match.
12666         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12667         // If this is an EXTLOAD, the kind of extension must match.
12668         (LLD->getExtensionType() != RLD->getExtensionType() &&
12669          // The only exception is if one of the extensions is anyext.
12670          LLD->getExtensionType() != ISD::EXTLOAD &&
12671          RLD->getExtensionType() != ISD::EXTLOAD) ||
12672         // FIXME: this discards src value information.  This is
12673         // over-conservative. It would be beneficial to be able to remember
12674         // both potential memory locations.  Since we are discarding
12675         // src value info, don't do the transformation if the memory
12676         // locations are not in the default address space.
12677         LLD->getPointerInfo().getAddrSpace() != 0 ||
12678         RLD->getPointerInfo().getAddrSpace() != 0 ||
12679         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12680                                       LLD->getBasePtr().getValueType()))
12681       return false;
12682
12683     // Check that the select condition doesn't reach either load.  If so,
12684     // folding this will induce a cycle into the DAG.  If not, this is safe to
12685     // xform, so create a select of the addresses.
12686     SDValue Addr;
12687     if (TheSelect->getOpcode() == ISD::SELECT) {
12688       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12689       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12690           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12691         return false;
12692       // The loads must not depend on one another.
12693       if (LLD->isPredecessorOf(RLD) ||
12694           RLD->isPredecessorOf(LLD))
12695         return false;
12696       Addr = DAG.getSelect(SDLoc(TheSelect),
12697                            LLD->getBasePtr().getValueType(),
12698                            TheSelect->getOperand(0), LLD->getBasePtr(),
12699                            RLD->getBasePtr());
12700     } else {  // Otherwise SELECT_CC
12701       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12702       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12703
12704       if ((LLD->hasAnyUseOfValue(1) &&
12705            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12706           (RLD->hasAnyUseOfValue(1) &&
12707            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12708         return false;
12709
12710       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12711                          LLD->getBasePtr().getValueType(),
12712                          TheSelect->getOperand(0),
12713                          TheSelect->getOperand(1),
12714                          LLD->getBasePtr(), RLD->getBasePtr(),
12715                          TheSelect->getOperand(4));
12716     }
12717
12718     SDValue Load;
12719     // It is safe to replace the two loads if they have different alignments,
12720     // but the new load must be the minimum (most restrictive) alignment of the
12721     // inputs.
12722     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12723     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12724     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12725       Load = DAG.getLoad(TheSelect->getValueType(0),
12726                          SDLoc(TheSelect),
12727                          // FIXME: Discards pointer and AA info.
12728                          LLD->getChain(), Addr, MachinePointerInfo(),
12729                          LLD->isVolatile(), LLD->isNonTemporal(),
12730                          isInvariant, Alignment);
12731     } else {
12732       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12733                             RLD->getExtensionType() : LLD->getExtensionType(),
12734                             SDLoc(TheSelect),
12735                             TheSelect->getValueType(0),
12736                             // FIXME: Discards pointer and AA info.
12737                             LLD->getChain(), Addr, MachinePointerInfo(),
12738                             LLD->getMemoryVT(), LLD->isVolatile(),
12739                             LLD->isNonTemporal(), isInvariant, Alignment);
12740     }
12741
12742     // Users of the select now use the result of the load.
12743     CombineTo(TheSelect, Load);
12744
12745     // Users of the old loads now use the new load's chain.  We know the
12746     // old-load value is dead now.
12747     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12748     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12749     return true;
12750   }
12751
12752   return false;
12753 }
12754
12755 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12756 /// where 'cond' is the comparison specified by CC.
12757 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12758                                       SDValue N2, SDValue N3,
12759                                       ISD::CondCode CC, bool NotExtCompare) {
12760   // (x ? y : y) -> y.
12761   if (N2 == N3) return N2;
12762
12763   EVT VT = N2.getValueType();
12764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12765   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12766   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12767
12768   // Determine if the condition we're dealing with is constant
12769   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12770                               N0, N1, CC, DL, false);
12771   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12772   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12773
12774   // fold select_cc true, x, y -> x
12775   if (SCCC && !SCCC->isNullValue())
12776     return N2;
12777   // fold select_cc false, x, y -> y
12778   if (SCCC && SCCC->isNullValue())
12779     return N3;
12780
12781   // Check to see if we can simplify the select into an fabs node
12782   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12783     // Allow either -0.0 or 0.0
12784     if (CFP->getValueAPF().isZero()) {
12785       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12786       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12787           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12788           N2 == N3.getOperand(0))
12789         return DAG.getNode(ISD::FABS, DL, VT, N0);
12790
12791       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12792       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12793           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12794           N2.getOperand(0) == N3)
12795         return DAG.getNode(ISD::FABS, DL, VT, N3);
12796     }
12797   }
12798
12799   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12800   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12801   // in it.  This is a win when the constant is not otherwise available because
12802   // it replaces two constant pool loads with one.  We only do this if the FP
12803   // type is known to be legal, because if it isn't, then we are before legalize
12804   // types an we want the other legalization to happen first (e.g. to avoid
12805   // messing with soft float) and if the ConstantFP is not legal, because if
12806   // it is legal, we may not need to store the FP constant in a constant pool.
12807   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12808     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12809       if (TLI.isTypeLegal(N2.getValueType()) &&
12810           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12811                TargetLowering::Legal &&
12812            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12813            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12814           // If both constants have multiple uses, then we won't need to do an
12815           // extra load, they are likely around in registers for other users.
12816           (TV->hasOneUse() || FV->hasOneUse())) {
12817         Constant *Elts[] = {
12818           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12819           const_cast<ConstantFP*>(TV->getConstantFPValue())
12820         };
12821         Type *FPTy = Elts[0]->getType();
12822         const DataLayout &TD = *TLI.getDataLayout();
12823
12824         // Create a ConstantArray of the two constants.
12825         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12826         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12827                                             TD.getPrefTypeAlignment(FPTy));
12828         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12829
12830         // Get the offsets to the 0 and 1 element of the array so that we can
12831         // select between them.
12832         SDValue Zero = DAG.getIntPtrConstant(0);
12833         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12834         SDValue One = DAG.getIntPtrConstant(EltSize);
12835
12836         SDValue Cond = DAG.getSetCC(DL,
12837                                     getSetCCResultType(N0.getValueType()),
12838                                     N0, N1, CC);
12839         AddToWorklist(Cond.getNode());
12840         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12841                                           Cond, One, Zero);
12842         AddToWorklist(CstOffset.getNode());
12843         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12844                             CstOffset);
12845         AddToWorklist(CPIdx.getNode());
12846         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12847                            MachinePointerInfo::getConstantPool(), false,
12848                            false, false, Alignment);
12849
12850       }
12851     }
12852
12853   // Check to see if we can perform the "gzip trick", transforming
12854   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12855   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12856       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12857        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12858     EVT XType = N0.getValueType();
12859     EVT AType = N2.getValueType();
12860     if (XType.bitsGE(AType)) {
12861       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12862       // single-bit constant.
12863       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12864         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12865         ShCtV = XType.getSizeInBits()-ShCtV-1;
12866         SDValue ShCt = DAG.getConstant(ShCtV,
12867                                        getShiftAmountTy(N0.getValueType()));
12868         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12869                                     XType, N0, ShCt);
12870         AddToWorklist(Shift.getNode());
12871
12872         if (XType.bitsGT(AType)) {
12873           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12874           AddToWorklist(Shift.getNode());
12875         }
12876
12877         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12878       }
12879
12880       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12881                                   XType, N0,
12882                                   DAG.getConstant(XType.getSizeInBits()-1,
12883                                          getShiftAmountTy(N0.getValueType())));
12884       AddToWorklist(Shift.getNode());
12885
12886       if (XType.bitsGT(AType)) {
12887         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12888         AddToWorklist(Shift.getNode());
12889       }
12890
12891       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12892     }
12893   }
12894
12895   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12896   // where y is has a single bit set.
12897   // A plaintext description would be, we can turn the SELECT_CC into an AND
12898   // when the condition can be materialized as an all-ones register.  Any
12899   // single bit-test can be materialized as an all-ones register with
12900   // shift-left and shift-right-arith.
12901   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12902       N0->getValueType(0) == VT &&
12903       N1C && N1C->isNullValue() &&
12904       N2C && N2C->isNullValue()) {
12905     SDValue AndLHS = N0->getOperand(0);
12906     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12907     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12908       // Shift the tested bit over the sign bit.
12909       APInt AndMask = ConstAndRHS->getAPIntValue();
12910       SDValue ShlAmt =
12911         DAG.getConstant(AndMask.countLeadingZeros(),
12912                         getShiftAmountTy(AndLHS.getValueType()));
12913       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12914
12915       // Now arithmetic right shift it all the way over, so the result is either
12916       // all-ones, or zero.
12917       SDValue ShrAmt =
12918         DAG.getConstant(AndMask.getBitWidth()-1,
12919                         getShiftAmountTy(Shl.getValueType()));
12920       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12921
12922       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12923     }
12924   }
12925
12926   // fold select C, 16, 0 -> shl C, 4
12927   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12928       TLI.getBooleanContents(N0.getValueType()) ==
12929           TargetLowering::ZeroOrOneBooleanContent) {
12930
12931     // If the caller doesn't want us to simplify this into a zext of a compare,
12932     // don't do it.
12933     if (NotExtCompare && N2C->getAPIntValue() == 1)
12934       return SDValue();
12935
12936     // Get a SetCC of the condition
12937     // NOTE: Don't create a SETCC if it's not legal on this target.
12938     if (!LegalOperations ||
12939         TLI.isOperationLegal(ISD::SETCC,
12940           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12941       SDValue Temp, SCC;
12942       // cast from setcc result type to select result type
12943       if (LegalTypes) {
12944         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12945                             N0, N1, CC);
12946         if (N2.getValueType().bitsLT(SCC.getValueType()))
12947           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12948                                         N2.getValueType());
12949         else
12950           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12951                              N2.getValueType(), SCC);
12952       } else {
12953         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12954         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12955                            N2.getValueType(), SCC);
12956       }
12957
12958       AddToWorklist(SCC.getNode());
12959       AddToWorklist(Temp.getNode());
12960
12961       if (N2C->getAPIntValue() == 1)
12962         return Temp;
12963
12964       // shl setcc result by log2 n2c
12965       return DAG.getNode(
12966           ISD::SHL, DL, N2.getValueType(), Temp,
12967           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12968                           getShiftAmountTy(Temp.getValueType())));
12969     }
12970   }
12971
12972   // Check to see if this is the equivalent of setcc
12973   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12974   // otherwise, go ahead with the folds.
12975   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12976     EVT XType = N0.getValueType();
12977     if (!LegalOperations ||
12978         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12979       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12980       if (Res.getValueType() != VT)
12981         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12982       return Res;
12983     }
12984
12985     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12986     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12987         (!LegalOperations ||
12988          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12989       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12990       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12991                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12992                                        getShiftAmountTy(Ctlz.getValueType())));
12993     }
12994     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12995     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12996       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12997                                   XType, DAG.getConstant(0, XType), N0);
12998       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12999       return DAG.getNode(ISD::SRL, DL, XType,
13000                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13001                          DAG.getConstant(XType.getSizeInBits()-1,
13002                                          getShiftAmountTy(XType)));
13003     }
13004     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13005     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13006       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
13007                                  DAG.getConstant(XType.getSizeInBits()-1,
13008                                          getShiftAmountTy(N0.getValueType())));
13009       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
13010     }
13011   }
13012
13013   // Check to see if this is an integer abs.
13014   // select_cc setg[te] X,  0,  X, -X ->
13015   // select_cc setgt    X, -1,  X, -X ->
13016   // select_cc setl[te] X,  0, -X,  X ->
13017   // select_cc setlt    X,  1, -X,  X ->
13018   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13019   if (N1C) {
13020     ConstantSDNode *SubC = nullptr;
13021     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13022          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13023         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13024       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13025     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13026               (N1C->isOne() && CC == ISD::SETLT)) &&
13027              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13028       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13029
13030     EVT XType = N0.getValueType();
13031     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13032       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
13033                                   N0,
13034                                   DAG.getConstant(XType.getSizeInBits()-1,
13035                                          getShiftAmountTy(N0.getValueType())));
13036       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
13037                                 XType, N0, Shift);
13038       AddToWorklist(Shift.getNode());
13039       AddToWorklist(Add.getNode());
13040       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13041     }
13042   }
13043
13044   return SDValue();
13045 }
13046
13047 /// This is a stub for TargetLowering::SimplifySetCC.
13048 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13049                                    SDValue N1, ISD::CondCode Cond,
13050                                    SDLoc DL, bool foldBooleans) {
13051   TargetLowering::DAGCombinerInfo
13052     DagCombineInfo(DAG, Level, false, this);
13053   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13054 }
13055
13056 /// Given an ISD::SDIV node expressing a divide by constant, return
13057 /// a DAG expression to select that will generate the same value by multiplying
13058 /// by a magic number.
13059 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13060 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13061   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13062   if (!C)
13063     return SDValue();
13064
13065   // Avoid division by zero.
13066   if (!C->getAPIntValue())
13067     return SDValue();
13068
13069   std::vector<SDNode*> Built;
13070   SDValue S =
13071       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13072
13073   for (SDNode *N : Built)
13074     AddToWorklist(N);
13075   return S;
13076 }
13077
13078 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13079 /// DAG expression that will generate the same value by right shifting.
13080 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13081   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13082   if (!C)
13083     return SDValue();
13084
13085   // Avoid division by zero.
13086   if (!C->getAPIntValue())
13087     return SDValue();
13088
13089   std::vector<SDNode *> Built;
13090   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13091
13092   for (SDNode *N : Built)
13093     AddToWorklist(N);
13094   return S;
13095 }
13096
13097 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13098 /// expression that will generate the same value by multiplying by a magic
13099 /// number.
13100 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13101 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13102   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13103   if (!C)
13104     return SDValue();
13105
13106   // Avoid division by zero.
13107   if (!C->getAPIntValue())
13108     return SDValue();
13109
13110   std::vector<SDNode*> Built;
13111   SDValue S =
13112       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13113
13114   for (SDNode *N : Built)
13115     AddToWorklist(N);
13116   return S;
13117 }
13118
13119 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13120   if (Level >= AfterLegalizeDAG)
13121     return SDValue();
13122
13123   // Expose the DAG combiner to the target combiner implementations.
13124   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13125
13126   unsigned Iterations = 0;
13127   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13128     if (Iterations) {
13129       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13130       // For the reciprocal, we need to find the zero of the function:
13131       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13132       //     =>
13133       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13134       //     does not require additional intermediate precision]
13135       EVT VT = Op.getValueType();
13136       SDLoc DL(Op);
13137       SDValue FPOne = DAG.getConstantFP(1.0, VT);
13138
13139       AddToWorklist(Est.getNode());
13140
13141       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13142       for (unsigned i = 0; i < Iterations; ++i) {
13143         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13144         AddToWorklist(NewEst.getNode());
13145
13146         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13147         AddToWorklist(NewEst.getNode());
13148
13149         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13150         AddToWorklist(NewEst.getNode());
13151
13152         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13153         AddToWorklist(Est.getNode());
13154       }
13155     }
13156     return Est;
13157   }
13158
13159   return SDValue();
13160 }
13161
13162 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13163 /// For the reciprocal sqrt, we need to find the zero of the function:
13164 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13165 ///     =>
13166 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13167 /// As a result, we precompute A/2 prior to the iteration loop.
13168 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13169                                           unsigned Iterations) {
13170   EVT VT = Arg.getValueType();
13171   SDLoc DL(Arg);
13172   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
13173
13174   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13175   // this entire sequence requires only one FP constant.
13176   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13177   AddToWorklist(HalfArg.getNode());
13178
13179   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13180   AddToWorklist(HalfArg.getNode());
13181
13182   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13183   for (unsigned i = 0; i < Iterations; ++i) {
13184     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13185     AddToWorklist(NewEst.getNode());
13186
13187     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13188     AddToWorklist(NewEst.getNode());
13189
13190     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13191     AddToWorklist(NewEst.getNode());
13192
13193     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13194     AddToWorklist(Est.getNode());
13195   }
13196   return Est;
13197 }
13198
13199 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13200 /// For the reciprocal sqrt, we need to find the zero of the function:
13201 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13202 ///     =>
13203 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13204 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13205                                           unsigned Iterations) {
13206   EVT VT = Arg.getValueType();
13207   SDLoc DL(Arg);
13208   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13209   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13210
13211   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13212   for (unsigned i = 0; i < Iterations; ++i) {
13213     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13214     AddToWorklist(HalfEst.getNode());
13215
13216     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13217     AddToWorklist(Est.getNode());
13218
13219     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13220     AddToWorklist(Est.getNode());
13221
13222     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13223     AddToWorklist(Est.getNode());
13224
13225     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13226     AddToWorklist(Est.getNode());
13227   }
13228   return Est;
13229 }
13230
13231 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13232   if (Level >= AfterLegalizeDAG)
13233     return SDValue();
13234
13235   // Expose the DAG combiner to the target combiner implementations.
13236   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13237   unsigned Iterations = 0;
13238   bool UseOneConstNR = false;
13239   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13240     AddToWorklist(Est.getNode());
13241     if (Iterations) {
13242       Est = UseOneConstNR ?
13243         BuildRsqrtNROneConst(Op, Est, Iterations) :
13244         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13245     }
13246     return Est;
13247   }
13248
13249   return SDValue();
13250 }
13251
13252 /// Return true if base is a frame index, which is known not to alias with
13253 /// anything but itself.  Provides base object and offset as results.
13254 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13255                            const GlobalValue *&GV, const void *&CV) {
13256   // Assume it is a primitive operation.
13257   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13258
13259   // If it's an adding a simple constant then integrate the offset.
13260   if (Base.getOpcode() == ISD::ADD) {
13261     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13262       Base = Base.getOperand(0);
13263       Offset += C->getZExtValue();
13264     }
13265   }
13266
13267   // Return the underlying GlobalValue, and update the Offset.  Return false
13268   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13269   // by multiple nodes with different offsets.
13270   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13271     GV = G->getGlobal();
13272     Offset += G->getOffset();
13273     return false;
13274   }
13275
13276   // Return the underlying Constant value, and update the Offset.  Return false
13277   // for ConstantSDNodes since the same constant pool entry may be represented
13278   // by multiple nodes with different offsets.
13279   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13280     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13281                                          : (const void *)C->getConstVal();
13282     Offset += C->getOffset();
13283     return false;
13284   }
13285   // If it's any of the following then it can't alias with anything but itself.
13286   return isa<FrameIndexSDNode>(Base);
13287 }
13288
13289 /// Return true if there is any possibility that the two addresses overlap.
13290 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13291   // If they are the same then they must be aliases.
13292   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13293
13294   // If they are both volatile then they cannot be reordered.
13295   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13296
13297   // Gather base node and offset information.
13298   SDValue Base1, Base2;
13299   int64_t Offset1, Offset2;
13300   const GlobalValue *GV1, *GV2;
13301   const void *CV1, *CV2;
13302   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13303                                       Base1, Offset1, GV1, CV1);
13304   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13305                                       Base2, Offset2, GV2, CV2);
13306
13307   // If they have a same base address then check to see if they overlap.
13308   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13309     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13310              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13311
13312   // It is possible for different frame indices to alias each other, mostly
13313   // when tail call optimization reuses return address slots for arguments.
13314   // To catch this case, look up the actual index of frame indices to compute
13315   // the real alias relationship.
13316   if (isFrameIndex1 && isFrameIndex2) {
13317     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13318     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13319     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13320     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13321              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13322   }
13323
13324   // Otherwise, if we know what the bases are, and they aren't identical, then
13325   // we know they cannot alias.
13326   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13327     return false;
13328
13329   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13330   // compared to the size and offset of the access, we may be able to prove they
13331   // do not alias.  This check is conservative for now to catch cases created by
13332   // splitting vector types.
13333   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13334       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13335       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13336        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13337       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13338     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13339     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13340
13341     // There is no overlap between these relatively aligned accesses of similar
13342     // size, return no alias.
13343     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13344         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13345       return false;
13346   }
13347
13348   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13349                    ? CombinerGlobalAA
13350                    : DAG.getSubtarget().useAA();
13351 #ifndef NDEBUG
13352   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13353       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13354     UseAA = false;
13355 #endif
13356   if (UseAA &&
13357       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13358     // Use alias analysis information.
13359     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13360                                  Op1->getSrcValueOffset());
13361     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13362         Op0->getSrcValueOffset() - MinOffset;
13363     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13364         Op1->getSrcValueOffset() - MinOffset;
13365     AliasAnalysis::AliasResult AAResult =
13366         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13367                                          Overlap1,
13368                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13369                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13370                                          Overlap2,
13371                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13372     if (AAResult == AliasAnalysis::NoAlias)
13373       return false;
13374   }
13375
13376   // Otherwise we have to assume they alias.
13377   return true;
13378 }
13379
13380 /// Walk up chain skipping non-aliasing memory nodes,
13381 /// looking for aliasing nodes and adding them to the Aliases vector.
13382 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13383                                    SmallVectorImpl<SDValue> &Aliases) {
13384   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13385   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13386
13387   // Get alias information for node.
13388   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13389
13390   // Starting off.
13391   Chains.push_back(OriginalChain);
13392   unsigned Depth = 0;
13393
13394   // Look at each chain and determine if it is an alias.  If so, add it to the
13395   // aliases list.  If not, then continue up the chain looking for the next
13396   // candidate.
13397   while (!Chains.empty()) {
13398     SDValue Chain = Chains.back();
13399     Chains.pop_back();
13400
13401     // For TokenFactor nodes, look at each operand and only continue up the
13402     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13403     // find more and revert to original chain since the xform is unlikely to be
13404     // profitable.
13405     //
13406     // FIXME: The depth check could be made to return the last non-aliasing
13407     // chain we found before we hit a tokenfactor rather than the original
13408     // chain.
13409     if (Depth > 6 || Aliases.size() == 2) {
13410       Aliases.clear();
13411       Aliases.push_back(OriginalChain);
13412       return;
13413     }
13414
13415     // Don't bother if we've been before.
13416     if (!Visited.insert(Chain.getNode()).second)
13417       continue;
13418
13419     switch (Chain.getOpcode()) {
13420     case ISD::EntryToken:
13421       // Entry token is ideal chain operand, but handled in FindBetterChain.
13422       break;
13423
13424     case ISD::LOAD:
13425     case ISD::STORE: {
13426       // Get alias information for Chain.
13427       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13428           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13429
13430       // If chain is alias then stop here.
13431       if (!(IsLoad && IsOpLoad) &&
13432           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13433         Aliases.push_back(Chain);
13434       } else {
13435         // Look further up the chain.
13436         Chains.push_back(Chain.getOperand(0));
13437         ++Depth;
13438       }
13439       break;
13440     }
13441
13442     case ISD::TokenFactor:
13443       // We have to check each of the operands of the token factor for "small"
13444       // token factors, so we queue them up.  Adding the operands to the queue
13445       // (stack) in reverse order maintains the original order and increases the
13446       // likelihood that getNode will find a matching token factor (CSE.)
13447       if (Chain.getNumOperands() > 16) {
13448         Aliases.push_back(Chain);
13449         break;
13450       }
13451       for (unsigned n = Chain.getNumOperands(); n;)
13452         Chains.push_back(Chain.getOperand(--n));
13453       ++Depth;
13454       break;
13455
13456     default:
13457       // For all other instructions we will just have to take what we can get.
13458       Aliases.push_back(Chain);
13459       break;
13460     }
13461   }
13462
13463   // We need to be careful here to also search for aliases through the
13464   // value operand of a store, etc. Consider the following situation:
13465   //   Token1 = ...
13466   //   L1 = load Token1, %52
13467   //   S1 = store Token1, L1, %51
13468   //   L2 = load Token1, %52+8
13469   //   S2 = store Token1, L2, %51+8
13470   //   Token2 = Token(S1, S2)
13471   //   L3 = load Token2, %53
13472   //   S3 = store Token2, L3, %52
13473   //   L4 = load Token2, %53+8
13474   //   S4 = store Token2, L4, %52+8
13475   // If we search for aliases of S3 (which loads address %52), and we look
13476   // only through the chain, then we'll miss the trivial dependence on L1
13477   // (which also loads from %52). We then might change all loads and
13478   // stores to use Token1 as their chain operand, which could result in
13479   // copying %53 into %52 before copying %52 into %51 (which should
13480   // happen first).
13481   //
13482   // The problem is, however, that searching for such data dependencies
13483   // can become expensive, and the cost is not directly related to the
13484   // chain depth. Instead, we'll rule out such configurations here by
13485   // insisting that we've visited all chain users (except for users
13486   // of the original chain, which is not necessary). When doing this,
13487   // we need to look through nodes we don't care about (otherwise, things
13488   // like register copies will interfere with trivial cases).
13489
13490   SmallVector<const SDNode *, 16> Worklist;
13491   for (const SDNode *N : Visited)
13492     if (N != OriginalChain.getNode())
13493       Worklist.push_back(N);
13494
13495   while (!Worklist.empty()) {
13496     const SDNode *M = Worklist.pop_back_val();
13497
13498     // We have already visited M, and want to make sure we've visited any uses
13499     // of M that we care about. For uses that we've not visisted, and don't
13500     // care about, queue them to the worklist.
13501
13502     for (SDNode::use_iterator UI = M->use_begin(),
13503          UIE = M->use_end(); UI != UIE; ++UI)
13504       if (UI.getUse().getValueType() == MVT::Other &&
13505           Visited.insert(*UI).second) {
13506         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13507           // We've not visited this use, and we care about it (it could have an
13508           // ordering dependency with the original node).
13509           Aliases.clear();
13510           Aliases.push_back(OriginalChain);
13511           return;
13512         }
13513
13514         // We've not visited this use, but we don't care about it. Mark it as
13515         // visited and enqueue it to the worklist.
13516         Worklist.push_back(*UI);
13517       }
13518   }
13519 }
13520
13521 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13522 /// (aliasing node.)
13523 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13524   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13525
13526   // Accumulate all the aliases to this node.
13527   GatherAllAliases(N, OldChain, Aliases);
13528
13529   // If no operands then chain to entry token.
13530   if (Aliases.size() == 0)
13531     return DAG.getEntryNode();
13532
13533   // If a single operand then chain to it.  We don't need to revisit it.
13534   if (Aliases.size() == 1)
13535     return Aliases[0];
13536
13537   // Construct a custom tailored token factor.
13538   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13539 }
13540
13541 /// This is the entry point for the file.
13542 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13543                            CodeGenOpt::Level OptLevel) {
13544   /// This is the main entry point to this class.
13545   DAGCombiner(*this, AA, OptLevel).Run(Level);
13546 }