Move private classes into anonymous namespaces
[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 SimplifyVUnaryOp(SDNode *N);
255     SDValue visitSHL(SDNode *N);
256     SDValue visitSRA(SDNode *N);
257     SDValue visitSRL(SDNode *N);
258     SDValue visitRotate(SDNode *N);
259     SDValue visitCTLZ(SDNode *N);
260     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTTZ(SDNode *N);
262     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTPOP(SDNode *N);
264     SDValue visitSELECT(SDNode *N);
265     SDValue visitVSELECT(SDNode *N);
266     SDValue visitSELECT_CC(SDNode *N);
267     SDValue visitSETCC(SDNode *N);
268     SDValue visitSIGN_EXTEND(SDNode *N);
269     SDValue visitZERO_EXTEND(SDNode *N);
270     SDValue visitANY_EXTEND(SDNode *N);
271     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272     SDValue visitTRUNCATE(SDNode *N);
273     SDValue visitBITCAST(SDNode *N);
274     SDValue visitBUILD_PAIR(SDNode *N);
275     SDValue visitFADD(SDNode *N);
276     SDValue visitFSUB(SDNode *N);
277     SDValue visitFMUL(SDNode *N);
278     SDValue visitFMA(SDNode *N);
279     SDValue visitFDIV(SDNode *N);
280     SDValue visitFREM(SDNode *N);
281     SDValue visitFSQRT(SDNode *N);
282     SDValue visitFCOPYSIGN(SDNode *N);
283     SDValue visitSINT_TO_FP(SDNode *N);
284     SDValue visitUINT_TO_FP(SDNode *N);
285     SDValue visitFP_TO_SINT(SDNode *N);
286     SDValue visitFP_TO_UINT(SDNode *N);
287     SDValue visitFP_ROUND(SDNode *N);
288     SDValue visitFP_ROUND_INREG(SDNode *N);
289     SDValue visitFP_EXTEND(SDNode *N);
290     SDValue visitFNEG(SDNode *N);
291     SDValue visitFABS(SDNode *N);
292     SDValue visitFCEIL(SDNode *N);
293     SDValue visitFTRUNC(SDNode *N);
294     SDValue visitFFLOOR(SDNode *N);
295     SDValue visitFMINNUM(SDNode *N);
296     SDValue visitFMAXNUM(SDNode *N);
297     SDValue visitBRCOND(SDNode *N);
298     SDValue visitBR_CC(SDNode *N);
299     SDValue visitLOAD(SDNode *N);
300     SDValue visitSTORE(SDNode *N);
301     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
302     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
303     SDValue visitBUILD_VECTOR(SDNode *N);
304     SDValue visitCONCAT_VECTORS(SDNode *N);
305     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
306     SDValue visitVECTOR_SHUFFLE(SDNode *N);
307     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
308     SDValue visitINSERT_SUBVECTOR(SDNode *N);
309     SDValue visitMLOAD(SDNode *N);
310     SDValue visitMSTORE(SDNode *N);
311
312     SDValue XformToShuffleWithZero(SDNode *N);
313     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
314
315     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
316
317     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
318     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
319     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
320     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
321                              SDValue N3, ISD::CondCode CC,
322                              bool NotExtCompare = false);
323     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
324                           SDLoc DL, bool foldBooleans = true);
325
326     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
327                            SDValue &CC) const;
328     bool isOneUseSetCC(SDValue N) const;
329
330     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
331                                          unsigned HiOp);
332     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
333     SDValue CombineExtLoad(SDNode *N);
334     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
335     SDValue BuildSDIV(SDNode *N);
336     SDValue BuildSDIVPow2(SDNode *N);
337     SDValue BuildUDIV(SDNode *N);
338     SDValue BuildReciprocalEstimate(SDValue Op);
339     SDValue BuildRsqrtEstimate(SDValue Op);
340     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
341     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
342     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
343                                bool DemandHighBits = true);
344     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
345     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
346                               SDValue InnerPos, SDValue InnerNeg,
347                               unsigned PosOpcode, unsigned NegOpcode,
348                               SDLoc DL);
349     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
350     SDValue ReduceLoadWidth(SDNode *N);
351     SDValue ReduceLoadOpStoreWidth(SDNode *N);
352     SDValue TransformFPLoadStorePair(SDNode *N);
353     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
354     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
355
356     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
357
358     /// Walk up chain skipping non-aliasing memory nodes,
359     /// looking for aliasing nodes and adding them to the Aliases vector.
360     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
361                           SmallVectorImpl<SDValue> &Aliases);
362
363     /// Return true if there is any possibility that the two addresses overlap.
364     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
365
366     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
367     /// chain (aliasing node.)
368     SDValue FindBetterChain(SDNode *N, SDValue Chain);
369
370     /// Holds a pointer to an LSBaseSDNode as well as information on where it
371     /// is located in a sequence of memory operations connected by a chain.
372     struct MemOpLink {
373       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
374       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
375       // Ptr to the mem node.
376       LSBaseSDNode *MemNode;
377       // Offset from the base ptr.
378       int64_t OffsetFromBase;
379       // What is the sequence number of this mem node.
380       // Lowest mem operand in the DAG starts at zero.
381       unsigned SequenceNum;
382     };
383
384     /// This is a helper function for MergeConsecutiveStores. When the source
385     /// elements of the consecutive stores are all constants or all extracted
386     /// vector elements, try to merge them into one larger store.
387     /// \return True if a merged store was created.
388     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
389                                          EVT MemVT, unsigned NumElem,
390                                          bool IsConstantSrc, bool UseVector);
391
392     /// Merge consecutive store operations into a wide store.
393     /// This optimization uses wide integers or vectors when possible.
394     /// \return True if some memory operations were changed.
395     bool MergeConsecutiveStores(StoreSDNode *N);
396
397     /// \brief Try to transform a truncation where C is a constant:
398     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
399     ///
400     /// \p N needs to be a truncation and its first operand an AND. Other
401     /// requirements are checked by the function (e.g. that trunc is
402     /// single-use) and if missed an empty SDValue is returned.
403     SDValue distributeTruncateThroughAnd(SDNode *N);
404
405   public:
406     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
407         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
408           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
409       auto *F = DAG.getMachineFunction().getFunction();
410       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
411                     F->hasFnAttribute(Attribute::MinSize);
412     }
413
414     /// Runs the dag combiner on all nodes in the work list
415     void Run(CombineLevel AtLevel);
416
417     SelectionDAG &getDAG() const { return DAG; }
418
419     /// Returns a type large enough to hold any valid shift amount - before type
420     /// legalization these can be huge.
421     EVT getShiftAmountTy(EVT LHSTy) {
422       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
423       if (LHSTy.isVector())
424         return LHSTy;
425       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
426                         : TLI.getPointerTy();
427     }
428
429     /// This method returns true if we are running before type legalization or
430     /// if the specified VT is legal.
431     bool isTypeLegal(const EVT &VT) {
432       if (!LegalTypes) return true;
433       return TLI.isTypeLegal(VT);
434     }
435
436     /// Convenience wrapper around TargetLowering::getSetCCResultType
437     EVT getSetCCResultType(EVT VT) const {
438       return TLI.getSetCCResultType(*DAG.getContext(), VT);
439     }
440   };
441 }
442
443
444 namespace {
445 /// This class is a DAGUpdateListener that removes any deleted
446 /// nodes from the worklist.
447 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
448   DAGCombiner &DC;
449 public:
450   explicit WorklistRemover(DAGCombiner &dc)
451     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
452
453   void NodeDeleted(SDNode *N, SDNode *E) override {
454     DC.removeFromWorklist(N);
455   }
456 };
457 }
458
459 //===----------------------------------------------------------------------===//
460 //  TargetLowering::DAGCombinerInfo implementation
461 //===----------------------------------------------------------------------===//
462
463 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
464   ((DAGCombiner*)DC)->AddToWorklist(N);
465 }
466
467 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
468   ((DAGCombiner*)DC)->removeFromWorklist(N);
469 }
470
471 SDValue TargetLowering::DAGCombinerInfo::
472 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
473   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
479 }
480
481
482 SDValue TargetLowering::DAGCombinerInfo::
483 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
484   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
485 }
486
487 void TargetLowering::DAGCombinerInfo::
488 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
489   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
490 }
491
492 //===----------------------------------------------------------------------===//
493 // Helper Functions
494 //===----------------------------------------------------------------------===//
495
496 void DAGCombiner::deleteAndRecombine(SDNode *N) {
497   removeFromWorklist(N);
498
499   // If the operands of this node are only used by the node, they will now be
500   // dead. Make sure to re-visit them and recursively delete dead nodes.
501   for (const SDValue &Op : N->ops())
502     // For an operand generating multiple values, one of the values may
503     // become dead allowing further simplification (e.g. split index
504     // arithmetic from an indexed load).
505     if (Op->hasOneUse() || Op->getNumValues() > 1)
506       AddToWorklist(Op.getNode());
507
508   DAG.DeleteNode(N);
509 }
510
511 /// Return 1 if we can compute the negated form of the specified expression for
512 /// the same cost as the expression itself, or 2 if we can compute the negated
513 /// form more cheaply than the expression itself.
514 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
515                                const TargetLowering &TLI,
516                                const TargetOptions *Options,
517                                unsigned Depth = 0) {
518   // fneg is removable even if it has multiple uses.
519   if (Op.getOpcode() == ISD::FNEG) return 2;
520
521   // Don't allow anything with multiple uses.
522   if (!Op.hasOneUse()) return 0;
523
524   // Don't recurse exponentially.
525   if (Depth > 6) return 0;
526
527   switch (Op.getOpcode()) {
528   default: return false;
529   case ISD::ConstantFP:
530     // Don't invert constant FP values after legalize.  The negated constant
531     // isn't necessarily legal.
532     return LegalOperations ? 0 : 1;
533   case ISD::FADD:
534     // FIXME: determine better conditions for this xform.
535     if (!Options->UnsafeFPMath) return 0;
536
537     // After operation legalization, it might not be legal to create new FSUBs.
538     if (LegalOperations &&
539         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
540       return 0;
541
542     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
543     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
544                                     Options, Depth + 1))
545       return V;
546     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
547     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
548                               Depth + 1);
549   case ISD::FSUB:
550     // We can't turn -(A-B) into B-A when we honor signed zeros.
551     if (!Options->UnsafeFPMath) return 0;
552
553     // fold (fneg (fsub A, B)) -> (fsub B, A)
554     return 1;
555
556   case ISD::FMUL:
557   case ISD::FDIV:
558     if (Options->HonorSignDependentRoundingFPMath()) return 0;
559
560     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
561     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
562                                     Options, Depth + 1))
563       return V;
564
565     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
566                               Depth + 1);
567
568   case ISD::FP_EXTEND:
569   case ISD::FP_ROUND:
570   case ISD::FSIN:
571     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
572                               Depth + 1);
573   }
574 }
575
576 /// If isNegatibleForFree returns true, return the newly negated expression.
577 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
578                                     bool LegalOperations, unsigned Depth = 0) {
579   const TargetOptions &Options = DAG.getTarget().Options;
580   // fneg is removable even if it has multiple uses.
581   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
582
583   // Don't allow anything with multiple uses.
584   assert(Op.hasOneUse() && "Unknown reuse!");
585
586   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
587   switch (Op.getOpcode()) {
588   default: llvm_unreachable("Unknown code");
589   case ISD::ConstantFP: {
590     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
591     V.changeSign();
592     return DAG.getConstantFP(V, Op.getValueType());
593   }
594   case ISD::FADD:
595     // FIXME: determine better conditions for this xform.
596     assert(Options.UnsafeFPMath);
597
598     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
599     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
600                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
601       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
602                          GetNegatedExpression(Op.getOperand(0), DAG,
603                                               LegalOperations, Depth+1),
604                          Op.getOperand(1));
605     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
606     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                        GetNegatedExpression(Op.getOperand(1), DAG,
608                                             LegalOperations, Depth+1),
609                        Op.getOperand(0));
610   case ISD::FSUB:
611     // We can't turn -(A-B) into B-A when we honor signed zeros.
612     assert(Options.UnsafeFPMath);
613
614     // fold (fneg (fsub 0, B)) -> B
615     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
616       if (N0CFP->getValueAPF().isZero())
617         return Op.getOperand(1);
618
619     // fold (fneg (fsub A, B)) -> (fsub B, A)
620     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
621                        Op.getOperand(1), Op.getOperand(0));
622
623   case ISD::FMUL:
624   case ISD::FDIV:
625     assert(!Options.HonorSignDependentRoundingFPMath());
626
627     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
628     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
629                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
630       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
631                          GetNegatedExpression(Op.getOperand(0), DAG,
632                                               LegalOperations, Depth+1),
633                          Op.getOperand(1));
634
635     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
636     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
637                        Op.getOperand(0),
638                        GetNegatedExpression(Op.getOperand(1), DAG,
639                                             LegalOperations, Depth+1));
640
641   case ISD::FP_EXTEND:
642   case ISD::FSIN:
643     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
644                        GetNegatedExpression(Op.getOperand(0), DAG,
645                                             LegalOperations, Depth+1));
646   case ISD::FP_ROUND:
647       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
648                          GetNegatedExpression(Op.getOperand(0), DAG,
649                                               LegalOperations, Depth+1),
650                          Op.getOperand(1));
651   }
652 }
653
654 // Return true if this node is a setcc, or is a select_cc
655 // that selects between the target values used for true and false, making it
656 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
657 // the appropriate nodes based on the type of node we are checking. This
658 // simplifies life a bit for the callers.
659 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
660                                     SDValue &CC) const {
661   if (N.getOpcode() == ISD::SETCC) {
662     LHS = N.getOperand(0);
663     RHS = N.getOperand(1);
664     CC  = N.getOperand(2);
665     return true;
666   }
667
668   if (N.getOpcode() != ISD::SELECT_CC ||
669       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
670       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
671     return false;
672
673   if (TLI.getBooleanContents(N.getValueType()) ==
674       TargetLowering::UndefinedBooleanContent)
675     return false;
676
677   LHS = N.getOperand(0);
678   RHS = N.getOperand(1);
679   CC  = N.getOperand(4);
680   return true;
681 }
682
683 /// Return true if this is a SetCC-equivalent operation with only one use.
684 /// If this is true, it allows the users to invert the operation for free when
685 /// it is profitable to do so.
686 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
687   SDValue N0, N1, N2;
688   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
689     return true;
690   return false;
691 }
692
693 /// Returns true if N is a BUILD_VECTOR node whose
694 /// elements are all the same constant or undefined.
695 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
696   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
697   if (!C)
698     return false;
699
700   APInt SplatUndef;
701   unsigned SplatBitSize;
702   bool HasAnyUndefs;
703   EVT EltVT = N->getValueType(0).getVectorElementType();
704   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
705                              HasAnyUndefs) &&
706           EltVT.getSizeInBits() >= SplatBitSize);
707 }
708
709 // \brief Returns the SDNode if it is a constant BuildVector or constant.
710 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
711   if (isa<ConstantSDNode>(N))
712     return N.getNode();
713   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
714   if (BV && BV->isConstant())
715     return BV;
716   return nullptr;
717 }
718
719 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
720 // int.
721 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
722   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
723     return CN;
724
725   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
726     BitVector UndefElements;
727     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
728
729     // BuildVectors can truncate their operands. Ignore that case here.
730     // FIXME: We blindly ignore splats which include undef which is overly
731     // pessimistic.
732     if (CN && UndefElements.none() &&
733         CN->getValueType(0) == N.getValueType().getScalarType())
734       return CN;
735   }
736
737   return nullptr;
738 }
739
740 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
741 // float.
742 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
743   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
744     return CN;
745
746   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
747     BitVector UndefElements;
748     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
749
750     if (CN && UndefElements.none())
751       return CN;
752   }
753
754   return nullptr;
755 }
756
757 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
758                                     SDValue N0, SDValue N1) {
759   EVT VT = N0.getValueType();
760   if (N0.getOpcode() == Opc) {
761     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
762       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
763         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
764         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
765           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
766         return SDValue();
767       }
768       if (N0.hasOneUse()) {
769         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
770         // use
771         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
772         if (!OpNode.getNode())
773           return SDValue();
774         AddToWorklist(OpNode.getNode());
775         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
776       }
777     }
778   }
779
780   if (N1.getOpcode() == Opc) {
781     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
782       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
783         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
784         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
785           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
786         return SDValue();
787       }
788       if (N1.hasOneUse()) {
789         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
790         // use
791         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
792         if (!OpNode.getNode())
793           return SDValue();
794         AddToWorklist(OpNode.getNode());
795         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
796       }
797     }
798   }
799
800   return SDValue();
801 }
802
803 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
804                                bool AddTo) {
805   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
806   ++NodesCombined;
807   DEBUG(dbgs() << "\nReplacing.1 ";
808         N->dump(&DAG);
809         dbgs() << "\nWith: ";
810         To[0].getNode()->dump(&DAG);
811         dbgs() << " and " << NumTo-1 << " other values\n");
812   for (unsigned i = 0, e = NumTo; i != e; ++i)
813     assert((!To[i].getNode() ||
814             N->getValueType(i) == To[i].getValueType()) &&
815            "Cannot combine value to value of different type!");
816
817   WorklistRemover DeadNodes(*this);
818   DAG.ReplaceAllUsesWith(N, To);
819   if (AddTo) {
820     // Push the new nodes and any users onto the worklist
821     for (unsigned i = 0, e = NumTo; i != e; ++i) {
822       if (To[i].getNode()) {
823         AddToWorklist(To[i].getNode());
824         AddUsersToWorklist(To[i].getNode());
825       }
826     }
827   }
828
829   // Finally, if the node is now dead, remove it from the graph.  The node
830   // may not be dead if the replacement process recursively simplified to
831   // something else needing this node.
832   if (N->use_empty())
833     deleteAndRecombine(N);
834   return SDValue(N, 0);
835 }
836
837 void DAGCombiner::
838 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
839   // Replace all uses.  If any nodes become isomorphic to other nodes and
840   // are deleted, make sure to remove them from our worklist.
841   WorklistRemover DeadNodes(*this);
842   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
843
844   // Push the new node and any (possibly new) users onto the worklist.
845   AddToWorklist(TLO.New.getNode());
846   AddUsersToWorklist(TLO.New.getNode());
847
848   // Finally, if the node is now dead, remove it from the graph.  The node
849   // may not be dead if the replacement process recursively simplified to
850   // something else needing this node.
851   if (TLO.Old.getNode()->use_empty())
852     deleteAndRecombine(TLO.Old.getNode());
853 }
854
855 /// Check the specified integer node value to see if it can be simplified or if
856 /// things it uses can be simplified by bit propagation. If so, return true.
857 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
858   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
859   APInt KnownZero, KnownOne;
860   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
861     return false;
862
863   // Revisit the node.
864   AddToWorklist(Op.getNode());
865
866   // Replace the old value with the new one.
867   ++NodesCombined;
868   DEBUG(dbgs() << "\nReplacing.2 ";
869         TLO.Old.getNode()->dump(&DAG);
870         dbgs() << "\nWith: ";
871         TLO.New.getNode()->dump(&DAG);
872         dbgs() << '\n');
873
874   CommitTargetLoweringOpt(TLO);
875   return true;
876 }
877
878 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
879   SDLoc dl(Load);
880   EVT VT = Load->getValueType(0);
881   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
882
883   DEBUG(dbgs() << "\nReplacing.9 ";
884         Load->dump(&DAG);
885         dbgs() << "\nWith: ";
886         Trunc.getNode()->dump(&DAG);
887         dbgs() << '\n');
888   WorklistRemover DeadNodes(*this);
889   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
890   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
891   deleteAndRecombine(Load);
892   AddToWorklist(Trunc.getNode());
893 }
894
895 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
896   Replace = false;
897   SDLoc dl(Op);
898   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
899     EVT MemVT = LD->getMemoryVT();
900     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
901       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
902                                                        : ISD::EXTLOAD)
903       : LD->getExtensionType();
904     Replace = true;
905     return DAG.getExtLoad(ExtType, dl, PVT,
906                           LD->getChain(), LD->getBasePtr(),
907                           MemVT, LD->getMemOperand());
908   }
909
910   unsigned Opc = Op.getOpcode();
911   switch (Opc) {
912   default: break;
913   case ISD::AssertSext:
914     return DAG.getNode(ISD::AssertSext, dl, PVT,
915                        SExtPromoteOperand(Op.getOperand(0), PVT),
916                        Op.getOperand(1));
917   case ISD::AssertZext:
918     return DAG.getNode(ISD::AssertZext, dl, PVT,
919                        ZExtPromoteOperand(Op.getOperand(0), PVT),
920                        Op.getOperand(1));
921   case ISD::Constant: {
922     unsigned ExtOpc =
923       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
924     return DAG.getNode(ExtOpc, dl, PVT, Op);
925   }
926   }
927
928   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
929     return SDValue();
930   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
931 }
932
933 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
934   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
935     return SDValue();
936   EVT OldVT = Op.getValueType();
937   SDLoc dl(Op);
938   bool Replace = false;
939   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
940   if (!NewOp.getNode())
941     return SDValue();
942   AddToWorklist(NewOp.getNode());
943
944   if (Replace)
945     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
946   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
947                      DAG.getValueType(OldVT));
948 }
949
950 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
962 }
963
964 /// Promote the specified integer binary operation if the target indicates it is
965 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
966 /// i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
968   if (!LegalOperations)
969     return SDValue();
970
971   EVT VT = Op.getValueType();
972   if (VT.isVector() || !VT.isInteger())
973     return SDValue();
974
975   // If operation type is 'undesirable', e.g. i16 on x86, consider
976   // promoting it.
977   unsigned Opc = Op.getOpcode();
978   if (TLI.isTypeDesirableForOp(Opc, VT))
979     return SDValue();
980
981   EVT PVT = VT;
982   // Consult target whether it is a good idea to promote this operation and
983   // what's the right type to promote it to.
984   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985     assert(PVT != VT && "Don't know what type to promote to!");
986
987     bool Replace0 = false;
988     SDValue N0 = Op.getOperand(0);
989     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
990     if (!NN0.getNode())
991       return SDValue();
992
993     bool Replace1 = false;
994     SDValue N1 = Op.getOperand(1);
995     SDValue NN1;
996     if (N0 == N1)
997       NN1 = NN0;
998     else {
999       NN1 = PromoteOperand(N1, PVT, Replace1);
1000       if (!NN1.getNode())
1001         return SDValue();
1002     }
1003
1004     AddToWorklist(NN0.getNode());
1005     if (NN1.getNode())
1006       AddToWorklist(NN1.getNode());
1007
1008     if (Replace0)
1009       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1010     if (Replace1)
1011       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1012
1013     DEBUG(dbgs() << "\nPromoting ";
1014           Op.getNode()->dump(&DAG));
1015     SDLoc dl(Op);
1016     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1017                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1018   }
1019   return SDValue();
1020 }
1021
1022 /// Promote the specified integer shift operation if the target indicates it is
1023 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1024 /// i32 since i16 instructions are longer.
1025 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1026   if (!LegalOperations)
1027     return SDValue();
1028
1029   EVT VT = Op.getValueType();
1030   if (VT.isVector() || !VT.isInteger())
1031     return SDValue();
1032
1033   // If operation type is 'undesirable', e.g. i16 on x86, consider
1034   // promoting it.
1035   unsigned Opc = Op.getOpcode();
1036   if (TLI.isTypeDesirableForOp(Opc, VT))
1037     return SDValue();
1038
1039   EVT PVT = VT;
1040   // Consult target whether it is a good idea to promote this operation and
1041   // what's the right type to promote it to.
1042   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1043     assert(PVT != VT && "Don't know what type to promote to!");
1044
1045     bool Replace = false;
1046     SDValue N0 = Op.getOperand(0);
1047     if (Opc == ISD::SRA)
1048       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1049     else if (Opc == ISD::SRL)
1050       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1051     else
1052       N0 = PromoteOperand(N0, PVT, Replace);
1053     if (!N0.getNode())
1054       return SDValue();
1055
1056     AddToWorklist(N0.getNode());
1057     if (Replace)
1058       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1059
1060     DEBUG(dbgs() << "\nPromoting ";
1061           Op.getNode()->dump(&DAG));
1062     SDLoc dl(Op);
1063     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1064                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1065   }
1066   return SDValue();
1067 }
1068
1069 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1070   if (!LegalOperations)
1071     return SDValue();
1072
1073   EVT VT = Op.getValueType();
1074   if (VT.isVector() || !VT.isInteger())
1075     return SDValue();
1076
1077   // If operation type is 'undesirable', e.g. i16 on x86, consider
1078   // promoting it.
1079   unsigned Opc = Op.getOpcode();
1080   if (TLI.isTypeDesirableForOp(Opc, VT))
1081     return SDValue();
1082
1083   EVT PVT = VT;
1084   // Consult target whether it is a good idea to promote this operation and
1085   // what's the right type to promote it to.
1086   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1087     assert(PVT != VT && "Don't know what type to promote to!");
1088     // fold (aext (aext x)) -> (aext x)
1089     // fold (aext (zext x)) -> (zext x)
1090     // fold (aext (sext x)) -> (sext x)
1091     DEBUG(dbgs() << "\nPromoting ";
1092           Op.getNode()->dump(&DAG));
1093     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1094   }
1095   return SDValue();
1096 }
1097
1098 bool DAGCombiner::PromoteLoad(SDValue Op) {
1099   if (!LegalOperations)
1100     return false;
1101
1102   EVT VT = Op.getValueType();
1103   if (VT.isVector() || !VT.isInteger())
1104     return false;
1105
1106   // If operation type is 'undesirable', e.g. i16 on x86, consider
1107   // promoting it.
1108   unsigned Opc = Op.getOpcode();
1109   if (TLI.isTypeDesirableForOp(Opc, VT))
1110     return false;
1111
1112   EVT PVT = VT;
1113   // Consult target whether it is a good idea to promote this operation and
1114   // what's the right type to promote it to.
1115   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1116     assert(PVT != VT && "Don't know what type to promote to!");
1117
1118     SDLoc dl(Op);
1119     SDNode *N = Op.getNode();
1120     LoadSDNode *LD = cast<LoadSDNode>(N);
1121     EVT MemVT = LD->getMemoryVT();
1122     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1123       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1124                                                        : ISD::EXTLOAD)
1125       : LD->getExtensionType();
1126     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1127                                    LD->getChain(), LD->getBasePtr(),
1128                                    MemVT, LD->getMemOperand());
1129     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1130
1131     DEBUG(dbgs() << "\nPromoting ";
1132           N->dump(&DAG);
1133           dbgs() << "\nTo: ";
1134           Result.getNode()->dump(&DAG);
1135           dbgs() << '\n');
1136     WorklistRemover DeadNodes(*this);
1137     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1138     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1139     deleteAndRecombine(N);
1140     AddToWorklist(Result.getNode());
1141     return true;
1142   }
1143   return false;
1144 }
1145
1146 /// \brief Recursively delete a node which has no uses and any operands for
1147 /// which it is the only use.
1148 ///
1149 /// Note that this both deletes the nodes and removes them from the worklist.
1150 /// It also adds any nodes who have had a user deleted to the worklist as they
1151 /// may now have only one use and subject to other combines.
1152 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1153   if (!N->use_empty())
1154     return false;
1155
1156   SmallSetVector<SDNode *, 16> Nodes;
1157   Nodes.insert(N);
1158   do {
1159     N = Nodes.pop_back_val();
1160     if (!N)
1161       continue;
1162
1163     if (N->use_empty()) {
1164       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1165         Nodes.insert(N->getOperand(i).getNode());
1166
1167       removeFromWorklist(N);
1168       DAG.DeleteNode(N);
1169     } else {
1170       AddToWorklist(N);
1171     }
1172   } while (!Nodes.empty());
1173   return true;
1174 }
1175
1176 //===----------------------------------------------------------------------===//
1177 //  Main DAG Combiner implementation
1178 //===----------------------------------------------------------------------===//
1179
1180 void DAGCombiner::Run(CombineLevel AtLevel) {
1181   // set the instance variables, so that the various visit routines may use it.
1182   Level = AtLevel;
1183   LegalOperations = Level >= AfterLegalizeVectorOps;
1184   LegalTypes = Level >= AfterLegalizeTypes;
1185
1186   // Early exit if this basic block is in an optnone function.
1187   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
1188           Attribute::OptimizeNone))
1189     return;
1190
1191   // Add all the dag nodes to the worklist.
1192   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1193        E = DAG.allnodes_end(); I != E; ++I)
1194     AddToWorklist(I);
1195
1196   // Create a dummy node (which is not added to allnodes), that adds a reference
1197   // to the root node, preventing it from being deleted, and tracking any
1198   // changes of the root.
1199   HandleSDNode Dummy(DAG.getRoot());
1200
1201   // while the worklist isn't empty, find a node and
1202   // try and combine it.
1203   while (!WorklistMap.empty()) {
1204     SDNode *N;
1205     // The Worklist holds the SDNodes in order, but it may contain null entries.
1206     do {
1207       N = Worklist.pop_back_val();
1208     } while (!N);
1209
1210     bool GoodWorklistEntry = WorklistMap.erase(N);
1211     (void)GoodWorklistEntry;
1212     assert(GoodWorklistEntry &&
1213            "Found a worklist entry without a corresponding map entry!");
1214
1215     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1216     // N is deleted from the DAG, since they too may now be dead or may have a
1217     // reduced number of uses, allowing other xforms.
1218     if (recursivelyDeleteUnusedNodes(N))
1219       continue;
1220
1221     WorklistRemover DeadNodes(*this);
1222
1223     // If this combine is running after legalizing the DAG, re-legalize any
1224     // nodes pulled off the worklist.
1225     if (Level == AfterLegalizeDAG) {
1226       SmallSetVector<SDNode *, 16> UpdatedNodes;
1227       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1228
1229       for (SDNode *LN : UpdatedNodes) {
1230         AddToWorklist(LN);
1231         AddUsersToWorklist(LN);
1232       }
1233       if (!NIsValid)
1234         continue;
1235     }
1236
1237     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1238
1239     // Add any operands of the new node which have not yet been combined to the
1240     // worklist as well. Because the worklist uniques things already, this
1241     // won't repeatedly process the same operand.
1242     CombinedNodes.insert(N);
1243     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1244       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1245         AddToWorklist(N->getOperand(i).getNode());
1246
1247     SDValue RV = combine(N);
1248
1249     if (!RV.getNode())
1250       continue;
1251
1252     ++NodesCombined;
1253
1254     // If we get back the same node we passed in, rather than a new node or
1255     // zero, we know that the node must have defined multiple values and
1256     // CombineTo was used.  Since CombineTo takes care of the worklist
1257     // mechanics for us, we have no work to do in this case.
1258     if (RV.getNode() == N)
1259       continue;
1260
1261     assert(N->getOpcode() != ISD::DELETED_NODE &&
1262            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1263            "Node was deleted but visit returned new node!");
1264
1265     DEBUG(dbgs() << " ... into: ";
1266           RV.getNode()->dump(&DAG));
1267
1268     // Transfer debug value.
1269     DAG.TransferDbgValues(SDValue(N, 0), RV);
1270     if (N->getNumValues() == RV.getNode()->getNumValues())
1271       DAG.ReplaceAllUsesWith(N, RV.getNode());
1272     else {
1273       assert(N->getValueType(0) == RV.getValueType() &&
1274              N->getNumValues() == 1 && "Type mismatch");
1275       SDValue OpV = RV;
1276       DAG.ReplaceAllUsesWith(N, &OpV);
1277     }
1278
1279     // Push the new node and any users onto the worklist
1280     AddToWorklist(RV.getNode());
1281     AddUsersToWorklist(RV.getNode());
1282
1283     // Finally, if the node is now dead, remove it from the graph.  The node
1284     // may not be dead if the replacement process recursively simplified to
1285     // something else needing this node. This will also take care of adding any
1286     // operands which have lost a user to the worklist.
1287     recursivelyDeleteUnusedNodes(N);
1288   }
1289
1290   // If the root changed (e.g. it was a dead load, update the root).
1291   DAG.setRoot(Dummy.getValue());
1292   DAG.RemoveDeadNodes();
1293 }
1294
1295 SDValue DAGCombiner::visit(SDNode *N) {
1296   switch (N->getOpcode()) {
1297   default: break;
1298   case ISD::TokenFactor:        return visitTokenFactor(N);
1299   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1300   case ISD::ADD:                return visitADD(N);
1301   case ISD::SUB:                return visitSUB(N);
1302   case ISD::ADDC:               return visitADDC(N);
1303   case ISD::SUBC:               return visitSUBC(N);
1304   case ISD::ADDE:               return visitADDE(N);
1305   case ISD::SUBE:               return visitSUBE(N);
1306   case ISD::MUL:                return visitMUL(N);
1307   case ISD::SDIV:               return visitSDIV(N);
1308   case ISD::UDIV:               return visitUDIV(N);
1309   case ISD::SREM:               return visitSREM(N);
1310   case ISD::UREM:               return visitUREM(N);
1311   case ISD::MULHU:              return visitMULHU(N);
1312   case ISD::MULHS:              return visitMULHS(N);
1313   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1314   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1315   case ISD::SMULO:              return visitSMULO(N);
1316   case ISD::UMULO:              return visitUMULO(N);
1317   case ISD::SDIVREM:            return visitSDIVREM(N);
1318   case ISD::UDIVREM:            return visitUDIVREM(N);
1319   case ISD::AND:                return visitAND(N);
1320   case ISD::OR:                 return visitOR(N);
1321   case ISD::XOR:                return visitXOR(N);
1322   case ISD::SHL:                return visitSHL(N);
1323   case ISD::SRA:                return visitSRA(N);
1324   case ISD::SRL:                return visitSRL(N);
1325   case ISD::ROTR:
1326   case ISD::ROTL:               return visitRotate(N);
1327   case ISD::CTLZ:               return visitCTLZ(N);
1328   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1329   case ISD::CTTZ:               return visitCTTZ(N);
1330   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1331   case ISD::CTPOP:              return visitCTPOP(N);
1332   case ISD::SELECT:             return visitSELECT(N);
1333   case ISD::VSELECT:            return visitVSELECT(N);
1334   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1335   case ISD::SETCC:              return visitSETCC(N);
1336   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1337   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1338   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1339   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1340   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1341   case ISD::BITCAST:            return visitBITCAST(N);
1342   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1343   case ISD::FADD:               return visitFADD(N);
1344   case ISD::FSUB:               return visitFSUB(N);
1345   case ISD::FMUL:               return visitFMUL(N);
1346   case ISD::FMA:                return visitFMA(N);
1347   case ISD::FDIV:               return visitFDIV(N);
1348   case ISD::FREM:               return visitFREM(N);
1349   case ISD::FSQRT:              return visitFSQRT(N);
1350   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1351   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1352   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1353   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1354   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1355   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1356   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1357   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1358   case ISD::FNEG:               return visitFNEG(N);
1359   case ISD::FABS:               return visitFABS(N);
1360   case ISD::FFLOOR:             return visitFFLOOR(N);
1361   case ISD::FMINNUM:            return visitFMINNUM(N);
1362   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1363   case ISD::FCEIL:              return visitFCEIL(N);
1364   case ISD::FTRUNC:             return visitFTRUNC(N);
1365   case ISD::BRCOND:             return visitBRCOND(N);
1366   case ISD::BR_CC:              return visitBR_CC(N);
1367   case ISD::LOAD:               return visitLOAD(N);
1368   case ISD::STORE:              return visitSTORE(N);
1369   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1370   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1371   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1372   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1373   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1374   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1375   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1376   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1377   case ISD::MLOAD:              return visitMLOAD(N);
1378   case ISD::MSTORE:             return visitMSTORE(N);
1379   }
1380   return SDValue();
1381 }
1382
1383 SDValue DAGCombiner::combine(SDNode *N) {
1384   SDValue RV = visit(N);
1385
1386   // If nothing happened, try a target-specific DAG combine.
1387   if (!RV.getNode()) {
1388     assert(N->getOpcode() != ISD::DELETED_NODE &&
1389            "Node was deleted but visit returned NULL!");
1390
1391     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1392         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1393
1394       // Expose the DAG combiner to the target combiner impls.
1395       TargetLowering::DAGCombinerInfo
1396         DagCombineInfo(DAG, Level, false, this);
1397
1398       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1399     }
1400   }
1401
1402   // If nothing happened still, try promoting the operation.
1403   if (!RV.getNode()) {
1404     switch (N->getOpcode()) {
1405     default: break;
1406     case ISD::ADD:
1407     case ISD::SUB:
1408     case ISD::MUL:
1409     case ISD::AND:
1410     case ISD::OR:
1411     case ISD::XOR:
1412       RV = PromoteIntBinOp(SDValue(N, 0));
1413       break;
1414     case ISD::SHL:
1415     case ISD::SRA:
1416     case ISD::SRL:
1417       RV = PromoteIntShiftOp(SDValue(N, 0));
1418       break;
1419     case ISD::SIGN_EXTEND:
1420     case ISD::ZERO_EXTEND:
1421     case ISD::ANY_EXTEND:
1422       RV = PromoteExtend(SDValue(N, 0));
1423       break;
1424     case ISD::LOAD:
1425       if (PromoteLoad(SDValue(N, 0)))
1426         RV = SDValue(N, 0);
1427       break;
1428     }
1429   }
1430
1431   // If N is a commutative binary node, try commuting it to enable more
1432   // sdisel CSE.
1433   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1434       N->getNumValues() == 1) {
1435     SDValue N0 = N->getOperand(0);
1436     SDValue N1 = N->getOperand(1);
1437
1438     // Constant operands are canonicalized to RHS.
1439     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1440       SDValue Ops[] = {N1, N0};
1441       SDNode *CSENode;
1442       if (const BinaryWithFlagsSDNode *BinNode =
1443               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1444         CSENode = DAG.getNodeIfExists(
1445             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1446             BinNode->hasNoSignedWrap(), BinNode->isExact());
1447       } else {
1448         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1449       }
1450       if (CSENode)
1451         return SDValue(CSENode, 0);
1452     }
1453   }
1454
1455   return RV;
1456 }
1457
1458 /// Given a node, return its input chain if it has one, otherwise return a null
1459 /// sd operand.
1460 static SDValue getInputChainForNode(SDNode *N) {
1461   if (unsigned NumOps = N->getNumOperands()) {
1462     if (N->getOperand(0).getValueType() == MVT::Other)
1463       return N->getOperand(0);
1464     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1465       return N->getOperand(NumOps-1);
1466     for (unsigned i = 1; i < NumOps-1; ++i)
1467       if (N->getOperand(i).getValueType() == MVT::Other)
1468         return N->getOperand(i);
1469   }
1470   return SDValue();
1471 }
1472
1473 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1474   // If N has two operands, where one has an input chain equal to the other,
1475   // the 'other' chain is redundant.
1476   if (N->getNumOperands() == 2) {
1477     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1478       return N->getOperand(0);
1479     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1480       return N->getOperand(1);
1481   }
1482
1483   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1484   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1485   SmallPtrSet<SDNode*, 16> SeenOps;
1486   bool Changed = false;             // If we should replace this token factor.
1487
1488   // Start out with this token factor.
1489   TFs.push_back(N);
1490
1491   // Iterate through token factors.  The TFs grows when new token factors are
1492   // encountered.
1493   for (unsigned i = 0; i < TFs.size(); ++i) {
1494     SDNode *TF = TFs[i];
1495
1496     // Check each of the operands.
1497     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1498       SDValue Op = TF->getOperand(i);
1499
1500       switch (Op.getOpcode()) {
1501       case ISD::EntryToken:
1502         // Entry tokens don't need to be added to the list. They are
1503         // redundant.
1504         Changed = true;
1505         break;
1506
1507       case ISD::TokenFactor:
1508         if (Op.hasOneUse() &&
1509             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1510           // Queue up for processing.
1511           TFs.push_back(Op.getNode());
1512           // Clean up in case the token factor is removed.
1513           AddToWorklist(Op.getNode());
1514           Changed = true;
1515           break;
1516         }
1517         // Fall thru
1518
1519       default:
1520         // Only add if it isn't already in the list.
1521         if (SeenOps.insert(Op.getNode()).second)
1522           Ops.push_back(Op);
1523         else
1524           Changed = true;
1525         break;
1526       }
1527     }
1528   }
1529
1530   SDValue Result;
1531
1532   // If we've changed things around then replace token factor.
1533   if (Changed) {
1534     if (Ops.empty()) {
1535       // The entry token is the only possible outcome.
1536       Result = DAG.getEntryNode();
1537     } else {
1538       // New and improved token factor.
1539       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1540     }
1541
1542     // Add users to worklist if AA is enabled, since it may introduce
1543     // a lot of new chained token factors while removing memory deps.
1544     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1545       : DAG.getSubtarget().useAA();
1546     return CombineTo(N, Result, UseAA /*add to worklist*/);
1547   }
1548
1549   return Result;
1550 }
1551
1552 /// MERGE_VALUES can always be eliminated.
1553 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1554   WorklistRemover DeadNodes(*this);
1555   // Replacing results may cause a different MERGE_VALUES to suddenly
1556   // be CSE'd with N, and carry its uses with it. Iterate until no
1557   // uses remain, to ensure that the node can be safely deleted.
1558   // First add the users of this node to the work list so that they
1559   // can be tried again once they have new operands.
1560   AddUsersToWorklist(N);
1561   do {
1562     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1563       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1564   } while (!N->use_empty());
1565   deleteAndRecombine(N);
1566   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1567 }
1568
1569 SDValue DAGCombiner::visitADD(SDNode *N) {
1570   SDValue N0 = N->getOperand(0);
1571   SDValue N1 = N->getOperand(1);
1572   EVT VT = N0.getValueType();
1573
1574   // fold vector ops
1575   if (VT.isVector()) {
1576     SDValue FoldedVOp = SimplifyVBinOp(N);
1577     if (FoldedVOp.getNode()) return FoldedVOp;
1578
1579     // fold (add x, 0) -> x, vector edition
1580     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1581       return N0;
1582     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1583       return N1;
1584   }
1585
1586   // fold (add x, undef) -> undef
1587   if (N0.getOpcode() == ISD::UNDEF)
1588     return N0;
1589   if (N1.getOpcode() == ISD::UNDEF)
1590     return N1;
1591   // fold (add c1, c2) -> c1+c2
1592   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1593   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1594   if (N0C && N1C)
1595     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1596   // canonicalize constant to RHS
1597   if (N0C && !N1C)
1598     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1599   // fold (add x, 0) -> x
1600   if (N1C && N1C->isNullValue())
1601     return N0;
1602   // fold (add Sym, c) -> Sym+c
1603   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1604     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1605         GA->getOpcode() == ISD::GlobalAddress)
1606       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1607                                   GA->getOffset() +
1608                                     (uint64_t)N1C->getSExtValue());
1609   // fold ((c1-A)+c2) -> (c1+c2)-A
1610   if (N1C && N0.getOpcode() == ISD::SUB)
1611     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1612       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1613                          DAG.getConstant(N1C->getAPIntValue()+
1614                                          N0C->getAPIntValue(), VT),
1615                          N0.getOperand(1));
1616   // reassociate add
1617   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1618   if (RADD.getNode())
1619     return RADD;
1620   // fold ((0-A) + B) -> B-A
1621   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1622       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1623     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1624   // fold (A + (0-B)) -> A-B
1625   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1626       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1627     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1628   // fold (A+(B-A)) -> B
1629   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1630     return N1.getOperand(0);
1631   // fold ((B-A)+A) -> B
1632   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1633     return N0.getOperand(0);
1634   // fold (A+(B-(A+C))) to (B-C)
1635   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1636       N0 == N1.getOperand(1).getOperand(0))
1637     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1638                        N1.getOperand(1).getOperand(1));
1639   // fold (A+(B-(C+A))) to (B-C)
1640   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1641       N0 == N1.getOperand(1).getOperand(1))
1642     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1643                        N1.getOperand(1).getOperand(0));
1644   // fold (A+((B-A)+or-C)) to (B+or-C)
1645   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1646       N1.getOperand(0).getOpcode() == ISD::SUB &&
1647       N0 == N1.getOperand(0).getOperand(1))
1648     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1649                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1650
1651   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1652   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1653     SDValue N00 = N0.getOperand(0);
1654     SDValue N01 = N0.getOperand(1);
1655     SDValue N10 = N1.getOperand(0);
1656     SDValue N11 = N1.getOperand(1);
1657
1658     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1659       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1660                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1661                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1662   }
1663
1664   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1665     return SDValue(N, 0);
1666
1667   // fold (a+b) -> (a|b) iff a and b share no bits.
1668   if (VT.isInteger() && !VT.isVector()) {
1669     APInt LHSZero, LHSOne;
1670     APInt RHSZero, RHSOne;
1671     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1672
1673     if (LHSZero.getBoolValue()) {
1674       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1675
1676       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1677       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1678       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1679         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1680           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1681       }
1682     }
1683   }
1684
1685   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1686   if (N1.getOpcode() == ISD::SHL &&
1687       N1.getOperand(0).getOpcode() == ISD::SUB)
1688     if (ConstantSDNode *C =
1689           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1690       if (C->getAPIntValue() == 0)
1691         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1692                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1693                                        N1.getOperand(0).getOperand(1),
1694                                        N1.getOperand(1)));
1695   if (N0.getOpcode() == ISD::SHL &&
1696       N0.getOperand(0).getOpcode() == ISD::SUB)
1697     if (ConstantSDNode *C =
1698           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1699       if (C->getAPIntValue() == 0)
1700         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1701                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1702                                        N0.getOperand(0).getOperand(1),
1703                                        N0.getOperand(1)));
1704
1705   if (N1.getOpcode() == ISD::AND) {
1706     SDValue AndOp0 = N1.getOperand(0);
1707     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1708     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1709     unsigned DestBits = VT.getScalarType().getSizeInBits();
1710
1711     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1712     // and similar xforms where the inner op is either ~0 or 0.
1713     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1714       SDLoc DL(N);
1715       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1716     }
1717   }
1718
1719   // add (sext i1), X -> sub X, (zext i1)
1720   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1721       N0.getOperand(0).getValueType() == MVT::i1 &&
1722       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1723     SDLoc DL(N);
1724     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1725     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1726   }
1727
1728   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1729   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1730     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1731     if (TN->getVT() == MVT::i1) {
1732       SDLoc DL(N);
1733       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1734                                  DAG.getConstant(1, VT));
1735       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1736     }
1737   }
1738
1739   return SDValue();
1740 }
1741
1742 SDValue DAGCombiner::visitADDC(SDNode *N) {
1743   SDValue N0 = N->getOperand(0);
1744   SDValue N1 = N->getOperand(1);
1745   EVT VT = N0.getValueType();
1746
1747   // If the flag result is dead, turn this into an ADD.
1748   if (!N->hasAnyUseOfValue(1))
1749     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1750                      DAG.getNode(ISD::CARRY_FALSE,
1751                                  SDLoc(N), MVT::Glue));
1752
1753   // canonicalize constant to RHS.
1754   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1755   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1756   if (N0C && !N1C)
1757     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1758
1759   // fold (addc x, 0) -> x + no carry out
1760   if (N1C && N1C->isNullValue())
1761     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1762                                         SDLoc(N), MVT::Glue));
1763
1764   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1765   APInt LHSZero, LHSOne;
1766   APInt RHSZero, RHSOne;
1767   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1768
1769   if (LHSZero.getBoolValue()) {
1770     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1771
1772     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1773     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1774     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1775       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1776                        DAG.getNode(ISD::CARRY_FALSE,
1777                                    SDLoc(N), MVT::Glue));
1778   }
1779
1780   return SDValue();
1781 }
1782
1783 SDValue DAGCombiner::visitADDE(SDNode *N) {
1784   SDValue N0 = N->getOperand(0);
1785   SDValue N1 = N->getOperand(1);
1786   SDValue CarryIn = N->getOperand(2);
1787
1788   // canonicalize constant to RHS
1789   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1790   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1791   if (N0C && !N1C)
1792     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1793                        N1, N0, CarryIn);
1794
1795   // fold (adde x, y, false) -> (addc x, y)
1796   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1797     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1798
1799   return SDValue();
1800 }
1801
1802 // Since it may not be valid to emit a fold to zero for vector initializers
1803 // check if we can before folding.
1804 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1805                              SelectionDAG &DAG,
1806                              bool LegalOperations, bool LegalTypes) {
1807   if (!VT.isVector())
1808     return DAG.getConstant(0, VT);
1809   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1810     return DAG.getConstant(0, VT);
1811   return SDValue();
1812 }
1813
1814 SDValue DAGCombiner::visitSUB(SDNode *N) {
1815   SDValue N0 = N->getOperand(0);
1816   SDValue N1 = N->getOperand(1);
1817   EVT VT = N0.getValueType();
1818
1819   // fold vector ops
1820   if (VT.isVector()) {
1821     SDValue FoldedVOp = SimplifyVBinOp(N);
1822     if (FoldedVOp.getNode()) return FoldedVOp;
1823
1824     // fold (sub x, 0) -> x, vector edition
1825     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1826       return N0;
1827   }
1828
1829   // fold (sub x, x) -> 0
1830   // FIXME: Refactor this and xor and other similar operations together.
1831   if (N0 == N1)
1832     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1833   // fold (sub c1, c2) -> c1-c2
1834   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1835   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1836   if (N0C && N1C)
1837     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1838   // fold (sub x, c) -> (add x, -c)
1839   if (N1C)
1840     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1841                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1842   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1843   if (N0C && N0C->isAllOnesValue())
1844     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1845   // fold A-(A-B) -> B
1846   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1847     return N1.getOperand(1);
1848   // fold (A+B)-A -> B
1849   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1850     return N0.getOperand(1);
1851   // fold (A+B)-B -> A
1852   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1853     return N0.getOperand(0);
1854   // fold C2-(A+C1) -> (C2-C1)-A
1855   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1856     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1857   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1858     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1859                                    VT);
1860     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1861                        N1.getOperand(0));
1862   }
1863   // fold ((A+(B+or-C))-B) -> A+or-C
1864   if (N0.getOpcode() == ISD::ADD &&
1865       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1866        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1867       N0.getOperand(1).getOperand(0) == N1)
1868     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1869                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1870   // fold ((A+(C+B))-B) -> A+C
1871   if (N0.getOpcode() == ISD::ADD &&
1872       N0.getOperand(1).getOpcode() == ISD::ADD &&
1873       N0.getOperand(1).getOperand(1) == N1)
1874     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1875                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1876   // fold ((A-(B-C))-C) -> A-B
1877   if (N0.getOpcode() == ISD::SUB &&
1878       N0.getOperand(1).getOpcode() == ISD::SUB &&
1879       N0.getOperand(1).getOperand(1) == N1)
1880     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1881                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1882
1883   // If either operand of a sub is undef, the result is undef
1884   if (N0.getOpcode() == ISD::UNDEF)
1885     return N0;
1886   if (N1.getOpcode() == ISD::UNDEF)
1887     return N1;
1888
1889   // If the relocation model supports it, consider symbol offsets.
1890   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1891     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1892       // fold (sub Sym, c) -> Sym-c
1893       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1894         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1895                                     GA->getOffset() -
1896                                       (uint64_t)N1C->getSExtValue());
1897       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1898       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1899         if (GA->getGlobal() == GB->getGlobal())
1900           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1901                                  VT);
1902     }
1903
1904   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1905   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1906     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1907     if (TN->getVT() == MVT::i1) {
1908       SDLoc DL(N);
1909       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1910                                  DAG.getConstant(1, VT));
1911       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1912     }
1913   }
1914
1915   return SDValue();
1916 }
1917
1918 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1919   SDValue N0 = N->getOperand(0);
1920   SDValue N1 = N->getOperand(1);
1921   EVT VT = N0.getValueType();
1922
1923   // If the flag result is dead, turn this into an SUB.
1924   if (!N->hasAnyUseOfValue(1))
1925     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1926                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1927                                  MVT::Glue));
1928
1929   // fold (subc x, x) -> 0 + no borrow
1930   if (N0 == N1)
1931     return CombineTo(N, DAG.getConstant(0, VT),
1932                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1933                                  MVT::Glue));
1934
1935   // fold (subc x, 0) -> x + no borrow
1936   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1937   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1938   if (N1C && N1C->isNullValue())
1939     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1940                                         MVT::Glue));
1941
1942   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1943   if (N0C && N0C->isAllOnesValue())
1944     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1945                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1946                                  MVT::Glue));
1947
1948   return SDValue();
1949 }
1950
1951 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1952   SDValue N0 = N->getOperand(0);
1953   SDValue N1 = N->getOperand(1);
1954   SDValue CarryIn = N->getOperand(2);
1955
1956   // fold (sube x, y, false) -> (subc x, y)
1957   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1958     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1959
1960   return SDValue();
1961 }
1962
1963 SDValue DAGCombiner::visitMUL(SDNode *N) {
1964   SDValue N0 = N->getOperand(0);
1965   SDValue N1 = N->getOperand(1);
1966   EVT VT = N0.getValueType();
1967
1968   // fold (mul x, undef) -> 0
1969   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1970     return DAG.getConstant(0, VT);
1971
1972   bool N0IsConst = false;
1973   bool N1IsConst = false;
1974   APInt ConstValue0, ConstValue1;
1975   // fold vector ops
1976   if (VT.isVector()) {
1977     SDValue FoldedVOp = SimplifyVBinOp(N);
1978     if (FoldedVOp.getNode()) return FoldedVOp;
1979
1980     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1981     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1982   } else {
1983     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1984     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1985                             : APInt();
1986     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1987     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1988                             : APInt();
1989   }
1990
1991   // fold (mul c1, c2) -> c1*c2
1992   if (N0IsConst && N1IsConst)
1993     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1994
1995   // canonicalize constant to RHS
1996   if (N0IsConst && !N1IsConst)
1997     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1998   // fold (mul x, 0) -> 0
1999   if (N1IsConst && ConstValue1 == 0)
2000     return N1;
2001   // We require a splat of the entire scalar bit width for non-contiguous
2002   // bit patterns.
2003   bool IsFullSplat =
2004     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2005   // fold (mul x, 1) -> x
2006   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2007     return N0;
2008   // fold (mul x, -1) -> 0-x
2009   if (N1IsConst && ConstValue1.isAllOnesValue())
2010     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2011                        DAG.getConstant(0, VT), N0);
2012   // fold (mul x, (1 << c)) -> x << c
2013   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2014     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2015                        DAG.getConstant(ConstValue1.logBase2(),
2016                                        getShiftAmountTy(N0.getValueType())));
2017   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2018   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2019     unsigned Log2Val = (-ConstValue1).logBase2();
2020     // FIXME: If the input is something that is easily negated (e.g. a
2021     // single-use add), we should put the negate there.
2022     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2023                        DAG.getConstant(0, VT),
2024                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2025                             DAG.getConstant(Log2Val,
2026                                       getShiftAmountTy(N0.getValueType()))));
2027   }
2028
2029   APInt Val;
2030   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2031   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2032       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2033                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2034     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2035                              N1, N0.getOperand(1));
2036     AddToWorklist(C3.getNode());
2037     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2038                        N0.getOperand(0), C3);
2039   }
2040
2041   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2042   // use.
2043   {
2044     SDValue Sh(nullptr,0), Y(nullptr,0);
2045     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2046     if (N0.getOpcode() == ISD::SHL &&
2047         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2048                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2049         N0.getNode()->hasOneUse()) {
2050       Sh = N0; Y = N1;
2051     } else if (N1.getOpcode() == ISD::SHL &&
2052                isa<ConstantSDNode>(N1.getOperand(1)) &&
2053                N1.getNode()->hasOneUse()) {
2054       Sh = N1; Y = N0;
2055     }
2056
2057     if (Sh.getNode()) {
2058       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2059                                 Sh.getOperand(0), Y);
2060       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2061                          Mul, Sh.getOperand(1));
2062     }
2063   }
2064
2065   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2066   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2067       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2068                      isa<ConstantSDNode>(N0.getOperand(1))))
2069     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2070                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2071                                    N0.getOperand(0), N1),
2072                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2073                                    N0.getOperand(1), N1));
2074
2075   // reassociate mul
2076   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2077   if (RMUL.getNode())
2078     return RMUL;
2079
2080   return SDValue();
2081 }
2082
2083 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2084   SDValue N0 = N->getOperand(0);
2085   SDValue N1 = N->getOperand(1);
2086   EVT VT = N->getValueType(0);
2087
2088   // fold vector ops
2089   if (VT.isVector()) {
2090     SDValue FoldedVOp = SimplifyVBinOp(N);
2091     if (FoldedVOp.getNode()) return FoldedVOp;
2092   }
2093
2094   // fold (sdiv c1, c2) -> c1/c2
2095   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2096   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2097   if (N0C && N1C && !N1C->isNullValue())
2098     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2099   // fold (sdiv X, 1) -> X
2100   if (N1C && N1C->getAPIntValue() == 1LL)
2101     return N0;
2102   // fold (sdiv X, -1) -> 0-X
2103   if (N1C && N1C->isAllOnesValue())
2104     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2105                        DAG.getConstant(0, VT), N0);
2106   // If we know the sign bits of both operands are zero, strength reduce to a
2107   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2108   if (!VT.isVector()) {
2109     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2110       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2111                          N0, N1);
2112   }
2113
2114   // fold (sdiv X, pow2) -> simple ops after legalize
2115   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2116                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2117     // If dividing by powers of two is cheap, then don't perform the following
2118     // fold.
2119     if (TLI.isPow2SDivCheap())
2120       return SDValue();
2121
2122     // Target-specific implementation of sdiv x, pow2.
2123     SDValue Res = BuildSDIVPow2(N);
2124     if (Res.getNode())
2125       return Res;
2126
2127     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2128
2129     // Splat the sign bit into the register
2130     SDValue SGN =
2131         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2132                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2133                                     getShiftAmountTy(N0.getValueType())));
2134     AddToWorklist(SGN.getNode());
2135
2136     // Add (N0 < 0) ? abs2 - 1 : 0;
2137     SDValue SRL =
2138         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2139                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2140                                     getShiftAmountTy(SGN.getValueType())));
2141     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2142     AddToWorklist(SRL.getNode());
2143     AddToWorklist(ADD.getNode());    // Divide by pow2
2144     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2145                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2146
2147     // If we're dividing by a positive value, we're done.  Otherwise, we must
2148     // negate the result.
2149     if (N1C->getAPIntValue().isNonNegative())
2150       return SRA;
2151
2152     AddToWorklist(SRA.getNode());
2153     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2154   }
2155
2156   // if integer divide is expensive and we satisfy the requirements, emit an
2157   // alternate sequence.
2158   if (N1C && !TLI.isIntDivCheap()) {
2159     SDValue Op = BuildSDIV(N);
2160     if (Op.getNode()) return Op;
2161   }
2162
2163   // undef / X -> 0
2164   if (N0.getOpcode() == ISD::UNDEF)
2165     return DAG.getConstant(0, VT);
2166   // X / undef -> undef
2167   if (N1.getOpcode() == ISD::UNDEF)
2168     return N1;
2169
2170   return SDValue();
2171 }
2172
2173 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2174   SDValue N0 = N->getOperand(0);
2175   SDValue N1 = N->getOperand(1);
2176   EVT VT = N->getValueType(0);
2177
2178   // fold vector ops
2179   if (VT.isVector()) {
2180     SDValue FoldedVOp = SimplifyVBinOp(N);
2181     if (FoldedVOp.getNode()) return FoldedVOp;
2182   }
2183
2184   // fold (udiv c1, c2) -> c1/c2
2185   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2186   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2187   if (N0C && N1C && !N1C->isNullValue())
2188     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2189   // fold (udiv x, (1 << c)) -> x >>u c
2190   if (N1C && N1C->getAPIntValue().isPowerOf2())
2191     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2192                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2193                                        getShiftAmountTy(N0.getValueType())));
2194   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2195   if (N1.getOpcode() == ISD::SHL) {
2196     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2197       if (SHC->getAPIntValue().isPowerOf2()) {
2198         EVT ADDVT = N1.getOperand(1).getValueType();
2199         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2200                                   N1.getOperand(1),
2201                                   DAG.getConstant(SHC->getAPIntValue()
2202                                                                   .logBase2(),
2203                                                   ADDVT));
2204         AddToWorklist(Add.getNode());
2205         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2206       }
2207     }
2208   }
2209   // fold (udiv x, c) -> alternate
2210   if (N1C && !TLI.isIntDivCheap()) {
2211     SDValue Op = BuildUDIV(N);
2212     if (Op.getNode()) return Op;
2213   }
2214
2215   // undef / X -> 0
2216   if (N0.getOpcode() == ISD::UNDEF)
2217     return DAG.getConstant(0, VT);
2218   // X / undef -> undef
2219   if (N1.getOpcode() == ISD::UNDEF)
2220     return N1;
2221
2222   return SDValue();
2223 }
2224
2225 SDValue DAGCombiner::visitSREM(SDNode *N) {
2226   SDValue N0 = N->getOperand(0);
2227   SDValue N1 = N->getOperand(1);
2228   EVT VT = N->getValueType(0);
2229
2230   // fold (srem c1, c2) -> c1%c2
2231   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2233   if (N0C && N1C && !N1C->isNullValue())
2234     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2235   // If we know the sign bits of both operands are zero, strength reduce to a
2236   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2237   if (!VT.isVector()) {
2238     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2239       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2240   }
2241
2242   // If X/C can be simplified by the division-by-constant logic, lower
2243   // X%C to the equivalent of X-X/C*C.
2244   if (N1C && !N1C->isNullValue()) {
2245     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2246     AddToWorklist(Div.getNode());
2247     SDValue OptimizedDiv = combine(Div.getNode());
2248     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2249       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2250                                 OptimizedDiv, N1);
2251       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2252       AddToWorklist(Mul.getNode());
2253       return Sub;
2254     }
2255   }
2256
2257   // undef % X -> 0
2258   if (N0.getOpcode() == ISD::UNDEF)
2259     return DAG.getConstant(0, VT);
2260   // X % undef -> undef
2261   if (N1.getOpcode() == ISD::UNDEF)
2262     return N1;
2263
2264   return SDValue();
2265 }
2266
2267 SDValue DAGCombiner::visitUREM(SDNode *N) {
2268   SDValue N0 = N->getOperand(0);
2269   SDValue N1 = N->getOperand(1);
2270   EVT VT = N->getValueType(0);
2271
2272   // fold (urem c1, c2) -> c1%c2
2273   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2274   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2275   if (N0C && N1C && !N1C->isNullValue())
2276     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2277   // fold (urem x, pow2) -> (and x, pow2-1)
2278   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2279     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2280                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2281   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2282   if (N1.getOpcode() == ISD::SHL) {
2283     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2284       if (SHC->getAPIntValue().isPowerOf2()) {
2285         SDValue Add =
2286           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2287                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2288                                  VT));
2289         AddToWorklist(Add.getNode());
2290         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2291       }
2292     }
2293   }
2294
2295   // If X/C can be simplified by the division-by-constant logic, lower
2296   // X%C to the equivalent of X-X/C*C.
2297   if (N1C && !N1C->isNullValue()) {
2298     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2299     AddToWorklist(Div.getNode());
2300     SDValue OptimizedDiv = combine(Div.getNode());
2301     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2302       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2303                                 OptimizedDiv, N1);
2304       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2305       AddToWorklist(Mul.getNode());
2306       return Sub;
2307     }
2308   }
2309
2310   // undef % X -> 0
2311   if (N0.getOpcode() == ISD::UNDEF)
2312     return DAG.getConstant(0, VT);
2313   // X % undef -> undef
2314   if (N1.getOpcode() == ISD::UNDEF)
2315     return N1;
2316
2317   return SDValue();
2318 }
2319
2320 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2321   SDValue N0 = N->getOperand(0);
2322   SDValue N1 = N->getOperand(1);
2323   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2324   EVT VT = N->getValueType(0);
2325   SDLoc DL(N);
2326
2327   // fold (mulhs x, 0) -> 0
2328   if (N1C && N1C->isNullValue())
2329     return N1;
2330   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2331   if (N1C && N1C->getAPIntValue() == 1)
2332     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2333                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2334                                        getShiftAmountTy(N0.getValueType())));
2335   // fold (mulhs x, undef) -> 0
2336   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2337     return DAG.getConstant(0, VT);
2338
2339   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2340   // plus a shift.
2341   if (VT.isSimple() && !VT.isVector()) {
2342     MVT Simple = VT.getSimpleVT();
2343     unsigned SimpleSize = Simple.getSizeInBits();
2344     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2345     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2346       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2347       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2348       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2349       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2350             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2351       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2352     }
2353   }
2354
2355   return SDValue();
2356 }
2357
2358 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2359   SDValue N0 = N->getOperand(0);
2360   SDValue N1 = N->getOperand(1);
2361   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2362   EVT VT = N->getValueType(0);
2363   SDLoc DL(N);
2364
2365   // fold (mulhu x, 0) -> 0
2366   if (N1C && N1C->isNullValue())
2367     return N1;
2368   // fold (mulhu x, 1) -> 0
2369   if (N1C && N1C->getAPIntValue() == 1)
2370     return DAG.getConstant(0, N0.getValueType());
2371   // fold (mulhu x, undef) -> 0
2372   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2373     return DAG.getConstant(0, VT);
2374
2375   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2376   // plus a shift.
2377   if (VT.isSimple() && !VT.isVector()) {
2378     MVT Simple = VT.getSimpleVT();
2379     unsigned SimpleSize = Simple.getSizeInBits();
2380     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2381     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2382       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2383       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2384       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2385       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2386             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2387       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2388     }
2389   }
2390
2391   return SDValue();
2392 }
2393
2394 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2395 /// give the opcodes for the two computations that are being performed. Return
2396 /// true if a simplification was made.
2397 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2398                                                 unsigned HiOp) {
2399   // If the high half is not needed, just compute the low half.
2400   bool HiExists = N->hasAnyUseOfValue(1);
2401   if (!HiExists &&
2402       (!LegalOperations ||
2403        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2404     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2405     return CombineTo(N, Res, Res);
2406   }
2407
2408   // If the low half is not needed, just compute the high half.
2409   bool LoExists = N->hasAnyUseOfValue(0);
2410   if (!LoExists &&
2411       (!LegalOperations ||
2412        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2413     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2414     return CombineTo(N, Res, Res);
2415   }
2416
2417   // If both halves are used, return as it is.
2418   if (LoExists && HiExists)
2419     return SDValue();
2420
2421   // If the two computed results can be simplified separately, separate them.
2422   if (LoExists) {
2423     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2424     AddToWorklist(Lo.getNode());
2425     SDValue LoOpt = combine(Lo.getNode());
2426     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2427         (!LegalOperations ||
2428          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2429       return CombineTo(N, LoOpt, LoOpt);
2430   }
2431
2432   if (HiExists) {
2433     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2434     AddToWorklist(Hi.getNode());
2435     SDValue HiOpt = combine(Hi.getNode());
2436     if (HiOpt.getNode() && HiOpt != Hi &&
2437         (!LegalOperations ||
2438          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2439       return CombineTo(N, HiOpt, HiOpt);
2440   }
2441
2442   return SDValue();
2443 }
2444
2445 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2446   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2447   if (Res.getNode()) return Res;
2448
2449   EVT VT = N->getValueType(0);
2450   SDLoc DL(N);
2451
2452   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2453   // plus a shift.
2454   if (VT.isSimple() && !VT.isVector()) {
2455     MVT Simple = VT.getSimpleVT();
2456     unsigned SimpleSize = Simple.getSizeInBits();
2457     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2458     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2459       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2460       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2461       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2462       // Compute the high part as N1.
2463       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2464             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2465       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2466       // Compute the low part as N0.
2467       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2468       return CombineTo(N, Lo, Hi);
2469     }
2470   }
2471
2472   return SDValue();
2473 }
2474
2475 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2476   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2477   if (Res.getNode()) return Res;
2478
2479   EVT VT = N->getValueType(0);
2480   SDLoc DL(N);
2481
2482   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2483   // plus a shift.
2484   if (VT.isSimple() && !VT.isVector()) {
2485     MVT Simple = VT.getSimpleVT();
2486     unsigned SimpleSize = Simple.getSizeInBits();
2487     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2488     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2489       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2490       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2491       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2492       // Compute the high part as N1.
2493       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2494             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2495       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2496       // Compute the low part as N0.
2497       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2498       return CombineTo(N, Lo, Hi);
2499     }
2500   }
2501
2502   return SDValue();
2503 }
2504
2505 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2506   // (smulo x, 2) -> (saddo x, x)
2507   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2508     if (C2->getAPIntValue() == 2)
2509       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2510                          N->getOperand(0), N->getOperand(0));
2511
2512   return SDValue();
2513 }
2514
2515 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2516   // (umulo x, 2) -> (uaddo x, x)
2517   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2518     if (C2->getAPIntValue() == 2)
2519       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2520                          N->getOperand(0), N->getOperand(0));
2521
2522   return SDValue();
2523 }
2524
2525 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2526   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2527   if (Res.getNode()) return Res;
2528
2529   return SDValue();
2530 }
2531
2532 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2533   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2534   if (Res.getNode()) return Res;
2535
2536   return SDValue();
2537 }
2538
2539 /// If this is a binary operator with two operands of the same opcode, try to
2540 /// simplify it.
2541 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2542   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2543   EVT VT = N0.getValueType();
2544   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2545
2546   // Bail early if none of these transforms apply.
2547   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2548
2549   // For each of OP in AND/OR/XOR:
2550   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2551   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2552   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2553   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2554   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2555   //
2556   // do not sink logical op inside of a vector extend, since it may combine
2557   // into a vsetcc.
2558   EVT Op0VT = N0.getOperand(0).getValueType();
2559   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2560        N0.getOpcode() == ISD::SIGN_EXTEND ||
2561        N0.getOpcode() == ISD::BSWAP ||
2562        // Avoid infinite looping with PromoteIntBinOp.
2563        (N0.getOpcode() == ISD::ANY_EXTEND &&
2564         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2565        (N0.getOpcode() == ISD::TRUNCATE &&
2566         (!TLI.isZExtFree(VT, Op0VT) ||
2567          !TLI.isTruncateFree(Op0VT, VT)) &&
2568         TLI.isTypeLegal(Op0VT))) &&
2569       !VT.isVector() &&
2570       Op0VT == N1.getOperand(0).getValueType() &&
2571       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2572     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2573                                  N0.getOperand(0).getValueType(),
2574                                  N0.getOperand(0), N1.getOperand(0));
2575     AddToWorklist(ORNode.getNode());
2576     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2577   }
2578
2579   // For each of OP in SHL/SRL/SRA/AND...
2580   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2581   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2582   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2583   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2584        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2585       N0.getOperand(1) == N1.getOperand(1)) {
2586     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2587                                  N0.getOperand(0).getValueType(),
2588                                  N0.getOperand(0), N1.getOperand(0));
2589     AddToWorklist(ORNode.getNode());
2590     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2591                        ORNode, N0.getOperand(1));
2592   }
2593
2594   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2595   // Only perform this optimization after type legalization and before
2596   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2597   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2598   // we don't want to undo this promotion.
2599   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2600   // on scalars.
2601   if ((N0.getOpcode() == ISD::BITCAST ||
2602        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2603       Level == AfterLegalizeTypes) {
2604     SDValue In0 = N0.getOperand(0);
2605     SDValue In1 = N1.getOperand(0);
2606     EVT In0Ty = In0.getValueType();
2607     EVT In1Ty = In1.getValueType();
2608     SDLoc DL(N);
2609     // If both incoming values are integers, and the original types are the
2610     // same.
2611     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2612       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2613       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2614       AddToWorklist(Op.getNode());
2615       return BC;
2616     }
2617   }
2618
2619   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2620   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2621   // If both shuffles use the same mask, and both shuffle within a single
2622   // vector, then it is worthwhile to move the swizzle after the operation.
2623   // The type-legalizer generates this pattern when loading illegal
2624   // vector types from memory. In many cases this allows additional shuffle
2625   // optimizations.
2626   // There are other cases where moving the shuffle after the xor/and/or
2627   // is profitable even if shuffles don't perform a swizzle.
2628   // If both shuffles use the same mask, and both shuffles have the same first
2629   // or second operand, then it might still be profitable to move the shuffle
2630   // after the xor/and/or operation.
2631   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2632     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2633     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2634
2635     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2636            "Inputs to shuffles are not the same type");
2637
2638     // Check that both shuffles use the same mask. The masks are known to be of
2639     // the same length because the result vector type is the same.
2640     // Check also that shuffles have only one use to avoid introducing extra
2641     // instructions.
2642     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2643         SVN0->getMask().equals(SVN1->getMask())) {
2644       SDValue ShOp = N0->getOperand(1);
2645
2646       // Don't try to fold this node if it requires introducing a
2647       // build vector of all zeros that might be illegal at this stage.
2648       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2649         if (!LegalTypes)
2650           ShOp = DAG.getConstant(0, VT);
2651         else
2652           ShOp = SDValue();
2653       }
2654
2655       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2656       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2657       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2658       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2659         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2660                                       N0->getOperand(0), N1->getOperand(0));
2661         AddToWorklist(NewNode.getNode());
2662         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2663                                     &SVN0->getMask()[0]);
2664       }
2665
2666       // Don't try to fold this node if it requires introducing a
2667       // build vector of all zeros that might be illegal at this stage.
2668       ShOp = N0->getOperand(0);
2669       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2670         if (!LegalTypes)
2671           ShOp = DAG.getConstant(0, VT);
2672         else
2673           ShOp = SDValue();
2674       }
2675
2676       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2677       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2678       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2679       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2680         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2681                                       N0->getOperand(1), N1->getOperand(1));
2682         AddToWorklist(NewNode.getNode());
2683         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2684                                     &SVN0->getMask()[0]);
2685       }
2686     }
2687   }
2688
2689   return SDValue();
2690 }
2691
2692 /// This contains all DAGCombine rules which reduce two values combined by
2693 /// an And operation to a single value. This makes them reusable in the context
2694 /// of visitSELECT(). Rules involving constants are not included as
2695 /// visitSELECT() already handles those cases.
2696 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2697                                   SDNode *LocReference) {
2698   EVT VT = N1.getValueType();
2699
2700   // fold (and x, undef) -> 0
2701   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2702     return DAG.getConstant(0, VT);
2703   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2704   SDValue LL, LR, RL, RR, CC0, CC1;
2705   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2706     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2707     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2708
2709     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2710         LL.getValueType().isInteger()) {
2711       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2712       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2713         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2714                                      LR.getValueType(), LL, RL);
2715         AddToWorklist(ORNode.getNode());
2716         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2717       }
2718       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2719       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2720         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2721                                       LR.getValueType(), LL, RL);
2722         AddToWorklist(ANDNode.getNode());
2723         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2724       }
2725       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2726       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2727         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2728                                      LR.getValueType(), LL, RL);
2729         AddToWorklist(ORNode.getNode());
2730         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2731       }
2732     }
2733     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2734     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2735         Op0 == Op1 && LL.getValueType().isInteger() &&
2736       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2737                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2738                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2739                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2740       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2741                                     LL, DAG.getConstant(1, LL.getValueType()));
2742       AddToWorklist(ADDNode.getNode());
2743       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2744                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2745     }
2746     // canonicalize equivalent to ll == rl
2747     if (LL == RR && LR == RL) {
2748       Op1 = ISD::getSetCCSwappedOperands(Op1);
2749       std::swap(RL, RR);
2750     }
2751     if (LL == RL && LR == RR) {
2752       bool isInteger = LL.getValueType().isInteger();
2753       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2754       if (Result != ISD::SETCC_INVALID &&
2755           (!LegalOperations ||
2756            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2757             TLI.isOperationLegal(ISD::SETCC,
2758                             getSetCCResultType(N0.getSimpleValueType())))))
2759         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2760                             LL, LR, Result);
2761     }
2762   }
2763
2764   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2765       VT.getSizeInBits() <= 64) {
2766     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2767       APInt ADDC = ADDI->getAPIntValue();
2768       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2769         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2770         // immediate for an add, but it is legal if its top c2 bits are set,
2771         // transform the ADD so the immediate doesn't need to be materialized
2772         // in a register.
2773         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2774           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2775                                              SRLI->getZExtValue());
2776           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2777             ADDC |= Mask;
2778             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2779               SDValue NewAdd =
2780                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2781                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2782               CombineTo(N0.getNode(), NewAdd);
2783               // Return N so it doesn't get rechecked!
2784               return SDValue(LocReference, 0);
2785             }
2786           }
2787         }
2788       }
2789     }
2790   }
2791
2792   return SDValue();
2793 }
2794
2795 SDValue DAGCombiner::visitAND(SDNode *N) {
2796   SDValue N0 = N->getOperand(0);
2797   SDValue N1 = N->getOperand(1);
2798   EVT VT = N1.getValueType();
2799
2800   // fold vector ops
2801   if (VT.isVector()) {
2802     SDValue FoldedVOp = SimplifyVBinOp(N);
2803     if (FoldedVOp.getNode()) return FoldedVOp;
2804
2805     // fold (and x, 0) -> 0, vector edition
2806     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2807       // do not return N0, because undef node may exist in N0
2808       return DAG.getConstant(
2809           APInt::getNullValue(
2810               N0.getValueType().getScalarType().getSizeInBits()),
2811           N0.getValueType());
2812     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2813       // do not return N1, because undef node may exist in N1
2814       return DAG.getConstant(
2815           APInt::getNullValue(
2816               N1.getValueType().getScalarType().getSizeInBits()),
2817           N1.getValueType());
2818
2819     // fold (and x, -1) -> x, vector edition
2820     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2821       return N1;
2822     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2823       return N0;
2824   }
2825
2826   // fold (and c1, c2) -> c1&c2
2827   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2828   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2829   if (N0C && N1C)
2830     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2831   // canonicalize constant to RHS
2832   if (N0C && !N1C)
2833     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2834   // fold (and x, -1) -> x
2835   if (N1C && N1C->isAllOnesValue())
2836     return N0;
2837   // if (and x, c) is known to be zero, return 0
2838   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2839   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2840                                    APInt::getAllOnesValue(BitWidth)))
2841     return DAG.getConstant(0, VT);
2842   // reassociate and
2843   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2844   if (RAND.getNode())
2845     return RAND;
2846   // fold (and (or x, C), D) -> D if (C & D) == D
2847   if (N1C && N0.getOpcode() == ISD::OR)
2848     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2849       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2850         return N1;
2851   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2852   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2853     SDValue N0Op0 = N0.getOperand(0);
2854     APInt Mask = ~N1C->getAPIntValue();
2855     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2856     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2857       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2858                                  N0.getValueType(), N0Op0);
2859
2860       // Replace uses of the AND with uses of the Zero extend node.
2861       CombineTo(N, Zext);
2862
2863       // We actually want to replace all uses of the any_extend with the
2864       // zero_extend, to avoid duplicating things.  This will later cause this
2865       // AND to be folded.
2866       CombineTo(N0.getNode(), Zext);
2867       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2868     }
2869   }
2870   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2871   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2872   // already be zero by virtue of the width of the base type of the load.
2873   //
2874   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2875   // more cases.
2876   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2877        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2878       N0.getOpcode() == ISD::LOAD) {
2879     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2880                                          N0 : N0.getOperand(0) );
2881
2882     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2883     // This can be a pure constant or a vector splat, in which case we treat the
2884     // vector as a scalar and use the splat value.
2885     APInt Constant = APInt::getNullValue(1);
2886     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2887       Constant = C->getAPIntValue();
2888     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2889       APInt SplatValue, SplatUndef;
2890       unsigned SplatBitSize;
2891       bool HasAnyUndefs;
2892       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2893                                              SplatBitSize, HasAnyUndefs);
2894       if (IsSplat) {
2895         // Undef bits can contribute to a possible optimisation if set, so
2896         // set them.
2897         SplatValue |= SplatUndef;
2898
2899         // The splat value may be something like "0x00FFFFFF", which means 0 for
2900         // the first vector value and FF for the rest, repeating. We need a mask
2901         // that will apply equally to all members of the vector, so AND all the
2902         // lanes of the constant together.
2903         EVT VT = Vector->getValueType(0);
2904         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2905
2906         // If the splat value has been compressed to a bitlength lower
2907         // than the size of the vector lane, we need to re-expand it to
2908         // the lane size.
2909         if (BitWidth > SplatBitSize)
2910           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2911                SplatBitSize < BitWidth;
2912                SplatBitSize = SplatBitSize * 2)
2913             SplatValue |= SplatValue.shl(SplatBitSize);
2914
2915         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2916         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2917         if (SplatBitSize % BitWidth == 0) {
2918           Constant = APInt::getAllOnesValue(BitWidth);
2919           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2920             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2921         }
2922       }
2923     }
2924
2925     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2926     // actually legal and isn't going to get expanded, else this is a false
2927     // optimisation.
2928     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2929                                                     Load->getValueType(0),
2930                                                     Load->getMemoryVT());
2931
2932     // Resize the constant to the same size as the original memory access before
2933     // extension. If it is still the AllOnesValue then this AND is completely
2934     // unneeded.
2935     Constant =
2936       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2937
2938     bool B;
2939     switch (Load->getExtensionType()) {
2940     default: B = false; break;
2941     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2942     case ISD::ZEXTLOAD:
2943     case ISD::NON_EXTLOAD: B = true; break;
2944     }
2945
2946     if (B && Constant.isAllOnesValue()) {
2947       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2948       // preserve semantics once we get rid of the AND.
2949       SDValue NewLoad(Load, 0);
2950       if (Load->getExtensionType() == ISD::EXTLOAD) {
2951         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2952                               Load->getValueType(0), SDLoc(Load),
2953                               Load->getChain(), Load->getBasePtr(),
2954                               Load->getOffset(), Load->getMemoryVT(),
2955                               Load->getMemOperand());
2956         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2957         if (Load->getNumValues() == 3) {
2958           // PRE/POST_INC loads have 3 values.
2959           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2960                            NewLoad.getValue(2) };
2961           CombineTo(Load, To, 3, true);
2962         } else {
2963           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2964         }
2965       }
2966
2967       // Fold the AND away, taking care not to fold to the old load node if we
2968       // replaced it.
2969       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2970
2971       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2972     }
2973   }
2974
2975   // fold (and (load x), 255) -> (zextload x, i8)
2976   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2977   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2978   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2979               (N0.getOpcode() == ISD::ANY_EXTEND &&
2980                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2981     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2982     LoadSDNode *LN0 = HasAnyExt
2983       ? cast<LoadSDNode>(N0.getOperand(0))
2984       : cast<LoadSDNode>(N0);
2985     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2986         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2987       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2988       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2989         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2990         EVT LoadedVT = LN0->getMemoryVT();
2991         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2992
2993         if (ExtVT == LoadedVT &&
2994             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2995                                                     ExtVT))) {
2996
2997           SDValue NewLoad =
2998             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2999                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3000                            LN0->getMemOperand());
3001           AddToWorklist(N);
3002           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3003           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3004         }
3005
3006         // Do not change the width of a volatile load.
3007         // Do not generate loads of non-round integer types since these can
3008         // be expensive (and would be wrong if the type is not byte sized).
3009         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3010             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3011                                                     ExtVT))) {
3012           EVT PtrType = LN0->getOperand(1).getValueType();
3013
3014           unsigned Alignment = LN0->getAlignment();
3015           SDValue NewPtr = LN0->getBasePtr();
3016
3017           // For big endian targets, we need to add an offset to the pointer
3018           // to load the correct bytes.  For little endian systems, we merely
3019           // need to read fewer bytes from the same pointer.
3020           if (TLI.isBigEndian()) {
3021             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3022             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3023             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3024             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3025                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3026             Alignment = MinAlign(Alignment, PtrOff);
3027           }
3028
3029           AddToWorklist(NewPtr.getNode());
3030
3031           SDValue Load =
3032             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3033                            LN0->getChain(), NewPtr,
3034                            LN0->getPointerInfo(),
3035                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3036                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3037           AddToWorklist(N);
3038           CombineTo(LN0, Load, Load.getValue(1));
3039           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3040         }
3041       }
3042     }
3043   }
3044
3045   if (SDValue Combined = visitANDLike(N0, N1, N))
3046     return Combined;
3047
3048   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3049   if (N0.getOpcode() == N1.getOpcode()) {
3050     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3051     if (Tmp.getNode()) return Tmp;
3052   }
3053
3054   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3055   // fold (and (sra)) -> (and (srl)) when possible.
3056   if (!VT.isVector() &&
3057       SimplifyDemandedBits(SDValue(N, 0)))
3058     return SDValue(N, 0);
3059
3060   // fold (zext_inreg (extload x)) -> (zextload x)
3061   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3062     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3063     EVT MemVT = LN0->getMemoryVT();
3064     // If we zero all the possible extended bits, then we can turn this into
3065     // a zextload if we are running before legalize or the operation is legal.
3066     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3067     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3068                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3069         ((!LegalOperations && !LN0->isVolatile()) ||
3070          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3071       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3072                                        LN0->getChain(), LN0->getBasePtr(),
3073                                        MemVT, LN0->getMemOperand());
3074       AddToWorklist(N);
3075       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3076       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3077     }
3078   }
3079   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3080   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3081       N0.hasOneUse()) {
3082     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3083     EVT MemVT = LN0->getMemoryVT();
3084     // If we zero all the possible extended bits, then we can turn this into
3085     // a zextload if we are running before legalize or the operation is legal.
3086     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3087     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3088                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3089         ((!LegalOperations && !LN0->isVolatile()) ||
3090          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3091       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3092                                        LN0->getChain(), LN0->getBasePtr(),
3093                                        MemVT, LN0->getMemOperand());
3094       AddToWorklist(N);
3095       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3096       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3097     }
3098   }
3099   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3100   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3101     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3102                                        N0.getOperand(1), false);
3103     if (BSwap.getNode())
3104       return BSwap;
3105   }
3106
3107   return SDValue();
3108 }
3109
3110 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3111 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3112                                         bool DemandHighBits) {
3113   if (!LegalOperations)
3114     return SDValue();
3115
3116   EVT VT = N->getValueType(0);
3117   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3118     return SDValue();
3119   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3120     return SDValue();
3121
3122   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3123   bool LookPassAnd0 = false;
3124   bool LookPassAnd1 = false;
3125   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3126       std::swap(N0, N1);
3127   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3128       std::swap(N0, N1);
3129   if (N0.getOpcode() == ISD::AND) {
3130     if (!N0.getNode()->hasOneUse())
3131       return SDValue();
3132     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3133     if (!N01C || N01C->getZExtValue() != 0xFF00)
3134       return SDValue();
3135     N0 = N0.getOperand(0);
3136     LookPassAnd0 = true;
3137   }
3138
3139   if (N1.getOpcode() == ISD::AND) {
3140     if (!N1.getNode()->hasOneUse())
3141       return SDValue();
3142     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3143     if (!N11C || N11C->getZExtValue() != 0xFF)
3144       return SDValue();
3145     N1 = N1.getOperand(0);
3146     LookPassAnd1 = true;
3147   }
3148
3149   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3150     std::swap(N0, N1);
3151   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3152     return SDValue();
3153   if (!N0.getNode()->hasOneUse() ||
3154       !N1.getNode()->hasOneUse())
3155     return SDValue();
3156
3157   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3158   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3159   if (!N01C || !N11C)
3160     return SDValue();
3161   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3162     return SDValue();
3163
3164   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3165   SDValue N00 = N0->getOperand(0);
3166   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3167     if (!N00.getNode()->hasOneUse())
3168       return SDValue();
3169     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3170     if (!N001C || N001C->getZExtValue() != 0xFF)
3171       return SDValue();
3172     N00 = N00.getOperand(0);
3173     LookPassAnd0 = true;
3174   }
3175
3176   SDValue N10 = N1->getOperand(0);
3177   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3178     if (!N10.getNode()->hasOneUse())
3179       return SDValue();
3180     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3181     if (!N101C || N101C->getZExtValue() != 0xFF00)
3182       return SDValue();
3183     N10 = N10.getOperand(0);
3184     LookPassAnd1 = true;
3185   }
3186
3187   if (N00 != N10)
3188     return SDValue();
3189
3190   // Make sure everything beyond the low halfword gets set to zero since the SRL
3191   // 16 will clear the top bits.
3192   unsigned OpSizeInBits = VT.getSizeInBits();
3193   if (DemandHighBits && OpSizeInBits > 16) {
3194     // If the left-shift isn't masked out then the only way this is a bswap is
3195     // if all bits beyond the low 8 are 0. In that case the entire pattern
3196     // reduces to a left shift anyway: leave it for other parts of the combiner.
3197     if (!LookPassAnd0)
3198       return SDValue();
3199
3200     // However, if the right shift isn't masked out then it might be because
3201     // it's not needed. See if we can spot that too.
3202     if (!LookPassAnd1 &&
3203         !DAG.MaskedValueIsZero(
3204             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3205       return SDValue();
3206   }
3207
3208   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3209   if (OpSizeInBits > 16)
3210     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3211                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3212   return Res;
3213 }
3214
3215 /// Return true if the specified node is an element that makes up a 32-bit
3216 /// packed halfword byteswap.
3217 /// ((x & 0x000000ff) << 8) |
3218 /// ((x & 0x0000ff00) >> 8) |
3219 /// ((x & 0x00ff0000) << 8) |
3220 /// ((x & 0xff000000) >> 8)
3221 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3222   if (!N.getNode()->hasOneUse())
3223     return false;
3224
3225   unsigned Opc = N.getOpcode();
3226   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3227     return false;
3228
3229   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3230   if (!N1C)
3231     return false;
3232
3233   unsigned Num;
3234   switch (N1C->getZExtValue()) {
3235   default:
3236     return false;
3237   case 0xFF:       Num = 0; break;
3238   case 0xFF00:     Num = 1; break;
3239   case 0xFF0000:   Num = 2; break;
3240   case 0xFF000000: Num = 3; break;
3241   }
3242
3243   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3244   SDValue N0 = N.getOperand(0);
3245   if (Opc == ISD::AND) {
3246     if (Num == 0 || Num == 2) {
3247       // (x >> 8) & 0xff
3248       // (x >> 8) & 0xff0000
3249       if (N0.getOpcode() != ISD::SRL)
3250         return false;
3251       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3252       if (!C || C->getZExtValue() != 8)
3253         return false;
3254     } else {
3255       // (x << 8) & 0xff00
3256       // (x << 8) & 0xff000000
3257       if (N0.getOpcode() != ISD::SHL)
3258         return false;
3259       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3260       if (!C || C->getZExtValue() != 8)
3261         return false;
3262     }
3263   } else if (Opc == ISD::SHL) {
3264     // (x & 0xff) << 8
3265     // (x & 0xff0000) << 8
3266     if (Num != 0 && Num != 2)
3267       return false;
3268     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3269     if (!C || C->getZExtValue() != 8)
3270       return false;
3271   } else { // Opc == ISD::SRL
3272     // (x & 0xff00) >> 8
3273     // (x & 0xff000000) >> 8
3274     if (Num != 1 && Num != 3)
3275       return false;
3276     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3277     if (!C || C->getZExtValue() != 8)
3278       return false;
3279   }
3280
3281   if (Parts[Num])
3282     return false;
3283
3284   Parts[Num] = N0.getOperand(0).getNode();
3285   return true;
3286 }
3287
3288 /// Match a 32-bit packed halfword bswap. That is
3289 /// ((x & 0x000000ff) << 8) |
3290 /// ((x & 0x0000ff00) >> 8) |
3291 /// ((x & 0x00ff0000) << 8) |
3292 /// ((x & 0xff000000) >> 8)
3293 /// => (rotl (bswap x), 16)
3294 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3295   if (!LegalOperations)
3296     return SDValue();
3297
3298   EVT VT = N->getValueType(0);
3299   if (VT != MVT::i32)
3300     return SDValue();
3301   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3302     return SDValue();
3303
3304   // Look for either
3305   // (or (or (and), (and)), (or (and), (and)))
3306   // (or (or (or (and), (and)), (and)), (and))
3307   if (N0.getOpcode() != ISD::OR)
3308     return SDValue();
3309   SDValue N00 = N0.getOperand(0);
3310   SDValue N01 = N0.getOperand(1);
3311   SDNode *Parts[4] = {};
3312
3313   if (N1.getOpcode() == ISD::OR &&
3314       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3315     // (or (or (and), (and)), (or (and), (and)))
3316     SDValue N000 = N00.getOperand(0);
3317     if (!isBSwapHWordElement(N000, Parts))
3318       return SDValue();
3319
3320     SDValue N001 = N00.getOperand(1);
3321     if (!isBSwapHWordElement(N001, Parts))
3322       return SDValue();
3323     SDValue N010 = N01.getOperand(0);
3324     if (!isBSwapHWordElement(N010, Parts))
3325       return SDValue();
3326     SDValue N011 = N01.getOperand(1);
3327     if (!isBSwapHWordElement(N011, Parts))
3328       return SDValue();
3329   } else {
3330     // (or (or (or (and), (and)), (and)), (and))
3331     if (!isBSwapHWordElement(N1, Parts))
3332       return SDValue();
3333     if (!isBSwapHWordElement(N01, Parts))
3334       return SDValue();
3335     if (N00.getOpcode() != ISD::OR)
3336       return SDValue();
3337     SDValue N000 = N00.getOperand(0);
3338     if (!isBSwapHWordElement(N000, Parts))
3339       return SDValue();
3340     SDValue N001 = N00.getOperand(1);
3341     if (!isBSwapHWordElement(N001, Parts))
3342       return SDValue();
3343   }
3344
3345   // Make sure the parts are all coming from the same node.
3346   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3347     return SDValue();
3348
3349   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3350                               SDValue(Parts[0],0));
3351
3352   // Result of the bswap should be rotated by 16. If it's not legal, then
3353   // do  (x << 16) | (x >> 16).
3354   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3355   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3356     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3357   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3358     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3359   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3360                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3361                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3362 }
3363
3364 /// This contains all DAGCombine rules which reduce two values combined by
3365 /// an Or operation to a single value \see visitANDLike().
3366 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3367   EVT VT = N1.getValueType();
3368   // fold (or x, undef) -> -1
3369   if (!LegalOperations &&
3370       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3371     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3372     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3373   }
3374   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3375   SDValue LL, LR, RL, RR, CC0, CC1;
3376   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3377     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3378     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3379
3380     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3381         LL.getValueType().isInteger()) {
3382       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3383       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3384       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3385           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3386         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3387                                      LR.getValueType(), LL, RL);
3388         AddToWorklist(ORNode.getNode());
3389         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3390       }
3391       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3392       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3393       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3394           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3395         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3396                                       LR.getValueType(), LL, RL);
3397         AddToWorklist(ANDNode.getNode());
3398         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3399       }
3400     }
3401     // canonicalize equivalent to ll == rl
3402     if (LL == RR && LR == RL) {
3403       Op1 = ISD::getSetCCSwappedOperands(Op1);
3404       std::swap(RL, RR);
3405     }
3406     if (LL == RL && LR == RR) {
3407       bool isInteger = LL.getValueType().isInteger();
3408       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3409       if (Result != ISD::SETCC_INVALID &&
3410           (!LegalOperations ||
3411            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3412             TLI.isOperationLegal(ISD::SETCC,
3413               getSetCCResultType(N0.getValueType())))))
3414         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3415                             LL, LR, Result);
3416     }
3417   }
3418
3419   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3420   if (N0.getOpcode() == ISD::AND &&
3421       N1.getOpcode() == ISD::AND &&
3422       N0.getOperand(1).getOpcode() == ISD::Constant &&
3423       N1.getOperand(1).getOpcode() == ISD::Constant &&
3424       // Don't increase # computations.
3425       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3426     // We can only do this xform if we know that bits from X that are set in C2
3427     // but not in C1 are already zero.  Likewise for Y.
3428     const APInt &LHSMask =
3429       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3430     const APInt &RHSMask =
3431       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3432
3433     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3434         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3435       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3436                               N0.getOperand(0), N1.getOperand(0));
3437       return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3438                          DAG.getConstant(LHSMask | RHSMask, VT));
3439     }
3440   }
3441
3442   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3443   if (N0.getOpcode() == ISD::AND &&
3444       N1.getOpcode() == ISD::AND &&
3445       N0.getOperand(0) == N1.getOperand(0) &&
3446       // Don't increase # computations.
3447       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3448     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3449                             N0.getOperand(1), N1.getOperand(1));
3450     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3451   }
3452
3453   return SDValue();
3454 }
3455
3456 SDValue DAGCombiner::visitOR(SDNode *N) {
3457   SDValue N0 = N->getOperand(0);
3458   SDValue N1 = N->getOperand(1);
3459   EVT VT = N1.getValueType();
3460
3461   // fold vector ops
3462   if (VT.isVector()) {
3463     SDValue FoldedVOp = SimplifyVBinOp(N);
3464     if (FoldedVOp.getNode()) return FoldedVOp;
3465
3466     // fold (or x, 0) -> x, vector edition
3467     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3468       return N1;
3469     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3470       return N0;
3471
3472     // fold (or x, -1) -> -1, vector edition
3473     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3474       // do not return N0, because undef node may exist in N0
3475       return DAG.getConstant(
3476           APInt::getAllOnesValue(
3477               N0.getValueType().getScalarType().getSizeInBits()),
3478           N0.getValueType());
3479     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3480       // do not return N1, because undef node may exist in N1
3481       return DAG.getConstant(
3482           APInt::getAllOnesValue(
3483               N1.getValueType().getScalarType().getSizeInBits()),
3484           N1.getValueType());
3485
3486     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3487     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3488     // Do this only if the resulting shuffle is legal.
3489     if (isa<ShuffleVectorSDNode>(N0) &&
3490         isa<ShuffleVectorSDNode>(N1) &&
3491         // Avoid folding a node with illegal type.
3492         TLI.isTypeLegal(VT) &&
3493         N0->getOperand(1) == N1->getOperand(1) &&
3494         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3495       bool CanFold = true;
3496       unsigned NumElts = VT.getVectorNumElements();
3497       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3498       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3499       // We construct two shuffle masks:
3500       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3501       // and N1 as the second operand.
3502       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3503       // and N0 as the second operand.
3504       // We do this because OR is commutable and therefore there might be
3505       // two ways to fold this node into a shuffle.
3506       SmallVector<int,4> Mask1;
3507       SmallVector<int,4> Mask2;
3508
3509       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3510         int M0 = SV0->getMaskElt(i);
3511         int M1 = SV1->getMaskElt(i);
3512
3513         // Both shuffle indexes are undef. Propagate Undef.
3514         if (M0 < 0 && M1 < 0) {
3515           Mask1.push_back(M0);
3516           Mask2.push_back(M0);
3517           continue;
3518         }
3519
3520         if (M0 < 0 || M1 < 0 ||
3521             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3522             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3523           CanFold = false;
3524           break;
3525         }
3526
3527         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3528         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3529       }
3530
3531       if (CanFold) {
3532         // Fold this sequence only if the resulting shuffle is 'legal'.
3533         if (TLI.isShuffleMaskLegal(Mask1, VT))
3534           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3535                                       N1->getOperand(0), &Mask1[0]);
3536         if (TLI.isShuffleMaskLegal(Mask2, VT))
3537           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3538                                       N0->getOperand(0), &Mask2[0]);
3539       }
3540     }
3541   }
3542
3543   // fold (or c1, c2) -> c1|c2
3544   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3545   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3546   if (N0C && N1C)
3547     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3548   // canonicalize constant to RHS
3549   if (N0C && !N1C)
3550     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3551   // fold (or x, 0) -> x
3552   if (N1C && N1C->isNullValue())
3553     return N0;
3554   // fold (or x, -1) -> -1
3555   if (N1C && N1C->isAllOnesValue())
3556     return N1;
3557   // fold (or x, c) -> c iff (x & ~c) == 0
3558   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3559     return N1;
3560
3561   if (SDValue Combined = visitORLike(N0, N1, N))
3562     return Combined;
3563
3564   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3565   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3566   if (BSwap.getNode())
3567     return BSwap;
3568   BSwap = MatchBSwapHWordLow(N, N0, N1);
3569   if (BSwap.getNode())
3570     return BSwap;
3571
3572   // reassociate or
3573   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3574   if (ROR.getNode())
3575     return ROR;
3576   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3577   // iff (c1 & c2) == 0.
3578   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3579              isa<ConstantSDNode>(N0.getOperand(1))) {
3580     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3581     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3582       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3583         return DAG.getNode(
3584             ISD::AND, SDLoc(N), VT,
3585             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3586       return SDValue();
3587     }
3588   }
3589   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3590   if (N0.getOpcode() == N1.getOpcode()) {
3591     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3592     if (Tmp.getNode()) return Tmp;
3593   }
3594
3595   // See if this is some rotate idiom.
3596   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3597     return SDValue(Rot, 0);
3598
3599   // Simplify the operands using demanded-bits information.
3600   if (!VT.isVector() &&
3601       SimplifyDemandedBits(SDValue(N, 0)))
3602     return SDValue(N, 0);
3603
3604   return SDValue();
3605 }
3606
3607 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3608 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3609   if (Op.getOpcode() == ISD::AND) {
3610     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3611       Mask = Op.getOperand(1);
3612       Op = Op.getOperand(0);
3613     } else {
3614       return false;
3615     }
3616   }
3617
3618   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3619     Shift = Op;
3620     return true;
3621   }
3622
3623   return false;
3624 }
3625
3626 // Return true if we can prove that, whenever Neg and Pos are both in the
3627 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3628 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3629 //
3630 //     (or (shift1 X, Neg), (shift2 X, Pos))
3631 //
3632 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3633 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3634 // to consider shift amounts with defined behavior.
3635 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3636   // If OpSize is a power of 2 then:
3637   //
3638   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3639   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3640   //
3641   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3642   // for the stronger condition:
3643   //
3644   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3645   //
3646   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3647   // we can just replace Neg with Neg' for the rest of the function.
3648   //
3649   // In other cases we check for the even stronger condition:
3650   //
3651   //     Neg == OpSize - Pos                                    [B]
3652   //
3653   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3654   // behavior if Pos == 0 (and consequently Neg == OpSize).
3655   //
3656   // We could actually use [A] whenever OpSize is a power of 2, but the
3657   // only extra cases that it would match are those uninteresting ones
3658   // where Neg and Pos are never in range at the same time.  E.g. for
3659   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3660   // as well as (sub 32, Pos), but:
3661   //
3662   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3663   //
3664   // always invokes undefined behavior for 32-bit X.
3665   //
3666   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3667   unsigned MaskLoBits = 0;
3668   if (Neg.getOpcode() == ISD::AND &&
3669       isPowerOf2_64(OpSize) &&
3670       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3671       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3672     Neg = Neg.getOperand(0);
3673     MaskLoBits = Log2_64(OpSize);
3674   }
3675
3676   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3677   if (Neg.getOpcode() != ISD::SUB)
3678     return 0;
3679   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3680   if (!NegC)
3681     return 0;
3682   SDValue NegOp1 = Neg.getOperand(1);
3683
3684   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3685   // Pos'.  The truncation is redundant for the purpose of the equality.
3686   if (MaskLoBits &&
3687       Pos.getOpcode() == ISD::AND &&
3688       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3689       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3690     Pos = Pos.getOperand(0);
3691
3692   // The condition we need is now:
3693   //
3694   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3695   //
3696   // If NegOp1 == Pos then we need:
3697   //
3698   //              OpSize & Mask == NegC & Mask
3699   //
3700   // (because "x & Mask" is a truncation and distributes through subtraction).
3701   APInt Width;
3702   if (Pos == NegOp1)
3703     Width = NegC->getAPIntValue();
3704   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3705   // Then the condition we want to prove becomes:
3706   //
3707   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3708   //
3709   // which, again because "x & Mask" is a truncation, becomes:
3710   //
3711   //                NegC & Mask == (OpSize - PosC) & Mask
3712   //              OpSize & Mask == (NegC + PosC) & Mask
3713   else if (Pos.getOpcode() == ISD::ADD &&
3714            Pos.getOperand(0) == NegOp1 &&
3715            Pos.getOperand(1).getOpcode() == ISD::Constant)
3716     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3717              NegC->getAPIntValue());
3718   else
3719     return false;
3720
3721   // Now we just need to check that OpSize & Mask == Width & Mask.
3722   if (MaskLoBits)
3723     // Opsize & Mask is 0 since Mask is Opsize - 1.
3724     return Width.getLoBits(MaskLoBits) == 0;
3725   return Width == OpSize;
3726 }
3727
3728 // A subroutine of MatchRotate used once we have found an OR of two opposite
3729 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3730 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3731 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3732 // Neg with outer conversions stripped away.
3733 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3734                                        SDValue Neg, SDValue InnerPos,
3735                                        SDValue InnerNeg, unsigned PosOpcode,
3736                                        unsigned NegOpcode, SDLoc DL) {
3737   // fold (or (shl x, (*ext y)),
3738   //          (srl x, (*ext (sub 32, y)))) ->
3739   //   (rotl x, y) or (rotr x, (sub 32, y))
3740   //
3741   // fold (or (shl x, (*ext (sub 32, y))),
3742   //          (srl x, (*ext y))) ->
3743   //   (rotr x, y) or (rotl x, (sub 32, y))
3744   EVT VT = Shifted.getValueType();
3745   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3746     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3747     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3748                        HasPos ? Pos : Neg).getNode();
3749   }
3750
3751   return nullptr;
3752 }
3753
3754 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3755 // idioms for rotate, and if the target supports rotation instructions, generate
3756 // a rot[lr].
3757 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3758   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3759   EVT VT = LHS.getValueType();
3760   if (!TLI.isTypeLegal(VT)) return nullptr;
3761
3762   // The target must have at least one rotate flavor.
3763   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3764   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3765   if (!HasROTL && !HasROTR) return nullptr;
3766
3767   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3768   SDValue LHSShift;   // The shift.
3769   SDValue LHSMask;    // AND value if any.
3770   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3771     return nullptr; // Not part of a rotate.
3772
3773   SDValue RHSShift;   // The shift.
3774   SDValue RHSMask;    // AND value if any.
3775   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3776     return nullptr; // Not part of a rotate.
3777
3778   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3779     return nullptr;   // Not shifting the same value.
3780
3781   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3782     return nullptr;   // Shifts must disagree.
3783
3784   // Canonicalize shl to left side in a shl/srl pair.
3785   if (RHSShift.getOpcode() == ISD::SHL) {
3786     std::swap(LHS, RHS);
3787     std::swap(LHSShift, RHSShift);
3788     std::swap(LHSMask , RHSMask );
3789   }
3790
3791   unsigned OpSizeInBits = VT.getSizeInBits();
3792   SDValue LHSShiftArg = LHSShift.getOperand(0);
3793   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3794   SDValue RHSShiftArg = RHSShift.getOperand(0);
3795   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3796
3797   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3798   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3799   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3800       RHSShiftAmt.getOpcode() == ISD::Constant) {
3801     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3802     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3803     if ((LShVal + RShVal) != OpSizeInBits)
3804       return nullptr;
3805
3806     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3807                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3808
3809     // If there is an AND of either shifted operand, apply it to the result.
3810     if (LHSMask.getNode() || RHSMask.getNode()) {
3811       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3812
3813       if (LHSMask.getNode()) {
3814         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3815         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3816       }
3817       if (RHSMask.getNode()) {
3818         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3819         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3820       }
3821
3822       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3823     }
3824
3825     return Rot.getNode();
3826   }
3827
3828   // If there is a mask here, and we have a variable shift, we can't be sure
3829   // that we're masking out the right stuff.
3830   if (LHSMask.getNode() || RHSMask.getNode())
3831     return nullptr;
3832
3833   // If the shift amount is sign/zext/any-extended just peel it off.
3834   SDValue LExtOp0 = LHSShiftAmt;
3835   SDValue RExtOp0 = RHSShiftAmt;
3836   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3837        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3838        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3839        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3840       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3841        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3842        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3843        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3844     LExtOp0 = LHSShiftAmt.getOperand(0);
3845     RExtOp0 = RHSShiftAmt.getOperand(0);
3846   }
3847
3848   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3849                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3850   if (TryL)
3851     return TryL;
3852
3853   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3854                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3855   if (TryR)
3856     return TryR;
3857
3858   return nullptr;
3859 }
3860
3861 SDValue DAGCombiner::visitXOR(SDNode *N) {
3862   SDValue N0 = N->getOperand(0);
3863   SDValue N1 = N->getOperand(1);
3864   EVT VT = N0.getValueType();
3865
3866   // fold vector ops
3867   if (VT.isVector()) {
3868     SDValue FoldedVOp = SimplifyVBinOp(N);
3869     if (FoldedVOp.getNode()) return FoldedVOp;
3870
3871     // fold (xor x, 0) -> x, vector edition
3872     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3873       return N1;
3874     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3875       return N0;
3876   }
3877
3878   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3879   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3880     return DAG.getConstant(0, VT);
3881   // fold (xor x, undef) -> undef
3882   if (N0.getOpcode() == ISD::UNDEF)
3883     return N0;
3884   if (N1.getOpcode() == ISD::UNDEF)
3885     return N1;
3886   // fold (xor c1, c2) -> c1^c2
3887   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3888   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3889   if (N0C && N1C)
3890     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3891   // canonicalize constant to RHS
3892   if (N0C && !N1C)
3893     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3894   // fold (xor x, 0) -> x
3895   if (N1C && N1C->isNullValue())
3896     return N0;
3897   // reassociate xor
3898   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3899   if (RXOR.getNode())
3900     return RXOR;
3901
3902   // fold !(x cc y) -> (x !cc y)
3903   SDValue LHS, RHS, CC;
3904   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3905     bool isInt = LHS.getValueType().isInteger();
3906     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3907                                                isInt);
3908
3909     if (!LegalOperations ||
3910         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3911       switch (N0.getOpcode()) {
3912       default:
3913         llvm_unreachable("Unhandled SetCC Equivalent!");
3914       case ISD::SETCC:
3915         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3916       case ISD::SELECT_CC:
3917         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3918                                N0.getOperand(3), NotCC);
3919       }
3920     }
3921   }
3922
3923   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3924   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3925       N0.getNode()->hasOneUse() &&
3926       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3927     SDValue V = N0.getOperand(0);
3928     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3929                     DAG.getConstant(1, V.getValueType()));
3930     AddToWorklist(V.getNode());
3931     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3932   }
3933
3934   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3935   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3936       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3937     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3938     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3939       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3940       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3941       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3942       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3943       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3944     }
3945   }
3946   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3947   if (N1C && N1C->isAllOnesValue() &&
3948       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3949     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3950     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3951       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3952       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3953       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3954       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3955       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3956     }
3957   }
3958   // fold (xor (and x, y), y) -> (and (not x), y)
3959   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3960       N0->getOperand(1) == N1) {
3961     SDValue X = N0->getOperand(0);
3962     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3963     AddToWorklist(NotX.getNode());
3964     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3965   }
3966   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3967   if (N1C && N0.getOpcode() == ISD::XOR) {
3968     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3969     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3970     if (N00C)
3971       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3972                          DAG.getConstant(N1C->getAPIntValue() ^
3973                                          N00C->getAPIntValue(), VT));
3974     if (N01C)
3975       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3976                          DAG.getConstant(N1C->getAPIntValue() ^
3977                                          N01C->getAPIntValue(), VT));
3978   }
3979   // fold (xor x, x) -> 0
3980   if (N0 == N1)
3981     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3982
3983   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3984   // Here is a concrete example of this equivalence:
3985   // i16   x ==  14
3986   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
3987   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3988   //
3989   // =>
3990   //
3991   // i16     ~1      == 0b1111111111111110
3992   // i16 rol(~1, 14) == 0b1011111111111111
3993   //
3994   // Some additional tips to help conceptualize this transform:
3995   // - Try to see the operation as placing a single zero in a value of all ones.
3996   // - There exists no value for x which would allow the result to contain zero.
3997   // - Values of x larger than the bitwidth are undefined and do not require a
3998   //   consistent result.
3999   // - Pushing the zero left requires shifting one bits in from the right.
4000   // A rotate left of ~1 is a nice way of achieving the desired result.
4001   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4002     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4003       if (N0.getOpcode() == ISD::SHL)
4004         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4005           if (N1C->isAllOnesValue() && ShlLHS->isOne())
4006             return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4007                                N0.getOperand(1));
4008
4009   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4010   if (N0.getOpcode() == N1.getOpcode()) {
4011     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4012     if (Tmp.getNode()) return Tmp;
4013   }
4014
4015   // Simplify the expression using non-local knowledge.
4016   if (!VT.isVector() &&
4017       SimplifyDemandedBits(SDValue(N, 0)))
4018     return SDValue(N, 0);
4019
4020   return SDValue();
4021 }
4022
4023 /// Handle transforms common to the three shifts, when the shift amount is a
4024 /// constant.
4025 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4026   // We can't and shouldn't fold opaque constants.
4027   if (Amt->isOpaque())
4028     return SDValue();
4029
4030   SDNode *LHS = N->getOperand(0).getNode();
4031   if (!LHS->hasOneUse()) return SDValue();
4032
4033   // We want to pull some binops through shifts, so that we have (and (shift))
4034   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4035   // thing happens with address calculations, so it's important to canonicalize
4036   // it.
4037   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4038
4039   switch (LHS->getOpcode()) {
4040   default: return SDValue();
4041   case ISD::OR:
4042   case ISD::XOR:
4043     HighBitSet = false; // We can only transform sra if the high bit is clear.
4044     break;
4045   case ISD::AND:
4046     HighBitSet = true;  // We can only transform sra if the high bit is set.
4047     break;
4048   case ISD::ADD:
4049     if (N->getOpcode() != ISD::SHL)
4050       return SDValue(); // only shl(add) not sr[al](add).
4051     HighBitSet = false; // We can only transform sra if the high bit is clear.
4052     break;
4053   }
4054
4055   // We require the RHS of the binop to be a constant and not opaque as well.
4056   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4057   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4058
4059   // FIXME: disable this unless the input to the binop is a shift by a constant.
4060   // If it is not a shift, it pessimizes some common cases like:
4061   //
4062   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4063   //    int bar(int *X, int i) { return X[i & 255]; }
4064   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4065   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4066        BinOpLHSVal->getOpcode() != ISD::SRA &&
4067        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4068       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4069     return SDValue();
4070
4071   EVT VT = N->getValueType(0);
4072
4073   // If this is a signed shift right, and the high bit is modified by the
4074   // logical operation, do not perform the transformation. The highBitSet
4075   // boolean indicates the value of the high bit of the constant which would
4076   // cause it to be modified for this operation.
4077   if (N->getOpcode() == ISD::SRA) {
4078     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4079     if (BinOpRHSSignSet != HighBitSet)
4080       return SDValue();
4081   }
4082
4083   if (!TLI.isDesirableToCommuteWithShift(LHS))
4084     return SDValue();
4085
4086   // Fold the constants, shifting the binop RHS by the shift amount.
4087   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4088                                N->getValueType(0),
4089                                LHS->getOperand(1), N->getOperand(1));
4090   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4091
4092   // Create the new shift.
4093   SDValue NewShift = DAG.getNode(N->getOpcode(),
4094                                  SDLoc(LHS->getOperand(0)),
4095                                  VT, LHS->getOperand(0), N->getOperand(1));
4096
4097   // Create the new binop.
4098   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4099 }
4100
4101 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4102   assert(N->getOpcode() == ISD::TRUNCATE);
4103   assert(N->getOperand(0).getOpcode() == ISD::AND);
4104
4105   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4106   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4107     SDValue N01 = N->getOperand(0).getOperand(1);
4108
4109     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4110       EVT TruncVT = N->getValueType(0);
4111       SDValue N00 = N->getOperand(0).getOperand(0);
4112       APInt TruncC = N01C->getAPIntValue();
4113       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4114
4115       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4116                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4117                          DAG.getConstant(TruncC, TruncVT));
4118     }
4119   }
4120
4121   return SDValue();
4122 }
4123
4124 SDValue DAGCombiner::visitRotate(SDNode *N) {
4125   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4126   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4127       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4128     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4129     if (NewOp1.getNode())
4130       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4131                          N->getOperand(0), NewOp1);
4132   }
4133   return SDValue();
4134 }
4135
4136 SDValue DAGCombiner::visitSHL(SDNode *N) {
4137   SDValue N0 = N->getOperand(0);
4138   SDValue N1 = N->getOperand(1);
4139   EVT VT = N0.getValueType();
4140   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4141
4142   // fold vector ops
4143   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4144   if (VT.isVector()) {
4145     SDValue FoldedVOp = SimplifyVBinOp(N);
4146     if (FoldedVOp.getNode()) return FoldedVOp;
4147
4148     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4149     // If setcc produces all-one true value then:
4150     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4151     if (N1CV && N1CV->isConstant()) {
4152       if (N0.getOpcode() == ISD::AND) {
4153         SDValue N00 = N0->getOperand(0);
4154         SDValue N01 = N0->getOperand(1);
4155         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4156
4157         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4158             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4159                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4160           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4161             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4162         }
4163       } else {
4164         N1C = isConstOrConstSplat(N1);
4165       }
4166     }
4167   }
4168
4169   // fold (shl c1, c2) -> c1<<c2
4170   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4171   if (N0C && N1C)
4172     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4173   // fold (shl 0, x) -> 0
4174   if (N0C && N0C->isNullValue())
4175     return N0;
4176   // fold (shl x, c >= size(x)) -> undef
4177   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4178     return DAG.getUNDEF(VT);
4179   // fold (shl x, 0) -> x
4180   if (N1C && N1C->isNullValue())
4181     return N0;
4182   // fold (shl undef, x) -> 0
4183   if (N0.getOpcode() == ISD::UNDEF)
4184     return DAG.getConstant(0, VT);
4185   // if (shl x, c) is known to be zero, return 0
4186   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4187                             APInt::getAllOnesValue(OpSizeInBits)))
4188     return DAG.getConstant(0, VT);
4189   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4190   if (N1.getOpcode() == ISD::TRUNCATE &&
4191       N1.getOperand(0).getOpcode() == ISD::AND) {
4192     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4193     if (NewOp1.getNode())
4194       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4195   }
4196
4197   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4198     return SDValue(N, 0);
4199
4200   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4201   if (N1C && N0.getOpcode() == ISD::SHL) {
4202     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4203       uint64_t c1 = N0C1->getZExtValue();
4204       uint64_t c2 = N1C->getZExtValue();
4205       if (c1 + c2 >= OpSizeInBits)
4206         return DAG.getConstant(0, VT);
4207       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4208                          DAG.getConstant(c1 + c2, N1.getValueType()));
4209     }
4210   }
4211
4212   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4213   // For this to be valid, the second form must not preserve any of the bits
4214   // that are shifted out by the inner shift in the first form.  This means
4215   // the outer shift size must be >= the number of bits added by the ext.
4216   // As a corollary, we don't care what kind of ext it is.
4217   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4218               N0.getOpcode() == ISD::ANY_EXTEND ||
4219               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4220       N0.getOperand(0).getOpcode() == ISD::SHL) {
4221     SDValue N0Op0 = N0.getOperand(0);
4222     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4223       uint64_t c1 = N0Op0C1->getZExtValue();
4224       uint64_t c2 = N1C->getZExtValue();
4225       EVT InnerShiftVT = N0Op0.getValueType();
4226       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4227       if (c2 >= OpSizeInBits - InnerShiftSize) {
4228         if (c1 + c2 >= OpSizeInBits)
4229           return DAG.getConstant(0, VT);
4230         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4231                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4232                                        N0Op0->getOperand(0)),
4233                            DAG.getConstant(c1 + c2, N1.getValueType()));
4234       }
4235     }
4236   }
4237
4238   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4239   // Only fold this if the inner zext has no other uses to avoid increasing
4240   // the total number of instructions.
4241   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4242       N0.getOperand(0).getOpcode() == ISD::SRL) {
4243     SDValue N0Op0 = N0.getOperand(0);
4244     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4245       uint64_t c1 = N0Op0C1->getZExtValue();
4246       if (c1 < VT.getScalarSizeInBits()) {
4247         uint64_t c2 = N1C->getZExtValue();
4248         if (c1 == c2) {
4249           SDValue NewOp0 = N0.getOperand(0);
4250           EVT CountVT = NewOp0.getOperand(1).getValueType();
4251           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4252                                        NewOp0, DAG.getConstant(c2, CountVT));
4253           AddToWorklist(NewSHL.getNode());
4254           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4255         }
4256       }
4257     }
4258   }
4259
4260   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4261   //                               (and (srl x, (sub c1, c2), MASK)
4262   // Only fold this if the inner shift has no other uses -- if it does, folding
4263   // this will increase the total number of instructions.
4264   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4265     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4266       uint64_t c1 = N0C1->getZExtValue();
4267       if (c1 < OpSizeInBits) {
4268         uint64_t c2 = N1C->getZExtValue();
4269         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4270         SDValue Shift;
4271         if (c2 > c1) {
4272           Mask = Mask.shl(c2 - c1);
4273           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4274                               DAG.getConstant(c2 - c1, N1.getValueType()));
4275         } else {
4276           Mask = Mask.lshr(c1 - c2);
4277           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4278                               DAG.getConstant(c1 - c2, N1.getValueType()));
4279         }
4280         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4281                            DAG.getConstant(Mask, VT));
4282       }
4283     }
4284   }
4285   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4286   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4287     unsigned BitSize = VT.getScalarSizeInBits();
4288     SDValue HiBitsMask =
4289       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4290                                             BitSize - N1C->getZExtValue()), VT);
4291     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4292                        HiBitsMask);
4293   }
4294
4295   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4296   // Variant of version done on multiply, except mul by a power of 2 is turned
4297   // into a shift.
4298   APInt Val;
4299   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4300       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4301        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4302     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4303     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4304     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4305   }
4306
4307   if (N1C) {
4308     SDValue NewSHL = visitShiftByConstant(N, N1C);
4309     if (NewSHL.getNode())
4310       return NewSHL;
4311   }
4312
4313   return SDValue();
4314 }
4315
4316 SDValue DAGCombiner::visitSRA(SDNode *N) {
4317   SDValue N0 = N->getOperand(0);
4318   SDValue N1 = N->getOperand(1);
4319   EVT VT = N0.getValueType();
4320   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4321
4322   // fold vector ops
4323   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4324   if (VT.isVector()) {
4325     SDValue FoldedVOp = SimplifyVBinOp(N);
4326     if (FoldedVOp.getNode()) return FoldedVOp;
4327
4328     N1C = isConstOrConstSplat(N1);
4329   }
4330
4331   // fold (sra c1, c2) -> (sra c1, c2)
4332   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4333   if (N0C && N1C)
4334     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4335   // fold (sra 0, x) -> 0
4336   if (N0C && N0C->isNullValue())
4337     return N0;
4338   // fold (sra -1, x) -> -1
4339   if (N0C && N0C->isAllOnesValue())
4340     return N0;
4341   // fold (sra x, (setge c, size(x))) -> undef
4342   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4343     return DAG.getUNDEF(VT);
4344   // fold (sra x, 0) -> x
4345   if (N1C && N1C->isNullValue())
4346     return N0;
4347   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4348   // sext_inreg.
4349   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4350     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4351     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4352     if (VT.isVector())
4353       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4354                                ExtVT, VT.getVectorNumElements());
4355     if ((!LegalOperations ||
4356          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4357       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4358                          N0.getOperand(0), DAG.getValueType(ExtVT));
4359   }
4360
4361   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4362   if (N1C && N0.getOpcode() == ISD::SRA) {
4363     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4364       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4365       if (Sum >= OpSizeInBits)
4366         Sum = OpSizeInBits - 1;
4367       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4368                          DAG.getConstant(Sum, N1.getValueType()));
4369     }
4370   }
4371
4372   // fold (sra (shl X, m), (sub result_size, n))
4373   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4374   // result_size - n != m.
4375   // If truncate is free for the target sext(shl) is likely to result in better
4376   // code.
4377   if (N0.getOpcode() == ISD::SHL && N1C) {
4378     // Get the two constanst of the shifts, CN0 = m, CN = n.
4379     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4380     if (N01C) {
4381       LLVMContext &Ctx = *DAG.getContext();
4382       // Determine what the truncate's result bitsize and type would be.
4383       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4384
4385       if (VT.isVector())
4386         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4387
4388       // Determine the residual right-shift amount.
4389       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4390
4391       // If the shift is not a no-op (in which case this should be just a sign
4392       // extend already), the truncated to type is legal, sign_extend is legal
4393       // on that type, and the truncate to that type is both legal and free,
4394       // perform the transform.
4395       if ((ShiftAmt > 0) &&
4396           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4397           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4398           TLI.isTruncateFree(VT, TruncVT)) {
4399
4400           SDValue Amt = DAG.getConstant(ShiftAmt,
4401               getShiftAmountTy(N0.getOperand(0).getValueType()));
4402           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4403                                       N0.getOperand(0), Amt);
4404           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4405                                       Shift);
4406           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4407                              N->getValueType(0), Trunc);
4408       }
4409     }
4410   }
4411
4412   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4413   if (N1.getOpcode() == ISD::TRUNCATE &&
4414       N1.getOperand(0).getOpcode() == ISD::AND) {
4415     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4416     if (NewOp1.getNode())
4417       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4418   }
4419
4420   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4421   //      if c1 is equal to the number of bits the trunc removes
4422   if (N0.getOpcode() == ISD::TRUNCATE &&
4423       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4424        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4425       N0.getOperand(0).hasOneUse() &&
4426       N0.getOperand(0).getOperand(1).hasOneUse() &&
4427       N1C) {
4428     SDValue N0Op0 = N0.getOperand(0);
4429     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4430       unsigned LargeShiftVal = LargeShift->getZExtValue();
4431       EVT LargeVT = N0Op0.getValueType();
4432
4433       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4434         SDValue Amt =
4435           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4436                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4437         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4438                                   N0Op0.getOperand(0), Amt);
4439         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4440       }
4441     }
4442   }
4443
4444   // Simplify, based on bits shifted out of the LHS.
4445   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4446     return SDValue(N, 0);
4447
4448
4449   // If the sign bit is known to be zero, switch this to a SRL.
4450   if (DAG.SignBitIsZero(N0))
4451     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4452
4453   if (N1C) {
4454     SDValue NewSRA = visitShiftByConstant(N, N1C);
4455     if (NewSRA.getNode())
4456       return NewSRA;
4457   }
4458
4459   return SDValue();
4460 }
4461
4462 SDValue DAGCombiner::visitSRL(SDNode *N) {
4463   SDValue N0 = N->getOperand(0);
4464   SDValue N1 = N->getOperand(1);
4465   EVT VT = N0.getValueType();
4466   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4467
4468   // fold vector ops
4469   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4470   if (VT.isVector()) {
4471     SDValue FoldedVOp = SimplifyVBinOp(N);
4472     if (FoldedVOp.getNode()) return FoldedVOp;
4473
4474     N1C = isConstOrConstSplat(N1);
4475   }
4476
4477   // fold (srl c1, c2) -> c1 >>u c2
4478   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4479   if (N0C && N1C)
4480     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4481   // fold (srl 0, x) -> 0
4482   if (N0C && N0C->isNullValue())
4483     return N0;
4484   // fold (srl x, c >= size(x)) -> undef
4485   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4486     return DAG.getUNDEF(VT);
4487   // fold (srl x, 0) -> x
4488   if (N1C && N1C->isNullValue())
4489     return N0;
4490   // if (srl x, c) is known to be zero, return 0
4491   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4492                                    APInt::getAllOnesValue(OpSizeInBits)))
4493     return DAG.getConstant(0, VT);
4494
4495   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4496   if (N1C && N0.getOpcode() == ISD::SRL) {
4497     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4498       uint64_t c1 = N01C->getZExtValue();
4499       uint64_t c2 = N1C->getZExtValue();
4500       if (c1 + c2 >= OpSizeInBits)
4501         return DAG.getConstant(0, VT);
4502       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4503                          DAG.getConstant(c1 + c2, N1.getValueType()));
4504     }
4505   }
4506
4507   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4508   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4509       N0.getOperand(0).getOpcode() == ISD::SRL &&
4510       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4511     uint64_t c1 =
4512       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4513     uint64_t c2 = N1C->getZExtValue();
4514     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4515     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4516     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4517     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4518     if (c1 + OpSizeInBits == InnerShiftSize) {
4519       if (c1 + c2 >= InnerShiftSize)
4520         return DAG.getConstant(0, VT);
4521       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4522                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4523                                      N0.getOperand(0)->getOperand(0),
4524                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4525     }
4526   }
4527
4528   // fold (srl (shl x, c), c) -> (and x, cst2)
4529   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4530     unsigned BitSize = N0.getScalarValueSizeInBits();
4531     if (BitSize <= 64) {
4532       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4533       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4534                          DAG.getConstant(~0ULL >> ShAmt, VT));
4535     }
4536   }
4537
4538   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4539   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4540     // Shifting in all undef bits?
4541     EVT SmallVT = N0.getOperand(0).getValueType();
4542     unsigned BitSize = SmallVT.getScalarSizeInBits();
4543     if (N1C->getZExtValue() >= BitSize)
4544       return DAG.getUNDEF(VT);
4545
4546     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4547       uint64_t ShiftAmt = N1C->getZExtValue();
4548       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4549                                        N0.getOperand(0),
4550                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4551       AddToWorklist(SmallShift.getNode());
4552       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4553       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4554                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4555                          DAG.getConstant(Mask, VT));
4556     }
4557   }
4558
4559   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4560   // bit, which is unmodified by sra.
4561   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4562     if (N0.getOpcode() == ISD::SRA)
4563       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4564   }
4565
4566   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4567   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4568       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4569     APInt KnownZero, KnownOne;
4570     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4571
4572     // If any of the input bits are KnownOne, then the input couldn't be all
4573     // zeros, thus the result of the srl will always be zero.
4574     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4575
4576     // If all of the bits input the to ctlz node are known to be zero, then
4577     // the result of the ctlz is "32" and the result of the shift is one.
4578     APInt UnknownBits = ~KnownZero;
4579     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4580
4581     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4582     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4583       // Okay, we know that only that the single bit specified by UnknownBits
4584       // could be set on input to the CTLZ node. If this bit is set, the SRL
4585       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4586       // to an SRL/XOR pair, which is likely to simplify more.
4587       unsigned ShAmt = UnknownBits.countTrailingZeros();
4588       SDValue Op = N0.getOperand(0);
4589
4590       if (ShAmt) {
4591         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4592                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4593         AddToWorklist(Op.getNode());
4594       }
4595
4596       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4597                          Op, DAG.getConstant(1, VT));
4598     }
4599   }
4600
4601   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4602   if (N1.getOpcode() == ISD::TRUNCATE &&
4603       N1.getOperand(0).getOpcode() == ISD::AND) {
4604     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4605     if (NewOp1.getNode())
4606       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4607   }
4608
4609   // fold operands of srl based on knowledge that the low bits are not
4610   // demanded.
4611   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4612     return SDValue(N, 0);
4613
4614   if (N1C) {
4615     SDValue NewSRL = visitShiftByConstant(N, N1C);
4616     if (NewSRL.getNode())
4617       return NewSRL;
4618   }
4619
4620   // Attempt to convert a srl of a load into a narrower zero-extending load.
4621   SDValue NarrowLoad = ReduceLoadWidth(N);
4622   if (NarrowLoad.getNode())
4623     return NarrowLoad;
4624
4625   // Here is a common situation. We want to optimize:
4626   //
4627   //   %a = ...
4628   //   %b = and i32 %a, 2
4629   //   %c = srl i32 %b, 1
4630   //   brcond i32 %c ...
4631   //
4632   // into
4633   //
4634   //   %a = ...
4635   //   %b = and %a, 2
4636   //   %c = setcc eq %b, 0
4637   //   brcond %c ...
4638   //
4639   // However when after the source operand of SRL is optimized into AND, the SRL
4640   // itself may not be optimized further. Look for it and add the BRCOND into
4641   // the worklist.
4642   if (N->hasOneUse()) {
4643     SDNode *Use = *N->use_begin();
4644     if (Use->getOpcode() == ISD::BRCOND)
4645       AddToWorklist(Use);
4646     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4647       // Also look pass the truncate.
4648       Use = *Use->use_begin();
4649       if (Use->getOpcode() == ISD::BRCOND)
4650         AddToWorklist(Use);
4651     }
4652   }
4653
4654   return SDValue();
4655 }
4656
4657 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4658   SDValue N0 = N->getOperand(0);
4659   EVT VT = N->getValueType(0);
4660
4661   // fold (ctlz c1) -> c2
4662   if (isa<ConstantSDNode>(N0))
4663     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4664   return SDValue();
4665 }
4666
4667 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4668   SDValue N0 = N->getOperand(0);
4669   EVT VT = N->getValueType(0);
4670
4671   // fold (ctlz_zero_undef c1) -> c2
4672   if (isa<ConstantSDNode>(N0))
4673     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4674   return SDValue();
4675 }
4676
4677 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4678   SDValue N0 = N->getOperand(0);
4679   EVT VT = N->getValueType(0);
4680
4681   // fold (cttz c1) -> c2
4682   if (isa<ConstantSDNode>(N0))
4683     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4684   return SDValue();
4685 }
4686
4687 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4688   SDValue N0 = N->getOperand(0);
4689   EVT VT = N->getValueType(0);
4690
4691   // fold (cttz_zero_undef c1) -> c2
4692   if (isa<ConstantSDNode>(N0))
4693     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4694   return SDValue();
4695 }
4696
4697 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4698   SDValue N0 = N->getOperand(0);
4699   EVT VT = N->getValueType(0);
4700
4701   // fold (ctpop c1) -> c2
4702   if (isa<ConstantSDNode>(N0))
4703     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4704   return SDValue();
4705 }
4706
4707
4708 /// \brief Generate Min/Max node
4709 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4710                                    SDValue True, SDValue False,
4711                                    ISD::CondCode CC, const TargetLowering &TLI,
4712                                    SelectionDAG &DAG) {
4713   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4714     return SDValue();
4715
4716   switch (CC) {
4717   case ISD::SETOLT:
4718   case ISD::SETOLE:
4719   case ISD::SETLT:
4720   case ISD::SETLE:
4721   case ISD::SETULT:
4722   case ISD::SETULE: {
4723     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4724     if (TLI.isOperationLegal(Opcode, VT))
4725       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4726     return SDValue();
4727   }
4728   case ISD::SETOGT:
4729   case ISD::SETOGE:
4730   case ISD::SETGT:
4731   case ISD::SETGE:
4732   case ISD::SETUGT:
4733   case ISD::SETUGE: {
4734     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4735     if (TLI.isOperationLegal(Opcode, VT))
4736       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4737     return SDValue();
4738   }
4739   default:
4740     return SDValue();
4741   }
4742 }
4743
4744 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4745   SDValue N0 = N->getOperand(0);
4746   SDValue N1 = N->getOperand(1);
4747   SDValue N2 = N->getOperand(2);
4748   EVT VT = N->getValueType(0);
4749   EVT VT0 = N0.getValueType();
4750
4751   // fold (select C, X, X) -> X
4752   if (N1 == N2)
4753     return N1;
4754   // fold (select true, X, Y) -> X
4755   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4756   if (N0C && !N0C->isNullValue())
4757     return N1;
4758   // fold (select false, X, Y) -> Y
4759   if (N0C && N0C->isNullValue())
4760     return N2;
4761   // fold (select C, 1, X) -> (or C, X)
4762   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4763   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4764     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4765   // fold (select C, 0, 1) -> (xor C, 1)
4766   // We can't do this reliably if integer based booleans have different contents
4767   // to floating point based booleans. This is because we can't tell whether we
4768   // have an integer-based boolean or a floating-point-based boolean unless we
4769   // can find the SETCC that produced it and inspect its operands. This is
4770   // fairly easy if C is the SETCC node, but it can potentially be
4771   // undiscoverable (or not reasonably discoverable). For example, it could be
4772   // in another basic block or it could require searching a complicated
4773   // expression.
4774   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4775   if (VT.isInteger() &&
4776       (VT0 == MVT::i1 || (VT0.isInteger() &&
4777                           TLI.getBooleanContents(false, false) ==
4778                               TLI.getBooleanContents(false, true) &&
4779                           TLI.getBooleanContents(false, false) ==
4780                               TargetLowering::ZeroOrOneBooleanContent)) &&
4781       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4782     SDValue XORNode;
4783     if (VT == VT0)
4784       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4785                          N0, DAG.getConstant(1, VT0));
4786     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4787                           N0, DAG.getConstant(1, VT0));
4788     AddToWorklist(XORNode.getNode());
4789     if (VT.bitsGT(VT0))
4790       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4791     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4792   }
4793   // fold (select C, 0, X) -> (and (not C), X)
4794   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4795     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4796     AddToWorklist(NOTNode.getNode());
4797     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4798   }
4799   // fold (select C, X, 1) -> (or (not C), X)
4800   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4801     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4802     AddToWorklist(NOTNode.getNode());
4803     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4804   }
4805   // fold (select C, X, 0) -> (and C, X)
4806   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4807     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4808   // fold (select X, X, Y) -> (or X, Y)
4809   // fold (select X, 1, Y) -> (or X, Y)
4810   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4811     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4812   // fold (select X, Y, X) -> (and X, Y)
4813   // fold (select X, Y, 0) -> (and X, Y)
4814   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4815     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4816
4817   // If we can fold this based on the true/false value, do so.
4818   if (SimplifySelectOps(N, N1, N2))
4819     return SDValue(N, 0);  // Don't revisit N.
4820
4821   // fold selects based on a setcc into other things, such as min/max/abs
4822   if (N0.getOpcode() == ISD::SETCC) {
4823     // select x, y (fcmp lt x, y) -> fminnum x, y
4824     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4825     //
4826     // This is OK if we don't care about what happens if either operand is a
4827     // NaN.
4828     //
4829
4830     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4831     // no signed zeros as well as no nans.
4832     const TargetOptions &Options = DAG.getTarget().Options;
4833     if (Options.UnsafeFPMath &&
4834         VT.isFloatingPoint() && N0.hasOneUse() &&
4835         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4836       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4837
4838       SDValue FMinMax =
4839           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4840                               N1, N2, CC, TLI, DAG);
4841       if (FMinMax)
4842         return FMinMax;
4843     }
4844
4845     if ((!LegalOperations &&
4846          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4847         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4848       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4849                          N0.getOperand(0), N0.getOperand(1),
4850                          N1, N2, N0.getOperand(2));
4851     return SimplifySelect(SDLoc(N), N0, N1, N2);
4852   }
4853
4854   if (VT0 == MVT::i1) {
4855     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4856       // select (and Cond0, Cond1), X, Y
4857       //   -> select Cond0, (select Cond1, X, Y), Y
4858       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4859         SDValue Cond0 = N0->getOperand(0);
4860         SDValue Cond1 = N0->getOperand(1);
4861         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4862                                           N1.getValueType(), Cond1, N1, N2);
4863         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4864                            InnerSelect, N2);
4865       }
4866       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4867       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4868         SDValue Cond0 = N0->getOperand(0);
4869         SDValue Cond1 = N0->getOperand(1);
4870         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4871                                           N1.getValueType(), Cond1, N1, N2);
4872         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4873                            InnerSelect);
4874       }
4875     }
4876
4877     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4878     if (N1->getOpcode() == ISD::SELECT) {
4879       SDValue N1_0 = N1->getOperand(0);
4880       SDValue N1_1 = N1->getOperand(1);
4881       SDValue N1_2 = N1->getOperand(2);
4882       if (N1_2 == N2) {
4883         // Create the actual and node if we can generate good code for it.
4884         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4885           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4886                                     N0, N1_0);
4887           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4888                              N1_1, N2);
4889         }
4890         // Otherwise see if we can optimize the "and" to a better pattern.
4891         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4892           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4893                              N1_1, N2);
4894       }
4895     }
4896     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4897     if (N2->getOpcode() == ISD::SELECT) {
4898       SDValue N2_0 = N2->getOperand(0);
4899       SDValue N2_1 = N2->getOperand(1);
4900       SDValue N2_2 = N2->getOperand(2);
4901       if (N2_1 == N1) {
4902         // Create the actual or node if we can generate good code for it.
4903         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4904           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4905                                    N0, N2_0);
4906           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4907                              N1, N2_2);
4908         }
4909         // Otherwise see if we can optimize to a better pattern.
4910         if (SDValue Combined = visitORLike(N0, N2_0, N))
4911           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4912                              N1, N2_2);
4913       }
4914     }
4915   }
4916
4917   return SDValue();
4918 }
4919
4920 static
4921 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4922   SDLoc DL(N);
4923   EVT LoVT, HiVT;
4924   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4925
4926   // Split the inputs.
4927   SDValue Lo, Hi, LL, LH, RL, RH;
4928   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4929   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4930
4931   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4932   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4933
4934   return std::make_pair(Lo, Hi);
4935 }
4936
4937 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4938 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4939 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4940   SDLoc dl(N);
4941   SDValue Cond = N->getOperand(0);
4942   SDValue LHS = N->getOperand(1);
4943   SDValue RHS = N->getOperand(2);
4944   EVT VT = N->getValueType(0);
4945   int NumElems = VT.getVectorNumElements();
4946   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4947          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4948          Cond.getOpcode() == ISD::BUILD_VECTOR);
4949
4950   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4951   // binary ones here.
4952   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4953     return SDValue();
4954
4955   // We're sure we have an even number of elements due to the
4956   // concat_vectors we have as arguments to vselect.
4957   // Skip BV elements until we find one that's not an UNDEF
4958   // After we find an UNDEF element, keep looping until we get to half the
4959   // length of the BV and see if all the non-undef nodes are the same.
4960   ConstantSDNode *BottomHalf = nullptr;
4961   for (int i = 0; i < NumElems / 2; ++i) {
4962     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4963       continue;
4964
4965     if (BottomHalf == nullptr)
4966       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4967     else if (Cond->getOperand(i).getNode() != BottomHalf)
4968       return SDValue();
4969   }
4970
4971   // Do the same for the second half of the BuildVector
4972   ConstantSDNode *TopHalf = nullptr;
4973   for (int i = NumElems / 2; i < NumElems; ++i) {
4974     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4975       continue;
4976
4977     if (TopHalf == nullptr)
4978       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4979     else if (Cond->getOperand(i).getNode() != TopHalf)
4980       return SDValue();
4981   }
4982
4983   assert(TopHalf && BottomHalf &&
4984          "One half of the selector was all UNDEFs and the other was all the "
4985          "same value. This should have been addressed before this function.");
4986   return DAG.getNode(
4987       ISD::CONCAT_VECTORS, dl, VT,
4988       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4989       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4990 }
4991
4992 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4993
4994   if (Level >= AfterLegalizeTypes)
4995     return SDValue();
4996
4997   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4998   SDValue Mask = MST->getMask();
4999   SDValue Data  = MST->getValue();
5000   SDLoc DL(N);
5001
5002   // If the MSTORE data type requires splitting and the mask is provided by a
5003   // SETCC, then split both nodes and its operands before legalization. This
5004   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5005   // and enables future optimizations (e.g. min/max pattern matching on X86).
5006   if (Mask.getOpcode() == ISD::SETCC) {
5007
5008     // Check if any splitting is required.
5009     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5010         TargetLowering::TypeSplitVector)
5011       return SDValue();
5012
5013     SDValue MaskLo, MaskHi, Lo, Hi;
5014     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5015
5016     EVT LoVT, HiVT;
5017     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5018
5019     SDValue Chain = MST->getChain();
5020     SDValue Ptr   = MST->getBasePtr();
5021
5022     EVT MemoryVT = MST->getMemoryVT();
5023     unsigned Alignment = MST->getOriginalAlignment();
5024
5025     // if Alignment is equal to the vector size,
5026     // take the half of it for the second part
5027     unsigned SecondHalfAlignment =
5028       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5029          Alignment/2 : Alignment;
5030
5031     EVT LoMemVT, HiMemVT;
5032     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5033
5034     SDValue DataLo, DataHi;
5035     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5036
5037     MachineMemOperand *MMO = DAG.getMachineFunction().
5038       getMachineMemOperand(MST->getPointerInfo(),
5039                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5040                            Alignment, MST->getAAInfo(), MST->getRanges());
5041
5042     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5043                             MST->isTruncatingStore());
5044
5045     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5046     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5047                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5048
5049     MMO = DAG.getMachineFunction().
5050       getMachineMemOperand(MST->getPointerInfo(),
5051                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5052                            SecondHalfAlignment, MST->getAAInfo(),
5053                            MST->getRanges());
5054
5055     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5056                             MST->isTruncatingStore());
5057
5058     AddToWorklist(Lo.getNode());
5059     AddToWorklist(Hi.getNode());
5060
5061     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5062   }
5063   return SDValue();
5064 }
5065
5066 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5067
5068   if (Level >= AfterLegalizeTypes)
5069     return SDValue();
5070
5071   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5072   SDValue Mask = MLD->getMask();
5073   SDLoc DL(N);
5074
5075   // If the MLOAD result requires splitting and the mask is provided by a
5076   // SETCC, then split both nodes and its operands before legalization. This
5077   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5078   // and enables future optimizations (e.g. min/max pattern matching on X86).
5079
5080   if (Mask.getOpcode() == ISD::SETCC) {
5081     EVT VT = N->getValueType(0);
5082
5083     // Check if any splitting is required.
5084     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5085         TargetLowering::TypeSplitVector)
5086       return SDValue();
5087
5088     SDValue MaskLo, MaskHi, Lo, Hi;
5089     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5090
5091     SDValue Src0 = MLD->getSrc0();
5092     SDValue Src0Lo, Src0Hi;
5093     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5094
5095     EVT LoVT, HiVT;
5096     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5097
5098     SDValue Chain = MLD->getChain();
5099     SDValue Ptr   = MLD->getBasePtr();
5100     EVT MemoryVT = MLD->getMemoryVT();
5101     unsigned Alignment = MLD->getOriginalAlignment();
5102
5103     // if Alignment is equal to the vector size,
5104     // take the half of it for the second part
5105     unsigned SecondHalfAlignment =
5106       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5107          Alignment/2 : Alignment;
5108
5109     EVT LoMemVT, HiMemVT;
5110     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5111
5112     MachineMemOperand *MMO = DAG.getMachineFunction().
5113     getMachineMemOperand(MLD->getPointerInfo(),
5114                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5115                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5116
5117     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5118                            ISD::NON_EXTLOAD);
5119
5120     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5121     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5122                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5123
5124     MMO = DAG.getMachineFunction().
5125     getMachineMemOperand(MLD->getPointerInfo(),
5126                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5127                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5128
5129     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5130                            ISD::NON_EXTLOAD);
5131
5132     AddToWorklist(Lo.getNode());
5133     AddToWorklist(Hi.getNode());
5134
5135     // Build a factor node to remember that this load is independent of the
5136     // other one.
5137     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5138                         Hi.getValue(1));
5139
5140     // Legalized the chain result - switch anything that used the old chain to
5141     // use the new one.
5142     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5143
5144     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5145
5146     SDValue RetOps[] = { LoadRes, Chain };
5147     return DAG.getMergeValues(RetOps, DL);
5148   }
5149   return SDValue();
5150 }
5151
5152 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5153   SDValue N0 = N->getOperand(0);
5154   SDValue N1 = N->getOperand(1);
5155   SDValue N2 = N->getOperand(2);
5156   SDLoc DL(N);
5157
5158   // Canonicalize integer abs.
5159   // vselect (setg[te] X,  0),  X, -X ->
5160   // vselect (setgt    X, -1),  X, -X ->
5161   // vselect (setl[te] X,  0), -X,  X ->
5162   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5163   if (N0.getOpcode() == ISD::SETCC) {
5164     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5165     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5166     bool isAbs = false;
5167     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5168
5169     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5170          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5171         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5172       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5173     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5174              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5175       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5176
5177     if (isAbs) {
5178       EVT VT = LHS.getValueType();
5179       SDValue Shift = DAG.getNode(
5180           ISD::SRA, DL, VT, LHS,
5181           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5182       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5183       AddToWorklist(Shift.getNode());
5184       AddToWorklist(Add.getNode());
5185       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5186     }
5187   }
5188
5189   // If the VSELECT result requires splitting and the mask is provided by a
5190   // SETCC, then split both nodes and its operands before legalization. This
5191   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5192   // and enables future optimizations (e.g. min/max pattern matching on X86).
5193   if (N0.getOpcode() == ISD::SETCC) {
5194     EVT VT = N->getValueType(0);
5195
5196     // Check if any splitting is required.
5197     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5198         TargetLowering::TypeSplitVector)
5199       return SDValue();
5200
5201     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5202     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5203     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5204     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5205
5206     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5207     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5208
5209     // Add the new VSELECT nodes to the work list in case they need to be split
5210     // again.
5211     AddToWorklist(Lo.getNode());
5212     AddToWorklist(Hi.getNode());
5213
5214     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5215   }
5216
5217   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5218   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5219     return N1;
5220   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5221   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5222     return N2;
5223
5224   // The ConvertSelectToConcatVector function is assuming both the above
5225   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5226   // and addressed.
5227   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5228       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5229       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5230     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5231     if (CV.getNode())
5232       return CV;
5233   }
5234
5235   return SDValue();
5236 }
5237
5238 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5239   SDValue N0 = N->getOperand(0);
5240   SDValue N1 = N->getOperand(1);
5241   SDValue N2 = N->getOperand(2);
5242   SDValue N3 = N->getOperand(3);
5243   SDValue N4 = N->getOperand(4);
5244   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5245
5246   // fold select_cc lhs, rhs, x, x, cc -> x
5247   if (N2 == N3)
5248     return N2;
5249
5250   // Determine if the condition we're dealing with is constant
5251   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5252                               N0, N1, CC, SDLoc(N), false);
5253   if (SCC.getNode()) {
5254     AddToWorklist(SCC.getNode());
5255
5256     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5257       if (!SCCC->isNullValue())
5258         return N2;    // cond always true -> true val
5259       else
5260         return N3;    // cond always false -> false val
5261     } else if (SCC->getOpcode() == ISD::UNDEF) {
5262       // When the condition is UNDEF, just return the first operand. This is
5263       // coherent the DAG creation, no setcc node is created in this case
5264       return N2;
5265     } else if (SCC.getOpcode() == ISD::SETCC) {
5266       // Fold to a simpler select_cc
5267       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5268                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5269                          SCC.getOperand(2));
5270     }
5271   }
5272
5273   // If we can fold this based on the true/false value, do so.
5274   if (SimplifySelectOps(N, N2, N3))
5275     return SDValue(N, 0);  // Don't revisit N.
5276
5277   // fold select_cc into other things, such as min/max/abs
5278   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5279 }
5280
5281 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5282   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5283                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5284                        SDLoc(N));
5285 }
5286
5287 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5288 // dag node into a ConstantSDNode or a build_vector of constants.
5289 // This function is called by the DAGCombiner when visiting sext/zext/aext
5290 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5291 // Vector extends are not folded if operations are legal; this is to
5292 // avoid introducing illegal build_vector dag nodes.
5293 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5294                                          SelectionDAG &DAG, bool LegalTypes,
5295                                          bool LegalOperations) {
5296   unsigned Opcode = N->getOpcode();
5297   SDValue N0 = N->getOperand(0);
5298   EVT VT = N->getValueType(0);
5299
5300   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5301          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5302
5303   // fold (sext c1) -> c1
5304   // fold (zext c1) -> c1
5305   // fold (aext c1) -> c1
5306   if (isa<ConstantSDNode>(N0))
5307     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5308
5309   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5310   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5311   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5312   EVT SVT = VT.getScalarType();
5313   if (!(VT.isVector() &&
5314       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5315       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5316     return nullptr;
5317
5318   // We can fold this node into a build_vector.
5319   unsigned VTBits = SVT.getSizeInBits();
5320   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5321   unsigned ShAmt = VTBits - EVTBits;
5322   SmallVector<SDValue, 8> Elts;
5323   unsigned NumElts = N0->getNumOperands();
5324   SDLoc DL(N);
5325
5326   for (unsigned i=0; i != NumElts; ++i) {
5327     SDValue Op = N0->getOperand(i);
5328     if (Op->getOpcode() == ISD::UNDEF) {
5329       Elts.push_back(DAG.getUNDEF(SVT));
5330       continue;
5331     }
5332
5333     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5334     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5335     if (Opcode == ISD::SIGN_EXTEND)
5336       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5337                                      SVT));
5338     else
5339       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5340                                      SVT));
5341   }
5342
5343   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5344 }
5345
5346 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5347 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5348 // transformation. Returns true if extension are possible and the above
5349 // mentioned transformation is profitable.
5350 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5351                                     unsigned ExtOpc,
5352                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5353                                     const TargetLowering &TLI) {
5354   bool HasCopyToRegUses = false;
5355   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5356   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5357                             UE = N0.getNode()->use_end();
5358        UI != UE; ++UI) {
5359     SDNode *User = *UI;
5360     if (User == N)
5361       continue;
5362     if (UI.getUse().getResNo() != N0.getResNo())
5363       continue;
5364     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5365     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5366       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5367       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5368         // Sign bits will be lost after a zext.
5369         return false;
5370       bool Add = false;
5371       for (unsigned i = 0; i != 2; ++i) {
5372         SDValue UseOp = User->getOperand(i);
5373         if (UseOp == N0)
5374           continue;
5375         if (!isa<ConstantSDNode>(UseOp))
5376           return false;
5377         Add = true;
5378       }
5379       if (Add)
5380         ExtendNodes.push_back(User);
5381       continue;
5382     }
5383     // If truncates aren't free and there are users we can't
5384     // extend, it isn't worthwhile.
5385     if (!isTruncFree)
5386       return false;
5387     // Remember if this value is live-out.
5388     if (User->getOpcode() == ISD::CopyToReg)
5389       HasCopyToRegUses = true;
5390   }
5391
5392   if (HasCopyToRegUses) {
5393     bool BothLiveOut = false;
5394     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5395          UI != UE; ++UI) {
5396       SDUse &Use = UI.getUse();
5397       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5398         BothLiveOut = true;
5399         break;
5400       }
5401     }
5402     if (BothLiveOut)
5403       // Both unextended and extended values are live out. There had better be
5404       // a good reason for the transformation.
5405       return ExtendNodes.size();
5406   }
5407   return true;
5408 }
5409
5410 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5411                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5412                                   ISD::NodeType ExtType) {
5413   // Extend SetCC uses if necessary.
5414   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5415     SDNode *SetCC = SetCCs[i];
5416     SmallVector<SDValue, 4> Ops;
5417
5418     for (unsigned j = 0; j != 2; ++j) {
5419       SDValue SOp = SetCC->getOperand(j);
5420       if (SOp == Trunc)
5421         Ops.push_back(ExtLoad);
5422       else
5423         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5424     }
5425
5426     Ops.push_back(SetCC->getOperand(2));
5427     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5428   }
5429 }
5430
5431 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5432 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5433   SDValue N0 = N->getOperand(0);
5434   EVT DstVT = N->getValueType(0);
5435   EVT SrcVT = N0.getValueType();
5436
5437   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5438           N->getOpcode() == ISD::ZERO_EXTEND) &&
5439          "Unexpected node type (not an extend)!");
5440
5441   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5442   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5443   //   (v8i32 (sext (v8i16 (load x))))
5444   // into:
5445   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5446   //                          (v4i32 (sextload (x + 16)))))
5447   // Where uses of the original load, i.e.:
5448   //   (v8i16 (load x))
5449   // are replaced with:
5450   //   (v8i16 (truncate
5451   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5452   //                            (v4i32 (sextload (x + 16)))))))
5453   //
5454   // This combine is only applicable to illegal, but splittable, vectors.
5455   // All legal types, and illegal non-vector types, are handled elsewhere.
5456   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5457   //
5458   if (N0->getOpcode() != ISD::LOAD)
5459     return SDValue();
5460
5461   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5462
5463   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5464       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5465       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5466     return SDValue();
5467
5468   SmallVector<SDNode *, 4> SetCCs;
5469   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5470     return SDValue();
5471
5472   ISD::LoadExtType ExtType =
5473       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5474
5475   // Try to split the vector types to get down to legal types.
5476   EVT SplitSrcVT = SrcVT;
5477   EVT SplitDstVT = DstVT;
5478   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5479          SplitSrcVT.getVectorNumElements() > 1) {
5480     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5481     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5482   }
5483
5484   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5485     return SDValue();
5486
5487   SDLoc DL(N);
5488   const unsigned NumSplits =
5489       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5490   const unsigned Stride = SplitSrcVT.getStoreSize();
5491   SmallVector<SDValue, 4> Loads;
5492   SmallVector<SDValue, 4> Chains;
5493
5494   SDValue BasePtr = LN0->getBasePtr();
5495   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5496     const unsigned Offset = Idx * Stride;
5497     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5498
5499     SDValue SplitLoad = DAG.getExtLoad(
5500         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5501         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5502         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5503         Align, LN0->getAAInfo());
5504
5505     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5506                           DAG.getConstant(Stride, BasePtr.getValueType()));
5507
5508     Loads.push_back(SplitLoad.getValue(0));
5509     Chains.push_back(SplitLoad.getValue(1));
5510   }
5511
5512   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5513   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5514
5515   CombineTo(N, NewValue);
5516
5517   // Replace uses of the original load (before extension)
5518   // with a truncate of the concatenated sextloaded vectors.
5519   SDValue Trunc =
5520       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5521   CombineTo(N0.getNode(), Trunc, NewChain);
5522   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5523                   (ISD::NodeType)N->getOpcode());
5524   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5525 }
5526
5527 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5528   SDValue N0 = N->getOperand(0);
5529   EVT VT = N->getValueType(0);
5530
5531   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5532                                               LegalOperations))
5533     return SDValue(Res, 0);
5534
5535   // fold (sext (sext x)) -> (sext x)
5536   // fold (sext (aext x)) -> (sext x)
5537   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5538     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5539                        N0.getOperand(0));
5540
5541   if (N0.getOpcode() == ISD::TRUNCATE) {
5542     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5543     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5544     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5545     if (NarrowLoad.getNode()) {
5546       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5547       if (NarrowLoad.getNode() != N0.getNode()) {
5548         CombineTo(N0.getNode(), NarrowLoad);
5549         // CombineTo deleted the truncate, if needed, but not what's under it.
5550         AddToWorklist(oye);
5551       }
5552       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5553     }
5554
5555     // See if the value being truncated is already sign extended.  If so, just
5556     // eliminate the trunc/sext pair.
5557     SDValue Op = N0.getOperand(0);
5558     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5559     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5560     unsigned DestBits = VT.getScalarType().getSizeInBits();
5561     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5562
5563     if (OpBits == DestBits) {
5564       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5565       // bits, it is already ready.
5566       if (NumSignBits > DestBits-MidBits)
5567         return Op;
5568     } else if (OpBits < DestBits) {
5569       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5570       // bits, just sext from i32.
5571       if (NumSignBits > OpBits-MidBits)
5572         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5573     } else {
5574       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5575       // bits, just truncate to i32.
5576       if (NumSignBits > OpBits-MidBits)
5577         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5578     }
5579
5580     // fold (sext (truncate x)) -> (sextinreg x).
5581     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5582                                                  N0.getValueType())) {
5583       if (OpBits < DestBits)
5584         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5585       else if (OpBits > DestBits)
5586         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5587       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5588                          DAG.getValueType(N0.getValueType()));
5589     }
5590   }
5591
5592   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5593   // Only generate vector extloads when 1) they're legal, and 2) they are
5594   // deemed desirable by the target.
5595   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5596       ((!LegalOperations && !VT.isVector() &&
5597         !cast<LoadSDNode>(N0)->isVolatile()) ||
5598        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5599     bool DoXform = true;
5600     SmallVector<SDNode*, 4> SetCCs;
5601     if (!N0.hasOneUse())
5602       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5603     if (VT.isVector())
5604       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5605     if (DoXform) {
5606       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5607       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5608                                        LN0->getChain(),
5609                                        LN0->getBasePtr(), N0.getValueType(),
5610                                        LN0->getMemOperand());
5611       CombineTo(N, ExtLoad);
5612       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5613                                   N0.getValueType(), ExtLoad);
5614       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5615       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5616                       ISD::SIGN_EXTEND);
5617       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5618     }
5619   }
5620
5621   // fold (sext (load x)) to multiple smaller sextloads.
5622   // Only on illegal but splittable vectors.
5623   if (SDValue ExtLoad = CombineExtLoad(N))
5624     return ExtLoad;
5625
5626   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5627   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5628   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5629       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5630     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5631     EVT MemVT = LN0->getMemoryVT();
5632     if ((!LegalOperations && !LN0->isVolatile()) ||
5633         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5634       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5635                                        LN0->getChain(),
5636                                        LN0->getBasePtr(), MemVT,
5637                                        LN0->getMemOperand());
5638       CombineTo(N, ExtLoad);
5639       CombineTo(N0.getNode(),
5640                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5641                             N0.getValueType(), ExtLoad),
5642                 ExtLoad.getValue(1));
5643       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5644     }
5645   }
5646
5647   // fold (sext (and/or/xor (load x), cst)) ->
5648   //      (and/or/xor (sextload x), (sext cst))
5649   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5650        N0.getOpcode() == ISD::XOR) &&
5651       isa<LoadSDNode>(N0.getOperand(0)) &&
5652       N0.getOperand(1).getOpcode() == ISD::Constant &&
5653       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5654       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5655     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5656     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5657       bool DoXform = true;
5658       SmallVector<SDNode*, 4> SetCCs;
5659       if (!N0.hasOneUse())
5660         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5661                                           SetCCs, TLI);
5662       if (DoXform) {
5663         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5664                                          LN0->getChain(), LN0->getBasePtr(),
5665                                          LN0->getMemoryVT(),
5666                                          LN0->getMemOperand());
5667         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5668         Mask = Mask.sext(VT.getSizeInBits());
5669         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5670                                   ExtLoad, DAG.getConstant(Mask, VT));
5671         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5672                                     SDLoc(N0.getOperand(0)),
5673                                     N0.getOperand(0).getValueType(), ExtLoad);
5674         CombineTo(N, And);
5675         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5676         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5677                         ISD::SIGN_EXTEND);
5678         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5679       }
5680     }
5681   }
5682
5683   if (N0.getOpcode() == ISD::SETCC) {
5684     EVT N0VT = N0.getOperand(0).getValueType();
5685     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5686     // Only do this before legalize for now.
5687     if (VT.isVector() && !LegalOperations &&
5688         TLI.getBooleanContents(N0VT) ==
5689             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5690       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5691       // of the same size as the compared operands. Only optimize sext(setcc())
5692       // if this is the case.
5693       EVT SVT = getSetCCResultType(N0VT);
5694
5695       // We know that the # elements of the results is the same as the
5696       // # elements of the compare (and the # elements of the compare result
5697       // for that matter).  Check to see that they are the same size.  If so,
5698       // we know that the element size of the sext'd result matches the
5699       // element size of the compare operands.
5700       if (VT.getSizeInBits() == SVT.getSizeInBits())
5701         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5702                              N0.getOperand(1),
5703                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5704
5705       // If the desired elements are smaller or larger than the source
5706       // elements we can use a matching integer vector type and then
5707       // truncate/sign extend
5708       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5709       if (SVT == MatchingVectorType) {
5710         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5711                                N0.getOperand(0), N0.getOperand(1),
5712                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5713         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5714       }
5715     }
5716
5717     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5718     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5719     SDValue NegOne =
5720       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5721     SDValue SCC =
5722       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5723                        NegOne, DAG.getConstant(0, VT),
5724                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5725     if (SCC.getNode()) return SCC;
5726
5727     if (!VT.isVector()) {
5728       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5729       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5730         SDLoc DL(N);
5731         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5732         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5733                                      N0.getOperand(0), N0.getOperand(1), CC);
5734         return DAG.getSelect(DL, VT, SetCC,
5735                              NegOne, DAG.getConstant(0, VT));
5736       }
5737     }
5738   }
5739
5740   // fold (sext x) -> (zext x) if the sign bit is known zero.
5741   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5742       DAG.SignBitIsZero(N0))
5743     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5744
5745   return SDValue();
5746 }
5747
5748 // isTruncateOf - If N is a truncate of some other value, return true, record
5749 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5750 // This function computes KnownZero to avoid a duplicated call to
5751 // computeKnownBits in the caller.
5752 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5753                          APInt &KnownZero) {
5754   APInt KnownOne;
5755   if (N->getOpcode() == ISD::TRUNCATE) {
5756     Op = N->getOperand(0);
5757     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5758     return true;
5759   }
5760
5761   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5762       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5763     return false;
5764
5765   SDValue Op0 = N->getOperand(0);
5766   SDValue Op1 = N->getOperand(1);
5767   assert(Op0.getValueType() == Op1.getValueType());
5768
5769   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5770   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5771   if (COp0 && COp0->isNullValue())
5772     Op = Op1;
5773   else if (COp1 && COp1->isNullValue())
5774     Op = Op0;
5775   else
5776     return false;
5777
5778   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5779
5780   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5781     return false;
5782
5783   return true;
5784 }
5785
5786 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5787   SDValue N0 = N->getOperand(0);
5788   EVT VT = N->getValueType(0);
5789
5790   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5791                                               LegalOperations))
5792     return SDValue(Res, 0);
5793
5794   // fold (zext (zext x)) -> (zext x)
5795   // fold (zext (aext x)) -> (zext x)
5796   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5797     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5798                        N0.getOperand(0));
5799
5800   // fold (zext (truncate x)) -> (zext x) or
5801   //      (zext (truncate x)) -> (truncate x)
5802   // This is valid when the truncated bits of x are already zero.
5803   // FIXME: We should extend this to work for vectors too.
5804   SDValue Op;
5805   APInt KnownZero;
5806   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5807     APInt TruncatedBits =
5808       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5809       APInt(Op.getValueSizeInBits(), 0) :
5810       APInt::getBitsSet(Op.getValueSizeInBits(),
5811                         N0.getValueSizeInBits(),
5812                         std::min(Op.getValueSizeInBits(),
5813                                  VT.getSizeInBits()));
5814     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5815       if (VT.bitsGT(Op.getValueType()))
5816         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5817       if (VT.bitsLT(Op.getValueType()))
5818         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5819
5820       return Op;
5821     }
5822   }
5823
5824   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5825   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5826   if (N0.getOpcode() == ISD::TRUNCATE) {
5827     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5828     if (NarrowLoad.getNode()) {
5829       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5830       if (NarrowLoad.getNode() != N0.getNode()) {
5831         CombineTo(N0.getNode(), NarrowLoad);
5832         // CombineTo deleted the truncate, if needed, but not what's under it.
5833         AddToWorklist(oye);
5834       }
5835       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5836     }
5837   }
5838
5839   // fold (zext (truncate x)) -> (and x, mask)
5840   if (N0.getOpcode() == ISD::TRUNCATE &&
5841       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5842
5843     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5844     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5845     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5846     if (NarrowLoad.getNode()) {
5847       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5848       if (NarrowLoad.getNode() != N0.getNode()) {
5849         CombineTo(N0.getNode(), NarrowLoad);
5850         // CombineTo deleted the truncate, if needed, but not what's under it.
5851         AddToWorklist(oye);
5852       }
5853       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5854     }
5855
5856     SDValue Op = N0.getOperand(0);
5857     if (Op.getValueType().bitsLT(VT)) {
5858       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5859       AddToWorklist(Op.getNode());
5860     } else if (Op.getValueType().bitsGT(VT)) {
5861       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5862       AddToWorklist(Op.getNode());
5863     }
5864     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5865                                   N0.getValueType().getScalarType());
5866   }
5867
5868   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5869   // if either of the casts is not free.
5870   if (N0.getOpcode() == ISD::AND &&
5871       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5872       N0.getOperand(1).getOpcode() == ISD::Constant &&
5873       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5874                            N0.getValueType()) ||
5875        !TLI.isZExtFree(N0.getValueType(), VT))) {
5876     SDValue X = N0.getOperand(0).getOperand(0);
5877     if (X.getValueType().bitsLT(VT)) {
5878       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5879     } else if (X.getValueType().bitsGT(VT)) {
5880       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5881     }
5882     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5883     Mask = Mask.zext(VT.getSizeInBits());
5884     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5885                        X, DAG.getConstant(Mask, VT));
5886   }
5887
5888   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5889   // Only generate vector extloads when 1) they're legal, and 2) they are
5890   // deemed desirable by the target.
5891   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5892       ((!LegalOperations && !VT.isVector() &&
5893         !cast<LoadSDNode>(N0)->isVolatile()) ||
5894        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5895     bool DoXform = true;
5896     SmallVector<SDNode*, 4> SetCCs;
5897     if (!N0.hasOneUse())
5898       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5899     if (VT.isVector())
5900       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5901     if (DoXform) {
5902       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5903       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5904                                        LN0->getChain(),
5905                                        LN0->getBasePtr(), N0.getValueType(),
5906                                        LN0->getMemOperand());
5907       CombineTo(N, ExtLoad);
5908       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5909                                   N0.getValueType(), ExtLoad);
5910       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5911
5912       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5913                       ISD::ZERO_EXTEND);
5914       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5915     }
5916   }
5917
5918   // fold (zext (load x)) to multiple smaller zextloads.
5919   // Only on illegal but splittable vectors.
5920   if (SDValue ExtLoad = CombineExtLoad(N))
5921     return ExtLoad;
5922
5923   // fold (zext (and/or/xor (load x), cst)) ->
5924   //      (and/or/xor (zextload x), (zext cst))
5925   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5926        N0.getOpcode() == ISD::XOR) &&
5927       isa<LoadSDNode>(N0.getOperand(0)) &&
5928       N0.getOperand(1).getOpcode() == ISD::Constant &&
5929       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5930       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5931     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5932     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5933       bool DoXform = true;
5934       SmallVector<SDNode*, 4> SetCCs;
5935       if (!N0.hasOneUse())
5936         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5937                                           SetCCs, TLI);
5938       if (DoXform) {
5939         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5940                                          LN0->getChain(), LN0->getBasePtr(),
5941                                          LN0->getMemoryVT(),
5942                                          LN0->getMemOperand());
5943         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5944         Mask = Mask.zext(VT.getSizeInBits());
5945         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5946                                   ExtLoad, DAG.getConstant(Mask, VT));
5947         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5948                                     SDLoc(N0.getOperand(0)),
5949                                     N0.getOperand(0).getValueType(), ExtLoad);
5950         CombineTo(N, And);
5951         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5952         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5953                         ISD::ZERO_EXTEND);
5954         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5955       }
5956     }
5957   }
5958
5959   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5960   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5961   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5962       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5963     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5964     EVT MemVT = LN0->getMemoryVT();
5965     if ((!LegalOperations && !LN0->isVolatile()) ||
5966         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5967       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5968                                        LN0->getChain(),
5969                                        LN0->getBasePtr(), MemVT,
5970                                        LN0->getMemOperand());
5971       CombineTo(N, ExtLoad);
5972       CombineTo(N0.getNode(),
5973                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5974                             ExtLoad),
5975                 ExtLoad.getValue(1));
5976       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5977     }
5978   }
5979
5980   if (N0.getOpcode() == ISD::SETCC) {
5981     if (!LegalOperations && VT.isVector() &&
5982         N0.getValueType().getVectorElementType() == MVT::i1) {
5983       EVT N0VT = N0.getOperand(0).getValueType();
5984       if (getSetCCResultType(N0VT) == N0.getValueType())
5985         return SDValue();
5986
5987       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5988       // Only do this before legalize for now.
5989       EVT EltVT = VT.getVectorElementType();
5990       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5991                                     DAG.getConstant(1, EltVT));
5992       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5993         // We know that the # elements of the results is the same as the
5994         // # elements of the compare (and the # elements of the compare result
5995         // for that matter).  Check to see that they are the same size.  If so,
5996         // we know that the element size of the sext'd result matches the
5997         // element size of the compare operands.
5998         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5999                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6000                                          N0.getOperand(1),
6001                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6002                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
6003                                        OneOps));
6004
6005       // If the desired elements are smaller or larger than the source
6006       // elements we can use a matching integer vector type and then
6007       // truncate/sign extend
6008       EVT MatchingElementType =
6009         EVT::getIntegerVT(*DAG.getContext(),
6010                           N0VT.getScalarType().getSizeInBits());
6011       EVT MatchingVectorType =
6012         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6013                          N0VT.getVectorNumElements());
6014       SDValue VsetCC =
6015         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6016                       N0.getOperand(1),
6017                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6018       return DAG.getNode(ISD::AND, SDLoc(N), VT,
6019                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
6020                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
6021     }
6022
6023     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6024     SDValue SCC =
6025       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6026                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6027                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6028     if (SCC.getNode()) return SCC;
6029   }
6030
6031   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6032   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6033       isa<ConstantSDNode>(N0.getOperand(1)) &&
6034       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6035       N0.hasOneUse()) {
6036     SDValue ShAmt = N0.getOperand(1);
6037     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6038     if (N0.getOpcode() == ISD::SHL) {
6039       SDValue InnerZExt = N0.getOperand(0);
6040       // If the original shl may be shifting out bits, do not perform this
6041       // transformation.
6042       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6043         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6044       if (ShAmtVal > KnownZeroBits)
6045         return SDValue();
6046     }
6047
6048     SDLoc DL(N);
6049
6050     // Ensure that the shift amount is wide enough for the shifted value.
6051     if (VT.getSizeInBits() >= 256)
6052       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6053
6054     return DAG.getNode(N0.getOpcode(), DL, VT,
6055                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6056                        ShAmt);
6057   }
6058
6059   return SDValue();
6060 }
6061
6062 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6063   SDValue N0 = N->getOperand(0);
6064   EVT VT = N->getValueType(0);
6065
6066   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6067                                               LegalOperations))
6068     return SDValue(Res, 0);
6069
6070   // fold (aext (aext x)) -> (aext x)
6071   // fold (aext (zext x)) -> (zext x)
6072   // fold (aext (sext x)) -> (sext x)
6073   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6074       N0.getOpcode() == ISD::ZERO_EXTEND ||
6075       N0.getOpcode() == ISD::SIGN_EXTEND)
6076     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6077
6078   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6079   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6080   if (N0.getOpcode() == ISD::TRUNCATE) {
6081     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6082     if (NarrowLoad.getNode()) {
6083       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6084       if (NarrowLoad.getNode() != N0.getNode()) {
6085         CombineTo(N0.getNode(), NarrowLoad);
6086         // CombineTo deleted the truncate, if needed, but not what's under it.
6087         AddToWorklist(oye);
6088       }
6089       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6090     }
6091   }
6092
6093   // fold (aext (truncate x))
6094   if (N0.getOpcode() == ISD::TRUNCATE) {
6095     SDValue TruncOp = N0.getOperand(0);
6096     if (TruncOp.getValueType() == VT)
6097       return TruncOp; // x iff x size == zext size.
6098     if (TruncOp.getValueType().bitsGT(VT))
6099       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6100     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6101   }
6102
6103   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6104   // if the trunc is not free.
6105   if (N0.getOpcode() == ISD::AND &&
6106       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6107       N0.getOperand(1).getOpcode() == ISD::Constant &&
6108       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6109                           N0.getValueType())) {
6110     SDValue X = N0.getOperand(0).getOperand(0);
6111     if (X.getValueType().bitsLT(VT)) {
6112       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6113     } else if (X.getValueType().bitsGT(VT)) {
6114       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6115     }
6116     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6117     Mask = Mask.zext(VT.getSizeInBits());
6118     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6119                        X, DAG.getConstant(Mask, VT));
6120   }
6121
6122   // fold (aext (load x)) -> (aext (truncate (extload x)))
6123   // None of the supported targets knows how to perform load and any_ext
6124   // on vectors in one instruction.  We only perform this transformation on
6125   // scalars.
6126   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6127       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6128       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6129     bool DoXform = true;
6130     SmallVector<SDNode*, 4> SetCCs;
6131     if (!N0.hasOneUse())
6132       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6133     if (DoXform) {
6134       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6135       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6136                                        LN0->getChain(),
6137                                        LN0->getBasePtr(), N0.getValueType(),
6138                                        LN0->getMemOperand());
6139       CombineTo(N, ExtLoad);
6140       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6141                                   N0.getValueType(), ExtLoad);
6142       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6143       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6144                       ISD::ANY_EXTEND);
6145       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6146     }
6147   }
6148
6149   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6150   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6151   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6152   if (N0.getOpcode() == ISD::LOAD &&
6153       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6154       N0.hasOneUse()) {
6155     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6156     ISD::LoadExtType ExtType = LN0->getExtensionType();
6157     EVT MemVT = LN0->getMemoryVT();
6158     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6159       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6160                                        VT, LN0->getChain(), LN0->getBasePtr(),
6161                                        MemVT, LN0->getMemOperand());
6162       CombineTo(N, ExtLoad);
6163       CombineTo(N0.getNode(),
6164                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6165                             N0.getValueType(), ExtLoad),
6166                 ExtLoad.getValue(1));
6167       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6168     }
6169   }
6170
6171   if (N0.getOpcode() == ISD::SETCC) {
6172     // For vectors:
6173     // aext(setcc) -> vsetcc
6174     // aext(setcc) -> truncate(vsetcc)
6175     // aext(setcc) -> aext(vsetcc)
6176     // Only do this before legalize for now.
6177     if (VT.isVector() && !LegalOperations) {
6178       EVT N0VT = N0.getOperand(0).getValueType();
6179         // We know that the # elements of the results is the same as the
6180         // # elements of the compare (and the # elements of the compare result
6181         // for that matter).  Check to see that they are the same size.  If so,
6182         // we know that the element size of the sext'd result matches the
6183         // element size of the compare operands.
6184       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6185         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6186                              N0.getOperand(1),
6187                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6188       // If the desired elements are smaller or larger than the source
6189       // elements we can use a matching integer vector type and then
6190       // truncate/any extend
6191       else {
6192         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6193         SDValue VsetCC =
6194           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6195                         N0.getOperand(1),
6196                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6197         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6198       }
6199     }
6200
6201     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6202     SDValue SCC =
6203       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6204                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6205                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6206     if (SCC.getNode())
6207       return SCC;
6208   }
6209
6210   return SDValue();
6211 }
6212
6213 /// See if the specified operand can be simplified with the knowledge that only
6214 /// the bits specified by Mask are used.  If so, return the simpler operand,
6215 /// otherwise return a null SDValue.
6216 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6217   switch (V.getOpcode()) {
6218   default: break;
6219   case ISD::Constant: {
6220     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6221     assert(CV && "Const value should be ConstSDNode.");
6222     const APInt &CVal = CV->getAPIntValue();
6223     APInt NewVal = CVal & Mask;
6224     if (NewVal != CVal)
6225       return DAG.getConstant(NewVal, V.getValueType());
6226     break;
6227   }
6228   case ISD::OR:
6229   case ISD::XOR:
6230     // If the LHS or RHS don't contribute bits to the or, drop them.
6231     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6232       return V.getOperand(1);
6233     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6234       return V.getOperand(0);
6235     break;
6236   case ISD::SRL:
6237     // Only look at single-use SRLs.
6238     if (!V.getNode()->hasOneUse())
6239       break;
6240     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6241       // See if we can recursively simplify the LHS.
6242       unsigned Amt = RHSC->getZExtValue();
6243
6244       // Watch out for shift count overflow though.
6245       if (Amt >= Mask.getBitWidth()) break;
6246       APInt NewMask = Mask << Amt;
6247       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6248       if (SimplifyLHS.getNode())
6249         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6250                            SimplifyLHS, V.getOperand(1));
6251     }
6252   }
6253   return SDValue();
6254 }
6255
6256 /// If the result of a wider load is shifted to right of N  bits and then
6257 /// truncated to a narrower type and where N is a multiple of number of bits of
6258 /// the narrower type, transform it to a narrower load from address + N / num of
6259 /// bits of new type. If the result is to be extended, also fold the extension
6260 /// to form a extending load.
6261 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6262   unsigned Opc = N->getOpcode();
6263
6264   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6265   SDValue N0 = N->getOperand(0);
6266   EVT VT = N->getValueType(0);
6267   EVT ExtVT = VT;
6268
6269   // This transformation isn't valid for vector loads.
6270   if (VT.isVector())
6271     return SDValue();
6272
6273   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6274   // extended to VT.
6275   if (Opc == ISD::SIGN_EXTEND_INREG) {
6276     ExtType = ISD::SEXTLOAD;
6277     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6278   } else if (Opc == ISD::SRL) {
6279     // Another special-case: SRL is basically zero-extending a narrower value.
6280     ExtType = ISD::ZEXTLOAD;
6281     N0 = SDValue(N, 0);
6282     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6283     if (!N01) return SDValue();
6284     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6285                               VT.getSizeInBits() - N01->getZExtValue());
6286   }
6287   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6288     return SDValue();
6289
6290   unsigned EVTBits = ExtVT.getSizeInBits();
6291
6292   // Do not generate loads of non-round integer types since these can
6293   // be expensive (and would be wrong if the type is not byte sized).
6294   if (!ExtVT.isRound())
6295     return SDValue();
6296
6297   unsigned ShAmt = 0;
6298   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6299     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6300       ShAmt = N01->getZExtValue();
6301       // Is the shift amount a multiple of size of VT?
6302       if ((ShAmt & (EVTBits-1)) == 0) {
6303         N0 = N0.getOperand(0);
6304         // Is the load width a multiple of size of VT?
6305         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6306           return SDValue();
6307       }
6308
6309       // At this point, we must have a load or else we can't do the transform.
6310       if (!isa<LoadSDNode>(N0)) return SDValue();
6311
6312       // Because a SRL must be assumed to *need* to zero-extend the high bits
6313       // (as opposed to anyext the high bits), we can't combine the zextload
6314       // lowering of SRL and an sextload.
6315       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6316         return SDValue();
6317
6318       // If the shift amount is larger than the input type then we're not
6319       // accessing any of the loaded bytes.  If the load was a zextload/extload
6320       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6321       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6322         return SDValue();
6323     }
6324   }
6325
6326   // If the load is shifted left (and the result isn't shifted back right),
6327   // we can fold the truncate through the shift.
6328   unsigned ShLeftAmt = 0;
6329   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6330       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6331     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6332       ShLeftAmt = N01->getZExtValue();
6333       N0 = N0.getOperand(0);
6334     }
6335   }
6336
6337   // If we haven't found a load, we can't narrow it.  Don't transform one with
6338   // multiple uses, this would require adding a new load.
6339   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6340     return SDValue();
6341
6342   // Don't change the width of a volatile load.
6343   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6344   if (LN0->isVolatile())
6345     return SDValue();
6346
6347   // Verify that we are actually reducing a load width here.
6348   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6349     return SDValue();
6350
6351   // For the transform to be legal, the load must produce only two values
6352   // (the value loaded and the chain).  Don't transform a pre-increment
6353   // load, for example, which produces an extra value.  Otherwise the
6354   // transformation is not equivalent, and the downstream logic to replace
6355   // uses gets things wrong.
6356   if (LN0->getNumValues() > 2)
6357     return SDValue();
6358
6359   // If the load that we're shrinking is an extload and we're not just
6360   // discarding the extension we can't simply shrink the load. Bail.
6361   // TODO: It would be possible to merge the extensions in some cases.
6362   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6363       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6364     return SDValue();
6365
6366   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6367     return SDValue();
6368
6369   EVT PtrType = N0.getOperand(1).getValueType();
6370
6371   if (PtrType == MVT::Untyped || PtrType.isExtended())
6372     // It's not possible to generate a constant of extended or untyped type.
6373     return SDValue();
6374
6375   // For big endian targets, we need to adjust the offset to the pointer to
6376   // load the correct bytes.
6377   if (TLI.isBigEndian()) {
6378     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6379     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6380     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6381   }
6382
6383   uint64_t PtrOff = ShAmt / 8;
6384   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6385   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6386                                PtrType, LN0->getBasePtr(),
6387                                DAG.getConstant(PtrOff, PtrType));
6388   AddToWorklist(NewPtr.getNode());
6389
6390   SDValue Load;
6391   if (ExtType == ISD::NON_EXTLOAD)
6392     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6393                         LN0->getPointerInfo().getWithOffset(PtrOff),
6394                         LN0->isVolatile(), LN0->isNonTemporal(),
6395                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6396   else
6397     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6398                           LN0->getPointerInfo().getWithOffset(PtrOff),
6399                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6400                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6401
6402   // Replace the old load's chain with the new load's chain.
6403   WorklistRemover DeadNodes(*this);
6404   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6405
6406   // Shift the result left, if we've swallowed a left shift.
6407   SDValue Result = Load;
6408   if (ShLeftAmt != 0) {
6409     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6410     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6411       ShImmTy = VT;
6412     // If the shift amount is as large as the result size (but, presumably,
6413     // no larger than the source) then the useful bits of the result are
6414     // zero; we can't simply return the shortened shift, because the result
6415     // of that operation is undefined.
6416     if (ShLeftAmt >= VT.getSizeInBits())
6417       Result = DAG.getConstant(0, VT);
6418     else
6419       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6420                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6421   }
6422
6423   // Return the new loaded value.
6424   return Result;
6425 }
6426
6427 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6428   SDValue N0 = N->getOperand(0);
6429   SDValue N1 = N->getOperand(1);
6430   EVT VT = N->getValueType(0);
6431   EVT EVT = cast<VTSDNode>(N1)->getVT();
6432   unsigned VTBits = VT.getScalarType().getSizeInBits();
6433   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6434
6435   // fold (sext_in_reg c1) -> c1
6436   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6437     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6438
6439   // If the input is already sign extended, just drop the extension.
6440   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6441     return N0;
6442
6443   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6444   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6445       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6446     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6447                        N0.getOperand(0), N1);
6448
6449   // fold (sext_in_reg (sext x)) -> (sext x)
6450   // fold (sext_in_reg (aext x)) -> (sext x)
6451   // if x is small enough.
6452   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6453     SDValue N00 = N0.getOperand(0);
6454     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6455         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6456       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6457   }
6458
6459   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6460   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6461     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6462
6463   // fold operands of sext_in_reg based on knowledge that the top bits are not
6464   // demanded.
6465   if (SimplifyDemandedBits(SDValue(N, 0)))
6466     return SDValue(N, 0);
6467
6468   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6469   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6470   SDValue NarrowLoad = ReduceLoadWidth(N);
6471   if (NarrowLoad.getNode())
6472     return NarrowLoad;
6473
6474   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6475   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6476   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6477   if (N0.getOpcode() == ISD::SRL) {
6478     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6479       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6480         // We can turn this into an SRA iff the input to the SRL is already sign
6481         // extended enough.
6482         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6483         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6484           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6485                              N0.getOperand(0), N0.getOperand(1));
6486       }
6487   }
6488
6489   // fold (sext_inreg (extload x)) -> (sextload x)
6490   if (ISD::isEXTLoad(N0.getNode()) &&
6491       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6492       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6493       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6494        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6495     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6496     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6497                                      LN0->getChain(),
6498                                      LN0->getBasePtr(), EVT,
6499                                      LN0->getMemOperand());
6500     CombineTo(N, ExtLoad);
6501     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6502     AddToWorklist(ExtLoad.getNode());
6503     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6504   }
6505   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6506   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6507       N0.hasOneUse() &&
6508       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6509       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6510        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6511     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6512     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6513                                      LN0->getChain(),
6514                                      LN0->getBasePtr(), EVT,
6515                                      LN0->getMemOperand());
6516     CombineTo(N, ExtLoad);
6517     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6518     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6519   }
6520
6521   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6522   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6523     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6524                                        N0.getOperand(1), false);
6525     if (BSwap.getNode())
6526       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6527                          BSwap, N1);
6528   }
6529
6530   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6531   // into a build_vector.
6532   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6533     SmallVector<SDValue, 8> Elts;
6534     unsigned NumElts = N0->getNumOperands();
6535     unsigned ShAmt = VTBits - EVTBits;
6536
6537     for (unsigned i = 0; i != NumElts; ++i) {
6538       SDValue Op = N0->getOperand(i);
6539       if (Op->getOpcode() == ISD::UNDEF) {
6540         Elts.push_back(Op);
6541         continue;
6542       }
6543
6544       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6545       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6546       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6547                                      Op.getValueType()));
6548     }
6549
6550     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6551   }
6552
6553   return SDValue();
6554 }
6555
6556 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6557   SDValue N0 = N->getOperand(0);
6558   EVT VT = N->getValueType(0);
6559   bool isLE = TLI.isLittleEndian();
6560
6561   // noop truncate
6562   if (N0.getValueType() == N->getValueType(0))
6563     return N0;
6564   // fold (truncate c1) -> c1
6565   if (isa<ConstantSDNode>(N0))
6566     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6567   // fold (truncate (truncate x)) -> (truncate x)
6568   if (N0.getOpcode() == ISD::TRUNCATE)
6569     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6570   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6571   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6572       N0.getOpcode() == ISD::SIGN_EXTEND ||
6573       N0.getOpcode() == ISD::ANY_EXTEND) {
6574     if (N0.getOperand(0).getValueType().bitsLT(VT))
6575       // if the source is smaller than the dest, we still need an extend
6576       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6577                          N0.getOperand(0));
6578     if (N0.getOperand(0).getValueType().bitsGT(VT))
6579       // if the source is larger than the dest, than we just need the truncate
6580       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6581     // if the source and dest are the same type, we can drop both the extend
6582     // and the truncate.
6583     return N0.getOperand(0);
6584   }
6585
6586   // Fold extract-and-trunc into a narrow extract. For example:
6587   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6588   //   i32 y = TRUNCATE(i64 x)
6589   //        -- becomes --
6590   //   v16i8 b = BITCAST (v2i64 val)
6591   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6592   //
6593   // Note: We only run this optimization after type legalization (which often
6594   // creates this pattern) and before operation legalization after which
6595   // we need to be more careful about the vector instructions that we generate.
6596   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6597       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6598
6599     EVT VecTy = N0.getOperand(0).getValueType();
6600     EVT ExTy = N0.getValueType();
6601     EVT TrTy = N->getValueType(0);
6602
6603     unsigned NumElem = VecTy.getVectorNumElements();
6604     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6605
6606     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6607     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6608
6609     SDValue EltNo = N0->getOperand(1);
6610     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6611       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6612       EVT IndexTy = TLI.getVectorIdxTy();
6613       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6614
6615       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6616                               NVT, N0.getOperand(0));
6617
6618       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6619                          SDLoc(N), TrTy, V,
6620                          DAG.getConstant(Index, IndexTy));
6621     }
6622   }
6623
6624   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6625   if (N0.getOpcode() == ISD::SELECT) {
6626     EVT SrcVT = N0.getValueType();
6627     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6628         TLI.isTruncateFree(SrcVT, VT)) {
6629       SDLoc SL(N0);
6630       SDValue Cond = N0.getOperand(0);
6631       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6632       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6633       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6634     }
6635   }
6636
6637   // Fold a series of buildvector, bitcast, and truncate if possible.
6638   // For example fold
6639   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6640   //   (2xi32 (buildvector x, y)).
6641   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6642       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6643       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6644       N0.getOperand(0).hasOneUse()) {
6645
6646     SDValue BuildVect = N0.getOperand(0);
6647     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6648     EVT TruncVecEltTy = VT.getVectorElementType();
6649
6650     // Check that the element types match.
6651     if (BuildVectEltTy == TruncVecEltTy) {
6652       // Now we only need to compute the offset of the truncated elements.
6653       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6654       unsigned TruncVecNumElts = VT.getVectorNumElements();
6655       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6656
6657       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6658              "Invalid number of elements");
6659
6660       SmallVector<SDValue, 8> Opnds;
6661       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6662         Opnds.push_back(BuildVect.getOperand(i));
6663
6664       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6665     }
6666   }
6667
6668   // See if we can simplify the input to this truncate through knowledge that
6669   // only the low bits are being used.
6670   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6671   // Currently we only perform this optimization on scalars because vectors
6672   // may have different active low bits.
6673   if (!VT.isVector()) {
6674     SDValue Shorter =
6675       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6676                                                VT.getSizeInBits()));
6677     if (Shorter.getNode())
6678       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6679   }
6680   // fold (truncate (load x)) -> (smaller load x)
6681   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6682   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6683     SDValue Reduced = ReduceLoadWidth(N);
6684     if (Reduced.getNode())
6685       return Reduced;
6686     // Handle the case where the load remains an extending load even
6687     // after truncation.
6688     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6689       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6690       if (!LN0->isVolatile() &&
6691           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6692         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6693                                          VT, LN0->getChain(), LN0->getBasePtr(),
6694                                          LN0->getMemoryVT(),
6695                                          LN0->getMemOperand());
6696         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6697         return NewLoad;
6698       }
6699     }
6700   }
6701   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6702   // where ... are all 'undef'.
6703   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6704     SmallVector<EVT, 8> VTs;
6705     SDValue V;
6706     unsigned Idx = 0;
6707     unsigned NumDefs = 0;
6708
6709     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6710       SDValue X = N0.getOperand(i);
6711       if (X.getOpcode() != ISD::UNDEF) {
6712         V = X;
6713         Idx = i;
6714         NumDefs++;
6715       }
6716       // Stop if more than one members are non-undef.
6717       if (NumDefs > 1)
6718         break;
6719       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6720                                      VT.getVectorElementType(),
6721                                      X.getValueType().getVectorNumElements()));
6722     }
6723
6724     if (NumDefs == 0)
6725       return DAG.getUNDEF(VT);
6726
6727     if (NumDefs == 1) {
6728       assert(V.getNode() && "The single defined operand is empty!");
6729       SmallVector<SDValue, 8> Opnds;
6730       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6731         if (i != Idx) {
6732           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6733           continue;
6734         }
6735         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6736         AddToWorklist(NV.getNode());
6737         Opnds.push_back(NV);
6738       }
6739       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6740     }
6741   }
6742
6743   // Simplify the operands using demanded-bits information.
6744   if (!VT.isVector() &&
6745       SimplifyDemandedBits(SDValue(N, 0)))
6746     return SDValue(N, 0);
6747
6748   return SDValue();
6749 }
6750
6751 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6752   SDValue Elt = N->getOperand(i);
6753   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6754     return Elt.getNode();
6755   return Elt.getOperand(Elt.getResNo()).getNode();
6756 }
6757
6758 /// build_pair (load, load) -> load
6759 /// if load locations are consecutive.
6760 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6761   assert(N->getOpcode() == ISD::BUILD_PAIR);
6762
6763   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6764   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6765   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6766       LD1->getAddressSpace() != LD2->getAddressSpace())
6767     return SDValue();
6768   EVT LD1VT = LD1->getValueType(0);
6769
6770   if (ISD::isNON_EXTLoad(LD2) &&
6771       LD2->hasOneUse() &&
6772       // If both are volatile this would reduce the number of volatile loads.
6773       // If one is volatile it might be ok, but play conservative and bail out.
6774       !LD1->isVolatile() &&
6775       !LD2->isVolatile() &&
6776       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6777     unsigned Align = LD1->getAlignment();
6778     unsigned NewAlign = TLI.getDataLayout()->
6779       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6780
6781     if (NewAlign <= Align &&
6782         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6783       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6784                          LD1->getBasePtr(), LD1->getPointerInfo(),
6785                          false, false, false, Align);
6786   }
6787
6788   return SDValue();
6789 }
6790
6791 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6792   SDValue N0 = N->getOperand(0);
6793   EVT VT = N->getValueType(0);
6794
6795   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6796   // Only do this before legalize, since afterward the target may be depending
6797   // on the bitconvert.
6798   // First check to see if this is all constant.
6799   if (!LegalTypes &&
6800       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6801       VT.isVector()) {
6802     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6803
6804     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6805     assert(!DestEltVT.isVector() &&
6806            "Element type of vector ValueType must not be vector!");
6807     if (isSimple)
6808       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6809   }
6810
6811   // If the input is a constant, let getNode fold it.
6812   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6813     // If we can't allow illegal operations, we need to check that this is just
6814     // a fp -> int or int -> conversion and that the resulting operation will
6815     // be legal.
6816     if (!LegalOperations ||
6817         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6818          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6819         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6820          TLI.isOperationLegal(ISD::Constant, VT)))
6821       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6822   }
6823
6824   // (conv (conv x, t1), t2) -> (conv x, t2)
6825   if (N0.getOpcode() == ISD::BITCAST)
6826     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6827                        N0.getOperand(0));
6828
6829   // fold (conv (load x)) -> (load (conv*)x)
6830   // If the resultant load doesn't need a higher alignment than the original!
6831   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6832       // Do not change the width of a volatile load.
6833       !cast<LoadSDNode>(N0)->isVolatile() &&
6834       // Do not remove the cast if the types differ in endian layout.
6835       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6836       TLI.hasBigEndianPartOrdering(VT) &&
6837       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6838       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6839     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6840     unsigned Align = TLI.getDataLayout()->
6841       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6842     unsigned OrigAlign = LN0->getAlignment();
6843
6844     if (Align <= OrigAlign) {
6845       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6846                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6847                                  LN0->isVolatile(), LN0->isNonTemporal(),
6848                                  LN0->isInvariant(), OrigAlign,
6849                                  LN0->getAAInfo());
6850       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6851       return Load;
6852     }
6853   }
6854
6855   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6856   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6857   // This often reduces constant pool loads.
6858   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6859        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6860       N0.getNode()->hasOneUse() && VT.isInteger() &&
6861       !VT.isVector() && !N0.getValueType().isVector()) {
6862     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6863                                   N0.getOperand(0));
6864     AddToWorklist(NewConv.getNode());
6865
6866     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6867     if (N0.getOpcode() == ISD::FNEG)
6868       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6869                          NewConv, DAG.getConstant(SignBit, VT));
6870     assert(N0.getOpcode() == ISD::FABS);
6871     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6872                        NewConv, DAG.getConstant(~SignBit, VT));
6873   }
6874
6875   // fold (bitconvert (fcopysign cst, x)) ->
6876   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6877   // Note that we don't handle (copysign x, cst) because this can always be
6878   // folded to an fneg or fabs.
6879   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6880       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6881       VT.isInteger() && !VT.isVector()) {
6882     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6883     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6884     if (isTypeLegal(IntXVT)) {
6885       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6886                               IntXVT, N0.getOperand(1));
6887       AddToWorklist(X.getNode());
6888
6889       // If X has a different width than the result/lhs, sext it or truncate it.
6890       unsigned VTWidth = VT.getSizeInBits();
6891       if (OrigXWidth < VTWidth) {
6892         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6893         AddToWorklist(X.getNode());
6894       } else if (OrigXWidth > VTWidth) {
6895         // To get the sign bit in the right place, we have to shift it right
6896         // before truncating.
6897         X = DAG.getNode(ISD::SRL, SDLoc(X),
6898                         X.getValueType(), X,
6899                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6900         AddToWorklist(X.getNode());
6901         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6902         AddToWorklist(X.getNode());
6903       }
6904
6905       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6906       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6907                       X, DAG.getConstant(SignBit, VT));
6908       AddToWorklist(X.getNode());
6909
6910       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6911                                 VT, N0.getOperand(0));
6912       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6913                         Cst, DAG.getConstant(~SignBit, VT));
6914       AddToWorklist(Cst.getNode());
6915
6916       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6917     }
6918   }
6919
6920   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6921   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6922     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6923     if (CombineLD.getNode())
6924       return CombineLD;
6925   }
6926
6927   return SDValue();
6928 }
6929
6930 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6931   EVT VT = N->getValueType(0);
6932   return CombineConsecutiveLoads(N, VT);
6933 }
6934
6935 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6936 /// operands. DstEltVT indicates the destination element value type.
6937 SDValue DAGCombiner::
6938 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6939   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6940
6941   // If this is already the right type, we're done.
6942   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6943
6944   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6945   unsigned DstBitSize = DstEltVT.getSizeInBits();
6946
6947   // If this is a conversion of N elements of one type to N elements of another
6948   // type, convert each element.  This handles FP<->INT cases.
6949   if (SrcBitSize == DstBitSize) {
6950     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6951                               BV->getValueType(0).getVectorNumElements());
6952
6953     // Due to the FP element handling below calling this routine recursively,
6954     // we can end up with a scalar-to-vector node here.
6955     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6956       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6957                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6958                                      DstEltVT, BV->getOperand(0)));
6959
6960     SmallVector<SDValue, 8> Ops;
6961     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6962       SDValue Op = BV->getOperand(i);
6963       // If the vector element type is not legal, the BUILD_VECTOR operands
6964       // are promoted and implicitly truncated.  Make that explicit here.
6965       if (Op.getValueType() != SrcEltVT)
6966         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6967       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6968                                 DstEltVT, Op));
6969       AddToWorklist(Ops.back().getNode());
6970     }
6971     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6972   }
6973
6974   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6975   // handle annoying details of growing/shrinking FP values, we convert them to
6976   // int first.
6977   if (SrcEltVT.isFloatingPoint()) {
6978     // Convert the input float vector to a int vector where the elements are the
6979     // same sizes.
6980     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6981     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6982     SrcEltVT = IntVT;
6983   }
6984
6985   // Now we know the input is an integer vector.  If the output is a FP type,
6986   // convert to integer first, then to FP of the right size.
6987   if (DstEltVT.isFloatingPoint()) {
6988     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6989     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6990
6991     // Next, convert to FP elements of the same size.
6992     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6993   }
6994
6995   // Okay, we know the src/dst types are both integers of differing types.
6996   // Handling growing first.
6997   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6998   if (SrcBitSize < DstBitSize) {
6999     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7000
7001     SmallVector<SDValue, 8> Ops;
7002     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7003          i += NumInputsPerOutput) {
7004       bool isLE = TLI.isLittleEndian();
7005       APInt NewBits = APInt(DstBitSize, 0);
7006       bool EltIsUndef = true;
7007       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7008         // Shift the previously computed bits over.
7009         NewBits <<= SrcBitSize;
7010         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7011         if (Op.getOpcode() == ISD::UNDEF) continue;
7012         EltIsUndef = false;
7013
7014         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7015                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7016       }
7017
7018       if (EltIsUndef)
7019         Ops.push_back(DAG.getUNDEF(DstEltVT));
7020       else
7021         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7022     }
7023
7024     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7025     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7026   }
7027
7028   // Finally, this must be the case where we are shrinking elements: each input
7029   // turns into multiple outputs.
7030   bool isS2V = ISD::isScalarToVector(BV);
7031   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7032   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7033                             NumOutputsPerInput*BV->getNumOperands());
7034   SmallVector<SDValue, 8> Ops;
7035
7036   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7037     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7038       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7039       continue;
7040     }
7041
7042     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7043                   getAPIntValue().zextOrTrunc(SrcBitSize);
7044
7045     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7046       APInt ThisVal = OpVal.trunc(DstBitSize);
7047       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7048       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
7049         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
7050         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7051                            Ops[0]);
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 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7064 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7065                                        bool Aggressive,
7066                                        SDNode *N,
7067                                        const TargetLowering &TLI,
7068                                        SelectionDAG &DAG) {
7069   SDValue N0 = N->getOperand(0);
7070   SDValue N1 = N->getOperand(1);
7071   EVT VT = N->getValueType(0);
7072
7073   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7074   if (N0.getOpcode() == ISD::FMUL &&
7075       (Aggressive || N0->hasOneUse())) {
7076     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7077                        N0.getOperand(0), N0.getOperand(1), N1);
7078   }
7079
7080   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7081   // Note: Commutes FADD operands.
7082   if (N1.getOpcode() == ISD::FMUL &&
7083       (Aggressive || N1->hasOneUse())) {
7084     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7085                        N1.getOperand(0), N1.getOperand(1), N0);
7086   }
7087
7088   // More folding opportunities when target permits.
7089   if (Aggressive) {
7090     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7091     if (N0.getOpcode() == ISD::FMA &&
7092         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7093       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7094                          N0.getOperand(0), N0.getOperand(1),
7095                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7096                                      N0.getOperand(2).getOperand(0),
7097                                      N0.getOperand(2).getOperand(1),
7098                                      N1));
7099     }
7100
7101     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7102     if (N1->getOpcode() == ISD::FMA &&
7103         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7104       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7105                          N1.getOperand(0), N1.getOperand(1),
7106                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7107                                      N1.getOperand(2).getOperand(0),
7108                                      N1.getOperand(2).getOperand(1),
7109                                      N0));
7110     }
7111   }
7112
7113   return SDValue();
7114 }
7115
7116 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7117                                        bool Aggressive,
7118                                        SDNode *N,
7119                                        const TargetLowering &TLI,
7120                                        SelectionDAG &DAG) {
7121   SDValue N0 = N->getOperand(0);
7122   SDValue N1 = N->getOperand(1);
7123   EVT VT = N->getValueType(0);
7124
7125   SDLoc SL(N);
7126
7127   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7128   if (N0.getOpcode() == ISD::FMUL &&
7129       (Aggressive || N0->hasOneUse())) {
7130     return DAG.getNode(FusedOpcode, SL, VT,
7131                        N0.getOperand(0), N0.getOperand(1),
7132                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7133   }
7134
7135   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7136   // Note: Commutes FSUB operands.
7137   if (N1.getOpcode() == ISD::FMUL &&
7138       (Aggressive || N1->hasOneUse()))
7139     return DAG.getNode(FusedOpcode, SL, VT,
7140                        DAG.getNode(ISD::FNEG, SL, VT,
7141                                    N1.getOperand(0)),
7142                        N1.getOperand(1), N0);
7143
7144   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7145   if (N0.getOpcode() == ISD::FNEG &&
7146       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7147       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7148     SDValue N00 = N0.getOperand(0).getOperand(0);
7149     SDValue N01 = N0.getOperand(0).getOperand(1);
7150     return DAG.getNode(FusedOpcode, SL, VT,
7151                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7152                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7153   }
7154
7155   // More folding opportunities when target permits.
7156   if (Aggressive) {
7157     // fold (fsub (fma x, y, (fmul u, v)), z)
7158     //   -> (fma x, y (fma u, v, (fneg z)))
7159     if (N0.getOpcode() == FusedOpcode &&
7160         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7161       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7162                          N0.getOperand(0), N0.getOperand(1),
7163                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7164                                      N0.getOperand(2).getOperand(0),
7165                                      N0.getOperand(2).getOperand(1),
7166                                      DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7167                                                  N1)));
7168     }
7169
7170     // fold (fsub x, (fma y, z, (fmul u, v)))
7171     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7172     if (N1.getOpcode() == FusedOpcode &&
7173         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7174       SDValue N20 = N1.getOperand(2).getOperand(0);
7175       SDValue N21 = N1.getOperand(2).getOperand(1);
7176       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7177                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7178                                      N1.getOperand(0)),
7179                          N1.getOperand(1),
7180                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7181                                      DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7182                                                  N20),
7183                                      N21, N0));
7184     }
7185   }
7186
7187   return SDValue();
7188 }
7189
7190 SDValue DAGCombiner::visitFADD(SDNode *N) {
7191   SDValue N0 = N->getOperand(0);
7192   SDValue N1 = N->getOperand(1);
7193   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7194   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7195   EVT VT = N->getValueType(0);
7196   const TargetOptions &Options = DAG.getTarget().Options;
7197
7198   // fold vector ops
7199   if (VT.isVector()) {
7200     SDValue FoldedVOp = SimplifyVBinOp(N);
7201     if (FoldedVOp.getNode()) return FoldedVOp;
7202   }
7203
7204   // fold (fadd c1, c2) -> c1 + c2
7205   if (N0CFP && N1CFP)
7206     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7207
7208   // canonicalize constant to RHS
7209   if (N0CFP && !N1CFP)
7210     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7211
7212   // fold (fadd A, (fneg B)) -> (fsub A, B)
7213   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7214       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7215     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7216                        GetNegatedExpression(N1, DAG, LegalOperations));
7217
7218   // fold (fadd (fneg A), B) -> (fsub B, A)
7219   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7220       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7221     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7222                        GetNegatedExpression(N0, DAG, LegalOperations));
7223
7224   // If 'unsafe math' is enabled, fold lots of things.
7225   if (Options.UnsafeFPMath) {
7226     // No FP constant should be created after legalization as Instruction
7227     // Selection pass has a hard time dealing with FP constants.
7228     bool AllowNewConst = (Level < AfterLegalizeDAG);
7229
7230     // fold (fadd A, 0) -> A
7231     if (N1CFP && N1CFP->getValueAPF().isZero())
7232       return N0;
7233
7234     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7235     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7236         isa<ConstantFPSDNode>(N0.getOperand(1)))
7237       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7238                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7239                                      N0.getOperand(1), N1));
7240
7241     // If allowed, fold (fadd (fneg x), x) -> 0.0
7242     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7243       return DAG.getConstantFP(0.0, VT);
7244
7245     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7246     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7247       return DAG.getConstantFP(0.0, VT);
7248
7249     // We can fold chains of FADD's of the same value into multiplications.
7250     // This transform is not safe in general because we are reducing the number
7251     // of rounding steps.
7252     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7253       if (N0.getOpcode() == ISD::FMUL) {
7254         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7255         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7256
7257         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7258         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7259           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7260                                        SDValue(CFP01, 0),
7261                                        DAG.getConstantFP(1.0, VT));
7262           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7263         }
7264
7265         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7266         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7267             N1.getOperand(0) == N1.getOperand(1) &&
7268             N0.getOperand(0) == N1.getOperand(0)) {
7269           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7270                                        SDValue(CFP01, 0),
7271                                        DAG.getConstantFP(2.0, VT));
7272           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7273                              N0.getOperand(0), NewCFP);
7274         }
7275       }
7276
7277       if (N1.getOpcode() == ISD::FMUL) {
7278         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7279         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7280
7281         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7282         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7283           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7284                                        SDValue(CFP11, 0),
7285                                        DAG.getConstantFP(1.0, VT));
7286           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7287         }
7288
7289         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7290         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7291             N0.getOperand(0) == N0.getOperand(1) &&
7292             N1.getOperand(0) == N0.getOperand(0)) {
7293           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7294                                        SDValue(CFP11, 0),
7295                                        DAG.getConstantFP(2.0, VT));
7296           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7297         }
7298       }
7299
7300       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7301         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7302         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7303         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7304             (N0.getOperand(0) == N1))
7305           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7306                              N1, DAG.getConstantFP(3.0, VT));
7307       }
7308
7309       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7310         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7311         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7312         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7313             N1.getOperand(0) == N0)
7314           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7315                              N0, DAG.getConstantFP(3.0, VT));
7316       }
7317
7318       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7319       if (AllowNewConst &&
7320           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7321           N0.getOperand(0) == N0.getOperand(1) &&
7322           N1.getOperand(0) == N1.getOperand(1) &&
7323           N0.getOperand(0) == N1.getOperand(0))
7324         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7325                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7326     }
7327   } // enable-unsafe-fp-math
7328
7329   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7330     // Assume if there is an fmad instruction that it should be aggressively
7331     // used.
7332     if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7333       return Fused;
7334   }
7335
7336   // FADD -> FMA combines:
7337   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7338       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7339       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7340
7341     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7342       // Don't form FMA if we are preferring FMAD.
7343       if (SDValue Fused
7344           = performFaddFmulCombines(ISD::FMA,
7345                                     TLI.enableAggressiveFMAFusion(VT),
7346                                     N, TLI, DAG)) {
7347         return Fused;
7348       }
7349     }
7350
7351     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7352     // to combine into FMA, arrange such nodes accordingly.
7353     if (TLI.isFPExtFree(VT)) {
7354
7355       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7356       if (N0.getOpcode() == ISD::FP_EXTEND) {
7357         SDValue N00 = N0.getOperand(0);
7358         if (N00.getOpcode() == ISD::FMUL)
7359           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7360                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7361                                          N00.getOperand(0)),
7362                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7363                                          N00.getOperand(1)), N1);
7364       }
7365
7366       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7367       // Note: Commutes FADD operands.
7368       if (N1.getOpcode() == ISD::FP_EXTEND) {
7369         SDValue N10 = N1.getOperand(0);
7370         if (N10.getOpcode() == ISD::FMUL)
7371           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7372                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7373                                          N10.getOperand(0)),
7374                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7375                                          N10.getOperand(1)), N0);
7376       }
7377     }
7378   }
7379
7380   return SDValue();
7381 }
7382
7383 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7384   SDValue N0 = N->getOperand(0);
7385   SDValue N1 = N->getOperand(1);
7386   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7387   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7388   EVT VT = N->getValueType(0);
7389   SDLoc dl(N);
7390   const TargetOptions &Options = DAG.getTarget().Options;
7391
7392   // fold vector ops
7393   if (VT.isVector()) {
7394     SDValue FoldedVOp = SimplifyVBinOp(N);
7395     if (FoldedVOp.getNode()) return FoldedVOp;
7396   }
7397
7398   // fold (fsub c1, c2) -> c1-c2
7399   if (N0CFP && N1CFP)
7400     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7401
7402   // fold (fsub A, (fneg B)) -> (fadd A, B)
7403   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7404     return DAG.getNode(ISD::FADD, dl, VT, N0,
7405                        GetNegatedExpression(N1, DAG, LegalOperations));
7406
7407   // If 'unsafe math' is enabled, fold lots of things.
7408   if (Options.UnsafeFPMath) {
7409     // (fsub A, 0) -> A
7410     if (N1CFP && N1CFP->getValueAPF().isZero())
7411       return N0;
7412
7413     // (fsub 0, B) -> -B
7414     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7415       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7416         return GetNegatedExpression(N1, DAG, LegalOperations);
7417       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7418         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7419     }
7420
7421     // (fsub x, x) -> 0.0
7422     if (N0 == N1)
7423       return DAG.getConstantFP(0.0f, VT);
7424
7425     // (fsub x, (fadd x, y)) -> (fneg y)
7426     // (fsub x, (fadd y, x)) -> (fneg y)
7427     if (N1.getOpcode() == ISD::FADD) {
7428       SDValue N10 = N1->getOperand(0);
7429       SDValue N11 = N1->getOperand(1);
7430
7431       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7432         return GetNegatedExpression(N11, DAG, LegalOperations);
7433
7434       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7435         return GetNegatedExpression(N10, DAG, LegalOperations);
7436     }
7437   }
7438
7439   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7440     // Assume if there is an fmad instruction that it should be aggressively
7441     // used.
7442     if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7443       return Fused;
7444   }
7445
7446   // FSUB -> FMA combines:
7447   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7448       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7449       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7450
7451     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7452       // Don't form FMA if we are preferring FMAD.
7453
7454       if (SDValue Fused
7455           = performFsubFmulCombines(ISD::FMA,
7456                                     TLI.enableAggressiveFMAFusion(VT),
7457                                     N, TLI, DAG)) {
7458         return Fused;
7459       }
7460     }
7461
7462     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7463     // to combine into FMA, arrange such nodes accordingly.
7464     if (TLI.isFPExtFree(VT)) {
7465       // fold (fsub (fpext (fmul x, y)), z)
7466       //   -> (fma (fpext x), (fpext y), (fneg z))
7467       if (N0.getOpcode() == ISD::FP_EXTEND) {
7468         SDValue N00 = N0.getOperand(0);
7469         if (N00.getOpcode() == ISD::FMUL)
7470           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7471                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7472                                          N00.getOperand(0)),
7473                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7474                                          N00.getOperand(1)),
7475                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7476       }
7477
7478       // fold (fsub x, (fpext (fmul y, z)))
7479       //   -> (fma (fneg (fpext y)), (fpext z), x)
7480       // Note: Commutes FSUB operands.
7481       if (N1.getOpcode() == ISD::FP_EXTEND) {
7482         SDValue N10 = N1.getOperand(0);
7483         if (N10.getOpcode() == ISD::FMUL)
7484           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7485                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7486                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7487                                                      VT, N10.getOperand(0))),
7488                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7489                                          N10.getOperand(1)),
7490                              N0);
7491       }
7492
7493       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7494       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7495       if (N0.getOpcode() == ISD::FP_EXTEND) {
7496         SDValue N00 = N0.getOperand(0);
7497         if (N00.getOpcode() == ISD::FNEG) {
7498           SDValue N000 = N00.getOperand(0);
7499           if (N000.getOpcode() == ISD::FMUL) {
7500             return DAG.getNode(ISD::FMA, dl, VT,
7501                                DAG.getNode(ISD::FNEG, dl, VT,
7502                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7503                                                        VT, N000.getOperand(0))),
7504                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7505                                            N000.getOperand(1)),
7506                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7507           }
7508         }
7509       }
7510
7511       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7512       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7513       if (N0.getOpcode() == ISD::FNEG) {
7514         SDValue N00 = N0.getOperand(0);
7515         if (N00.getOpcode() == ISD::FP_EXTEND) {
7516           SDValue N000 = N00.getOperand(0);
7517           if (N000.getOpcode() == ISD::FMUL) {
7518             return DAG.getNode(ISD::FMA, dl, VT,
7519                                DAG.getNode(ISD::FNEG, dl, VT,
7520                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7521                                            VT, N000.getOperand(0))),
7522                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7523                                            N000.getOperand(1)),
7524                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7525           }
7526         }
7527       }
7528     }
7529   }
7530
7531   return SDValue();
7532 }
7533
7534 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7535   SDValue N0 = N->getOperand(0);
7536   SDValue N1 = N->getOperand(1);
7537   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7538   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7539   EVT VT = N->getValueType(0);
7540   const TargetOptions &Options = DAG.getTarget().Options;
7541
7542   // fold vector ops
7543   if (VT.isVector()) {
7544     // This just handles C1 * C2 for vectors. Other vector folds are below.
7545     SDValue FoldedVOp = SimplifyVBinOp(N);
7546     if (FoldedVOp.getNode())
7547       return FoldedVOp;
7548     // Canonicalize vector constant to RHS.
7549     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7550         N1.getOpcode() != ISD::BUILD_VECTOR)
7551       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7552         if (BV0->isConstant())
7553           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7554   }
7555
7556   // fold (fmul c1, c2) -> c1*c2
7557   if (N0CFP && N1CFP)
7558     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7559
7560   // canonicalize constant to RHS
7561   if (N0CFP && !N1CFP)
7562     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7563
7564   // fold (fmul A, 1.0) -> A
7565   if (N1CFP && N1CFP->isExactlyValue(1.0))
7566     return N0;
7567
7568   if (Options.UnsafeFPMath) {
7569     // fold (fmul A, 0) -> 0
7570     if (N1CFP && N1CFP->getValueAPF().isZero())
7571       return N1;
7572
7573     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7574     if (N0.getOpcode() == ISD::FMUL) {
7575       // Fold scalars or any vector constants (not just splats).
7576       // This fold is done in general by InstCombine, but extra fmul insts
7577       // may have been generated during lowering.
7578       SDValue N00 = N0.getOperand(0);
7579       SDValue N01 = N0.getOperand(1);
7580       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7581       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7582       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7583       
7584       // Check 1: Make sure that the first operand of the inner multiply is NOT
7585       // a constant. Otherwise, we may induce infinite looping.
7586       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7587         // Check 2: Make sure that the second operand of the inner multiply and
7588         // the second operand of the outer multiply are constants.
7589         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7590             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7591           SDLoc SL(N);
7592           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7593           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7594         }
7595       }
7596     }
7597
7598     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7599     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7600     // during an early run of DAGCombiner can prevent folding with fmuls
7601     // inserted during lowering.
7602     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7603       SDLoc SL(N);
7604       const SDValue Two = DAG.getConstantFP(2.0, VT);
7605       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7606       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7607     }
7608   }
7609
7610   // fold (fmul X, 2.0) -> (fadd X, X)
7611   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7612     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7613
7614   // fold (fmul X, -1.0) -> (fneg X)
7615   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7616     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7617       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7618
7619   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7620   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7621     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7622       // Both can be negated for free, check to see if at least one is cheaper
7623       // negated.
7624       if (LHSNeg == 2 || RHSNeg == 2)
7625         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7626                            GetNegatedExpression(N0, DAG, LegalOperations),
7627                            GetNegatedExpression(N1, DAG, LegalOperations));
7628     }
7629   }
7630
7631   return SDValue();
7632 }
7633
7634 SDValue DAGCombiner::visitFMA(SDNode *N) {
7635   SDValue N0 = N->getOperand(0);
7636   SDValue N1 = N->getOperand(1);
7637   SDValue N2 = N->getOperand(2);
7638   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7639   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7640   EVT VT = N->getValueType(0);
7641   SDLoc dl(N);
7642   const TargetOptions &Options = DAG.getTarget().Options;
7643
7644   // Constant fold FMA.
7645   if (isa<ConstantFPSDNode>(N0) &&
7646       isa<ConstantFPSDNode>(N1) &&
7647       isa<ConstantFPSDNode>(N2)) {
7648     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7649   }
7650
7651   if (Options.UnsafeFPMath) {
7652     if (N0CFP && N0CFP->isZero())
7653       return N2;
7654     if (N1CFP && N1CFP->isZero())
7655       return N2;
7656   }
7657   if (N0CFP && N0CFP->isExactlyValue(1.0))
7658     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7659   if (N1CFP && N1CFP->isExactlyValue(1.0))
7660     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7661
7662   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7663   if (N0CFP && !N1CFP)
7664     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7665
7666   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7667   if (Options.UnsafeFPMath && N1CFP &&
7668       N2.getOpcode() == ISD::FMUL &&
7669       N0 == N2.getOperand(0) &&
7670       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7671     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7672                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7673   }
7674
7675
7676   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7677   if (Options.UnsafeFPMath &&
7678       N0.getOpcode() == ISD::FMUL && N1CFP &&
7679       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7680     return DAG.getNode(ISD::FMA, dl, VT,
7681                        N0.getOperand(0),
7682                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7683                        N2);
7684   }
7685
7686   // (fma x, 1, y) -> (fadd x, y)
7687   // (fma x, -1, y) -> (fadd (fneg x), y)
7688   if (N1CFP) {
7689     if (N1CFP->isExactlyValue(1.0))
7690       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7691
7692     if (N1CFP->isExactlyValue(-1.0) &&
7693         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7694       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7695       AddToWorklist(RHSNeg.getNode());
7696       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7697     }
7698   }
7699
7700   // (fma x, c, x) -> (fmul x, (c+1))
7701   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7702     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7703                        DAG.getNode(ISD::FADD, dl, VT,
7704                                    N1, DAG.getConstantFP(1.0, VT)));
7705
7706   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7707   if (Options.UnsafeFPMath && N1CFP &&
7708       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7709     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7710                        DAG.getNode(ISD::FADD, dl, VT,
7711                                    N1, DAG.getConstantFP(-1.0, VT)));
7712
7713
7714   return SDValue();
7715 }
7716
7717 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7718   SDValue N0 = N->getOperand(0);
7719   SDValue N1 = N->getOperand(1);
7720   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7721   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7722   EVT VT = N->getValueType(0);
7723   SDLoc DL(N);
7724   const TargetOptions &Options = DAG.getTarget().Options;
7725
7726   // fold vector ops
7727   if (VT.isVector()) {
7728     SDValue FoldedVOp = SimplifyVBinOp(N);
7729     if (FoldedVOp.getNode()) return FoldedVOp;
7730   }
7731
7732   // fold (fdiv c1, c2) -> c1/c2
7733   if (N0CFP && N1CFP)
7734     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7735
7736   if (Options.UnsafeFPMath) {
7737     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7738     if (N1CFP) {
7739       // Compute the reciprocal 1.0 / c2.
7740       APFloat N1APF = N1CFP->getValueAPF();
7741       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7742       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7743       // Only do the transform if the reciprocal is a legal fp immediate that
7744       // isn't too nasty (eg NaN, denormal, ...).
7745       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7746           (!LegalOperations ||
7747            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7748            // backend)... we should handle this gracefully after Legalize.
7749            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7750            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7751            TLI.isFPImmLegal(Recip, VT)))
7752         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7753                            DAG.getConstantFP(Recip, VT));
7754     }
7755
7756     // If this FDIV is part of a reciprocal square root, it may be folded
7757     // into a target-specific square root estimate instruction.
7758     if (N1.getOpcode() == ISD::FSQRT) {
7759       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7760         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7761       }
7762     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7763                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7764       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7765         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7766         AddToWorklist(RV.getNode());
7767         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7768       }
7769     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7770                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7771       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7772         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7773         AddToWorklist(RV.getNode());
7774         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7775       }
7776     } else if (N1.getOpcode() == ISD::FMUL) {
7777       // Look through an FMUL. Even though this won't remove the FDIV directly,
7778       // it's still worthwhile to get rid of the FSQRT if possible.
7779       SDValue SqrtOp;
7780       SDValue OtherOp;
7781       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7782         SqrtOp = N1.getOperand(0);
7783         OtherOp = N1.getOperand(1);
7784       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7785         SqrtOp = N1.getOperand(1);
7786         OtherOp = N1.getOperand(0);
7787       }
7788       if (SqrtOp.getNode()) {
7789         // We found a FSQRT, so try to make this fold:
7790         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7791         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7792           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7793           AddToWorklist(RV.getNode());
7794           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7795         }
7796       }
7797     }
7798
7799     // Fold into a reciprocal estimate and multiply instead of a real divide.
7800     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7801       AddToWorklist(RV.getNode());
7802       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7803     }
7804   }
7805
7806   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7807   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7808     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7809       // Both can be negated for free, check to see if at least one is cheaper
7810       // negated.
7811       if (LHSNeg == 2 || RHSNeg == 2)
7812         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7813                            GetNegatedExpression(N0, DAG, LegalOperations),
7814                            GetNegatedExpression(N1, DAG, LegalOperations));
7815     }
7816   }
7817
7818   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7819   // reciprocal.
7820   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7821   // Notice that this is not always beneficial. One reason is different target
7822   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7823   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7824   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7825   if (Options.UnsafeFPMath) {
7826     // Skip if current node is a reciprocal.
7827     if (N0CFP && N0CFP->isExactlyValue(1.0))
7828       return SDValue();
7829
7830     SmallVector<SDNode *, 4> Users;
7831     // Find all FDIV users of the same divisor.
7832     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7833                               UE = N1.getNode()->use_end();
7834          UI != UE; ++UI) {
7835       SDNode *User = UI.getUse().getUser();
7836       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7837         Users.push_back(User);
7838     }
7839
7840     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7841       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7842       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7843
7844       // Dividend / Divisor -> Dividend * Reciprocal
7845       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7846         if ((*I)->getOperand(0) != FPOne) {
7847           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7848                                         (*I)->getOperand(0), Reciprocal);
7849           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7850         }
7851       }
7852       return SDValue();
7853     }
7854   }
7855
7856   return SDValue();
7857 }
7858
7859 SDValue DAGCombiner::visitFREM(SDNode *N) {
7860   SDValue N0 = N->getOperand(0);
7861   SDValue N1 = N->getOperand(1);
7862   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7863   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7864   EVT VT = N->getValueType(0);
7865
7866   // fold (frem c1, c2) -> fmod(c1,c2)
7867   if (N0CFP && N1CFP)
7868     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7869
7870   return SDValue();
7871 }
7872
7873 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7874   if (DAG.getTarget().Options.UnsafeFPMath &&
7875       !TLI.isFsqrtCheap()) {
7876     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7877     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7878       EVT VT = RV.getValueType();
7879       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7880       AddToWorklist(RV.getNode());
7881
7882       // Unfortunately, RV is now NaN if the input was exactly 0.
7883       // Select out this case and force the answer to 0.
7884       SDValue Zero = DAG.getConstantFP(0.0, VT);
7885       SDValue ZeroCmp =
7886         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7887                      N->getOperand(0), Zero, ISD::SETEQ);
7888       AddToWorklist(ZeroCmp.getNode());
7889       AddToWorklist(RV.getNode());
7890
7891       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7892                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7893       return RV;
7894     }
7895   }
7896   return SDValue();
7897 }
7898
7899 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7900   SDValue N0 = N->getOperand(0);
7901   SDValue N1 = N->getOperand(1);
7902   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7903   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7904   EVT VT = N->getValueType(0);
7905
7906   if (N0CFP && N1CFP)  // Constant fold
7907     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7908
7909   if (N1CFP) {
7910     const APFloat& V = N1CFP->getValueAPF();
7911     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7912     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7913     if (!V.isNegative()) {
7914       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7915         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7916     } else {
7917       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7918         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7919                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7920     }
7921   }
7922
7923   // copysign(fabs(x), y) -> copysign(x, y)
7924   // copysign(fneg(x), y) -> copysign(x, y)
7925   // copysign(copysign(x,z), y) -> copysign(x, y)
7926   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7927       N0.getOpcode() == ISD::FCOPYSIGN)
7928     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7929                        N0.getOperand(0), N1);
7930
7931   // copysign(x, abs(y)) -> abs(x)
7932   if (N1.getOpcode() == ISD::FABS)
7933     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7934
7935   // copysign(x, copysign(y,z)) -> copysign(x, z)
7936   if (N1.getOpcode() == ISD::FCOPYSIGN)
7937     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7938                        N0, N1.getOperand(1));
7939
7940   // copysign(x, fp_extend(y)) -> copysign(x, y)
7941   // copysign(x, fp_round(y)) -> copysign(x, y)
7942   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7943     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7944                        N0, N1.getOperand(0));
7945
7946   return SDValue();
7947 }
7948
7949 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7950   SDValue N0 = N->getOperand(0);
7951   EVT VT = N->getValueType(0);
7952   EVT OpVT = N0.getValueType();
7953
7954   // fold (sint_to_fp c1) -> c1fp
7955   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7956   if (N0C &&
7957       // ...but only if the target supports immediate floating-point values
7958       (!LegalOperations ||
7959        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7960     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7961
7962   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7963   // but UINT_TO_FP is legal on this target, try to convert.
7964   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7965       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7966     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7967     if (DAG.SignBitIsZero(N0))
7968       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7969   }
7970
7971   // The next optimizations are desirable only if SELECT_CC can be lowered.
7972   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7973     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7974     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7975         !VT.isVector() &&
7976         (!LegalOperations ||
7977          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7978       SDValue Ops[] =
7979         { N0.getOperand(0), N0.getOperand(1),
7980           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7981           N0.getOperand(2) };
7982       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7983     }
7984
7985     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7986     //      (select_cc x, y, 1.0, 0.0,, cc)
7987     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7988         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7989         (!LegalOperations ||
7990          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7991       SDValue Ops[] =
7992         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7993           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7994           N0.getOperand(0).getOperand(2) };
7995       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7996     }
7997   }
7998
7999   return SDValue();
8000 }
8001
8002 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8003   SDValue N0 = N->getOperand(0);
8004   EVT VT = N->getValueType(0);
8005   EVT OpVT = N0.getValueType();
8006
8007   // fold (uint_to_fp c1) -> c1fp
8008   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
8009   if (N0C &&
8010       // ...but only if the target supports immediate floating-point values
8011       (!LegalOperations ||
8012        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8013     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8014
8015   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8016   // but SINT_TO_FP is legal on this target, try to convert.
8017   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8018       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8019     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8020     if (DAG.SignBitIsZero(N0))
8021       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8022   }
8023
8024   // The next optimizations are desirable only if SELECT_CC can be lowered.
8025   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8026     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8027
8028     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8029         (!LegalOperations ||
8030          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8031       SDValue Ops[] =
8032         { N0.getOperand(0), N0.getOperand(1),
8033           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
8034           N0.getOperand(2) };
8035       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8036     }
8037   }
8038
8039   return SDValue();
8040 }
8041
8042 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8043 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8044   SDValue N0 = N->getOperand(0);
8045   EVT VT = N->getValueType(0);
8046
8047   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8048     return SDValue();
8049
8050   SDValue Src = N0.getOperand(0);
8051   EVT SrcVT = Src.getValueType();
8052   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8053   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8054
8055   // We can safely assume the conversion won't overflow the output range,
8056   // because (for example) (uint8_t)18293.f is undefined behavior.
8057
8058   // Since we can assume the conversion won't overflow, our decision as to
8059   // whether the input will fit in the float should depend on the minimum
8060   // of the input range and output range.
8061
8062   // This means this is also safe for a signed input and unsigned output, since
8063   // a negative input would lead to undefined behavior.
8064   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8065   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8066   unsigned ActualSize = std::min(InputSize, OutputSize);
8067   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8068
8069   // We can only fold away the float conversion if the input range can be
8070   // represented exactly in the float range.
8071   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8072     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8073       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8074                                                        : ISD::ZERO_EXTEND;
8075       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8076     }
8077     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8078       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8079     if (SrcVT == VT)
8080       return Src;
8081     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8082   }
8083   return SDValue();
8084 }
8085
8086 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8087   SDValue N0 = N->getOperand(0);
8088   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8089   EVT VT = N->getValueType(0);
8090
8091   // fold (fp_to_sint c1fp) -> c1
8092   if (N0CFP)
8093     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8094
8095   return FoldIntToFPToInt(N, DAG);
8096 }
8097
8098 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8099   SDValue N0 = N->getOperand(0);
8100   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8101   EVT VT = N->getValueType(0);
8102
8103   // fold (fp_to_uint c1fp) -> c1
8104   if (N0CFP)
8105     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8106
8107   return FoldIntToFPToInt(N, DAG);
8108 }
8109
8110 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8111   SDValue N0 = N->getOperand(0);
8112   SDValue N1 = N->getOperand(1);
8113   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8114   EVT VT = N->getValueType(0);
8115
8116   // fold (fp_round c1fp) -> c1fp
8117   if (N0CFP)
8118     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8119
8120   // fold (fp_round (fp_extend x)) -> x
8121   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8122     return N0.getOperand(0);
8123
8124   // fold (fp_round (fp_round x)) -> (fp_round x)
8125   if (N0.getOpcode() == ISD::FP_ROUND) {
8126     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8127     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8128     // If the first fp_round isn't a value preserving truncation, it might
8129     // introduce a tie in the second fp_round, that wouldn't occur in the
8130     // single-step fp_round we want to fold to.
8131     // In other words, double rounding isn't the same as rounding.
8132     // Also, this is a value preserving truncation iff both fp_round's are.
8133     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8134       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8135                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8136   }
8137
8138   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8139   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8140     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8141                               N0.getOperand(0), N1);
8142     AddToWorklist(Tmp.getNode());
8143     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8144                        Tmp, N0.getOperand(1));
8145   }
8146
8147   return SDValue();
8148 }
8149
8150 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8151   SDValue N0 = N->getOperand(0);
8152   EVT VT = N->getValueType(0);
8153   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8154   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8155
8156   // fold (fp_round_inreg c1fp) -> c1fp
8157   if (N0CFP && isTypeLegal(EVT)) {
8158     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8159     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8160   }
8161
8162   return SDValue();
8163 }
8164
8165 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8166   SDValue N0 = N->getOperand(0);
8167   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8168   EVT VT = N->getValueType(0);
8169
8170   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8171   if (N->hasOneUse() &&
8172       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8173     return SDValue();
8174
8175   // fold (fp_extend c1fp) -> c1fp
8176   if (N0CFP)
8177     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8178
8179   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8180   // value of X.
8181   if (N0.getOpcode() == ISD::FP_ROUND
8182       && N0.getNode()->getConstantOperandVal(1) == 1) {
8183     SDValue In = N0.getOperand(0);
8184     if (In.getValueType() == VT) return In;
8185     if (VT.bitsLT(In.getValueType()))
8186       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8187                          In, N0.getOperand(1));
8188     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8189   }
8190
8191   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8192   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8193        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8194     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8195     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8196                                      LN0->getChain(),
8197                                      LN0->getBasePtr(), N0.getValueType(),
8198                                      LN0->getMemOperand());
8199     CombineTo(N, ExtLoad);
8200     CombineTo(N0.getNode(),
8201               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8202                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8203               ExtLoad.getValue(1));
8204     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8205   }
8206
8207   return SDValue();
8208 }
8209
8210 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8211   SDValue N0 = N->getOperand(0);
8212   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8213   EVT VT = N->getValueType(0);
8214
8215   // fold (fceil c1) -> fceil(c1)
8216   if (N0CFP)
8217     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8218
8219   return SDValue();
8220 }
8221
8222 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8223   SDValue N0 = N->getOperand(0);
8224   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8225   EVT VT = N->getValueType(0);
8226
8227   // fold (ftrunc c1) -> ftrunc(c1)
8228   if (N0CFP)
8229     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8230
8231   return SDValue();
8232 }
8233
8234 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8235   SDValue N0 = N->getOperand(0);
8236   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8237   EVT VT = N->getValueType(0);
8238
8239   // fold (ffloor c1) -> ffloor(c1)
8240   if (N0CFP)
8241     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8242
8243   return SDValue();
8244 }
8245
8246 // FIXME: FNEG and FABS have a lot in common; refactor.
8247 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8248   SDValue N0 = N->getOperand(0);
8249   EVT VT = N->getValueType(0);
8250
8251   if (VT.isVector()) {
8252     SDValue FoldedVOp = SimplifyVUnaryOp(N);
8253     if (FoldedVOp.getNode()) return FoldedVOp;
8254   }
8255
8256   // Constant fold FNEG.
8257   if (isa<ConstantFPSDNode>(N0))
8258     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8259
8260   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8261                          &DAG.getTarget().Options))
8262     return GetNegatedExpression(N0, DAG, LegalOperations);
8263
8264   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8265   // constant pool values.
8266   if (!TLI.isFNegFree(VT) &&
8267       N0.getOpcode() == ISD::BITCAST &&
8268       N0.getNode()->hasOneUse()) {
8269     SDValue Int = N0.getOperand(0);
8270     EVT IntVT = Int.getValueType();
8271     if (IntVT.isInteger() && !IntVT.isVector()) {
8272       APInt SignMask;
8273       if (N0.getValueType().isVector()) {
8274         // For a vector, get a mask such as 0x80... per scalar element
8275         // and splat it.
8276         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8277         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8278       } else {
8279         // For a scalar, just generate 0x80...
8280         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8281       }
8282       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8283                         DAG.getConstant(SignMask, IntVT));
8284       AddToWorklist(Int.getNode());
8285       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8286     }
8287   }
8288
8289   // (fneg (fmul c, x)) -> (fmul -c, x)
8290   if (N0.getOpcode() == ISD::FMUL) {
8291     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8292     if (CFP1) {
8293       APFloat CVal = CFP1->getValueAPF();
8294       CVal.changeSign();
8295       if (Level >= AfterLegalizeDAG &&
8296           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8297            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8298         return DAG.getNode(
8299             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8300             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8301     }
8302   }
8303
8304   return SDValue();
8305 }
8306
8307 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8308   SDValue N0 = N->getOperand(0);
8309   SDValue N1 = N->getOperand(1);
8310   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8311   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8312
8313   if (N0CFP && N1CFP) {
8314     const APFloat &C0 = N0CFP->getValueAPF();
8315     const APFloat &C1 = N1CFP->getValueAPF();
8316     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8317   }
8318
8319   if (N0CFP) {
8320     EVT VT = N->getValueType(0);
8321     // Canonicalize to constant on RHS.
8322     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8323   }
8324
8325   return SDValue();
8326 }
8327
8328 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8329   SDValue N0 = N->getOperand(0);
8330   SDValue N1 = N->getOperand(1);
8331   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8332   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8333
8334   if (N0CFP && N1CFP) {
8335     const APFloat &C0 = N0CFP->getValueAPF();
8336     const APFloat &C1 = N1CFP->getValueAPF();
8337     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8338   }
8339
8340   if (N0CFP) {
8341     EVT VT = N->getValueType(0);
8342     // Canonicalize to constant on RHS.
8343     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8344   }
8345
8346   return SDValue();
8347 }
8348
8349 SDValue DAGCombiner::visitFABS(SDNode *N) {
8350   SDValue N0 = N->getOperand(0);
8351   EVT VT = N->getValueType(0);
8352
8353   if (VT.isVector()) {
8354     SDValue FoldedVOp = SimplifyVUnaryOp(N);
8355     if (FoldedVOp.getNode()) return FoldedVOp;
8356   }
8357
8358   // fold (fabs c1) -> fabs(c1)
8359   if (isa<ConstantFPSDNode>(N0))
8360     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8361
8362   // fold (fabs (fabs x)) -> (fabs x)
8363   if (N0.getOpcode() == ISD::FABS)
8364     return N->getOperand(0);
8365
8366   // fold (fabs (fneg x)) -> (fabs x)
8367   // fold (fabs (fcopysign x, y)) -> (fabs x)
8368   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8369     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8370
8371   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8372   // constant pool values.
8373   if (!TLI.isFAbsFree(VT) &&
8374       N0.getOpcode() == ISD::BITCAST &&
8375       N0.getNode()->hasOneUse()) {
8376     SDValue Int = N0.getOperand(0);
8377     EVT IntVT = Int.getValueType();
8378     if (IntVT.isInteger() && !IntVT.isVector()) {
8379       APInt SignMask;
8380       if (N0.getValueType().isVector()) {
8381         // For a vector, get a mask such as 0x7f... per scalar element
8382         // and splat it.
8383         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8384         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8385       } else {
8386         // For a scalar, just generate 0x7f...
8387         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8388       }
8389       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8390                         DAG.getConstant(SignMask, IntVT));
8391       AddToWorklist(Int.getNode());
8392       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8393     }
8394   }
8395
8396   return SDValue();
8397 }
8398
8399 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8400   SDValue Chain = N->getOperand(0);
8401   SDValue N1 = N->getOperand(1);
8402   SDValue N2 = N->getOperand(2);
8403
8404   // If N is a constant we could fold this into a fallthrough or unconditional
8405   // branch. However that doesn't happen very often in normal code, because
8406   // Instcombine/SimplifyCFG should have handled the available opportunities.
8407   // If we did this folding here, it would be necessary to update the
8408   // MachineBasicBlock CFG, which is awkward.
8409
8410   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8411   // on the target.
8412   if (N1.getOpcode() == ISD::SETCC &&
8413       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8414                                    N1.getOperand(0).getValueType())) {
8415     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8416                        Chain, N1.getOperand(2),
8417                        N1.getOperand(0), N1.getOperand(1), N2);
8418   }
8419
8420   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8421       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8422        (N1.getOperand(0).hasOneUse() &&
8423         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8424     SDNode *Trunc = nullptr;
8425     if (N1.getOpcode() == ISD::TRUNCATE) {
8426       // Look pass the truncate.
8427       Trunc = N1.getNode();
8428       N1 = N1.getOperand(0);
8429     }
8430
8431     // Match this pattern so that we can generate simpler code:
8432     //
8433     //   %a = ...
8434     //   %b = and i32 %a, 2
8435     //   %c = srl i32 %b, 1
8436     //   brcond i32 %c ...
8437     //
8438     // into
8439     //
8440     //   %a = ...
8441     //   %b = and i32 %a, 2
8442     //   %c = setcc eq %b, 0
8443     //   brcond %c ...
8444     //
8445     // This applies only when the AND constant value has one bit set and the
8446     // SRL constant is equal to the log2 of the AND constant. The back-end is
8447     // smart enough to convert the result into a TEST/JMP sequence.
8448     SDValue Op0 = N1.getOperand(0);
8449     SDValue Op1 = N1.getOperand(1);
8450
8451     if (Op0.getOpcode() == ISD::AND &&
8452         Op1.getOpcode() == ISD::Constant) {
8453       SDValue AndOp1 = Op0.getOperand(1);
8454
8455       if (AndOp1.getOpcode() == ISD::Constant) {
8456         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8457
8458         if (AndConst.isPowerOf2() &&
8459             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8460           SDValue SetCC =
8461             DAG.getSetCC(SDLoc(N),
8462                          getSetCCResultType(Op0.getValueType()),
8463                          Op0, DAG.getConstant(0, Op0.getValueType()),
8464                          ISD::SETNE);
8465
8466           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8467                                           MVT::Other, Chain, SetCC, N2);
8468           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8469           // will convert it back to (X & C1) >> C2.
8470           CombineTo(N, NewBRCond, false);
8471           // Truncate is dead.
8472           if (Trunc)
8473             deleteAndRecombine(Trunc);
8474           // Replace the uses of SRL with SETCC
8475           WorklistRemover DeadNodes(*this);
8476           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8477           deleteAndRecombine(N1.getNode());
8478           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8479         }
8480       }
8481     }
8482
8483     if (Trunc)
8484       // Restore N1 if the above transformation doesn't match.
8485       N1 = N->getOperand(1);
8486   }
8487
8488   // Transform br(xor(x, y)) -> br(x != y)
8489   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8490   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8491     SDNode *TheXor = N1.getNode();
8492     SDValue Op0 = TheXor->getOperand(0);
8493     SDValue Op1 = TheXor->getOperand(1);
8494     if (Op0.getOpcode() == Op1.getOpcode()) {
8495       // Avoid missing important xor optimizations.
8496       SDValue Tmp = visitXOR(TheXor);
8497       if (Tmp.getNode()) {
8498         if (Tmp.getNode() != TheXor) {
8499           DEBUG(dbgs() << "\nReplacing.8 ";
8500                 TheXor->dump(&DAG);
8501                 dbgs() << "\nWith: ";
8502                 Tmp.getNode()->dump(&DAG);
8503                 dbgs() << '\n');
8504           WorklistRemover DeadNodes(*this);
8505           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8506           deleteAndRecombine(TheXor);
8507           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8508                              MVT::Other, Chain, Tmp, N2);
8509         }
8510
8511         // visitXOR has changed XOR's operands or replaced the XOR completely,
8512         // bail out.
8513         return SDValue(N, 0);
8514       }
8515     }
8516
8517     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8518       bool Equal = false;
8519       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8520         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8521             Op0.getOpcode() == ISD::XOR) {
8522           TheXor = Op0.getNode();
8523           Equal = true;
8524         }
8525
8526       EVT SetCCVT = N1.getValueType();
8527       if (LegalTypes)
8528         SetCCVT = getSetCCResultType(SetCCVT);
8529       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8530                                    SetCCVT,
8531                                    Op0, Op1,
8532                                    Equal ? ISD::SETEQ : ISD::SETNE);
8533       // Replace the uses of XOR with SETCC
8534       WorklistRemover DeadNodes(*this);
8535       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8536       deleteAndRecombine(N1.getNode());
8537       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8538                          MVT::Other, Chain, SetCC, N2);
8539     }
8540   }
8541
8542   return SDValue();
8543 }
8544
8545 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8546 //
8547 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8548   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8549   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8550
8551   // If N is a constant we could fold this into a fallthrough or unconditional
8552   // branch. However that doesn't happen very often in normal code, because
8553   // Instcombine/SimplifyCFG should have handled the available opportunities.
8554   // If we did this folding here, it would be necessary to update the
8555   // MachineBasicBlock CFG, which is awkward.
8556
8557   // Use SimplifySetCC to simplify SETCC's.
8558   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8559                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8560                                false);
8561   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8562
8563   // fold to a simpler setcc
8564   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8565     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8566                        N->getOperand(0), Simp.getOperand(2),
8567                        Simp.getOperand(0), Simp.getOperand(1),
8568                        N->getOperand(4));
8569
8570   return SDValue();
8571 }
8572
8573 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8574 /// and that N may be folded in the load / store addressing mode.
8575 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8576                                     SelectionDAG &DAG,
8577                                     const TargetLowering &TLI) {
8578   EVT VT;
8579   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8580     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8581       return false;
8582     VT = Use->getValueType(0);
8583   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8584     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8585       return false;
8586     VT = ST->getValue().getValueType();
8587   } else
8588     return false;
8589
8590   TargetLowering::AddrMode AM;
8591   if (N->getOpcode() == ISD::ADD) {
8592     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8593     if (Offset)
8594       // [reg +/- imm]
8595       AM.BaseOffs = Offset->getSExtValue();
8596     else
8597       // [reg +/- reg]
8598       AM.Scale = 1;
8599   } else if (N->getOpcode() == ISD::SUB) {
8600     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8601     if (Offset)
8602       // [reg +/- imm]
8603       AM.BaseOffs = -Offset->getSExtValue();
8604     else
8605       // [reg +/- reg]
8606       AM.Scale = 1;
8607   } else
8608     return false;
8609
8610   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8611 }
8612
8613 /// Try turning a load/store into a pre-indexed load/store when the base
8614 /// pointer is an add or subtract and it has other uses besides the load/store.
8615 /// After the transformation, the new indexed load/store has effectively folded
8616 /// the add/subtract in and all of its other uses are redirected to the
8617 /// new load/store.
8618 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8619   if (Level < AfterLegalizeDAG)
8620     return false;
8621
8622   bool isLoad = true;
8623   SDValue Ptr;
8624   EVT VT;
8625   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8626     if (LD->isIndexed())
8627       return false;
8628     VT = LD->getMemoryVT();
8629     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8630         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8631       return false;
8632     Ptr = LD->getBasePtr();
8633   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8634     if (ST->isIndexed())
8635       return false;
8636     VT = ST->getMemoryVT();
8637     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8638         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8639       return false;
8640     Ptr = ST->getBasePtr();
8641     isLoad = false;
8642   } else {
8643     return false;
8644   }
8645
8646   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8647   // out.  There is no reason to make this a preinc/predec.
8648   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8649       Ptr.getNode()->hasOneUse())
8650     return false;
8651
8652   // Ask the target to do addressing mode selection.
8653   SDValue BasePtr;
8654   SDValue Offset;
8655   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8656   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8657     return false;
8658
8659   // Backends without true r+i pre-indexed forms may need to pass a
8660   // constant base with a variable offset so that constant coercion
8661   // will work with the patterns in canonical form.
8662   bool Swapped = false;
8663   if (isa<ConstantSDNode>(BasePtr)) {
8664     std::swap(BasePtr, Offset);
8665     Swapped = true;
8666   }
8667
8668   // Don't create a indexed load / store with zero offset.
8669   if (isa<ConstantSDNode>(Offset) &&
8670       cast<ConstantSDNode>(Offset)->isNullValue())
8671     return false;
8672
8673   // Try turning it into a pre-indexed load / store except when:
8674   // 1) The new base ptr is a frame index.
8675   // 2) If N is a store and the new base ptr is either the same as or is a
8676   //    predecessor of the value being stored.
8677   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8678   //    that would create a cycle.
8679   // 4) All uses are load / store ops that use it as old base ptr.
8680
8681   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8682   // (plus the implicit offset) to a register to preinc anyway.
8683   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8684     return false;
8685
8686   // Check #2.
8687   if (!isLoad) {
8688     SDValue Val = cast<StoreSDNode>(N)->getValue();
8689     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8690       return false;
8691   }
8692
8693   // If the offset is a constant, there may be other adds of constants that
8694   // can be folded with this one. We should do this to avoid having to keep
8695   // a copy of the original base pointer.
8696   SmallVector<SDNode *, 16> OtherUses;
8697   if (isa<ConstantSDNode>(Offset))
8698     for (SDNode *Use : BasePtr.getNode()->uses()) {
8699       if (Use == Ptr.getNode())
8700         continue;
8701
8702       if (Use->isPredecessorOf(N))
8703         continue;
8704
8705       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8706         OtherUses.clear();
8707         break;
8708       }
8709
8710       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8711       if (Op1.getNode() == BasePtr.getNode())
8712         std::swap(Op0, Op1);
8713       assert(Op0.getNode() == BasePtr.getNode() &&
8714              "Use of ADD/SUB but not an operand");
8715
8716       if (!isa<ConstantSDNode>(Op1)) {
8717         OtherUses.clear();
8718         break;
8719       }
8720
8721       // FIXME: In some cases, we can be smarter about this.
8722       if (Op1.getValueType() != Offset.getValueType()) {
8723         OtherUses.clear();
8724         break;
8725       }
8726
8727       OtherUses.push_back(Use);
8728     }
8729
8730   if (Swapped)
8731     std::swap(BasePtr, Offset);
8732
8733   // Now check for #3 and #4.
8734   bool RealUse = false;
8735
8736   // Caches for hasPredecessorHelper
8737   SmallPtrSet<const SDNode *, 32> Visited;
8738   SmallVector<const SDNode *, 16> Worklist;
8739
8740   for (SDNode *Use : Ptr.getNode()->uses()) {
8741     if (Use == N)
8742       continue;
8743     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8744       return false;
8745
8746     // If Ptr may be folded in addressing mode of other use, then it's
8747     // not profitable to do this transformation.
8748     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8749       RealUse = true;
8750   }
8751
8752   if (!RealUse)
8753     return false;
8754
8755   SDValue Result;
8756   if (isLoad)
8757     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8758                                 BasePtr, Offset, AM);
8759   else
8760     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8761                                  BasePtr, Offset, AM);
8762   ++PreIndexedNodes;
8763   ++NodesCombined;
8764   DEBUG(dbgs() << "\nReplacing.4 ";
8765         N->dump(&DAG);
8766         dbgs() << "\nWith: ";
8767         Result.getNode()->dump(&DAG);
8768         dbgs() << '\n');
8769   WorklistRemover DeadNodes(*this);
8770   if (isLoad) {
8771     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8772     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8773   } else {
8774     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8775   }
8776
8777   // Finally, since the node is now dead, remove it from the graph.
8778   deleteAndRecombine(N);
8779
8780   if (Swapped)
8781     std::swap(BasePtr, Offset);
8782
8783   // Replace other uses of BasePtr that can be updated to use Ptr
8784   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8785     unsigned OffsetIdx = 1;
8786     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8787       OffsetIdx = 0;
8788     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8789            BasePtr.getNode() && "Expected BasePtr operand");
8790
8791     // We need to replace ptr0 in the following expression:
8792     //   x0 * offset0 + y0 * ptr0 = t0
8793     // knowing that
8794     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8795     //
8796     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8797     // indexed load/store and the expresion that needs to be re-written.
8798     //
8799     // Therefore, we have:
8800     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8801
8802     ConstantSDNode *CN =
8803       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8804     int X0, X1, Y0, Y1;
8805     APInt Offset0 = CN->getAPIntValue();
8806     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8807
8808     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8809     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8810     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8811     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8812
8813     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8814
8815     APInt CNV = Offset0;
8816     if (X0 < 0) CNV = -CNV;
8817     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8818     else CNV = CNV - Offset1;
8819
8820     // We can now generate the new expression.
8821     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8822     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8823
8824     SDValue NewUse = DAG.getNode(Opcode,
8825                                  SDLoc(OtherUses[i]),
8826                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8827     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8828     deleteAndRecombine(OtherUses[i]);
8829   }
8830
8831   // Replace the uses of Ptr with uses of the updated base value.
8832   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8833   deleteAndRecombine(Ptr.getNode());
8834
8835   return true;
8836 }
8837
8838 /// Try to combine a load/store with a add/sub of the base pointer node into a
8839 /// post-indexed load/store. The transformation folded the add/subtract into the
8840 /// new indexed load/store effectively and all of its uses are redirected to the
8841 /// new load/store.
8842 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8843   if (Level < AfterLegalizeDAG)
8844     return false;
8845
8846   bool isLoad = true;
8847   SDValue Ptr;
8848   EVT VT;
8849   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8850     if (LD->isIndexed())
8851       return false;
8852     VT = LD->getMemoryVT();
8853     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8854         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8855       return false;
8856     Ptr = LD->getBasePtr();
8857   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8858     if (ST->isIndexed())
8859       return false;
8860     VT = ST->getMemoryVT();
8861     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8862         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8863       return false;
8864     Ptr = ST->getBasePtr();
8865     isLoad = false;
8866   } else {
8867     return false;
8868   }
8869
8870   if (Ptr.getNode()->hasOneUse())
8871     return false;
8872
8873   for (SDNode *Op : Ptr.getNode()->uses()) {
8874     if (Op == N ||
8875         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8876       continue;
8877
8878     SDValue BasePtr;
8879     SDValue Offset;
8880     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8881     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8882       // Don't create a indexed load / store with zero offset.
8883       if (isa<ConstantSDNode>(Offset) &&
8884           cast<ConstantSDNode>(Offset)->isNullValue())
8885         continue;
8886
8887       // Try turning it into a post-indexed load / store except when
8888       // 1) All uses are load / store ops that use it as base ptr (and
8889       //    it may be folded as addressing mmode).
8890       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8891       //    nor a successor of N. Otherwise, if Op is folded that would
8892       //    create a cycle.
8893
8894       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8895         continue;
8896
8897       // Check for #1.
8898       bool TryNext = false;
8899       for (SDNode *Use : BasePtr.getNode()->uses()) {
8900         if (Use == Ptr.getNode())
8901           continue;
8902
8903         // If all the uses are load / store addresses, then don't do the
8904         // transformation.
8905         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8906           bool RealUse = false;
8907           for (SDNode *UseUse : Use->uses()) {
8908             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8909               RealUse = true;
8910           }
8911
8912           if (!RealUse) {
8913             TryNext = true;
8914             break;
8915           }
8916         }
8917       }
8918
8919       if (TryNext)
8920         continue;
8921
8922       // Check for #2
8923       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8924         SDValue Result = isLoad
8925           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8926                                BasePtr, Offset, AM)
8927           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8928                                 BasePtr, Offset, AM);
8929         ++PostIndexedNodes;
8930         ++NodesCombined;
8931         DEBUG(dbgs() << "\nReplacing.5 ";
8932               N->dump(&DAG);
8933               dbgs() << "\nWith: ";
8934               Result.getNode()->dump(&DAG);
8935               dbgs() << '\n');
8936         WorklistRemover DeadNodes(*this);
8937         if (isLoad) {
8938           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8939           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8940         } else {
8941           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8942         }
8943
8944         // Finally, since the node is now dead, remove it from the graph.
8945         deleteAndRecombine(N);
8946
8947         // Replace the uses of Use with uses of the updated base value.
8948         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8949                                       Result.getValue(isLoad ? 1 : 0));
8950         deleteAndRecombine(Op);
8951         return true;
8952       }
8953     }
8954   }
8955
8956   return false;
8957 }
8958
8959 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8960 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8961   ISD::MemIndexedMode AM = LD->getAddressingMode();
8962   assert(AM != ISD::UNINDEXED);
8963   SDValue BP = LD->getOperand(1);
8964   SDValue Inc = LD->getOperand(2);
8965
8966   // Some backends use TargetConstants for load offsets, but don't expect
8967   // TargetConstants in general ADD nodes. We can convert these constants into
8968   // regular Constants (if the constant is not opaque).
8969   assert((Inc.getOpcode() != ISD::TargetConstant ||
8970           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8971          "Cannot split out indexing using opaque target constants");
8972   if (Inc.getOpcode() == ISD::TargetConstant) {
8973     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8974     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8975                           ConstInc->getValueType(0));
8976   }
8977
8978   unsigned Opc =
8979       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8980   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8981 }
8982
8983 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8984   LoadSDNode *LD  = cast<LoadSDNode>(N);
8985   SDValue Chain = LD->getChain();
8986   SDValue Ptr   = LD->getBasePtr();
8987
8988   // If load is not volatile and there are no uses of the loaded value (and
8989   // the updated indexed value in case of indexed loads), change uses of the
8990   // chain value into uses of the chain input (i.e. delete the dead load).
8991   if (!LD->isVolatile()) {
8992     if (N->getValueType(1) == MVT::Other) {
8993       // Unindexed loads.
8994       if (!N->hasAnyUseOfValue(0)) {
8995         // It's not safe to use the two value CombineTo variant here. e.g.
8996         // v1, chain2 = load chain1, loc
8997         // v2, chain3 = load chain2, loc
8998         // v3         = add v2, c
8999         // Now we replace use of chain2 with chain1.  This makes the second load
9000         // isomorphic to the one we are deleting, and thus makes this load live.
9001         DEBUG(dbgs() << "\nReplacing.6 ";
9002               N->dump(&DAG);
9003               dbgs() << "\nWith chain: ";
9004               Chain.getNode()->dump(&DAG);
9005               dbgs() << "\n");
9006         WorklistRemover DeadNodes(*this);
9007         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9008
9009         if (N->use_empty())
9010           deleteAndRecombine(N);
9011
9012         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9013       }
9014     } else {
9015       // Indexed loads.
9016       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9017
9018       // If this load has an opaque TargetConstant offset, then we cannot split
9019       // the indexing into an add/sub directly (that TargetConstant may not be
9020       // valid for a different type of node, and we cannot convert an opaque
9021       // target constant into a regular constant).
9022       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9023                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9024
9025       if (!N->hasAnyUseOfValue(0) &&
9026           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9027         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9028         SDValue Index;
9029         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9030           Index = SplitIndexingFromLoad(LD);
9031           // Try to fold the base pointer arithmetic into subsequent loads and
9032           // stores.
9033           AddUsersToWorklist(N);
9034         } else
9035           Index = DAG.getUNDEF(N->getValueType(1));
9036         DEBUG(dbgs() << "\nReplacing.7 ";
9037               N->dump(&DAG);
9038               dbgs() << "\nWith: ";
9039               Undef.getNode()->dump(&DAG);
9040               dbgs() << " and 2 other values\n");
9041         WorklistRemover DeadNodes(*this);
9042         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9043         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9044         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9045         deleteAndRecombine(N);
9046         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9047       }
9048     }
9049   }
9050
9051   // If this load is directly stored, replace the load value with the stored
9052   // value.
9053   // TODO: Handle store large -> read small portion.
9054   // TODO: Handle TRUNCSTORE/LOADEXT
9055   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9056     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9057       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9058       if (PrevST->getBasePtr() == Ptr &&
9059           PrevST->getValue().getValueType() == N->getValueType(0))
9060       return CombineTo(N, Chain.getOperand(1), Chain);
9061     }
9062   }
9063
9064   // Try to infer better alignment information than the load already has.
9065   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9066     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9067       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9068         SDValue NewLoad =
9069                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9070                               LD->getValueType(0),
9071                               Chain, Ptr, LD->getPointerInfo(),
9072                               LD->getMemoryVT(),
9073                               LD->isVolatile(), LD->isNonTemporal(),
9074                               LD->isInvariant(), Align, LD->getAAInfo());
9075         if (NewLoad.getNode() != N)
9076           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9077       }
9078     }
9079   }
9080
9081   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9082                                                   : DAG.getSubtarget().useAA();
9083 #ifndef NDEBUG
9084   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9085       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9086     UseAA = false;
9087 #endif
9088   if (UseAA && LD->isUnindexed()) {
9089     // Walk up chain skipping non-aliasing memory nodes.
9090     SDValue BetterChain = FindBetterChain(N, Chain);
9091
9092     // If there is a better chain.
9093     if (Chain != BetterChain) {
9094       SDValue ReplLoad;
9095
9096       // Replace the chain to void dependency.
9097       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9098         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9099                                BetterChain, Ptr, LD->getMemOperand());
9100       } else {
9101         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9102                                   LD->getValueType(0),
9103                                   BetterChain, Ptr, LD->getMemoryVT(),
9104                                   LD->getMemOperand());
9105       }
9106
9107       // Create token factor to keep old chain connected.
9108       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9109                                   MVT::Other, Chain, ReplLoad.getValue(1));
9110
9111       // Make sure the new and old chains are cleaned up.
9112       AddToWorklist(Token.getNode());
9113
9114       // Replace uses with load result and token factor. Don't add users
9115       // to work list.
9116       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9117     }
9118   }
9119
9120   // Try transforming N to an indexed load.
9121   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9122     return SDValue(N, 0);
9123
9124   // Try to slice up N to more direct loads if the slices are mapped to
9125   // different register banks or pairing can take place.
9126   if (SliceUpLoad(N))
9127     return SDValue(N, 0);
9128
9129   return SDValue();
9130 }
9131
9132 namespace {
9133 /// \brief Helper structure used to slice a load in smaller loads.
9134 /// Basically a slice is obtained from the following sequence:
9135 /// Origin = load Ty1, Base
9136 /// Shift = srl Ty1 Origin, CstTy Amount
9137 /// Inst = trunc Shift to Ty2
9138 ///
9139 /// Then, it will be rewriten into:
9140 /// Slice = load SliceTy, Base + SliceOffset
9141 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9142 ///
9143 /// SliceTy is deduced from the number of bits that are actually used to
9144 /// build Inst.
9145 struct LoadedSlice {
9146   /// \brief Helper structure used to compute the cost of a slice.
9147   struct Cost {
9148     /// Are we optimizing for code size.
9149     bool ForCodeSize;
9150     /// Various cost.
9151     unsigned Loads;
9152     unsigned Truncates;
9153     unsigned CrossRegisterBanksCopies;
9154     unsigned ZExts;
9155     unsigned Shift;
9156
9157     Cost(bool ForCodeSize = false)
9158         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9159           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9160
9161     /// \brief Get the cost of one isolated slice.
9162     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9163         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9164           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9165       EVT TruncType = LS.Inst->getValueType(0);
9166       EVT LoadedType = LS.getLoadedType();
9167       if (TruncType != LoadedType &&
9168           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9169         ZExts = 1;
9170     }
9171
9172     /// \brief Account for slicing gain in the current cost.
9173     /// Slicing provide a few gains like removing a shift or a
9174     /// truncate. This method allows to grow the cost of the original
9175     /// load with the gain from this slice.
9176     void addSliceGain(const LoadedSlice &LS) {
9177       // Each slice saves a truncate.
9178       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9179       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9180                               LS.Inst->getOperand(0).getValueType()))
9181         ++Truncates;
9182       // If there is a shift amount, this slice gets rid of it.
9183       if (LS.Shift)
9184         ++Shift;
9185       // If this slice can merge a cross register bank copy, account for it.
9186       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9187         ++CrossRegisterBanksCopies;
9188     }
9189
9190     Cost &operator+=(const Cost &RHS) {
9191       Loads += RHS.Loads;
9192       Truncates += RHS.Truncates;
9193       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9194       ZExts += RHS.ZExts;
9195       Shift += RHS.Shift;
9196       return *this;
9197     }
9198
9199     bool operator==(const Cost &RHS) const {
9200       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9201              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9202              ZExts == RHS.ZExts && Shift == RHS.Shift;
9203     }
9204
9205     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9206
9207     bool operator<(const Cost &RHS) const {
9208       // Assume cross register banks copies are as expensive as loads.
9209       // FIXME: Do we want some more target hooks?
9210       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9211       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9212       // Unless we are optimizing for code size, consider the
9213       // expensive operation first.
9214       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9215         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9216       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9217              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9218     }
9219
9220     bool operator>(const Cost &RHS) const { return RHS < *this; }
9221
9222     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9223
9224     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9225   };
9226   // The last instruction that represent the slice. This should be a
9227   // truncate instruction.
9228   SDNode *Inst;
9229   // The original load instruction.
9230   LoadSDNode *Origin;
9231   // The right shift amount in bits from the original load.
9232   unsigned Shift;
9233   // The DAG from which Origin came from.
9234   // This is used to get some contextual information about legal types, etc.
9235   SelectionDAG *DAG;
9236
9237   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9238               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9239       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9240
9241   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9242   /// \return Result is \p BitWidth and has used bits set to 1 and
9243   ///         not used bits set to 0.
9244   APInt getUsedBits() const {
9245     // Reproduce the trunc(lshr) sequence:
9246     // - Start from the truncated value.
9247     // - Zero extend to the desired bit width.
9248     // - Shift left.
9249     assert(Origin && "No original load to compare against.");
9250     unsigned BitWidth = Origin->getValueSizeInBits(0);
9251     assert(Inst && "This slice is not bound to an instruction");
9252     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9253            "Extracted slice is bigger than the whole type!");
9254     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9255     UsedBits.setAllBits();
9256     UsedBits = UsedBits.zext(BitWidth);
9257     UsedBits <<= Shift;
9258     return UsedBits;
9259   }
9260
9261   /// \brief Get the size of the slice to be loaded in bytes.
9262   unsigned getLoadedSize() const {
9263     unsigned SliceSize = getUsedBits().countPopulation();
9264     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9265     return SliceSize / 8;
9266   }
9267
9268   /// \brief Get the type that will be loaded for this slice.
9269   /// Note: This may not be the final type for the slice.
9270   EVT getLoadedType() const {
9271     assert(DAG && "Missing context");
9272     LLVMContext &Ctxt = *DAG->getContext();
9273     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9274   }
9275
9276   /// \brief Get the alignment of the load used for this slice.
9277   unsigned getAlignment() const {
9278     unsigned Alignment = Origin->getAlignment();
9279     unsigned Offset = getOffsetFromBase();
9280     if (Offset != 0)
9281       Alignment = MinAlign(Alignment, Alignment + Offset);
9282     return Alignment;
9283   }
9284
9285   /// \brief Check if this slice can be rewritten with legal operations.
9286   bool isLegal() const {
9287     // An invalid slice is not legal.
9288     if (!Origin || !Inst || !DAG)
9289       return false;
9290
9291     // Offsets are for indexed load only, we do not handle that.
9292     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9293       return false;
9294
9295     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9296
9297     // Check that the type is legal.
9298     EVT SliceType = getLoadedType();
9299     if (!TLI.isTypeLegal(SliceType))
9300       return false;
9301
9302     // Check that the load is legal for this type.
9303     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9304       return false;
9305
9306     // Check that the offset can be computed.
9307     // 1. Check its type.
9308     EVT PtrType = Origin->getBasePtr().getValueType();
9309     if (PtrType == MVT::Untyped || PtrType.isExtended())
9310       return false;
9311
9312     // 2. Check that it fits in the immediate.
9313     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9314       return false;
9315
9316     // 3. Check that the computation is legal.
9317     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9318       return false;
9319
9320     // Check that the zext is legal if it needs one.
9321     EVT TruncateType = Inst->getValueType(0);
9322     if (TruncateType != SliceType &&
9323         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9324       return false;
9325
9326     return true;
9327   }
9328
9329   /// \brief Get the offset in bytes of this slice in the original chunk of
9330   /// bits.
9331   /// \pre DAG != nullptr.
9332   uint64_t getOffsetFromBase() const {
9333     assert(DAG && "Missing context.");
9334     bool IsBigEndian =
9335         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9336     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9337     uint64_t Offset = Shift / 8;
9338     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9339     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9340            "The size of the original loaded type is not a multiple of a"
9341            " byte.");
9342     // If Offset is bigger than TySizeInBytes, it means we are loading all
9343     // zeros. This should have been optimized before in the process.
9344     assert(TySizeInBytes > Offset &&
9345            "Invalid shift amount for given loaded size");
9346     if (IsBigEndian)
9347       Offset = TySizeInBytes - Offset - getLoadedSize();
9348     return Offset;
9349   }
9350
9351   /// \brief Generate the sequence of instructions to load the slice
9352   /// represented by this object and redirect the uses of this slice to
9353   /// this new sequence of instructions.
9354   /// \pre this->Inst && this->Origin are valid Instructions and this
9355   /// object passed the legal check: LoadedSlice::isLegal returned true.
9356   /// \return The last instruction of the sequence used to load the slice.
9357   SDValue loadSlice() const {
9358     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9359     const SDValue &OldBaseAddr = Origin->getBasePtr();
9360     SDValue BaseAddr = OldBaseAddr;
9361     // Get the offset in that chunk of bytes w.r.t. the endianess.
9362     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9363     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9364     if (Offset) {
9365       // BaseAddr = BaseAddr + Offset.
9366       EVT ArithType = BaseAddr.getValueType();
9367       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9368                               DAG->getConstant(Offset, ArithType));
9369     }
9370
9371     // Create the type of the loaded slice according to its size.
9372     EVT SliceType = getLoadedType();
9373
9374     // Create the load for the slice.
9375     SDValue LastInst = DAG->getLoad(
9376         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9377         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9378         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9379     // If the final type is not the same as the loaded type, this means that
9380     // we have to pad with zero. Create a zero extend for that.
9381     EVT FinalType = Inst->getValueType(0);
9382     if (SliceType != FinalType)
9383       LastInst =
9384           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9385     return LastInst;
9386   }
9387
9388   /// \brief Check if this slice can be merged with an expensive cross register
9389   /// bank copy. E.g.,
9390   /// i = load i32
9391   /// f = bitcast i32 i to float
9392   bool canMergeExpensiveCrossRegisterBankCopy() const {
9393     if (!Inst || !Inst->hasOneUse())
9394       return false;
9395     SDNode *Use = *Inst->use_begin();
9396     if (Use->getOpcode() != ISD::BITCAST)
9397       return false;
9398     assert(DAG && "Missing context");
9399     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9400     EVT ResVT = Use->getValueType(0);
9401     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9402     const TargetRegisterClass *ArgRC =
9403         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9404     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9405       return false;
9406
9407     // At this point, we know that we perform a cross-register-bank copy.
9408     // Check if it is expensive.
9409     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9410     // Assume bitcasts are cheap, unless both register classes do not
9411     // explicitly share a common sub class.
9412     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9413       return false;
9414
9415     // Check if it will be merged with the load.
9416     // 1. Check the alignment constraint.
9417     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9418         ResVT.getTypeForEVT(*DAG->getContext()));
9419
9420     if (RequiredAlignment > getAlignment())
9421       return false;
9422
9423     // 2. Check that the load is a legal operation for that type.
9424     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9425       return false;
9426
9427     // 3. Check that we do not have a zext in the way.
9428     if (Inst->getValueType(0) != getLoadedType())
9429       return false;
9430
9431     return true;
9432   }
9433 };
9434 }
9435
9436 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9437 /// \p UsedBits looks like 0..0 1..1 0..0.
9438 static bool areUsedBitsDense(const APInt &UsedBits) {
9439   // If all the bits are one, this is dense!
9440   if (UsedBits.isAllOnesValue())
9441     return true;
9442
9443   // Get rid of the unused bits on the right.
9444   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9445   // Get rid of the unused bits on the left.
9446   if (NarrowedUsedBits.countLeadingZeros())
9447     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9448   // Check that the chunk of bits is completely used.
9449   return NarrowedUsedBits.isAllOnesValue();
9450 }
9451
9452 /// \brief Check whether or not \p First and \p Second are next to each other
9453 /// in memory. This means that there is no hole between the bits loaded
9454 /// by \p First and the bits loaded by \p Second.
9455 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9456                                      const LoadedSlice &Second) {
9457   assert(First.Origin == Second.Origin && First.Origin &&
9458          "Unable to match different memory origins.");
9459   APInt UsedBits = First.getUsedBits();
9460   assert((UsedBits & Second.getUsedBits()) == 0 &&
9461          "Slices are not supposed to overlap.");
9462   UsedBits |= Second.getUsedBits();
9463   return areUsedBitsDense(UsedBits);
9464 }
9465
9466 /// \brief Adjust the \p GlobalLSCost according to the target
9467 /// paring capabilities and the layout of the slices.
9468 /// \pre \p GlobalLSCost should account for at least as many loads as
9469 /// there is in the slices in \p LoadedSlices.
9470 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9471                                  LoadedSlice::Cost &GlobalLSCost) {
9472   unsigned NumberOfSlices = LoadedSlices.size();
9473   // If there is less than 2 elements, no pairing is possible.
9474   if (NumberOfSlices < 2)
9475     return;
9476
9477   // Sort the slices so that elements that are likely to be next to each
9478   // other in memory are next to each other in the list.
9479   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9480             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9481     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9482     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9483   });
9484   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9485   // First (resp. Second) is the first (resp. Second) potentially candidate
9486   // to be placed in a paired load.
9487   const LoadedSlice *First = nullptr;
9488   const LoadedSlice *Second = nullptr;
9489   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9490                 // Set the beginning of the pair.
9491                                                            First = Second) {
9492
9493     Second = &LoadedSlices[CurrSlice];
9494
9495     // If First is NULL, it means we start a new pair.
9496     // Get to the next slice.
9497     if (!First)
9498       continue;
9499
9500     EVT LoadedType = First->getLoadedType();
9501
9502     // If the types of the slices are different, we cannot pair them.
9503     if (LoadedType != Second->getLoadedType())
9504       continue;
9505
9506     // Check if the target supplies paired loads for this type.
9507     unsigned RequiredAlignment = 0;
9508     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9509       // move to the next pair, this type is hopeless.
9510       Second = nullptr;
9511       continue;
9512     }
9513     // Check if we meet the alignment requirement.
9514     if (RequiredAlignment > First->getAlignment())
9515       continue;
9516
9517     // Check that both loads are next to each other in memory.
9518     if (!areSlicesNextToEachOther(*First, *Second))
9519       continue;
9520
9521     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9522     --GlobalLSCost.Loads;
9523     // Move to the next pair.
9524     Second = nullptr;
9525   }
9526 }
9527
9528 /// \brief Check the profitability of all involved LoadedSlice.
9529 /// Currently, it is considered profitable if there is exactly two
9530 /// involved slices (1) which are (2) next to each other in memory, and
9531 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9532 ///
9533 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9534 /// the elements themselves.
9535 ///
9536 /// FIXME: When the cost model will be mature enough, we can relax
9537 /// constraints (1) and (2).
9538 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9539                                 const APInt &UsedBits, bool ForCodeSize) {
9540   unsigned NumberOfSlices = LoadedSlices.size();
9541   if (StressLoadSlicing)
9542     return NumberOfSlices > 1;
9543
9544   // Check (1).
9545   if (NumberOfSlices != 2)
9546     return false;
9547
9548   // Check (2).
9549   if (!areUsedBitsDense(UsedBits))
9550     return false;
9551
9552   // Check (3).
9553   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9554   // The original code has one big load.
9555   OrigCost.Loads = 1;
9556   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9557     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9558     // Accumulate the cost of all the slices.
9559     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9560     GlobalSlicingCost += SliceCost;
9561
9562     // Account as cost in the original configuration the gain obtained
9563     // with the current slices.
9564     OrigCost.addSliceGain(LS);
9565   }
9566
9567   // If the target supports paired load, adjust the cost accordingly.
9568   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9569   return OrigCost > GlobalSlicingCost;
9570 }
9571
9572 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9573 /// operations, split it in the various pieces being extracted.
9574 ///
9575 /// This sort of thing is introduced by SROA.
9576 /// This slicing takes care not to insert overlapping loads.
9577 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9578 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9579   if (Level < AfterLegalizeDAG)
9580     return false;
9581
9582   LoadSDNode *LD = cast<LoadSDNode>(N);
9583   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9584       !LD->getValueType(0).isInteger())
9585     return false;
9586
9587   // Keep track of already used bits to detect overlapping values.
9588   // In that case, we will just abort the transformation.
9589   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9590
9591   SmallVector<LoadedSlice, 4> LoadedSlices;
9592
9593   // Check if this load is used as several smaller chunks of bits.
9594   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9595   // of computation for each trunc.
9596   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9597        UI != UIEnd; ++UI) {
9598     // Skip the uses of the chain.
9599     if (UI.getUse().getResNo() != 0)
9600       continue;
9601
9602     SDNode *User = *UI;
9603     unsigned Shift = 0;
9604
9605     // Check if this is a trunc(lshr).
9606     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9607         isa<ConstantSDNode>(User->getOperand(1))) {
9608       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9609       User = *User->use_begin();
9610     }
9611
9612     // At this point, User is a Truncate, iff we encountered, trunc or
9613     // trunc(lshr).
9614     if (User->getOpcode() != ISD::TRUNCATE)
9615       return false;
9616
9617     // The width of the type must be a power of 2 and greater than 8-bits.
9618     // Otherwise the load cannot be represented in LLVM IR.
9619     // Moreover, if we shifted with a non-8-bits multiple, the slice
9620     // will be across several bytes. We do not support that.
9621     unsigned Width = User->getValueSizeInBits(0);
9622     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9623       return 0;
9624
9625     // Build the slice for this chain of computations.
9626     LoadedSlice LS(User, LD, Shift, &DAG);
9627     APInt CurrentUsedBits = LS.getUsedBits();
9628
9629     // Check if this slice overlaps with another.
9630     if ((CurrentUsedBits & UsedBits) != 0)
9631       return false;
9632     // Update the bits used globally.
9633     UsedBits |= CurrentUsedBits;
9634
9635     // Check if the new slice would be legal.
9636     if (!LS.isLegal())
9637       return false;
9638
9639     // Record the slice.
9640     LoadedSlices.push_back(LS);
9641   }
9642
9643   // Abort slicing if it does not seem to be profitable.
9644   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9645     return false;
9646
9647   ++SlicedLoads;
9648
9649   // Rewrite each chain to use an independent load.
9650   // By construction, each chain can be represented by a unique load.
9651
9652   // Prepare the argument for the new token factor for all the slices.
9653   SmallVector<SDValue, 8> ArgChains;
9654   for (SmallVectorImpl<LoadedSlice>::const_iterator
9655            LSIt = LoadedSlices.begin(),
9656            LSItEnd = LoadedSlices.end();
9657        LSIt != LSItEnd; ++LSIt) {
9658     SDValue SliceInst = LSIt->loadSlice();
9659     CombineTo(LSIt->Inst, SliceInst, true);
9660     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9661       SliceInst = SliceInst.getOperand(0);
9662     assert(SliceInst->getOpcode() == ISD::LOAD &&
9663            "It takes more than a zext to get to the loaded slice!!");
9664     ArgChains.push_back(SliceInst.getValue(1));
9665   }
9666
9667   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9668                               ArgChains);
9669   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9670   return true;
9671 }
9672
9673 /// Check to see if V is (and load (ptr), imm), where the load is having
9674 /// specific bytes cleared out.  If so, return the byte size being masked out
9675 /// and the shift amount.
9676 static std::pair<unsigned, unsigned>
9677 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9678   std::pair<unsigned, unsigned> Result(0, 0);
9679
9680   // Check for the structure we're looking for.
9681   if (V->getOpcode() != ISD::AND ||
9682       !isa<ConstantSDNode>(V->getOperand(1)) ||
9683       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9684     return Result;
9685
9686   // Check the chain and pointer.
9687   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9688   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9689
9690   // The store should be chained directly to the load or be an operand of a
9691   // tokenfactor.
9692   if (LD == Chain.getNode())
9693     ; // ok.
9694   else if (Chain->getOpcode() != ISD::TokenFactor)
9695     return Result; // Fail.
9696   else {
9697     bool isOk = false;
9698     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9699       if (Chain->getOperand(i).getNode() == LD) {
9700         isOk = true;
9701         break;
9702       }
9703     if (!isOk) return Result;
9704   }
9705
9706   // This only handles simple types.
9707   if (V.getValueType() != MVT::i16 &&
9708       V.getValueType() != MVT::i32 &&
9709       V.getValueType() != MVT::i64)
9710     return Result;
9711
9712   // Check the constant mask.  Invert it so that the bits being masked out are
9713   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9714   // follow the sign bit for uniformity.
9715   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9716   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9717   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9718   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9719   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9720   if (NotMaskLZ == 64) return Result;  // All zero mask.
9721
9722   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9723   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9724     return Result;
9725
9726   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9727   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9728     NotMaskLZ -= 64-V.getValueSizeInBits();
9729
9730   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9731   switch (MaskedBytes) {
9732   case 1:
9733   case 2:
9734   case 4: break;
9735   default: return Result; // All one mask, or 5-byte mask.
9736   }
9737
9738   // Verify that the first bit starts at a multiple of mask so that the access
9739   // is aligned the same as the access width.
9740   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9741
9742   Result.first = MaskedBytes;
9743   Result.second = NotMaskTZ/8;
9744   return Result;
9745 }
9746
9747
9748 /// Check to see if IVal is something that provides a value as specified by
9749 /// MaskInfo. If so, replace the specified store with a narrower store of
9750 /// truncated IVal.
9751 static SDNode *
9752 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9753                                 SDValue IVal, StoreSDNode *St,
9754                                 DAGCombiner *DC) {
9755   unsigned NumBytes = MaskInfo.first;
9756   unsigned ByteShift = MaskInfo.second;
9757   SelectionDAG &DAG = DC->getDAG();
9758
9759   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9760   // that uses this.  If not, this is not a replacement.
9761   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9762                                   ByteShift*8, (ByteShift+NumBytes)*8);
9763   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9764
9765   // Check that it is legal on the target to do this.  It is legal if the new
9766   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9767   // legalization.
9768   MVT VT = MVT::getIntegerVT(NumBytes*8);
9769   if (!DC->isTypeLegal(VT))
9770     return nullptr;
9771
9772   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9773   // shifted by ByteShift and truncated down to NumBytes.
9774   if (ByteShift)
9775     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9776                        DAG.getConstant(ByteShift*8,
9777                                     DC->getShiftAmountTy(IVal.getValueType())));
9778
9779   // Figure out the offset for the store and the alignment of the access.
9780   unsigned StOffset;
9781   unsigned NewAlign = St->getAlignment();
9782
9783   if (DAG.getTargetLoweringInfo().isLittleEndian())
9784     StOffset = ByteShift;
9785   else
9786     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9787
9788   SDValue Ptr = St->getBasePtr();
9789   if (StOffset) {
9790     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9791                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9792     NewAlign = MinAlign(NewAlign, StOffset);
9793   }
9794
9795   // Truncate down to the new size.
9796   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9797
9798   ++OpsNarrowed;
9799   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9800                       St->getPointerInfo().getWithOffset(StOffset),
9801                       false, false, NewAlign).getNode();
9802 }
9803
9804
9805 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9806 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9807 /// narrowing the load and store if it would end up being a win for performance
9808 /// or code size.
9809 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9810   StoreSDNode *ST  = cast<StoreSDNode>(N);
9811   if (ST->isVolatile())
9812     return SDValue();
9813
9814   SDValue Chain = ST->getChain();
9815   SDValue Value = ST->getValue();
9816   SDValue Ptr   = ST->getBasePtr();
9817   EVT VT = Value.getValueType();
9818
9819   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9820     return SDValue();
9821
9822   unsigned Opc = Value.getOpcode();
9823
9824   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9825   // is a byte mask indicating a consecutive number of bytes, check to see if
9826   // Y is known to provide just those bytes.  If so, we try to replace the
9827   // load + replace + store sequence with a single (narrower) store, which makes
9828   // the load dead.
9829   if (Opc == ISD::OR) {
9830     std::pair<unsigned, unsigned> MaskedLoad;
9831     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9832     if (MaskedLoad.first)
9833       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9834                                                   Value.getOperand(1), ST,this))
9835         return SDValue(NewST, 0);
9836
9837     // Or is commutative, so try swapping X and Y.
9838     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9839     if (MaskedLoad.first)
9840       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9841                                                   Value.getOperand(0), ST,this))
9842         return SDValue(NewST, 0);
9843   }
9844
9845   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9846       Value.getOperand(1).getOpcode() != ISD::Constant)
9847     return SDValue();
9848
9849   SDValue N0 = Value.getOperand(0);
9850   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9851       Chain == SDValue(N0.getNode(), 1)) {
9852     LoadSDNode *LD = cast<LoadSDNode>(N0);
9853     if (LD->getBasePtr() != Ptr ||
9854         LD->getPointerInfo().getAddrSpace() !=
9855         ST->getPointerInfo().getAddrSpace())
9856       return SDValue();
9857
9858     // Find the type to narrow it the load / op / store to.
9859     SDValue N1 = Value.getOperand(1);
9860     unsigned BitWidth = N1.getValueSizeInBits();
9861     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9862     if (Opc == ISD::AND)
9863       Imm ^= APInt::getAllOnesValue(BitWidth);
9864     if (Imm == 0 || Imm.isAllOnesValue())
9865       return SDValue();
9866     unsigned ShAmt = Imm.countTrailingZeros();
9867     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9868     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9869     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9870     // The narrowing should be profitable, the load/store operation should be
9871     // legal (or custom) and the store size should be equal to the NewVT width.
9872     while (NewBW < BitWidth &&
9873            (NewVT.getStoreSizeInBits() != NewBW ||
9874             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9875             !TLI.isNarrowingProfitable(VT, NewVT))) {
9876       NewBW = NextPowerOf2(NewBW);
9877       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9878     }
9879     if (NewBW >= BitWidth)
9880       return SDValue();
9881
9882     // If the lsb changed does not start at the type bitwidth boundary,
9883     // start at the previous one.
9884     if (ShAmt % NewBW)
9885       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9886     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9887                                    std::min(BitWidth, ShAmt + NewBW));
9888     if ((Imm & Mask) == Imm) {
9889       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9890       if (Opc == ISD::AND)
9891         NewImm ^= APInt::getAllOnesValue(NewBW);
9892       uint64_t PtrOff = ShAmt / 8;
9893       // For big endian targets, we need to adjust the offset to the pointer to
9894       // load the correct bytes.
9895       if (TLI.isBigEndian())
9896         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9897
9898       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9899       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9900       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9901         return SDValue();
9902
9903       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9904                                    Ptr.getValueType(), Ptr,
9905                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9906       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9907                                   LD->getChain(), NewPtr,
9908                                   LD->getPointerInfo().getWithOffset(PtrOff),
9909                                   LD->isVolatile(), LD->isNonTemporal(),
9910                                   LD->isInvariant(), NewAlign,
9911                                   LD->getAAInfo());
9912       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9913                                    DAG.getConstant(NewImm, NewVT));
9914       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9915                                    NewVal, NewPtr,
9916                                    ST->getPointerInfo().getWithOffset(PtrOff),
9917                                    false, false, NewAlign);
9918
9919       AddToWorklist(NewPtr.getNode());
9920       AddToWorklist(NewLD.getNode());
9921       AddToWorklist(NewVal.getNode());
9922       WorklistRemover DeadNodes(*this);
9923       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9924       ++OpsNarrowed;
9925       return NewST;
9926     }
9927   }
9928
9929   return SDValue();
9930 }
9931
9932 /// For a given floating point load / store pair, if the load value isn't used
9933 /// by any other operations, then consider transforming the pair to integer
9934 /// load / store operations if the target deems the transformation profitable.
9935 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9936   StoreSDNode *ST  = cast<StoreSDNode>(N);
9937   SDValue Chain = ST->getChain();
9938   SDValue Value = ST->getValue();
9939   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9940       Value.hasOneUse() &&
9941       Chain == SDValue(Value.getNode(), 1)) {
9942     LoadSDNode *LD = cast<LoadSDNode>(Value);
9943     EVT VT = LD->getMemoryVT();
9944     if (!VT.isFloatingPoint() ||
9945         VT != ST->getMemoryVT() ||
9946         LD->isNonTemporal() ||
9947         ST->isNonTemporal() ||
9948         LD->getPointerInfo().getAddrSpace() != 0 ||
9949         ST->getPointerInfo().getAddrSpace() != 0)
9950       return SDValue();
9951
9952     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9953     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9954         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9955         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9956         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9957       return SDValue();
9958
9959     unsigned LDAlign = LD->getAlignment();
9960     unsigned STAlign = ST->getAlignment();
9961     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9962     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9963     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9964       return SDValue();
9965
9966     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9967                                 LD->getChain(), LD->getBasePtr(),
9968                                 LD->getPointerInfo(),
9969                                 false, false, false, LDAlign);
9970
9971     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9972                                  NewLD, ST->getBasePtr(),
9973                                  ST->getPointerInfo(),
9974                                  false, false, STAlign);
9975
9976     AddToWorklist(NewLD.getNode());
9977     AddToWorklist(NewST.getNode());
9978     WorklistRemover DeadNodes(*this);
9979     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9980     ++LdStFP2Int;
9981     return NewST;
9982   }
9983
9984   return SDValue();
9985 }
9986
9987 namespace {
9988 /// Helper struct to parse and store a memory address as base + index + offset.
9989 /// We ignore sign extensions when it is safe to do so.
9990 /// The following two expressions are not equivalent. To differentiate we need
9991 /// to store whether there was a sign extension involved in the index
9992 /// computation.
9993 ///  (load (i64 add (i64 copyfromreg %c)
9994 ///                 (i64 signextend (add (i8 load %index)
9995 ///                                      (i8 1))))
9996 /// vs
9997 ///
9998 /// (load (i64 add (i64 copyfromreg %c)
9999 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10000 ///                                         (i32 1)))))
10001 struct BaseIndexOffset {
10002   SDValue Base;
10003   SDValue Index;
10004   int64_t Offset;
10005   bool IsIndexSignExt;
10006
10007   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10008
10009   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10010                   bool IsIndexSignExt) :
10011     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10012
10013   bool equalBaseIndex(const BaseIndexOffset &Other) {
10014     return Other.Base == Base && Other.Index == Index &&
10015       Other.IsIndexSignExt == IsIndexSignExt;
10016   }
10017
10018   /// Parses tree in Ptr for base, index, offset addresses.
10019   static BaseIndexOffset match(SDValue Ptr) {
10020     bool IsIndexSignExt = false;
10021
10022     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10023     // instruction, then it could be just the BASE or everything else we don't
10024     // know how to handle. Just use Ptr as BASE and give up.
10025     if (Ptr->getOpcode() != ISD::ADD)
10026       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10027
10028     // We know that we have at least an ADD instruction. Try to pattern match
10029     // the simple case of BASE + OFFSET.
10030     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10031       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10032       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10033                               IsIndexSignExt);
10034     }
10035
10036     // Inside a loop the current BASE pointer is calculated using an ADD and a
10037     // MUL instruction. In this case Ptr is the actual BASE pointer.
10038     // (i64 add (i64 %array_ptr)
10039     //          (i64 mul (i64 %induction_var)
10040     //                   (i64 %element_size)))
10041     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10042       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10043
10044     // Look at Base + Index + Offset cases.
10045     SDValue Base = Ptr->getOperand(0);
10046     SDValue IndexOffset = Ptr->getOperand(1);
10047
10048     // Skip signextends.
10049     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10050       IndexOffset = IndexOffset->getOperand(0);
10051       IsIndexSignExt = true;
10052     }
10053
10054     // Either the case of Base + Index (no offset) or something else.
10055     if (IndexOffset->getOpcode() != ISD::ADD)
10056       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10057
10058     // Now we have the case of Base + Index + offset.
10059     SDValue Index = IndexOffset->getOperand(0);
10060     SDValue Offset = IndexOffset->getOperand(1);
10061
10062     if (!isa<ConstantSDNode>(Offset))
10063       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10064
10065     // Ignore signextends.
10066     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10067       Index = Index->getOperand(0);
10068       IsIndexSignExt = true;
10069     } else IsIndexSignExt = false;
10070
10071     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10072     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10073   }
10074 };
10075 } // namespace
10076
10077 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10078                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10079                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10080   // Make sure we have something to merge.
10081   if (NumElem < 2)
10082     return false;
10083
10084   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10085   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10086   unsigned EarliestNodeUsed = 0;
10087
10088   for (unsigned i=0; i < NumElem; ++i) {
10089     // Find a chain for the new wide-store operand. Notice that some
10090     // of the store nodes that we found may not be selected for inclusion
10091     // in the wide store. The chain we use needs to be the chain of the
10092     // earliest store node which is *used* and replaced by the wide store.
10093     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10094       EarliestNodeUsed = i;
10095   }
10096
10097   // The earliest Node in the DAG.
10098   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10099   SDLoc DL(StoreNodes[0].MemNode);
10100
10101   SDValue StoredVal;
10102   if (UseVector) {
10103     // Find a legal type for the vector store.
10104     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10105     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10106     if (IsConstantSrc) {
10107       // A vector store with a constant source implies that the constant is
10108       // zero; we only handle merging stores of constant zeros because the zero
10109       // can be materialized without a load.
10110       // It may be beneficial to loosen this restriction to allow non-zero
10111       // store merging.
10112       StoredVal = DAG.getConstant(0, Ty);
10113     } else {
10114       SmallVector<SDValue, 8> Ops;
10115       for (unsigned i = 0; i < NumElem ; ++i) {
10116         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10117         SDValue Val = St->getValue();
10118         // All of the operands of a BUILD_VECTOR must have the same type.
10119         if (Val.getValueType() != MemVT)
10120           return false;
10121         Ops.push_back(Val);
10122       }
10123
10124       // Build the extracted vector elements back into a vector.
10125       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10126     }
10127   } else {
10128     // We should always use a vector store when merging extracted vector
10129     // elements, so this path implies a store of constants.
10130     assert(IsConstantSrc && "Merged vector elements should use vector store");
10131
10132     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10133     APInt StoreInt(StoreBW, 0);
10134
10135     // Construct a single integer constant which is made of the smaller
10136     // constant inputs.
10137     bool IsLE = TLI.isLittleEndian();
10138     for (unsigned i = 0; i < NumElem ; ++i) {
10139       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10140       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10141       SDValue Val = St->getValue();
10142       StoreInt <<= ElementSizeBytes*8;
10143       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10144         StoreInt |= C->getAPIntValue().zext(StoreBW);
10145       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10146         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10147       } else {
10148         llvm_unreachable("Invalid constant element type");
10149       }
10150     }
10151
10152     // Create the new Load and Store operations.
10153     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10154     StoredVal = DAG.getConstant(StoreInt, StoreTy);
10155   }
10156
10157   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10158                                   FirstInChain->getBasePtr(),
10159                                   FirstInChain->getPointerInfo(),
10160                                   false, false,
10161                                   FirstInChain->getAlignment());
10162
10163   // Replace the first store with the new store
10164   CombineTo(EarliestOp, NewStore);
10165   // Erase all other stores.
10166   for (unsigned i = 0; i < NumElem ; ++i) {
10167     if (StoreNodes[i].MemNode == EarliestOp)
10168       continue;
10169     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10170     // ReplaceAllUsesWith will replace all uses that existed when it was
10171     // called, but graph optimizations may cause new ones to appear. For
10172     // example, the case in pr14333 looks like
10173     //
10174     //  St's chain -> St -> another store -> X
10175     //
10176     // And the only difference from St to the other store is the chain.
10177     // When we change it's chain to be St's chain they become identical,
10178     // get CSEed and the net result is that X is now a use of St.
10179     // Since we know that St is redundant, just iterate.
10180     while (!St->use_empty())
10181       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10182     deleteAndRecombine(St);
10183   }
10184
10185   return true;
10186 }
10187
10188 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10189   if (OptLevel == CodeGenOpt::None)
10190     return false;
10191
10192   EVT MemVT = St->getMemoryVT();
10193   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10194   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10195       Attribute::NoImplicitFloat);
10196
10197   // Don't merge vectors into wider inputs.
10198   if (MemVT.isVector() || !MemVT.isSimple())
10199     return false;
10200
10201   // Perform an early exit check. Do not bother looking at stored values that
10202   // are not constants, loads, or extracted vector elements.
10203   SDValue StoredVal = St->getValue();
10204   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10205   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10206                        isa<ConstantFPSDNode>(StoredVal);
10207   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10208
10209   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10210     return false;
10211
10212   // Only look at ends of store sequences.
10213   SDValue Chain = SDValue(St, 0);
10214   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10215     return false;
10216
10217   // This holds the base pointer, index, and the offset in bytes from the base
10218   // pointer.
10219   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10220
10221   // We must have a base and an offset.
10222   if (!BasePtr.Base.getNode())
10223     return false;
10224
10225   // Do not handle stores to undef base pointers.
10226   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10227     return false;
10228
10229   // Save the LoadSDNodes that we find in the chain.
10230   // We need to make sure that these nodes do not interfere with
10231   // any of the store nodes.
10232   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10233
10234   // Save the StoreSDNodes that we find in the chain.
10235   SmallVector<MemOpLink, 8> StoreNodes;
10236
10237   // Walk up the chain and look for nodes with offsets from the same
10238   // base pointer. Stop when reaching an instruction with a different kind
10239   // or instruction which has a different base pointer.
10240   unsigned Seq = 0;
10241   StoreSDNode *Index = St;
10242   while (Index) {
10243     // If the chain has more than one use, then we can't reorder the mem ops.
10244     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10245       break;
10246
10247     // Find the base pointer and offset for this memory node.
10248     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10249
10250     // Check that the base pointer is the same as the original one.
10251     if (!Ptr.equalBaseIndex(BasePtr))
10252       break;
10253
10254     // Check that the alignment is the same.
10255     if (Index->getAlignment() != St->getAlignment())
10256       break;
10257
10258     // The memory operands must not be volatile.
10259     if (Index->isVolatile() || Index->isIndexed())
10260       break;
10261
10262     // No truncation.
10263     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10264       if (St->isTruncatingStore())
10265         break;
10266
10267     // The stored memory type must be the same.
10268     if (Index->getMemoryVT() != MemVT)
10269       break;
10270
10271     // We do not allow unaligned stores because we want to prevent overriding
10272     // stores.
10273     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10274       break;
10275
10276     // We found a potential memory operand to merge.
10277     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10278
10279     // Find the next memory operand in the chain. If the next operand in the
10280     // chain is a store then move up and continue the scan with the next
10281     // memory operand. If the next operand is a load save it and use alias
10282     // information to check if it interferes with anything.
10283     SDNode *NextInChain = Index->getChain().getNode();
10284     while (1) {
10285       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10286         // We found a store node. Use it for the next iteration.
10287         Index = STn;
10288         break;
10289       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10290         if (Ldn->isVolatile()) {
10291           Index = nullptr;
10292           break;
10293         }
10294
10295         // Save the load node for later. Continue the scan.
10296         AliasLoadNodes.push_back(Ldn);
10297         NextInChain = Ldn->getChain().getNode();
10298         continue;
10299       } else {
10300         Index = nullptr;
10301         break;
10302       }
10303     }
10304   }
10305
10306   // Check if there is anything to merge.
10307   if (StoreNodes.size() < 2)
10308     return false;
10309
10310   // Sort the memory operands according to their distance from the base pointer.
10311   std::sort(StoreNodes.begin(), StoreNodes.end(),
10312             [](MemOpLink LHS, MemOpLink RHS) {
10313     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10314            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10315             LHS.SequenceNum > RHS.SequenceNum);
10316   });
10317
10318   // Scan the memory operations on the chain and find the first non-consecutive
10319   // store memory address.
10320   unsigned LastConsecutiveStore = 0;
10321   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10322   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10323
10324     // Check that the addresses are consecutive starting from the second
10325     // element in the list of stores.
10326     if (i > 0) {
10327       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10328       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10329         break;
10330     }
10331
10332     bool Alias = false;
10333     // Check if this store interferes with any of the loads that we found.
10334     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10335       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10336         Alias = true;
10337         break;
10338       }
10339     // We found a load that alias with this store. Stop the sequence.
10340     if (Alias)
10341       break;
10342
10343     // Mark this node as useful.
10344     LastConsecutiveStore = i;
10345   }
10346
10347   // The node with the lowest store address.
10348   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10349
10350   // Store the constants into memory as one consecutive store.
10351   if (IsConstantSrc) {
10352     unsigned LastLegalType = 0;
10353     unsigned LastLegalVectorType = 0;
10354     bool NonZero = false;
10355     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10356       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10357       SDValue StoredVal = St->getValue();
10358
10359       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10360         NonZero |= !C->isNullValue();
10361       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10362         NonZero |= !C->getConstantFPValue()->isNullValue();
10363       } else {
10364         // Non-constant.
10365         break;
10366       }
10367
10368       // Find a legal type for the constant store.
10369       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10370       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10371       if (TLI.isTypeLegal(StoreTy))
10372         LastLegalType = i+1;
10373       // Or check whether a truncstore is legal.
10374       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10375                TargetLowering::TypePromoteInteger) {
10376         EVT LegalizedStoredValueTy =
10377           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10378         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10379           LastLegalType = i+1;
10380       }
10381
10382       // Find a legal type for the vector store.
10383       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10384       if (TLI.isTypeLegal(Ty))
10385         LastLegalVectorType = i + 1;
10386     }
10387
10388     // We only use vectors if the constant is known to be zero and the
10389     // function is not marked with the noimplicitfloat attribute.
10390     if (NonZero || NoVectors)
10391       LastLegalVectorType = 0;
10392
10393     // Check if we found a legal integer type to store.
10394     if (LastLegalType == 0 && LastLegalVectorType == 0)
10395       return false;
10396
10397     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10398     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10399
10400     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10401                                            true, UseVector);
10402   }
10403
10404   // When extracting multiple vector elements, try to store them
10405   // in one vector store rather than a sequence of scalar stores.
10406   if (IsExtractVecEltSrc) {
10407     unsigned NumElem = 0;
10408     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10409       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10410       SDValue StoredVal = St->getValue();
10411       // This restriction could be loosened.
10412       // Bail out if any stored values are not elements extracted from a vector.
10413       // It should be possible to handle mixed sources, but load sources need
10414       // more careful handling (see the block of code below that handles
10415       // consecutive loads).
10416       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10417         return false;
10418
10419       // Find a legal type for the vector store.
10420       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10421       if (TLI.isTypeLegal(Ty))
10422         NumElem = i + 1;
10423     }
10424
10425     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10426                                            false, true);
10427   }
10428
10429   // Below we handle the case of multiple consecutive stores that
10430   // come from multiple consecutive loads. We merge them into a single
10431   // wide load and a single wide store.
10432
10433   // Look for load nodes which are used by the stored values.
10434   SmallVector<MemOpLink, 8> LoadNodes;
10435
10436   // Find acceptable loads. Loads need to have the same chain (token factor),
10437   // must not be zext, volatile, indexed, and they must be consecutive.
10438   BaseIndexOffset LdBasePtr;
10439   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10440     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10441     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10442     if (!Ld) break;
10443
10444     // Loads must only have one use.
10445     if (!Ld->hasNUsesOfValue(1, 0))
10446       break;
10447
10448     // Check that the alignment is the same as the stores.
10449     if (Ld->getAlignment() != St->getAlignment())
10450       break;
10451
10452     // The memory operands must not be volatile.
10453     if (Ld->isVolatile() || Ld->isIndexed())
10454       break;
10455
10456     // We do not accept ext loads.
10457     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10458       break;
10459
10460     // The stored memory type must be the same.
10461     if (Ld->getMemoryVT() != MemVT)
10462       break;
10463
10464     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10465     // If this is not the first ptr that we check.
10466     if (LdBasePtr.Base.getNode()) {
10467       // The base ptr must be the same.
10468       if (!LdPtr.equalBaseIndex(LdBasePtr))
10469         break;
10470     } else {
10471       // Check that all other base pointers are the same as this one.
10472       LdBasePtr = LdPtr;
10473     }
10474
10475     // We found a potential memory operand to merge.
10476     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10477   }
10478
10479   if (LoadNodes.size() < 2)
10480     return false;
10481
10482   // If we have load/store pair instructions and we only have two values,
10483   // don't bother.
10484   unsigned RequiredAlignment;
10485   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10486       St->getAlignment() >= RequiredAlignment)
10487     return false;
10488
10489   // Scan the memory operations on the chain and find the first non-consecutive
10490   // load memory address. These variables hold the index in the store node
10491   // array.
10492   unsigned LastConsecutiveLoad = 0;
10493   // This variable refers to the size and not index in the array.
10494   unsigned LastLegalVectorType = 0;
10495   unsigned LastLegalIntegerType = 0;
10496   StartAddress = LoadNodes[0].OffsetFromBase;
10497   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10498   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10499     // All loads much share the same chain.
10500     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10501       break;
10502
10503     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10504     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10505       break;
10506     LastConsecutiveLoad = i;
10507
10508     // Find a legal type for the vector store.
10509     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10510     if (TLI.isTypeLegal(StoreTy))
10511       LastLegalVectorType = i + 1;
10512
10513     // Find a legal type for the integer store.
10514     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10515     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10516     if (TLI.isTypeLegal(StoreTy))
10517       LastLegalIntegerType = i + 1;
10518     // Or check whether a truncstore and extload is legal.
10519     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10520              TargetLowering::TypePromoteInteger) {
10521       EVT LegalizedStoredValueTy =
10522         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10523       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10524           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10525           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10526           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10527         LastLegalIntegerType = i+1;
10528     }
10529   }
10530
10531   // Only use vector types if the vector type is larger than the integer type.
10532   // If they are the same, use integers.
10533   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10534   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10535
10536   // We add +1 here because the LastXXX variables refer to location while
10537   // the NumElem refers to array/index size.
10538   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10539   NumElem = std::min(LastLegalType, NumElem);
10540
10541   if (NumElem < 2)
10542     return false;
10543
10544   // The earliest Node in the DAG.
10545   unsigned EarliestNodeUsed = 0;
10546   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10547   for (unsigned i=1; i<NumElem; ++i) {
10548     // Find a chain for the new wide-store operand. Notice that some
10549     // of the store nodes that we found may not be selected for inclusion
10550     // in the wide store. The chain we use needs to be the chain of the
10551     // earliest store node which is *used* and replaced by the wide store.
10552     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10553       EarliestNodeUsed = i;
10554   }
10555
10556   // Find if it is better to use vectors or integers to load and store
10557   // to memory.
10558   EVT JointMemOpVT;
10559   if (UseVectorTy) {
10560     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10561   } else {
10562     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10563     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10564   }
10565
10566   SDLoc LoadDL(LoadNodes[0].MemNode);
10567   SDLoc StoreDL(StoreNodes[0].MemNode);
10568
10569   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10570   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10571                                 FirstLoad->getChain(),
10572                                 FirstLoad->getBasePtr(),
10573                                 FirstLoad->getPointerInfo(),
10574                                 false, false, false,
10575                                 FirstLoad->getAlignment());
10576
10577   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10578                                   FirstInChain->getBasePtr(),
10579                                   FirstInChain->getPointerInfo(), false, false,
10580                                   FirstInChain->getAlignment());
10581
10582   // Replace one of the loads with the new load.
10583   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10584   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10585                                 SDValue(NewLoad.getNode(), 1));
10586
10587   // Remove the rest of the load chains.
10588   for (unsigned i = 1; i < NumElem ; ++i) {
10589     // Replace all chain users of the old load nodes with the chain of the new
10590     // load node.
10591     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10592     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10593   }
10594
10595   // Replace the first store with the new store.
10596   CombineTo(EarliestOp, NewStore);
10597   // Erase all other stores.
10598   for (unsigned i = 0; i < NumElem ; ++i) {
10599     // Remove all Store nodes.
10600     if (StoreNodes[i].MemNode == EarliestOp)
10601       continue;
10602     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10603     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10604     deleteAndRecombine(St);
10605   }
10606
10607   return true;
10608 }
10609
10610 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10611   StoreSDNode *ST  = cast<StoreSDNode>(N);
10612   SDValue Chain = ST->getChain();
10613   SDValue Value = ST->getValue();
10614   SDValue Ptr   = ST->getBasePtr();
10615
10616   // If this is a store of a bit convert, store the input value if the
10617   // resultant store does not need a higher alignment than the original.
10618   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10619       ST->isUnindexed()) {
10620     unsigned OrigAlign = ST->getAlignment();
10621     EVT SVT = Value.getOperand(0).getValueType();
10622     unsigned Align = TLI.getDataLayout()->
10623       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10624     if (Align <= OrigAlign &&
10625         ((!LegalOperations && !ST->isVolatile()) ||
10626          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10627       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10628                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10629                           ST->isNonTemporal(), OrigAlign,
10630                           ST->getAAInfo());
10631   }
10632
10633   // Turn 'store undef, Ptr' -> nothing.
10634   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10635     return Chain;
10636
10637   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10638   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10639     // NOTE: If the original store is volatile, this transform must not increase
10640     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10641     // processor operation but an i64 (which is not legal) requires two.  So the
10642     // transform should not be done in this case.
10643     if (Value.getOpcode() != ISD::TargetConstantFP) {
10644       SDValue Tmp;
10645       switch (CFP->getSimpleValueType(0).SimpleTy) {
10646       default: llvm_unreachable("Unknown FP type");
10647       case MVT::f16:    // We don't do this for these yet.
10648       case MVT::f80:
10649       case MVT::f128:
10650       case MVT::ppcf128:
10651         break;
10652       case MVT::f32:
10653         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10654             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10655           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10656                               bitcastToAPInt().getZExtValue(), MVT::i32);
10657           return DAG.getStore(Chain, SDLoc(N), Tmp,
10658                               Ptr, ST->getMemOperand());
10659         }
10660         break;
10661       case MVT::f64:
10662         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10663              !ST->isVolatile()) ||
10664             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10665           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10666                                 getZExtValue(), MVT::i64);
10667           return DAG.getStore(Chain, SDLoc(N), Tmp,
10668                               Ptr, ST->getMemOperand());
10669         }
10670
10671         if (!ST->isVolatile() &&
10672             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10673           // Many FP stores are not made apparent until after legalize, e.g. for
10674           // argument passing.  Since this is so common, custom legalize the
10675           // 64-bit integer store into two 32-bit stores.
10676           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10677           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10678           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10679           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10680
10681           unsigned Alignment = ST->getAlignment();
10682           bool isVolatile = ST->isVolatile();
10683           bool isNonTemporal = ST->isNonTemporal();
10684           AAMDNodes AAInfo = ST->getAAInfo();
10685
10686           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10687                                      Ptr, ST->getPointerInfo(),
10688                                      isVolatile, isNonTemporal,
10689                                      ST->getAlignment(), AAInfo);
10690           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10691                             DAG.getConstant(4, Ptr.getValueType()));
10692           Alignment = MinAlign(Alignment, 4U);
10693           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10694                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10695                                      isVolatile, isNonTemporal,
10696                                      Alignment, AAInfo);
10697           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10698                              St0, St1);
10699         }
10700
10701         break;
10702       }
10703     }
10704   }
10705
10706   // Try to infer better alignment information than the store already has.
10707   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10708     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10709       if (Align > ST->getAlignment()) {
10710         SDValue NewStore =
10711                DAG.getTruncStore(Chain, SDLoc(N), Value,
10712                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10713                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10714                                  ST->getAAInfo());
10715         if (NewStore.getNode() != N)
10716           return CombineTo(ST, NewStore, true);
10717       }
10718     }
10719   }
10720
10721   // Try transforming a pair floating point load / store ops to integer
10722   // load / store ops.
10723   SDValue NewST = TransformFPLoadStorePair(N);
10724   if (NewST.getNode())
10725     return NewST;
10726
10727   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10728                                                   : DAG.getSubtarget().useAA();
10729 #ifndef NDEBUG
10730   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10731       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10732     UseAA = false;
10733 #endif
10734   if (UseAA && ST->isUnindexed()) {
10735     // Walk up chain skipping non-aliasing memory nodes.
10736     SDValue BetterChain = FindBetterChain(N, Chain);
10737
10738     // If there is a better chain.
10739     if (Chain != BetterChain) {
10740       SDValue ReplStore;
10741
10742       // Replace the chain to avoid dependency.
10743       if (ST->isTruncatingStore()) {
10744         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10745                                       ST->getMemoryVT(), ST->getMemOperand());
10746       } else {
10747         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10748                                  ST->getMemOperand());
10749       }
10750
10751       // Create token to keep both nodes around.
10752       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10753                                   MVT::Other, Chain, ReplStore);
10754
10755       // Make sure the new and old chains are cleaned up.
10756       AddToWorklist(Token.getNode());
10757
10758       // Don't add users to work list.
10759       return CombineTo(N, Token, false);
10760     }
10761   }
10762
10763   // Try transforming N to an indexed store.
10764   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10765     return SDValue(N, 0);
10766
10767   // FIXME: is there such a thing as a truncating indexed store?
10768   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10769       Value.getValueType().isInteger()) {
10770     // See if we can simplify the input to this truncstore with knowledge that
10771     // only the low bits are being used.  For example:
10772     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10773     SDValue Shorter =
10774       GetDemandedBits(Value,
10775                       APInt::getLowBitsSet(
10776                         Value.getValueType().getScalarType().getSizeInBits(),
10777                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10778     AddToWorklist(Value.getNode());
10779     if (Shorter.getNode())
10780       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10781                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10782
10783     // Otherwise, see if we can simplify the operation with
10784     // SimplifyDemandedBits, which only works if the value has a single use.
10785     if (SimplifyDemandedBits(Value,
10786                         APInt::getLowBitsSet(
10787                           Value.getValueType().getScalarType().getSizeInBits(),
10788                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10789       return SDValue(N, 0);
10790   }
10791
10792   // If this is a load followed by a store to the same location, then the store
10793   // is dead/noop.
10794   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10795     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10796         ST->isUnindexed() && !ST->isVolatile() &&
10797         // There can't be any side effects between the load and store, such as
10798         // a call or store.
10799         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10800       // The store is dead, remove it.
10801       return Chain;
10802     }
10803   }
10804
10805   // If this is a store followed by a store with the same value to the same
10806   // location, then the store is dead/noop.
10807   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10808     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10809         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10810         ST1->isUnindexed() && !ST1->isVolatile()) {
10811       // The store is dead, remove it.
10812       return Chain;
10813     }
10814   }
10815
10816   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10817   // truncating store.  We can do this even if this is already a truncstore.
10818   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10819       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10820       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10821                             ST->getMemoryVT())) {
10822     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10823                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10824   }
10825
10826   // Only perform this optimization before the types are legal, because we
10827   // don't want to perform this optimization on every DAGCombine invocation.
10828   if (!LegalTypes) {
10829     bool EverChanged = false;
10830
10831     do {
10832       // There can be multiple store sequences on the same chain.
10833       // Keep trying to merge store sequences until we are unable to do so
10834       // or until we merge the last store on the chain.
10835       bool Changed = MergeConsecutiveStores(ST);
10836       EverChanged |= Changed;
10837       if (!Changed) break;
10838     } while (ST->getOpcode() != ISD::DELETED_NODE);
10839
10840     if (EverChanged)
10841       return SDValue(N, 0);
10842   }
10843
10844   return ReduceLoadOpStoreWidth(N);
10845 }
10846
10847 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10848   SDValue InVec = N->getOperand(0);
10849   SDValue InVal = N->getOperand(1);
10850   SDValue EltNo = N->getOperand(2);
10851   SDLoc dl(N);
10852
10853   // If the inserted element is an UNDEF, just use the input vector.
10854   if (InVal.getOpcode() == ISD::UNDEF)
10855     return InVec;
10856
10857   EVT VT = InVec.getValueType();
10858
10859   // If we can't generate a legal BUILD_VECTOR, exit
10860   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10861     return SDValue();
10862
10863   // Check that we know which element is being inserted
10864   if (!isa<ConstantSDNode>(EltNo))
10865     return SDValue();
10866   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10867
10868   // Canonicalize insert_vector_elt dag nodes.
10869   // Example:
10870   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10871   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10872   //
10873   // Do this only if the child insert_vector node has one use; also
10874   // do this only if indices are both constants and Idx1 < Idx0.
10875   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10876       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10877     unsigned OtherElt =
10878       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10879     if (Elt < OtherElt) {
10880       // Swap nodes.
10881       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10882                                   InVec.getOperand(0), InVal, EltNo);
10883       AddToWorklist(NewOp.getNode());
10884       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10885                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10886     }
10887   }
10888
10889   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10890   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10891   // vector elements.
10892   SmallVector<SDValue, 8> Ops;
10893   // Do not combine these two vectors if the output vector will not replace
10894   // the input vector.
10895   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10896     Ops.append(InVec.getNode()->op_begin(),
10897                InVec.getNode()->op_end());
10898   } else if (InVec.getOpcode() == ISD::UNDEF) {
10899     unsigned NElts = VT.getVectorNumElements();
10900     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10901   } else {
10902     return SDValue();
10903   }
10904
10905   // Insert the element
10906   if (Elt < Ops.size()) {
10907     // All the operands of BUILD_VECTOR must have the same type;
10908     // we enforce that here.
10909     EVT OpVT = Ops[0].getValueType();
10910     if (InVal.getValueType() != OpVT)
10911       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10912                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10913                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10914     Ops[Elt] = InVal;
10915   }
10916
10917   // Return the new vector
10918   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10919 }
10920
10921 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10922     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10923   EVT ResultVT = EVE->getValueType(0);
10924   EVT VecEltVT = InVecVT.getVectorElementType();
10925   unsigned Align = OriginalLoad->getAlignment();
10926   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10927       VecEltVT.getTypeForEVT(*DAG.getContext()));
10928
10929   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10930     return SDValue();
10931
10932   Align = NewAlign;
10933
10934   SDValue NewPtr = OriginalLoad->getBasePtr();
10935   SDValue Offset;
10936   EVT PtrType = NewPtr.getValueType();
10937   MachinePointerInfo MPI;
10938   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10939     int Elt = ConstEltNo->getZExtValue();
10940     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10941     if (TLI.isBigEndian())
10942       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10943     Offset = DAG.getConstant(PtrOff, PtrType);
10944     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10945   } else {
10946     Offset = DAG.getNode(
10947         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10948         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10949     if (TLI.isBigEndian())
10950       Offset = DAG.getNode(
10951           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10952           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10953     MPI = OriginalLoad->getPointerInfo();
10954   }
10955   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10956
10957   // The replacement we need to do here is a little tricky: we need to
10958   // replace an extractelement of a load with a load.
10959   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10960   // Note that this replacement assumes that the extractvalue is the only
10961   // use of the load; that's okay because we don't want to perform this
10962   // transformation in other cases anyway.
10963   SDValue Load;
10964   SDValue Chain;
10965   if (ResultVT.bitsGT(VecEltVT)) {
10966     // If the result type of vextract is wider than the load, then issue an
10967     // extending load instead.
10968     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10969                                                   VecEltVT)
10970                                    ? ISD::ZEXTLOAD
10971                                    : ISD::EXTLOAD;
10972     Load = DAG.getExtLoad(
10973         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10974         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10975         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10976     Chain = Load.getValue(1);
10977   } else {
10978     Load = DAG.getLoad(
10979         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10980         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10981         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10982     Chain = Load.getValue(1);
10983     if (ResultVT.bitsLT(VecEltVT))
10984       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10985     else
10986       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10987   }
10988   WorklistRemover DeadNodes(*this);
10989   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10990   SDValue To[] = { Load, Chain };
10991   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10992   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10993   // worklist explicitly as well.
10994   AddToWorklist(Load.getNode());
10995   AddUsersToWorklist(Load.getNode()); // Add users too
10996   // Make sure to revisit this node to clean it up; it will usually be dead.
10997   AddToWorklist(EVE);
10998   ++OpsNarrowed;
10999   return SDValue(EVE, 0);
11000 }
11001
11002 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11003   // (vextract (scalar_to_vector val, 0) -> val
11004   SDValue InVec = N->getOperand(0);
11005   EVT VT = InVec.getValueType();
11006   EVT NVT = N->getValueType(0);
11007
11008   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11009     // Check if the result type doesn't match the inserted element type. A
11010     // SCALAR_TO_VECTOR may truncate the inserted element and the
11011     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11012     SDValue InOp = InVec.getOperand(0);
11013     if (InOp.getValueType() != NVT) {
11014       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11015       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11016     }
11017     return InOp;
11018   }
11019
11020   SDValue EltNo = N->getOperand(1);
11021   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11022
11023   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11024   // We only perform this optimization before the op legalization phase because
11025   // we may introduce new vector instructions which are not backed by TD
11026   // patterns. For example on AVX, extracting elements from a wide vector
11027   // without using extract_subvector. However, if we can find an underlying
11028   // scalar value, then we can always use that.
11029   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11030       && ConstEltNo) {
11031     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11032     int NumElem = VT.getVectorNumElements();
11033     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11034     // Find the new index to extract from.
11035     int OrigElt = SVOp->getMaskElt(Elt);
11036
11037     // Extracting an undef index is undef.
11038     if (OrigElt == -1)
11039       return DAG.getUNDEF(NVT);
11040
11041     // Select the right vector half to extract from.
11042     SDValue SVInVec;
11043     if (OrigElt < NumElem) {
11044       SVInVec = InVec->getOperand(0);
11045     } else {
11046       SVInVec = InVec->getOperand(1);
11047       OrigElt -= NumElem;
11048     }
11049
11050     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11051       SDValue InOp = SVInVec.getOperand(OrigElt);
11052       if (InOp.getValueType() != NVT) {
11053         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11054         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11055       }
11056
11057       return InOp;
11058     }
11059
11060     // FIXME: We should handle recursing on other vector shuffles and
11061     // scalar_to_vector here as well.
11062
11063     if (!LegalOperations) {
11064       EVT IndexTy = TLI.getVectorIdxTy();
11065       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11066                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
11067     }
11068   }
11069
11070   bool BCNumEltsChanged = false;
11071   EVT ExtVT = VT.getVectorElementType();
11072   EVT LVT = ExtVT;
11073
11074   // If the result of load has to be truncated, then it's not necessarily
11075   // profitable.
11076   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11077     return SDValue();
11078
11079   if (InVec.getOpcode() == ISD::BITCAST) {
11080     // Don't duplicate a load with other uses.
11081     if (!InVec.hasOneUse())
11082       return SDValue();
11083
11084     EVT BCVT = InVec.getOperand(0).getValueType();
11085     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11086       return SDValue();
11087     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11088       BCNumEltsChanged = true;
11089     InVec = InVec.getOperand(0);
11090     ExtVT = BCVT.getVectorElementType();
11091   }
11092
11093   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11094   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11095       ISD::isNormalLoad(InVec.getNode()) &&
11096       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11097     SDValue Index = N->getOperand(1);
11098     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11099       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11100                                                            OrigLoad);
11101   }
11102
11103   // Perform only after legalization to ensure build_vector / vector_shuffle
11104   // optimizations have already been done.
11105   if (!LegalOperations) return SDValue();
11106
11107   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11108   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11109   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11110
11111   if (ConstEltNo) {
11112     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11113
11114     LoadSDNode *LN0 = nullptr;
11115     const ShuffleVectorSDNode *SVN = nullptr;
11116     if (ISD::isNormalLoad(InVec.getNode())) {
11117       LN0 = cast<LoadSDNode>(InVec);
11118     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11119                InVec.getOperand(0).getValueType() == ExtVT &&
11120                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11121       // Don't duplicate a load with other uses.
11122       if (!InVec.hasOneUse())
11123         return SDValue();
11124
11125       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11126     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11127       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11128       // =>
11129       // (load $addr+1*size)
11130
11131       // Don't duplicate a load with other uses.
11132       if (!InVec.hasOneUse())
11133         return SDValue();
11134
11135       // If the bit convert changed the number of elements, it is unsafe
11136       // to examine the mask.
11137       if (BCNumEltsChanged)
11138         return SDValue();
11139
11140       // Select the input vector, guarding against out of range extract vector.
11141       unsigned NumElems = VT.getVectorNumElements();
11142       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11143       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11144
11145       if (InVec.getOpcode() == ISD::BITCAST) {
11146         // Don't duplicate a load with other uses.
11147         if (!InVec.hasOneUse())
11148           return SDValue();
11149
11150         InVec = InVec.getOperand(0);
11151       }
11152       if (ISD::isNormalLoad(InVec.getNode())) {
11153         LN0 = cast<LoadSDNode>(InVec);
11154         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11155         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11156       }
11157     }
11158
11159     // Make sure we found a non-volatile load and the extractelement is
11160     // the only use.
11161     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11162       return SDValue();
11163
11164     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11165     if (Elt == -1)
11166       return DAG.getUNDEF(LVT);
11167
11168     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11169   }
11170
11171   return SDValue();
11172 }
11173
11174 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11175 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11176   // We perform this optimization post type-legalization because
11177   // the type-legalizer often scalarizes integer-promoted vectors.
11178   // Performing this optimization before may create bit-casts which
11179   // will be type-legalized to complex code sequences.
11180   // We perform this optimization only before the operation legalizer because we
11181   // may introduce illegal operations.
11182   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11183     return SDValue();
11184
11185   unsigned NumInScalars = N->getNumOperands();
11186   SDLoc dl(N);
11187   EVT VT = N->getValueType(0);
11188
11189   // Check to see if this is a BUILD_VECTOR of a bunch of values
11190   // which come from any_extend or zero_extend nodes. If so, we can create
11191   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11192   // optimizations. We do not handle sign-extend because we can't fill the sign
11193   // using shuffles.
11194   EVT SourceType = MVT::Other;
11195   bool AllAnyExt = true;
11196
11197   for (unsigned i = 0; i != NumInScalars; ++i) {
11198     SDValue In = N->getOperand(i);
11199     // Ignore undef inputs.
11200     if (In.getOpcode() == ISD::UNDEF) continue;
11201
11202     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11203     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11204
11205     // Abort if the element is not an extension.
11206     if (!ZeroExt && !AnyExt) {
11207       SourceType = MVT::Other;
11208       break;
11209     }
11210
11211     // The input is a ZeroExt or AnyExt. Check the original type.
11212     EVT InTy = In.getOperand(0).getValueType();
11213
11214     // Check that all of the widened source types are the same.
11215     if (SourceType == MVT::Other)
11216       // First time.
11217       SourceType = InTy;
11218     else if (InTy != SourceType) {
11219       // Multiple income types. Abort.
11220       SourceType = MVT::Other;
11221       break;
11222     }
11223
11224     // Check if all of the extends are ANY_EXTENDs.
11225     AllAnyExt &= AnyExt;
11226   }
11227
11228   // In order to have valid types, all of the inputs must be extended from the
11229   // same source type and all of the inputs must be any or zero extend.
11230   // Scalar sizes must be a power of two.
11231   EVT OutScalarTy = VT.getScalarType();
11232   bool ValidTypes = SourceType != MVT::Other &&
11233                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11234                  isPowerOf2_32(SourceType.getSizeInBits());
11235
11236   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11237   // turn into a single shuffle instruction.
11238   if (!ValidTypes)
11239     return SDValue();
11240
11241   bool isLE = TLI.isLittleEndian();
11242   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11243   assert(ElemRatio > 1 && "Invalid element size ratio");
11244   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11245                                DAG.getConstant(0, SourceType);
11246
11247   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11248   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11249
11250   // Populate the new build_vector
11251   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11252     SDValue Cast = N->getOperand(i);
11253     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11254             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11255             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11256     SDValue In;
11257     if (Cast.getOpcode() == ISD::UNDEF)
11258       In = DAG.getUNDEF(SourceType);
11259     else
11260       In = Cast->getOperand(0);
11261     unsigned Index = isLE ? (i * ElemRatio) :
11262                             (i * ElemRatio + (ElemRatio - 1));
11263
11264     assert(Index < Ops.size() && "Invalid index");
11265     Ops[Index] = In;
11266   }
11267
11268   // The type of the new BUILD_VECTOR node.
11269   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11270   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11271          "Invalid vector size");
11272   // Check if the new vector type is legal.
11273   if (!isTypeLegal(VecVT)) return SDValue();
11274
11275   // Make the new BUILD_VECTOR.
11276   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11277
11278   // The new BUILD_VECTOR node has the potential to be further optimized.
11279   AddToWorklist(BV.getNode());
11280   // Bitcast to the desired type.
11281   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11282 }
11283
11284 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11285   EVT VT = N->getValueType(0);
11286
11287   unsigned NumInScalars = N->getNumOperands();
11288   SDLoc dl(N);
11289
11290   EVT SrcVT = MVT::Other;
11291   unsigned Opcode = ISD::DELETED_NODE;
11292   unsigned NumDefs = 0;
11293
11294   for (unsigned i = 0; i != NumInScalars; ++i) {
11295     SDValue In = N->getOperand(i);
11296     unsigned Opc = In.getOpcode();
11297
11298     if (Opc == ISD::UNDEF)
11299       continue;
11300
11301     // If all scalar values are floats and converted from integers.
11302     if (Opcode == ISD::DELETED_NODE &&
11303         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11304       Opcode = Opc;
11305     }
11306
11307     if (Opc != Opcode)
11308       return SDValue();
11309
11310     EVT InVT = In.getOperand(0).getValueType();
11311
11312     // If all scalar values are typed differently, bail out. It's chosen to
11313     // simplify BUILD_VECTOR of integer types.
11314     if (SrcVT == MVT::Other)
11315       SrcVT = InVT;
11316     if (SrcVT != InVT)
11317       return SDValue();
11318     NumDefs++;
11319   }
11320
11321   // If the vector has just one element defined, it's not worth to fold it into
11322   // a vectorized one.
11323   if (NumDefs < 2)
11324     return SDValue();
11325
11326   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11327          && "Should only handle conversion from integer to float.");
11328   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11329
11330   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11331
11332   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11333     return SDValue();
11334
11335   // Just because the floating-point vector type is legal does not necessarily
11336   // mean that the corresponding integer vector type is.
11337   if (!isTypeLegal(NVT))
11338     return SDValue();
11339
11340   SmallVector<SDValue, 8> Opnds;
11341   for (unsigned i = 0; i != NumInScalars; ++i) {
11342     SDValue In = N->getOperand(i);
11343
11344     if (In.getOpcode() == ISD::UNDEF)
11345       Opnds.push_back(DAG.getUNDEF(SrcVT));
11346     else
11347       Opnds.push_back(In.getOperand(0));
11348   }
11349   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11350   AddToWorklist(BV.getNode());
11351
11352   return DAG.getNode(Opcode, dl, VT, BV);
11353 }
11354
11355 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11356   unsigned NumInScalars = N->getNumOperands();
11357   SDLoc dl(N);
11358   EVT VT = N->getValueType(0);
11359
11360   // A vector built entirely of undefs is undef.
11361   if (ISD::allOperandsUndef(N))
11362     return DAG.getUNDEF(VT);
11363
11364   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11365     return V;
11366
11367   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11368     return V;
11369
11370   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11371   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11372   // at most two distinct vectors, turn this into a shuffle node.
11373
11374   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11375   if (!isTypeLegal(VT))
11376     return SDValue();
11377
11378   // May only combine to shuffle after legalize if shuffle is legal.
11379   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11380     return SDValue();
11381
11382   SDValue VecIn1, VecIn2;
11383   bool UsesZeroVector = false;
11384   for (unsigned i = 0; i != NumInScalars; ++i) {
11385     SDValue Op = N->getOperand(i);
11386     // Ignore undef inputs.
11387     if (Op.getOpcode() == ISD::UNDEF) continue;
11388
11389     // See if we can combine this build_vector into a blend with a zero vector.
11390     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11391         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11392         (Op.getOpcode() == ISD::ConstantFP &&
11393         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11394       UsesZeroVector = true;
11395       continue;
11396     }
11397
11398     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11399     // constant index, bail out.
11400     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11401         !isa<ConstantSDNode>(Op.getOperand(1))) {
11402       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11403       break;
11404     }
11405
11406     // We allow up to two distinct input vectors.
11407     SDValue ExtractedFromVec = Op.getOperand(0);
11408     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11409       continue;
11410
11411     if (!VecIn1.getNode()) {
11412       VecIn1 = ExtractedFromVec;
11413     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11414       VecIn2 = ExtractedFromVec;
11415     } else {
11416       // Too many inputs.
11417       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11418       break;
11419     }
11420   }
11421
11422   // If everything is good, we can make a shuffle operation.
11423   if (VecIn1.getNode()) {
11424     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11425     SmallVector<int, 8> Mask;
11426     for (unsigned i = 0; i != NumInScalars; ++i) {
11427       unsigned Opcode = N->getOperand(i).getOpcode();
11428       if (Opcode == ISD::UNDEF) {
11429         Mask.push_back(-1);
11430         continue;
11431       }
11432
11433       // Operands can also be zero.
11434       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11435         assert(UsesZeroVector &&
11436                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11437                "Unexpected node found!");
11438         Mask.push_back(NumInScalars+i);
11439         continue;
11440       }
11441
11442       // If extracting from the first vector, just use the index directly.
11443       SDValue Extract = N->getOperand(i);
11444       SDValue ExtVal = Extract.getOperand(1);
11445       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11446       if (Extract.getOperand(0) == VecIn1) {
11447         Mask.push_back(ExtIndex);
11448         continue;
11449       }
11450
11451       // Otherwise, use InIdx + InputVecSize
11452       Mask.push_back(InNumElements + ExtIndex);
11453     }
11454
11455     // Avoid introducing illegal shuffles with zero.
11456     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11457       return SDValue();
11458
11459     // We can't generate a shuffle node with mismatched input and output types.
11460     // Attempt to transform a single input vector to the correct type.
11461     if ((VT != VecIn1.getValueType())) {
11462       // If the input vector type has a different base type to the output
11463       // vector type, bail out.
11464       EVT VTElemType = VT.getVectorElementType();
11465       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11466           (VecIn2.getNode() &&
11467            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11468         return SDValue();
11469
11470       // If the input vector is too small, widen it.
11471       // We only support widening of vectors which are half the size of the
11472       // output registers. For example XMM->YMM widening on X86 with AVX.
11473       EVT VecInT = VecIn1.getValueType();
11474       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11475         // If we only have one small input, widen it by adding undef values.
11476         if (!VecIn2.getNode())
11477           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11478                                DAG.getUNDEF(VecIn1.getValueType()));
11479         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11480           // If we have two small inputs of the same type, try to concat them.
11481           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11482           VecIn2 = SDValue(nullptr, 0);
11483         } else
11484           return SDValue();
11485       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11486         // If the input vector is too large, try to split it.
11487         // We don't support having two input vectors that are too large.
11488         // If the zero vector was used, we can not split the vector,
11489         // since we'd need 3 inputs.
11490         if (UsesZeroVector || VecIn2.getNode())
11491           return SDValue();
11492
11493         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11494           return SDValue();
11495
11496         // Try to replace VecIn1 with two extract_subvectors
11497         // No need to update the masks, they should still be correct.
11498         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11499           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11500         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11501           DAG.getConstant(0, TLI.getVectorIdxTy()));
11502       } else
11503         return SDValue();
11504     }
11505
11506     if (UsesZeroVector)
11507       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11508                                 DAG.getConstantFP(0.0, VT);
11509     else
11510       // If VecIn2 is unused then change it to undef.
11511       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11512
11513     // Check that we were able to transform all incoming values to the same
11514     // type.
11515     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11516         VecIn1.getValueType() != VT)
11517           return SDValue();
11518
11519     // Return the new VECTOR_SHUFFLE node.
11520     SDValue Ops[2];
11521     Ops[0] = VecIn1;
11522     Ops[1] = VecIn2;
11523     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11524   }
11525
11526   return SDValue();
11527 }
11528
11529 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11530   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11531   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11532   // inputs come from at most two distinct vectors, turn this into a shuffle
11533   // node.
11534
11535   // If we only have one input vector, we don't need to do any concatenation.
11536   if (N->getNumOperands() == 1)
11537     return N->getOperand(0);
11538
11539   // Check if all of the operands are undefs.
11540   EVT VT = N->getValueType(0);
11541   if (ISD::allOperandsUndef(N))
11542     return DAG.getUNDEF(VT);
11543
11544   // Optimize concat_vectors where one of the vectors is undef.
11545   if (N->getNumOperands() == 2 &&
11546       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11547     SDValue In = N->getOperand(0);
11548     assert(In.getValueType().isVector() && "Must concat vectors");
11549
11550     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11551     if (In->getOpcode() == ISD::BITCAST &&
11552         !In->getOperand(0)->getValueType(0).isVector()) {
11553       SDValue Scalar = In->getOperand(0);
11554       EVT SclTy = Scalar->getValueType(0);
11555
11556       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11557         return SDValue();
11558
11559       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11560                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11561       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11562         return SDValue();
11563
11564       SDLoc dl = SDLoc(N);
11565       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11566       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11567     }
11568   }
11569
11570   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11571   // We have already tested above for an UNDEF only concatenation.
11572   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11573   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11574   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11575     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11576   };
11577   bool AllBuildVectorsOrUndefs =
11578       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11579   if (AllBuildVectorsOrUndefs) {
11580     SmallVector<SDValue, 8> Opnds;
11581     EVT SVT = VT.getScalarType();
11582
11583     EVT MinVT = SVT;
11584     if (!SVT.isFloatingPoint()) {
11585       // If BUILD_VECTOR are from built from integer, they may have different
11586       // operand types. Get the smallest type and truncate all operands to it.
11587       bool FoundMinVT = false;
11588       for (const SDValue &Op : N->ops())
11589         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11590           EVT OpSVT = Op.getOperand(0)->getValueType(0);
11591           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11592           FoundMinVT = true;
11593         }
11594       assert(FoundMinVT && "Concat vector type mismatch");
11595     }
11596
11597     for (const SDValue &Op : N->ops()) {
11598       EVT OpVT = Op.getValueType();
11599       unsigned NumElts = OpVT.getVectorNumElements();
11600
11601       if (ISD::UNDEF == Op.getOpcode())
11602         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11603
11604       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11605         if (SVT.isFloatingPoint()) {
11606           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11607           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11608         } else {
11609           for (unsigned i = 0; i != NumElts; ++i)
11610             Opnds.push_back(
11611                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11612         }
11613       }
11614     }
11615
11616     assert(VT.getVectorNumElements() == Opnds.size() &&
11617            "Concat vector type mismatch");
11618     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11619   }
11620
11621   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11622   // nodes often generate nop CONCAT_VECTOR nodes.
11623   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11624   // place the incoming vectors at the exact same location.
11625   SDValue SingleSource = SDValue();
11626   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11627
11628   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11629     SDValue Op = N->getOperand(i);
11630
11631     if (Op.getOpcode() == ISD::UNDEF)
11632       continue;
11633
11634     // Check if this is the identity extract:
11635     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11636       return SDValue();
11637
11638     // Find the single incoming vector for the extract_subvector.
11639     if (SingleSource.getNode()) {
11640       if (Op.getOperand(0) != SingleSource)
11641         return SDValue();
11642     } else {
11643       SingleSource = Op.getOperand(0);
11644
11645       // Check the source type is the same as the type of the result.
11646       // If not, this concat may extend the vector, so we can not
11647       // optimize it away.
11648       if (SingleSource.getValueType() != N->getValueType(0))
11649         return SDValue();
11650     }
11651
11652     unsigned IdentityIndex = i * PartNumElem;
11653     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11654     // The extract index must be constant.
11655     if (!CS)
11656       return SDValue();
11657
11658     // Check that we are reading from the identity index.
11659     if (CS->getZExtValue() != IdentityIndex)
11660       return SDValue();
11661   }
11662
11663   if (SingleSource.getNode())
11664     return SingleSource;
11665
11666   return SDValue();
11667 }
11668
11669 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11670   EVT NVT = N->getValueType(0);
11671   SDValue V = N->getOperand(0);
11672
11673   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11674     // Combine:
11675     //    (extract_subvec (concat V1, V2, ...), i)
11676     // Into:
11677     //    Vi if possible
11678     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11679     // type.
11680     if (V->getOperand(0).getValueType() != NVT)
11681       return SDValue();
11682     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11683     unsigned NumElems = NVT.getVectorNumElements();
11684     assert((Idx % NumElems) == 0 &&
11685            "IDX in concat is not a multiple of the result vector length.");
11686     return V->getOperand(Idx / NumElems);
11687   }
11688
11689   // Skip bitcasting
11690   if (V->getOpcode() == ISD::BITCAST)
11691     V = V.getOperand(0);
11692
11693   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11694     SDLoc dl(N);
11695     // Handle only simple case where vector being inserted and vector
11696     // being extracted are of same type, and are half size of larger vectors.
11697     EVT BigVT = V->getOperand(0).getValueType();
11698     EVT SmallVT = V->getOperand(1).getValueType();
11699     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11700       return SDValue();
11701
11702     // Only handle cases where both indexes are constants with the same type.
11703     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11704     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11705
11706     if (InsIdx && ExtIdx &&
11707         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11708         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11709       // Combine:
11710       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11711       // Into:
11712       //    indices are equal or bit offsets are equal => V1
11713       //    otherwise => (extract_subvec V1, ExtIdx)
11714       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11715           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11716         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11717       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11718                          DAG.getNode(ISD::BITCAST, dl,
11719                                      N->getOperand(0).getValueType(),
11720                                      V->getOperand(0)), N->getOperand(1));
11721     }
11722   }
11723
11724   return SDValue();
11725 }
11726
11727 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11728                                                  SDValue V, SelectionDAG &DAG) {
11729   SDLoc DL(V);
11730   EVT VT = V.getValueType();
11731
11732   switch (V.getOpcode()) {
11733   default:
11734     return V;
11735
11736   case ISD::CONCAT_VECTORS: {
11737     EVT OpVT = V->getOperand(0).getValueType();
11738     int OpSize = OpVT.getVectorNumElements();
11739     SmallBitVector OpUsedElements(OpSize, false);
11740     bool FoundSimplification = false;
11741     SmallVector<SDValue, 4> NewOps;
11742     NewOps.reserve(V->getNumOperands());
11743     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11744       SDValue Op = V->getOperand(i);
11745       bool OpUsed = false;
11746       for (int j = 0; j < OpSize; ++j)
11747         if (UsedElements[i * OpSize + j]) {
11748           OpUsedElements[j] = true;
11749           OpUsed = true;
11750         }
11751       NewOps.push_back(
11752           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11753                  : DAG.getUNDEF(OpVT));
11754       FoundSimplification |= Op == NewOps.back();
11755       OpUsedElements.reset();
11756     }
11757     if (FoundSimplification)
11758       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11759     return V;
11760   }
11761
11762   case ISD::INSERT_SUBVECTOR: {
11763     SDValue BaseV = V->getOperand(0);
11764     SDValue SubV = V->getOperand(1);
11765     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11766     if (!IdxN)
11767       return V;
11768
11769     int SubSize = SubV.getValueType().getVectorNumElements();
11770     int Idx = IdxN->getZExtValue();
11771     bool SubVectorUsed = false;
11772     SmallBitVector SubUsedElements(SubSize, false);
11773     for (int i = 0; i < SubSize; ++i)
11774       if (UsedElements[i + Idx]) {
11775         SubVectorUsed = true;
11776         SubUsedElements[i] = true;
11777         UsedElements[i + Idx] = false;
11778       }
11779
11780     // Now recurse on both the base and sub vectors.
11781     SDValue SimplifiedSubV =
11782         SubVectorUsed
11783             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11784             : DAG.getUNDEF(SubV.getValueType());
11785     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11786     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11787       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11788                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11789     return V;
11790   }
11791   }
11792 }
11793
11794 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11795                                        SDValue N1, SelectionDAG &DAG) {
11796   EVT VT = SVN->getValueType(0);
11797   int NumElts = VT.getVectorNumElements();
11798   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11799   for (int M : SVN->getMask())
11800     if (M >= 0 && M < NumElts)
11801       N0UsedElements[M] = true;
11802     else if (M >= NumElts)
11803       N1UsedElements[M - NumElts] = true;
11804
11805   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11806   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11807   if (S0 == N0 && S1 == N1)
11808     return SDValue();
11809
11810   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11811 }
11812
11813 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11814 // or turn a shuffle of a single concat into simpler shuffle then concat.
11815 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11816   EVT VT = N->getValueType(0);
11817   unsigned NumElts = VT.getVectorNumElements();
11818
11819   SDValue N0 = N->getOperand(0);
11820   SDValue N1 = N->getOperand(1);
11821   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11822
11823   SmallVector<SDValue, 4> Ops;
11824   EVT ConcatVT = N0.getOperand(0).getValueType();
11825   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11826   unsigned NumConcats = NumElts / NumElemsPerConcat;
11827
11828   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11829   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11830   // half vector elements.
11831   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11832       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11833                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11834     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11835                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11836     N1 = DAG.getUNDEF(ConcatVT);
11837     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11838   }
11839
11840   // Look at every vector that's inserted. We're looking for exact
11841   // subvector-sized copies from a concatenated vector
11842   for (unsigned I = 0; I != NumConcats; ++I) {
11843     // Make sure we're dealing with a copy.
11844     unsigned Begin = I * NumElemsPerConcat;
11845     bool AllUndef = true, NoUndef = true;
11846     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11847       if (SVN->getMaskElt(J) >= 0)
11848         AllUndef = false;
11849       else
11850         NoUndef = false;
11851     }
11852
11853     if (NoUndef) {
11854       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11855         return SDValue();
11856
11857       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11858         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11859           return SDValue();
11860
11861       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11862       if (FirstElt < N0.getNumOperands())
11863         Ops.push_back(N0.getOperand(FirstElt));
11864       else
11865         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11866
11867     } else if (AllUndef) {
11868       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11869     } else { // Mixed with general masks and undefs, can't do optimization.
11870       return SDValue();
11871     }
11872   }
11873
11874   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11875 }
11876
11877 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11878   EVT VT = N->getValueType(0);
11879   unsigned NumElts = VT.getVectorNumElements();
11880
11881   SDValue N0 = N->getOperand(0);
11882   SDValue N1 = N->getOperand(1);
11883
11884   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11885
11886   // Canonicalize shuffle undef, undef -> undef
11887   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11888     return DAG.getUNDEF(VT);
11889
11890   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11891
11892   // Canonicalize shuffle v, v -> v, undef
11893   if (N0 == N1) {
11894     SmallVector<int, 8> NewMask;
11895     for (unsigned i = 0; i != NumElts; ++i) {
11896       int Idx = SVN->getMaskElt(i);
11897       if (Idx >= (int)NumElts) Idx -= NumElts;
11898       NewMask.push_back(Idx);
11899     }
11900     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11901                                 &NewMask[0]);
11902   }
11903
11904   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11905   if (N0.getOpcode() == ISD::UNDEF) {
11906     SmallVector<int, 8> NewMask;
11907     for (unsigned i = 0; i != NumElts; ++i) {
11908       int Idx = SVN->getMaskElt(i);
11909       if (Idx >= 0) {
11910         if (Idx >= (int)NumElts)
11911           Idx -= NumElts;
11912         else
11913           Idx = -1; // remove reference to lhs
11914       }
11915       NewMask.push_back(Idx);
11916     }
11917     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11918                                 &NewMask[0]);
11919   }
11920
11921   // Remove references to rhs if it is undef
11922   if (N1.getOpcode() == ISD::UNDEF) {
11923     bool Changed = false;
11924     SmallVector<int, 8> NewMask;
11925     for (unsigned i = 0; i != NumElts; ++i) {
11926       int Idx = SVN->getMaskElt(i);
11927       if (Idx >= (int)NumElts) {
11928         Idx = -1;
11929         Changed = true;
11930       }
11931       NewMask.push_back(Idx);
11932     }
11933     if (Changed)
11934       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11935   }
11936
11937   // If it is a splat, check if the argument vector is another splat or a
11938   // build_vector.
11939   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11940     SDNode *V = N0.getNode();
11941
11942     // If this is a bit convert that changes the element type of the vector but
11943     // not the number of vector elements, look through it.  Be careful not to
11944     // look though conversions that change things like v4f32 to v2f64.
11945     if (V->getOpcode() == ISD::BITCAST) {
11946       SDValue ConvInput = V->getOperand(0);
11947       if (ConvInput.getValueType().isVector() &&
11948           ConvInput.getValueType().getVectorNumElements() == NumElts)
11949         V = ConvInput.getNode();
11950     }
11951
11952     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11953       assert(V->getNumOperands() == NumElts &&
11954              "BUILD_VECTOR has wrong number of operands");
11955       SDValue Base;
11956       bool AllSame = true;
11957       for (unsigned i = 0; i != NumElts; ++i) {
11958         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11959           Base = V->getOperand(i);
11960           break;
11961         }
11962       }
11963       // Splat of <u, u, u, u>, return <u, u, u, u>
11964       if (!Base.getNode())
11965         return N0;
11966       for (unsigned i = 0; i != NumElts; ++i) {
11967         if (V->getOperand(i) != Base) {
11968           AllSame = false;
11969           break;
11970         }
11971       }
11972       // Splat of <x, x, x, x>, return <x, x, x, x>
11973       if (AllSame)
11974         return N0;
11975
11976       // Canonicalize any other splat as a build_vector.
11977       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11978       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11979       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11980                                   V->getValueType(0), Ops);
11981
11982       // We may have jumped through bitcasts, so the type of the
11983       // BUILD_VECTOR may not match the type of the shuffle.
11984       if (V->getValueType(0) != VT)
11985           NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11986       return NewBV;
11987     }
11988   }
11989
11990   // There are various patterns used to build up a vector from smaller vectors,
11991   // subvectors, or elements. Scan chains of these and replace unused insertions
11992   // or components with undef.
11993   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11994     return S;
11995
11996   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11997       Level < AfterLegalizeVectorOps &&
11998       (N1.getOpcode() == ISD::UNDEF ||
11999       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12000        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12001     SDValue V = partitionShuffleOfConcats(N, DAG);
12002
12003     if (V.getNode())
12004       return V;
12005   }
12006
12007   // If this shuffle only has a single input that is a bitcasted shuffle,
12008   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12009   // back to their original types.
12010   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12011       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12012       TLI.isTypeLegal(VT)) {
12013
12014     // Peek through the bitcast only if there is one user.
12015     SDValue BC0 = N0;
12016     while (BC0.getOpcode() == ISD::BITCAST) {
12017       if (!BC0.hasOneUse())
12018         break;
12019       BC0 = BC0.getOperand(0);
12020     }
12021
12022     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12023       if (Scale == 1)
12024         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12025
12026       SmallVector<int, 8> NewMask;
12027       for (int M : Mask)
12028         for (int s = 0; s != Scale; ++s)
12029           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12030       return NewMask;
12031     };
12032
12033     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12034       EVT SVT = VT.getScalarType();
12035       EVT InnerVT = BC0->getValueType(0);
12036       EVT InnerSVT = InnerVT.getScalarType();
12037
12038       // Determine which shuffle works with the smaller scalar type.
12039       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12040       EVT ScaleSVT = ScaleVT.getScalarType();
12041
12042       if (TLI.isTypeLegal(ScaleVT) &&
12043           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12044           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12045
12046         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12047         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12048
12049         // Scale the shuffle masks to the smaller scalar type.
12050         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12051         SmallVector<int, 8> InnerMask =
12052             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12053         SmallVector<int, 8> OuterMask =
12054             ScaleShuffleMask(SVN->getMask(), OuterScale);
12055
12056         // Merge the shuffle masks.
12057         SmallVector<int, 8> NewMask;
12058         for (int M : OuterMask)
12059           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12060
12061         // Test for shuffle mask legality over both commutations.
12062         SDValue SV0 = BC0->getOperand(0);
12063         SDValue SV1 = BC0->getOperand(1);
12064         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12065         if (!LegalMask) {
12066           std::swap(SV0, SV1);
12067           ShuffleVectorSDNode::commuteMask(NewMask);
12068           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12069         }
12070
12071         if (LegalMask) {
12072           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12073           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12074           return DAG.getNode(
12075               ISD::BITCAST, SDLoc(N), VT,
12076               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12077         }
12078       }
12079     }
12080   }
12081
12082   // Canonicalize shuffles according to rules:
12083   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12084   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12085   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12086   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12087       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12088       TLI.isTypeLegal(VT)) {
12089     // The incoming shuffle must be of the same type as the result of the
12090     // current shuffle.
12091     assert(N1->getOperand(0).getValueType() == VT &&
12092            "Shuffle types don't match");
12093
12094     SDValue SV0 = N1->getOperand(0);
12095     SDValue SV1 = N1->getOperand(1);
12096     bool HasSameOp0 = N0 == SV0;
12097     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12098     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12099       // Commute the operands of this shuffle so that next rule
12100       // will trigger.
12101       return DAG.getCommutedVectorShuffle(*SVN);
12102   }
12103
12104   // Try to fold according to rules:
12105   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12106   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12107   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12108   // Don't try to fold shuffles with illegal type.
12109   // Only fold if this shuffle is the only user of the other shuffle.
12110   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12111       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12112     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12113
12114     // The incoming shuffle must be of the same type as the result of the
12115     // current shuffle.
12116     assert(OtherSV->getOperand(0).getValueType() == VT &&
12117            "Shuffle types don't match");
12118
12119     SDValue SV0, SV1;
12120     SmallVector<int, 4> Mask;
12121     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12122     // operand, and SV1 as the second operand.
12123     for (unsigned i = 0; i != NumElts; ++i) {
12124       int Idx = SVN->getMaskElt(i);
12125       if (Idx < 0) {
12126         // Propagate Undef.
12127         Mask.push_back(Idx);
12128         continue;
12129       }
12130
12131       SDValue CurrentVec;
12132       if (Idx < (int)NumElts) {
12133         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12134         // shuffle mask to identify which vector is actually referenced.
12135         Idx = OtherSV->getMaskElt(Idx);
12136         if (Idx < 0) {
12137           // Propagate Undef.
12138           Mask.push_back(Idx);
12139           continue;
12140         }
12141
12142         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12143                                            : OtherSV->getOperand(1);
12144       } else {
12145         // This shuffle index references an element within N1.
12146         CurrentVec = N1;
12147       }
12148
12149       // Simple case where 'CurrentVec' is UNDEF.
12150       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12151         Mask.push_back(-1);
12152         continue;
12153       }
12154
12155       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12156       // will be the first or second operand of the combined shuffle.
12157       Idx = Idx % NumElts;
12158       if (!SV0.getNode() || SV0 == CurrentVec) {
12159         // Ok. CurrentVec is the left hand side.
12160         // Update the mask accordingly.
12161         SV0 = CurrentVec;
12162         Mask.push_back(Idx);
12163         continue;
12164       }
12165
12166       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12167       if (SV1.getNode() && SV1 != CurrentVec)
12168         return SDValue();
12169
12170       // Ok. CurrentVec is the right hand side.
12171       // Update the mask accordingly.
12172       SV1 = CurrentVec;
12173       Mask.push_back(Idx + NumElts);
12174     }
12175
12176     // Check if all indices in Mask are Undef. In case, propagate Undef.
12177     bool isUndefMask = true;
12178     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12179       isUndefMask &= Mask[i] < 0;
12180
12181     if (isUndefMask)
12182       return DAG.getUNDEF(VT);
12183
12184     if (!SV0.getNode())
12185       SV0 = DAG.getUNDEF(VT);
12186     if (!SV1.getNode())
12187       SV1 = DAG.getUNDEF(VT);
12188
12189     // Avoid introducing shuffles with illegal mask.
12190     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12191       ShuffleVectorSDNode::commuteMask(Mask);
12192
12193       if (!TLI.isShuffleMaskLegal(Mask, VT))
12194         return SDValue();
12195
12196       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12197       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12198       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12199       std::swap(SV0, SV1);
12200     }
12201
12202     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12203     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12204     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12205     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12206   }
12207
12208   return SDValue();
12209 }
12210
12211 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12212   SDValue InVal = N->getOperand(0);
12213   EVT VT = N->getValueType(0);
12214
12215   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12216   // with a VECTOR_SHUFFLE.
12217   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12218     SDValue InVec = InVal->getOperand(0);
12219     SDValue EltNo = InVal->getOperand(1);
12220
12221     // FIXME: We could support implicit truncation if the shuffle can be
12222     // scaled to a smaller vector scalar type.
12223     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12224     if (C0 && VT == InVec.getValueType() &&
12225         VT.getScalarType() == InVal.getValueType()) {
12226       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12227       int Elt = C0->getZExtValue();
12228       NewMask[0] = Elt;
12229
12230       if (TLI.isShuffleMaskLegal(NewMask, VT))
12231         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12232                                     NewMask);
12233     }
12234   }
12235
12236   return SDValue();
12237 }
12238
12239 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12240   SDValue N0 = N->getOperand(0);
12241   SDValue N2 = N->getOperand(2);
12242
12243   // If the input vector is a concatenation, and the insert replaces
12244   // one of the halves, we can optimize into a single concat_vectors.
12245   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12246       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12247     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12248     EVT VT = N->getValueType(0);
12249
12250     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12251     // (concat_vectors Z, Y)
12252     if (InsIdx == 0)
12253       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12254                          N->getOperand(1), N0.getOperand(1));
12255
12256     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12257     // (concat_vectors X, Z)
12258     if (InsIdx == VT.getVectorNumElements()/2)
12259       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12260                          N0.getOperand(0), N->getOperand(1));
12261   }
12262
12263   return SDValue();
12264 }
12265
12266 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12267 /// with the destination vector and a zero vector.
12268 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12269 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12270 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12271   EVT VT = N->getValueType(0);
12272   SDValue LHS = N->getOperand(0);
12273   SDValue RHS = N->getOperand(1);
12274   SDLoc dl(N);
12275
12276   // Make sure we're not running after operation legalization where it 
12277   // may have custom lowered the vector shuffles.
12278   if (LegalOperations)
12279     return SDValue();
12280
12281   if (N->getOpcode() != ISD::AND)
12282     return SDValue();
12283
12284   if (RHS.getOpcode() == ISD::BITCAST)
12285     RHS = RHS.getOperand(0);
12286
12287   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12288     SmallVector<int, 8> Indices;
12289     unsigned NumElts = RHS.getNumOperands();
12290
12291     for (unsigned i = 0; i != NumElts; ++i) {
12292       SDValue Elt = RHS.getOperand(i);
12293       if (!isa<ConstantSDNode>(Elt))
12294         return SDValue();
12295
12296       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12297         Indices.push_back(i);
12298       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12299         Indices.push_back(NumElts+i);
12300       else
12301         return SDValue();
12302     }
12303
12304     // Let's see if the target supports this vector_shuffle.
12305     EVT RVT = RHS.getValueType();
12306     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12307       return SDValue();
12308
12309     // Return the new VECTOR_SHUFFLE node.
12310     EVT EltVT = RVT.getVectorElementType();
12311     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12312                                    DAG.getConstant(0, EltVT));
12313     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12314     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12315     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12316     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12317   }
12318
12319   return SDValue();
12320 }
12321
12322 /// Visit a binary vector operation, like ADD.
12323 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12324   assert(N->getValueType(0).isVector() &&
12325          "SimplifyVBinOp only works on vectors!");
12326
12327   SDValue LHS = N->getOperand(0);
12328   SDValue RHS = N->getOperand(1);
12329
12330   if (SDValue Shuffle = XformToShuffleWithZero(N))
12331     return Shuffle;
12332
12333   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12334   // this operation.
12335   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12336       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12337     // Check if both vectors are constants. If not bail out.
12338     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12339           cast<BuildVectorSDNode>(RHS)->isConstant()))
12340       return SDValue();
12341
12342     SmallVector<SDValue, 8> Ops;
12343     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12344       SDValue LHSOp = LHS.getOperand(i);
12345       SDValue RHSOp = RHS.getOperand(i);
12346
12347       // Can't fold divide by zero.
12348       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12349           N->getOpcode() == ISD::FDIV) {
12350         if ((RHSOp.getOpcode() == ISD::Constant &&
12351              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12352             (RHSOp.getOpcode() == ISD::ConstantFP &&
12353              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12354           break;
12355       }
12356
12357       EVT VT = LHSOp.getValueType();
12358       EVT RVT = RHSOp.getValueType();
12359       if (RVT != VT) {
12360         // Integer BUILD_VECTOR operands may have types larger than the element
12361         // size (e.g., when the element type is not legal).  Prior to type
12362         // legalization, the types may not match between the two BUILD_VECTORS.
12363         // Truncate one of the operands to make them match.
12364         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12365           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12366         } else {
12367           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12368           VT = RVT;
12369         }
12370       }
12371       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12372                                    LHSOp, RHSOp);
12373       if (FoldOp.getOpcode() != ISD::UNDEF &&
12374           FoldOp.getOpcode() != ISD::Constant &&
12375           FoldOp.getOpcode() != ISD::ConstantFP)
12376         break;
12377       Ops.push_back(FoldOp);
12378       AddToWorklist(FoldOp.getNode());
12379     }
12380
12381     if (Ops.size() == LHS.getNumOperands())
12382       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12383   }
12384
12385   // Type legalization might introduce new shuffles in the DAG.
12386   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12387   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12388   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12389       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12390       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12391       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12392     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12393     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12394
12395     if (SVN0->getMask().equals(SVN1->getMask())) {
12396       EVT VT = N->getValueType(0);
12397       SDValue UndefVector = LHS.getOperand(1);
12398       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12399                                      LHS.getOperand(0), RHS.getOperand(0));
12400       AddUsersToWorklist(N);
12401       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12402                                   &SVN0->getMask()[0]);
12403     }
12404   }
12405
12406   return SDValue();
12407 }
12408
12409 /// Visit a binary vector operation, like FABS/FNEG.
12410 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
12411   assert(N->getValueType(0).isVector() &&
12412          "SimplifyVUnaryOp only works on vectors!");
12413
12414   SDValue N0 = N->getOperand(0);
12415
12416   if (N0.getOpcode() != ISD::BUILD_VECTOR)
12417     return SDValue();
12418
12419   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12420   SmallVector<SDValue, 8> Ops;
12421   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12422     SDValue Op = N0.getOperand(i);
12423     if (Op.getOpcode() != ISD::UNDEF &&
12424         Op.getOpcode() != ISD::ConstantFP)
12425       break;
12426     EVT EltVT = Op.getValueType();
12427     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
12428     if (FoldOp.getOpcode() != ISD::UNDEF &&
12429         FoldOp.getOpcode() != ISD::ConstantFP)
12430       break;
12431     Ops.push_back(FoldOp);
12432     AddToWorklist(FoldOp.getNode());
12433   }
12434
12435   if (Ops.size() != N0.getNumOperands())
12436     return SDValue();
12437
12438   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
12439 }
12440
12441 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12442                                     SDValue N1, SDValue N2){
12443   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12444
12445   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12446                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12447
12448   // If we got a simplified select_cc node back from SimplifySelectCC, then
12449   // break it down into a new SETCC node, and a new SELECT node, and then return
12450   // the SELECT node, since we were called with a SELECT node.
12451   if (SCC.getNode()) {
12452     // Check to see if we got a select_cc back (to turn into setcc/select).
12453     // Otherwise, just return whatever node we got back, like fabs.
12454     if (SCC.getOpcode() == ISD::SELECT_CC) {
12455       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12456                                   N0.getValueType(),
12457                                   SCC.getOperand(0), SCC.getOperand(1),
12458                                   SCC.getOperand(4));
12459       AddToWorklist(SETCC.getNode());
12460       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12461                            SCC.getOperand(2), SCC.getOperand(3));
12462     }
12463
12464     return SCC;
12465   }
12466   return SDValue();
12467 }
12468
12469 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12470 /// being selected between, see if we can simplify the select.  Callers of this
12471 /// should assume that TheSelect is deleted if this returns true.  As such, they
12472 /// should return the appropriate thing (e.g. the node) back to the top-level of
12473 /// the DAG combiner loop to avoid it being looked at.
12474 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12475                                     SDValue RHS) {
12476
12477   // Cannot simplify select with vector condition
12478   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12479
12480   // If this is a select from two identical things, try to pull the operation
12481   // through the select.
12482   if (LHS.getOpcode() != RHS.getOpcode() ||
12483       !LHS.hasOneUse() || !RHS.hasOneUse())
12484     return false;
12485
12486   // If this is a load and the token chain is identical, replace the select
12487   // of two loads with a load through a select of the address to load from.
12488   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12489   // constants have been dropped into the constant pool.
12490   if (LHS.getOpcode() == ISD::LOAD) {
12491     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12492     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12493
12494     // Token chains must be identical.
12495     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12496         // Do not let this transformation reduce the number of volatile loads.
12497         LLD->isVolatile() || RLD->isVolatile() ||
12498         // If this is an EXTLOAD, the VT's must match.
12499         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12500         // If this is an EXTLOAD, the kind of extension must match.
12501         (LLD->getExtensionType() != RLD->getExtensionType() &&
12502          // The only exception is if one of the extensions is anyext.
12503          LLD->getExtensionType() != ISD::EXTLOAD &&
12504          RLD->getExtensionType() != ISD::EXTLOAD) ||
12505         // FIXME: this discards src value information.  This is
12506         // over-conservative. It would be beneficial to be able to remember
12507         // both potential memory locations.  Since we are discarding
12508         // src value info, don't do the transformation if the memory
12509         // locations are not in the default address space.
12510         LLD->getPointerInfo().getAddrSpace() != 0 ||
12511         RLD->getPointerInfo().getAddrSpace() != 0 ||
12512         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12513                                       LLD->getBasePtr().getValueType()))
12514       return false;
12515
12516     // Check that the select condition doesn't reach either load.  If so,
12517     // folding this will induce a cycle into the DAG.  If not, this is safe to
12518     // xform, so create a select of the addresses.
12519     SDValue Addr;
12520     if (TheSelect->getOpcode() == ISD::SELECT) {
12521       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12522       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12523           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12524         return false;
12525       // The loads must not depend on one another.
12526       if (LLD->isPredecessorOf(RLD) ||
12527           RLD->isPredecessorOf(LLD))
12528         return false;
12529       Addr = DAG.getSelect(SDLoc(TheSelect),
12530                            LLD->getBasePtr().getValueType(),
12531                            TheSelect->getOperand(0), LLD->getBasePtr(),
12532                            RLD->getBasePtr());
12533     } else {  // Otherwise SELECT_CC
12534       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12535       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12536
12537       if ((LLD->hasAnyUseOfValue(1) &&
12538            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12539           (RLD->hasAnyUseOfValue(1) &&
12540            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12541         return false;
12542
12543       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12544                          LLD->getBasePtr().getValueType(),
12545                          TheSelect->getOperand(0),
12546                          TheSelect->getOperand(1),
12547                          LLD->getBasePtr(), RLD->getBasePtr(),
12548                          TheSelect->getOperand(4));
12549     }
12550
12551     SDValue Load;
12552     // It is safe to replace the two loads if they have different alignments,
12553     // but the new load must be the minimum (most restrictive) alignment of the
12554     // inputs.
12555     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12556     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12557     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12558       Load = DAG.getLoad(TheSelect->getValueType(0),
12559                          SDLoc(TheSelect),
12560                          // FIXME: Discards pointer and AA info.
12561                          LLD->getChain(), Addr, MachinePointerInfo(),
12562                          LLD->isVolatile(), LLD->isNonTemporal(),
12563                          isInvariant, Alignment);
12564     } else {
12565       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12566                             RLD->getExtensionType() : LLD->getExtensionType(),
12567                             SDLoc(TheSelect),
12568                             TheSelect->getValueType(0),
12569                             // FIXME: Discards pointer and AA info.
12570                             LLD->getChain(), Addr, MachinePointerInfo(),
12571                             LLD->getMemoryVT(), LLD->isVolatile(),
12572                             LLD->isNonTemporal(), isInvariant, Alignment);
12573     }
12574
12575     // Users of the select now use the result of the load.
12576     CombineTo(TheSelect, Load);
12577
12578     // Users of the old loads now use the new load's chain.  We know the
12579     // old-load value is dead now.
12580     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12581     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12582     return true;
12583   }
12584
12585   return false;
12586 }
12587
12588 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12589 /// where 'cond' is the comparison specified by CC.
12590 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12591                                       SDValue N2, SDValue N3,
12592                                       ISD::CondCode CC, bool NotExtCompare) {
12593   // (x ? y : y) -> y.
12594   if (N2 == N3) return N2;
12595
12596   EVT VT = N2.getValueType();
12597   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12598   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12599   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12600
12601   // Determine if the condition we're dealing with is constant
12602   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12603                               N0, N1, CC, DL, false);
12604   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12605   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12606
12607   // fold select_cc true, x, y -> x
12608   if (SCCC && !SCCC->isNullValue())
12609     return N2;
12610   // fold select_cc false, x, y -> y
12611   if (SCCC && SCCC->isNullValue())
12612     return N3;
12613
12614   // Check to see if we can simplify the select into an fabs node
12615   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12616     // Allow either -0.0 or 0.0
12617     if (CFP->getValueAPF().isZero()) {
12618       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12619       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12620           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12621           N2 == N3.getOperand(0))
12622         return DAG.getNode(ISD::FABS, DL, VT, N0);
12623
12624       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12625       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12626           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12627           N2.getOperand(0) == N3)
12628         return DAG.getNode(ISD::FABS, DL, VT, N3);
12629     }
12630   }
12631
12632   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12633   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12634   // in it.  This is a win when the constant is not otherwise available because
12635   // it replaces two constant pool loads with one.  We only do this if the FP
12636   // type is known to be legal, because if it isn't, then we are before legalize
12637   // types an we want the other legalization to happen first (e.g. to avoid
12638   // messing with soft float) and if the ConstantFP is not legal, because if
12639   // it is legal, we may not need to store the FP constant in a constant pool.
12640   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12641     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12642       if (TLI.isTypeLegal(N2.getValueType()) &&
12643           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12644                TargetLowering::Legal &&
12645            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12646            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12647           // If both constants have multiple uses, then we won't need to do an
12648           // extra load, they are likely around in registers for other users.
12649           (TV->hasOneUse() || FV->hasOneUse())) {
12650         Constant *Elts[] = {
12651           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12652           const_cast<ConstantFP*>(TV->getConstantFPValue())
12653         };
12654         Type *FPTy = Elts[0]->getType();
12655         const DataLayout &TD = *TLI.getDataLayout();
12656
12657         // Create a ConstantArray of the two constants.
12658         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12659         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12660                                             TD.getPrefTypeAlignment(FPTy));
12661         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12662
12663         // Get the offsets to the 0 and 1 element of the array so that we can
12664         // select between them.
12665         SDValue Zero = DAG.getIntPtrConstant(0);
12666         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12667         SDValue One = DAG.getIntPtrConstant(EltSize);
12668
12669         SDValue Cond = DAG.getSetCC(DL,
12670                                     getSetCCResultType(N0.getValueType()),
12671                                     N0, N1, CC);
12672         AddToWorklist(Cond.getNode());
12673         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12674                                           Cond, One, Zero);
12675         AddToWorklist(CstOffset.getNode());
12676         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12677                             CstOffset);
12678         AddToWorklist(CPIdx.getNode());
12679         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12680                            MachinePointerInfo::getConstantPool(), false,
12681                            false, false, Alignment);
12682
12683       }
12684     }
12685
12686   // Check to see if we can perform the "gzip trick", transforming
12687   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12688   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12689       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12690        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12691     EVT XType = N0.getValueType();
12692     EVT AType = N2.getValueType();
12693     if (XType.bitsGE(AType)) {
12694       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12695       // single-bit constant.
12696       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12697         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12698         ShCtV = XType.getSizeInBits()-ShCtV-1;
12699         SDValue ShCt = DAG.getConstant(ShCtV,
12700                                        getShiftAmountTy(N0.getValueType()));
12701         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12702                                     XType, N0, ShCt);
12703         AddToWorklist(Shift.getNode());
12704
12705         if (XType.bitsGT(AType)) {
12706           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12707           AddToWorklist(Shift.getNode());
12708         }
12709
12710         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12711       }
12712
12713       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12714                                   XType, N0,
12715                                   DAG.getConstant(XType.getSizeInBits()-1,
12716                                          getShiftAmountTy(N0.getValueType())));
12717       AddToWorklist(Shift.getNode());
12718
12719       if (XType.bitsGT(AType)) {
12720         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12721         AddToWorklist(Shift.getNode());
12722       }
12723
12724       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12725     }
12726   }
12727
12728   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12729   // where y is has a single bit set.
12730   // A plaintext description would be, we can turn the SELECT_CC into an AND
12731   // when the condition can be materialized as an all-ones register.  Any
12732   // single bit-test can be materialized as an all-ones register with
12733   // shift-left and shift-right-arith.
12734   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12735       N0->getValueType(0) == VT &&
12736       N1C && N1C->isNullValue() &&
12737       N2C && N2C->isNullValue()) {
12738     SDValue AndLHS = N0->getOperand(0);
12739     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12740     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12741       // Shift the tested bit over the sign bit.
12742       APInt AndMask = ConstAndRHS->getAPIntValue();
12743       SDValue ShlAmt =
12744         DAG.getConstant(AndMask.countLeadingZeros(),
12745                         getShiftAmountTy(AndLHS.getValueType()));
12746       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12747
12748       // Now arithmetic right shift it all the way over, so the result is either
12749       // all-ones, or zero.
12750       SDValue ShrAmt =
12751         DAG.getConstant(AndMask.getBitWidth()-1,
12752                         getShiftAmountTy(Shl.getValueType()));
12753       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12754
12755       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12756     }
12757   }
12758
12759   // fold select C, 16, 0 -> shl C, 4
12760   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12761       TLI.getBooleanContents(N0.getValueType()) ==
12762           TargetLowering::ZeroOrOneBooleanContent) {
12763
12764     // If the caller doesn't want us to simplify this into a zext of a compare,
12765     // don't do it.
12766     if (NotExtCompare && N2C->getAPIntValue() == 1)
12767       return SDValue();
12768
12769     // Get a SetCC of the condition
12770     // NOTE: Don't create a SETCC if it's not legal on this target.
12771     if (!LegalOperations ||
12772         TLI.isOperationLegal(ISD::SETCC,
12773           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12774       SDValue Temp, SCC;
12775       // cast from setcc result type to select result type
12776       if (LegalTypes) {
12777         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12778                             N0, N1, CC);
12779         if (N2.getValueType().bitsLT(SCC.getValueType()))
12780           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12781                                         N2.getValueType());
12782         else
12783           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12784                              N2.getValueType(), SCC);
12785       } else {
12786         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12787         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12788                            N2.getValueType(), SCC);
12789       }
12790
12791       AddToWorklist(SCC.getNode());
12792       AddToWorklist(Temp.getNode());
12793
12794       if (N2C->getAPIntValue() == 1)
12795         return Temp;
12796
12797       // shl setcc result by log2 n2c
12798       return DAG.getNode(
12799           ISD::SHL, DL, N2.getValueType(), Temp,
12800           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12801                           getShiftAmountTy(Temp.getValueType())));
12802     }
12803   }
12804
12805   // Check to see if this is the equivalent of setcc
12806   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12807   // otherwise, go ahead with the folds.
12808   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12809     EVT XType = N0.getValueType();
12810     if (!LegalOperations ||
12811         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12812       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12813       if (Res.getValueType() != VT)
12814         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12815       return Res;
12816     }
12817
12818     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12819     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12820         (!LegalOperations ||
12821          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12822       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12823       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12824                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12825                                        getShiftAmountTy(Ctlz.getValueType())));
12826     }
12827     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12828     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12829       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12830                                   XType, DAG.getConstant(0, XType), N0);
12831       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12832       return DAG.getNode(ISD::SRL, DL, XType,
12833                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12834                          DAG.getConstant(XType.getSizeInBits()-1,
12835                                          getShiftAmountTy(XType)));
12836     }
12837     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12838     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12839       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12840                                  DAG.getConstant(XType.getSizeInBits()-1,
12841                                          getShiftAmountTy(N0.getValueType())));
12842       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12843     }
12844   }
12845
12846   // Check to see if this is an integer abs.
12847   // select_cc setg[te] X,  0,  X, -X ->
12848   // select_cc setgt    X, -1,  X, -X ->
12849   // select_cc setl[te] X,  0, -X,  X ->
12850   // select_cc setlt    X,  1, -X,  X ->
12851   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12852   if (N1C) {
12853     ConstantSDNode *SubC = nullptr;
12854     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12855          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12856         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12857       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12858     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12859               (N1C->isOne() && CC == ISD::SETLT)) &&
12860              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12861       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12862
12863     EVT XType = N0.getValueType();
12864     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12865       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12866                                   N0,
12867                                   DAG.getConstant(XType.getSizeInBits()-1,
12868                                          getShiftAmountTy(N0.getValueType())));
12869       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12870                                 XType, N0, Shift);
12871       AddToWorklist(Shift.getNode());
12872       AddToWorklist(Add.getNode());
12873       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12874     }
12875   }
12876
12877   return SDValue();
12878 }
12879
12880 /// This is a stub for TargetLowering::SimplifySetCC.
12881 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12882                                    SDValue N1, ISD::CondCode Cond,
12883                                    SDLoc DL, bool foldBooleans) {
12884   TargetLowering::DAGCombinerInfo
12885     DagCombineInfo(DAG, Level, false, this);
12886   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12887 }
12888
12889 /// Given an ISD::SDIV node expressing a divide by constant, return
12890 /// a DAG expression to select that will generate the same value by multiplying
12891 /// by a magic number.
12892 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12893 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12894   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12895   if (!C)
12896     return SDValue();
12897
12898   // Avoid division by zero.
12899   if (!C->getAPIntValue())
12900     return SDValue();
12901
12902   std::vector<SDNode*> Built;
12903   SDValue S =
12904       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12905
12906   for (SDNode *N : Built)
12907     AddToWorklist(N);
12908   return S;
12909 }
12910
12911 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12912 /// DAG expression that will generate the same value by right shifting.
12913 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12914   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12915   if (!C)
12916     return SDValue();
12917
12918   // Avoid division by zero.
12919   if (!C->getAPIntValue())
12920     return SDValue();
12921
12922   std::vector<SDNode *> Built;
12923   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12924
12925   for (SDNode *N : Built)
12926     AddToWorklist(N);
12927   return S;
12928 }
12929
12930 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12931 /// expression that will generate the same value by multiplying by a magic
12932 /// number.
12933 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12934 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12935   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12936   if (!C)
12937     return SDValue();
12938
12939   // Avoid division by zero.
12940   if (!C->getAPIntValue())
12941     return SDValue();
12942
12943   std::vector<SDNode*> Built;
12944   SDValue S =
12945       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12946
12947   for (SDNode *N : Built)
12948     AddToWorklist(N);
12949   return S;
12950 }
12951
12952 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12953   if (Level >= AfterLegalizeDAG)
12954     return SDValue();
12955
12956   // Expose the DAG combiner to the target combiner implementations.
12957   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12958
12959   unsigned Iterations = 0;
12960   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12961     if (Iterations) {
12962       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12963       // For the reciprocal, we need to find the zero of the function:
12964       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12965       //     =>
12966       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12967       //     does not require additional intermediate precision]
12968       EVT VT = Op.getValueType();
12969       SDLoc DL(Op);
12970       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12971
12972       AddToWorklist(Est.getNode());
12973
12974       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12975       for (unsigned i = 0; i < Iterations; ++i) {
12976         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12977         AddToWorklist(NewEst.getNode());
12978
12979         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12980         AddToWorklist(NewEst.getNode());
12981
12982         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12983         AddToWorklist(NewEst.getNode());
12984
12985         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12986         AddToWorklist(Est.getNode());
12987       }
12988     }
12989     return Est;
12990   }
12991
12992   return SDValue();
12993 }
12994
12995 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12996 /// For the reciprocal sqrt, we need to find the zero of the function:
12997 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12998 ///     =>
12999 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13000 /// As a result, we precompute A/2 prior to the iteration loop.
13001 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13002                                           unsigned Iterations) {
13003   EVT VT = Arg.getValueType();
13004   SDLoc DL(Arg);
13005   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
13006
13007   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13008   // this entire sequence requires only one FP constant.
13009   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13010   AddToWorklist(HalfArg.getNode());
13011
13012   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13013   AddToWorklist(HalfArg.getNode());
13014
13015   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13016   for (unsigned i = 0; i < Iterations; ++i) {
13017     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13018     AddToWorklist(NewEst.getNode());
13019
13020     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13021     AddToWorklist(NewEst.getNode());
13022
13023     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13024     AddToWorklist(NewEst.getNode());
13025
13026     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13027     AddToWorklist(Est.getNode());
13028   }
13029   return Est;
13030 }
13031
13032 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13033 /// For the reciprocal sqrt, we need to find the zero of the function:
13034 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13035 ///     =>
13036 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13037 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13038                                           unsigned Iterations) {
13039   EVT VT = Arg.getValueType();
13040   SDLoc DL(Arg);
13041   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13042   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13043
13044   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13045   for (unsigned i = 0; i < Iterations; ++i) {
13046     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13047     AddToWorklist(HalfEst.getNode());
13048
13049     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13050     AddToWorklist(Est.getNode());
13051
13052     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13053     AddToWorklist(Est.getNode());
13054
13055     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13056     AddToWorklist(Est.getNode());
13057
13058     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13059     AddToWorklist(Est.getNode());
13060   }
13061   return Est;
13062 }
13063
13064 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13065   if (Level >= AfterLegalizeDAG)
13066     return SDValue();
13067
13068   // Expose the DAG combiner to the target combiner implementations.
13069   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13070   unsigned Iterations = 0;
13071   bool UseOneConstNR = false;
13072   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13073     AddToWorklist(Est.getNode());
13074     if (Iterations) {
13075       Est = UseOneConstNR ?
13076         BuildRsqrtNROneConst(Op, Est, Iterations) :
13077         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13078     }
13079     return Est;
13080   }
13081
13082   return SDValue();
13083 }
13084
13085 /// Return true if base is a frame index, which is known not to alias with
13086 /// anything but itself.  Provides base object and offset as results.
13087 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13088                            const GlobalValue *&GV, const void *&CV) {
13089   // Assume it is a primitive operation.
13090   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13091
13092   // If it's an adding a simple constant then integrate the offset.
13093   if (Base.getOpcode() == ISD::ADD) {
13094     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13095       Base = Base.getOperand(0);
13096       Offset += C->getZExtValue();
13097     }
13098   }
13099
13100   // Return the underlying GlobalValue, and update the Offset.  Return false
13101   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13102   // by multiple nodes with different offsets.
13103   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13104     GV = G->getGlobal();
13105     Offset += G->getOffset();
13106     return false;
13107   }
13108
13109   // Return the underlying Constant value, and update the Offset.  Return false
13110   // for ConstantSDNodes since the same constant pool entry may be represented
13111   // by multiple nodes with different offsets.
13112   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13113     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13114                                          : (const void *)C->getConstVal();
13115     Offset += C->getOffset();
13116     return false;
13117   }
13118   // If it's any of the following then it can't alias with anything but itself.
13119   return isa<FrameIndexSDNode>(Base);
13120 }
13121
13122 /// Return true if there is any possibility that the two addresses overlap.
13123 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13124   // If they are the same then they must be aliases.
13125   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13126
13127   // If they are both volatile then they cannot be reordered.
13128   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13129
13130   // Gather base node and offset information.
13131   SDValue Base1, Base2;
13132   int64_t Offset1, Offset2;
13133   const GlobalValue *GV1, *GV2;
13134   const void *CV1, *CV2;
13135   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13136                                       Base1, Offset1, GV1, CV1);
13137   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13138                                       Base2, Offset2, GV2, CV2);
13139
13140   // If they have a same base address then check to see if they overlap.
13141   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13142     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13143              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13144
13145   // It is possible for different frame indices to alias each other, mostly
13146   // when tail call optimization reuses return address slots for arguments.
13147   // To catch this case, look up the actual index of frame indices to compute
13148   // the real alias relationship.
13149   if (isFrameIndex1 && isFrameIndex2) {
13150     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13151     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13152     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13153     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13154              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13155   }
13156
13157   // Otherwise, if we know what the bases are, and they aren't identical, then
13158   // we know they cannot alias.
13159   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13160     return false;
13161
13162   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13163   // compared to the size and offset of the access, we may be able to prove they
13164   // do not alias.  This check is conservative for now to catch cases created by
13165   // splitting vector types.
13166   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13167       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13168       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13169        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13170       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13171     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13172     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13173
13174     // There is no overlap between these relatively aligned accesses of similar
13175     // size, return no alias.
13176     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13177         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13178       return false;
13179   }
13180
13181   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13182                    ? CombinerGlobalAA
13183                    : DAG.getSubtarget().useAA();
13184 #ifndef NDEBUG
13185   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13186       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13187     UseAA = false;
13188 #endif
13189   if (UseAA &&
13190       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13191     // Use alias analysis information.
13192     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13193                                  Op1->getSrcValueOffset());
13194     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13195         Op0->getSrcValueOffset() - MinOffset;
13196     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13197         Op1->getSrcValueOffset() - MinOffset;
13198     AliasAnalysis::AliasResult AAResult =
13199         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13200                                          Overlap1,
13201                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13202                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13203                                          Overlap2,
13204                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13205     if (AAResult == AliasAnalysis::NoAlias)
13206       return false;
13207   }
13208
13209   // Otherwise we have to assume they alias.
13210   return true;
13211 }
13212
13213 /// Walk up chain skipping non-aliasing memory nodes,
13214 /// looking for aliasing nodes and adding them to the Aliases vector.
13215 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13216                                    SmallVectorImpl<SDValue> &Aliases) {
13217   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13218   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13219
13220   // Get alias information for node.
13221   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13222
13223   // Starting off.
13224   Chains.push_back(OriginalChain);
13225   unsigned Depth = 0;
13226
13227   // Look at each chain and determine if it is an alias.  If so, add it to the
13228   // aliases list.  If not, then continue up the chain looking for the next
13229   // candidate.
13230   while (!Chains.empty()) {
13231     SDValue Chain = Chains.back();
13232     Chains.pop_back();
13233
13234     // For TokenFactor nodes, look at each operand and only continue up the
13235     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13236     // find more and revert to original chain since the xform is unlikely to be
13237     // profitable.
13238     //
13239     // FIXME: The depth check could be made to return the last non-aliasing
13240     // chain we found before we hit a tokenfactor rather than the original
13241     // chain.
13242     if (Depth > 6 || Aliases.size() == 2) {
13243       Aliases.clear();
13244       Aliases.push_back(OriginalChain);
13245       return;
13246     }
13247
13248     // Don't bother if we've been before.
13249     if (!Visited.insert(Chain.getNode()).second)
13250       continue;
13251
13252     switch (Chain.getOpcode()) {
13253     case ISD::EntryToken:
13254       // Entry token is ideal chain operand, but handled in FindBetterChain.
13255       break;
13256
13257     case ISD::LOAD:
13258     case ISD::STORE: {
13259       // Get alias information for Chain.
13260       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13261           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13262
13263       // If chain is alias then stop here.
13264       if (!(IsLoad && IsOpLoad) &&
13265           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13266         Aliases.push_back(Chain);
13267       } else {
13268         // Look further up the chain.
13269         Chains.push_back(Chain.getOperand(0));
13270         ++Depth;
13271       }
13272       break;
13273     }
13274
13275     case ISD::TokenFactor:
13276       // We have to check each of the operands of the token factor for "small"
13277       // token factors, so we queue them up.  Adding the operands to the queue
13278       // (stack) in reverse order maintains the original order and increases the
13279       // likelihood that getNode will find a matching token factor (CSE.)
13280       if (Chain.getNumOperands() > 16) {
13281         Aliases.push_back(Chain);
13282         break;
13283       }
13284       for (unsigned n = Chain.getNumOperands(); n;)
13285         Chains.push_back(Chain.getOperand(--n));
13286       ++Depth;
13287       break;
13288
13289     default:
13290       // For all other instructions we will just have to take what we can get.
13291       Aliases.push_back(Chain);
13292       break;
13293     }
13294   }
13295
13296   // We need to be careful here to also search for aliases through the
13297   // value operand of a store, etc. Consider the following situation:
13298   //   Token1 = ...
13299   //   L1 = load Token1, %52
13300   //   S1 = store Token1, L1, %51
13301   //   L2 = load Token1, %52+8
13302   //   S2 = store Token1, L2, %51+8
13303   //   Token2 = Token(S1, S2)
13304   //   L3 = load Token2, %53
13305   //   S3 = store Token2, L3, %52
13306   //   L4 = load Token2, %53+8
13307   //   S4 = store Token2, L4, %52+8
13308   // If we search for aliases of S3 (which loads address %52), and we look
13309   // only through the chain, then we'll miss the trivial dependence on L1
13310   // (which also loads from %52). We then might change all loads and
13311   // stores to use Token1 as their chain operand, which could result in
13312   // copying %53 into %52 before copying %52 into %51 (which should
13313   // happen first).
13314   //
13315   // The problem is, however, that searching for such data dependencies
13316   // can become expensive, and the cost is not directly related to the
13317   // chain depth. Instead, we'll rule out such configurations here by
13318   // insisting that we've visited all chain users (except for users
13319   // of the original chain, which is not necessary). When doing this,
13320   // we need to look through nodes we don't care about (otherwise, things
13321   // like register copies will interfere with trivial cases).
13322
13323   SmallVector<const SDNode *, 16> Worklist;
13324   for (const SDNode *N : Visited)
13325     if (N != OriginalChain.getNode())
13326       Worklist.push_back(N);
13327
13328   while (!Worklist.empty()) {
13329     const SDNode *M = Worklist.pop_back_val();
13330
13331     // We have already visited M, and want to make sure we've visited any uses
13332     // of M that we care about. For uses that we've not visisted, and don't
13333     // care about, queue them to the worklist.
13334
13335     for (SDNode::use_iterator UI = M->use_begin(),
13336          UIE = M->use_end(); UI != UIE; ++UI)
13337       if (UI.getUse().getValueType() == MVT::Other &&
13338           Visited.insert(*UI).second) {
13339         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13340           // We've not visited this use, and we care about it (it could have an
13341           // ordering dependency with the original node).
13342           Aliases.clear();
13343           Aliases.push_back(OriginalChain);
13344           return;
13345         }
13346
13347         // We've not visited this use, but we don't care about it. Mark it as
13348         // visited and enqueue it to the worklist.
13349         Worklist.push_back(*UI);
13350       }
13351   }
13352 }
13353
13354 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13355 /// (aliasing node.)
13356 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13357   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13358
13359   // Accumulate all the aliases to this node.
13360   GatherAllAliases(N, OldChain, Aliases);
13361
13362   // If no operands then chain to entry token.
13363   if (Aliases.size() == 0)
13364     return DAG.getEntryNode();
13365
13366   // If a single operand then chain to it.  We don't need to revisit it.
13367   if (Aliases.size() == 1)
13368     return Aliases[0];
13369
13370   // Construct a custom tailored token factor.
13371   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13372 }
13373
13374 /// This is the entry point for the file.
13375 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13376                            CodeGenOpt::Level OptLevel) {
13377   /// This is the main entry point to this class.
13378   DAGCombiner(*this, AA, OptLevel).Run(Level);
13379 }