70f6185964cd3fa347ccc085c7bba248d0e95b6b
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310
311     SDValue XformToShuffleWithZero(SDNode *N);
312     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
313
314     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
315
316     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
317     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
318     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
319     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
320                              SDValue N3, ISD::CondCode CC,
321                              bool NotExtCompare = false);
322     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
323                           SDLoc DL, bool foldBooleans = true);
324
325     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
326                            SDValue &CC) const;
327     bool isOneUseSetCC(SDValue N) const;
328
329     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
330                                          unsigned HiOp);
331     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
332     SDValue CombineExtLoad(SDNode *N);
333     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
334     SDValue BuildSDIV(SDNode *N);
335     SDValue BuildSDIVPow2(SDNode *N);
336     SDValue BuildUDIV(SDNode *N);
337     SDValue BuildReciprocalEstimate(SDValue Op);
338     SDValue BuildRsqrtEstimate(SDValue Op);
339     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
340     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
341     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
342                                bool DemandHighBits = true);
343     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
344     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
345                               SDValue InnerPos, SDValue InnerNeg,
346                               unsigned PosOpcode, unsigned NegOpcode,
347                               SDLoc DL);
348     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
349     SDValue ReduceLoadWidth(SDNode *N);
350     SDValue ReduceLoadOpStoreWidth(SDNode *N);
351     SDValue TransformFPLoadStorePair(SDNode *N);
352     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
353     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
354
355     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
356
357     /// Walk up chain skipping non-aliasing memory nodes,
358     /// looking for aliasing nodes and adding them to the Aliases vector.
359     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
360                           SmallVectorImpl<SDValue> &Aliases);
361
362     /// Return true if there is any possibility that the two addresses overlap.
363     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
364
365     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
366     /// chain (aliasing node.)
367     SDValue FindBetterChain(SDNode *N, SDValue Chain);
368
369     /// Holds a pointer to an LSBaseSDNode as well as information on where it
370     /// is located in a sequence of memory operations connected by a chain.
371     struct MemOpLink {
372       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
373       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
374       // Ptr to the mem node.
375       LSBaseSDNode *MemNode;
376       // Offset from the base ptr.
377       int64_t OffsetFromBase;
378       // What is the sequence number of this mem node.
379       // Lowest mem operand in the DAG starts at zero.
380       unsigned SequenceNum;
381     };
382
383     /// This is a helper function for MergeConsecutiveStores. When the source
384     /// elements of the consecutive stores are all constants or all extracted
385     /// vector elements, try to merge them into one larger store.
386     /// \return True if a merged store was created.
387     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
388                                          EVT MemVT, unsigned NumElem,
389                                          bool IsConstantSrc, bool UseVector);
390
391     /// Merge consecutive store operations into a wide store.
392     /// This optimization uses wide integers or vectors when possible.
393     /// \return True if some memory operations were changed.
394     bool MergeConsecutiveStores(StoreSDNode *N);
395
396     /// \brief Try to transform a truncation where C is a constant:
397     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
398     ///
399     /// \p N needs to be a truncation and its first operand an AND. Other
400     /// requirements are checked by the function (e.g. that trunc is
401     /// single-use) and if missed an empty SDValue is returned.
402     SDValue distributeTruncateThroughAnd(SDNode *N);
403
404   public:
405     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
406         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
407           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
408       auto *F = DAG.getMachineFunction().getFunction();
409       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
410                     F->hasFnAttribute(Attribute::MinSize);
411     }
412
413     /// Runs the dag combiner on all nodes in the work list
414     void Run(CombineLevel AtLevel);
415
416     SelectionDAG &getDAG() const { return DAG; }
417
418     /// Returns a type large enough to hold any valid shift amount - before type
419     /// legalization these can be huge.
420     EVT getShiftAmountTy(EVT LHSTy) {
421       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
422       if (LHSTy.isVector())
423         return LHSTy;
424       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
425                         : TLI.getPointerTy();
426     }
427
428     /// This method returns true if we are running before type legalization or
429     /// if the specified VT is legal.
430     bool isTypeLegal(const EVT &VT) {
431       if (!LegalTypes) return true;
432       return TLI.isTypeLegal(VT);
433     }
434
435     /// Convenience wrapper around TargetLowering::getSetCCResultType
436     EVT getSetCCResultType(EVT VT) const {
437       return TLI.getSetCCResultType(*DAG.getContext(), VT);
438     }
439   };
440 }
441
442
443 namespace {
444 /// This class is a DAGUpdateListener that removes any deleted
445 /// nodes from the worklist.
446 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
447   DAGCombiner &DC;
448 public:
449   explicit WorklistRemover(DAGCombiner &dc)
450     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
451
452   void NodeDeleted(SDNode *N, SDNode *E) override {
453     DC.removeFromWorklist(N);
454   }
455 };
456 }
457
458 //===----------------------------------------------------------------------===//
459 //  TargetLowering::DAGCombinerInfo implementation
460 //===----------------------------------------------------------------------===//
461
462 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
463   ((DAGCombiner*)DC)->AddToWorklist(N);
464 }
465
466 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
467   ((DAGCombiner*)DC)->removeFromWorklist(N);
468 }
469
470 SDValue TargetLowering::DAGCombinerInfo::
471 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
472   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
473 }
474
475 SDValue TargetLowering::DAGCombinerInfo::
476 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
477   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
478 }
479
480
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
483   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
484 }
485
486 void TargetLowering::DAGCombinerInfo::
487 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
488   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
489 }
490
491 //===----------------------------------------------------------------------===//
492 // Helper Functions
493 //===----------------------------------------------------------------------===//
494
495 void DAGCombiner::deleteAndRecombine(SDNode *N) {
496   removeFromWorklist(N);
497
498   // If the operands of this node are only used by the node, they will now be
499   // dead. Make sure to re-visit them and recursively delete dead nodes.
500   for (const SDValue &Op : N->ops())
501     // For an operand generating multiple values, one of the values may
502     // become dead allowing further simplification (e.g. split index
503     // arithmetic from an indexed load).
504     if (Op->hasOneUse() || Op->getNumValues() > 1)
505       AddToWorklist(Op.getNode());
506
507   DAG.DeleteNode(N);
508 }
509
510 /// Return 1 if we can compute the negated form of the specified expression for
511 /// the same cost as the expression itself, or 2 if we can compute the negated
512 /// form more cheaply than the expression itself.
513 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
514                                const TargetLowering &TLI,
515                                const TargetOptions *Options,
516                                unsigned Depth = 0) {
517   // fneg is removable even if it has multiple uses.
518   if (Op.getOpcode() == ISD::FNEG) return 2;
519
520   // Don't allow anything with multiple uses.
521   if (!Op.hasOneUse()) return 0;
522
523   // Don't recurse exponentially.
524   if (Depth > 6) return 0;
525
526   switch (Op.getOpcode()) {
527   default: return false;
528   case ISD::ConstantFP:
529     // Don't invert constant FP values after legalize.  The negated constant
530     // isn't necessarily legal.
531     return LegalOperations ? 0 : 1;
532   case ISD::FADD:
533     // FIXME: determine better conditions for this xform.
534     if (!Options->UnsafeFPMath) return 0;
535
536     // After operation legalization, it might not be legal to create new FSUBs.
537     if (LegalOperations &&
538         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
539       return 0;
540
541     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
543                                     Options, Depth + 1))
544       return V;
545     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
546     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
547                               Depth + 1);
548   case ISD::FSUB:
549     // We can't turn -(A-B) into B-A when we honor signed zeros.
550     if (!Options->UnsafeFPMath) return 0;
551
552     // fold (fneg (fsub A, B)) -> (fsub B, A)
553     return 1;
554
555   case ISD::FMUL:
556   case ISD::FDIV:
557     if (Options->HonorSignDependentRoundingFPMath()) return 0;
558
559     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
560     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
561                                     Options, Depth + 1))
562       return V;
563
564     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
565                               Depth + 1);
566
567   case ISD::FP_EXTEND:
568   case ISD::FP_ROUND:
569   case ISD::FSIN:
570     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
571                               Depth + 1);
572   }
573 }
574
575 /// If isNegatibleForFree returns true, return the newly negated expression.
576 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
577                                     bool LegalOperations, unsigned Depth = 0) {
578   const TargetOptions &Options = DAG.getTarget().Options;
579   // fneg is removable even if it has multiple uses.
580   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
581
582   // Don't allow anything with multiple uses.
583   assert(Op.hasOneUse() && "Unknown reuse!");
584
585   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
586   switch (Op.getOpcode()) {
587   default: llvm_unreachable("Unknown code");
588   case ISD::ConstantFP: {
589     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
590     V.changeSign();
591     return DAG.getConstantFP(V, Op.getValueType());
592   }
593   case ISD::FADD:
594     // FIXME: determine better conditions for this xform.
595     assert(Options.UnsafeFPMath);
596
597     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
598     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
599                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
600       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
601                          GetNegatedExpression(Op.getOperand(0), DAG,
602                                               LegalOperations, Depth+1),
603                          Op.getOperand(1));
604     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
605     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
606                        GetNegatedExpression(Op.getOperand(1), DAG,
607                                             LegalOperations, Depth+1),
608                        Op.getOperand(0));
609   case ISD::FSUB:
610     // We can't turn -(A-B) into B-A when we honor signed zeros.
611     assert(Options.UnsafeFPMath);
612
613     // fold (fneg (fsub 0, B)) -> B
614     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
615       if (N0CFP->getValueAPF().isZero())
616         return Op.getOperand(1);
617
618     // fold (fneg (fsub A, B)) -> (fsub B, A)
619     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
620                        Op.getOperand(1), Op.getOperand(0));
621
622   case ISD::FMUL:
623   case ISD::FDIV:
624     assert(!Options.HonorSignDependentRoundingFPMath());
625
626     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
627     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
628                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
629       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
630                          GetNegatedExpression(Op.getOperand(0), DAG,
631                                               LegalOperations, Depth+1),
632                          Op.getOperand(1));
633
634     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
635     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636                        Op.getOperand(0),
637                        GetNegatedExpression(Op.getOperand(1), DAG,
638                                             LegalOperations, Depth+1));
639
640   case ISD::FP_EXTEND:
641   case ISD::FSIN:
642     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643                        GetNegatedExpression(Op.getOperand(0), DAG,
644                                             LegalOperations, Depth+1));
645   case ISD::FP_ROUND:
646       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
647                          GetNegatedExpression(Op.getOperand(0), DAG,
648                                               LegalOperations, Depth+1),
649                          Op.getOperand(1));
650   }
651 }
652
653 // Return true if this node is a setcc, or is a select_cc
654 // that selects between the target values used for true and false, making it
655 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
656 // the appropriate nodes based on the type of node we are checking. This
657 // simplifies life a bit for the callers.
658 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
659                                     SDValue &CC) const {
660   if (N.getOpcode() == ISD::SETCC) {
661     LHS = N.getOperand(0);
662     RHS = N.getOperand(1);
663     CC  = N.getOperand(2);
664     return true;
665   }
666
667   if (N.getOpcode() != ISD::SELECT_CC ||
668       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
669       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
670     return false;
671
672   if (TLI.getBooleanContents(N.getValueType()) ==
673       TargetLowering::UndefinedBooleanContent)
674     return false;
675
676   LHS = N.getOperand(0);
677   RHS = N.getOperand(1);
678   CC  = N.getOperand(4);
679   return true;
680 }
681
682 /// Return true if this is a SetCC-equivalent operation with only one use.
683 /// If this is true, it allows the users to invert the operation for free when
684 /// it is profitable to do so.
685 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
686   SDValue N0, N1, N2;
687   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
688     return true;
689   return false;
690 }
691
692 /// Returns true if N is a BUILD_VECTOR node whose
693 /// elements are all the same constant or undefined.
694 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
695   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
696   if (!C)
697     return false;
698
699   APInt SplatUndef;
700   unsigned SplatBitSize;
701   bool HasAnyUndefs;
702   EVT EltVT = N->getValueType(0).getVectorElementType();
703   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
704                              HasAnyUndefs) &&
705           EltVT.getSizeInBits() >= SplatBitSize);
706 }
707
708 // \brief Returns the SDNode if it is a constant integer BuildVector
709 // or constant integer.
710 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
711   if (isa<ConstantSDNode>(N))
712     return N.getNode();
713   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
714     return N.getNode();
715   return nullptr;
716 }
717
718 // \brief Returns the SDNode if it is a constant float BuildVector
719 // or constant float.
720 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
721   if (isa<ConstantFPSDNode>(N))
722     return N.getNode();
723   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
724     return N.getNode();
725   return nullptr;
726 }
727
728 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
729 // int.
730 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
731   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
732     return CN;
733
734   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
735     BitVector UndefElements;
736     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
737
738     // BuildVectors can truncate their operands. Ignore that case here.
739     // FIXME: We blindly ignore splats which include undef which is overly
740     // pessimistic.
741     if (CN && UndefElements.none() &&
742         CN->getValueType(0) == N.getValueType().getScalarType())
743       return CN;
744   }
745
746   return nullptr;
747 }
748
749 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
750 // float.
751 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
752   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
753     return CN;
754
755   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
756     BitVector UndefElements;
757     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
758
759     if (CN && UndefElements.none())
760       return CN;
761   }
762
763   return nullptr;
764 }
765
766 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
767                                     SDValue N0, SDValue N1) {
768   EVT VT = N0.getValueType();
769   if (N0.getOpcode() == Opc) {
770     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
771       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
772         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
773         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
774           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
775         return SDValue();
776       }
777       if (N0.hasOneUse()) {
778         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
779         // use
780         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
781         if (!OpNode.getNode())
782           return SDValue();
783         AddToWorklist(OpNode.getNode());
784         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
785       }
786     }
787   }
788
789   if (N1.getOpcode() == Opc) {
790     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
791       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
792         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
793         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
794           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
795         return SDValue();
796       }
797       if (N1.hasOneUse()) {
798         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
799         // use
800         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
801         if (!OpNode.getNode())
802           return SDValue();
803         AddToWorklist(OpNode.getNode());
804         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
805       }
806     }
807   }
808
809   return SDValue();
810 }
811
812 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
813                                bool AddTo) {
814   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
815   ++NodesCombined;
816   DEBUG(dbgs() << "\nReplacing.1 ";
817         N->dump(&DAG);
818         dbgs() << "\nWith: ";
819         To[0].getNode()->dump(&DAG);
820         dbgs() << " and " << NumTo-1 << " other values\n");
821   for (unsigned i = 0, e = NumTo; i != e; ++i)
822     assert((!To[i].getNode() ||
823             N->getValueType(i) == To[i].getValueType()) &&
824            "Cannot combine value to value of different type!");
825
826   WorklistRemover DeadNodes(*this);
827   DAG.ReplaceAllUsesWith(N, To);
828   if (AddTo) {
829     // Push the new nodes and any users onto the worklist
830     for (unsigned i = 0, e = NumTo; i != e; ++i) {
831       if (To[i].getNode()) {
832         AddToWorklist(To[i].getNode());
833         AddUsersToWorklist(To[i].getNode());
834       }
835     }
836   }
837
838   // Finally, if the node is now dead, remove it from the graph.  The node
839   // may not be dead if the replacement process recursively simplified to
840   // something else needing this node.
841   if (N->use_empty())
842     deleteAndRecombine(N);
843   return SDValue(N, 0);
844 }
845
846 void DAGCombiner::
847 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
848   // Replace all uses.  If any nodes become isomorphic to other nodes and
849   // are deleted, make sure to remove them from our worklist.
850   WorklistRemover DeadNodes(*this);
851   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
852
853   // Push the new node and any (possibly new) users onto the worklist.
854   AddToWorklist(TLO.New.getNode());
855   AddUsersToWorklist(TLO.New.getNode());
856
857   // Finally, if the node is now dead, remove it from the graph.  The node
858   // may not be dead if the replacement process recursively simplified to
859   // something else needing this node.
860   if (TLO.Old.getNode()->use_empty())
861     deleteAndRecombine(TLO.Old.getNode());
862 }
863
864 /// Check the specified integer node value to see if it can be simplified or if
865 /// things it uses can be simplified by bit propagation. If so, return true.
866 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
867   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
868   APInt KnownZero, KnownOne;
869   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
870     return false;
871
872   // Revisit the node.
873   AddToWorklist(Op.getNode());
874
875   // Replace the old value with the new one.
876   ++NodesCombined;
877   DEBUG(dbgs() << "\nReplacing.2 ";
878         TLO.Old.getNode()->dump(&DAG);
879         dbgs() << "\nWith: ";
880         TLO.New.getNode()->dump(&DAG);
881         dbgs() << '\n');
882
883   CommitTargetLoweringOpt(TLO);
884   return true;
885 }
886
887 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
888   SDLoc dl(Load);
889   EVT VT = Load->getValueType(0);
890   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
891
892   DEBUG(dbgs() << "\nReplacing.9 ";
893         Load->dump(&DAG);
894         dbgs() << "\nWith: ";
895         Trunc.getNode()->dump(&DAG);
896         dbgs() << '\n');
897   WorklistRemover DeadNodes(*this);
898   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
899   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
900   deleteAndRecombine(Load);
901   AddToWorklist(Trunc.getNode());
902 }
903
904 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
905   Replace = false;
906   SDLoc dl(Op);
907   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
908     EVT MemVT = LD->getMemoryVT();
909     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
910       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
911                                                        : ISD::EXTLOAD)
912       : LD->getExtensionType();
913     Replace = true;
914     return DAG.getExtLoad(ExtType, dl, PVT,
915                           LD->getChain(), LD->getBasePtr(),
916                           MemVT, LD->getMemOperand());
917   }
918
919   unsigned Opc = Op.getOpcode();
920   switch (Opc) {
921   default: break;
922   case ISD::AssertSext:
923     return DAG.getNode(ISD::AssertSext, dl, PVT,
924                        SExtPromoteOperand(Op.getOperand(0), PVT),
925                        Op.getOperand(1));
926   case ISD::AssertZext:
927     return DAG.getNode(ISD::AssertZext, dl, PVT,
928                        ZExtPromoteOperand(Op.getOperand(0), PVT),
929                        Op.getOperand(1));
930   case ISD::Constant: {
931     unsigned ExtOpc =
932       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
933     return DAG.getNode(ExtOpc, dl, PVT, Op);
934   }
935   }
936
937   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
938     return SDValue();
939   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
940 }
941
942 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
943   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
944     return SDValue();
945   EVT OldVT = Op.getValueType();
946   SDLoc dl(Op);
947   bool Replace = false;
948   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
949   if (!NewOp.getNode())
950     return SDValue();
951   AddToWorklist(NewOp.getNode());
952
953   if (Replace)
954     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
955   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
956                      DAG.getValueType(OldVT));
957 }
958
959 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
960   EVT OldVT = Op.getValueType();
961   SDLoc dl(Op);
962   bool Replace = false;
963   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
964   if (!NewOp.getNode())
965     return SDValue();
966   AddToWorklist(NewOp.getNode());
967
968   if (Replace)
969     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
970   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
971 }
972
973 /// Promote the specified integer binary operation if the target indicates it is
974 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
975 /// i32 since i16 instructions are longer.
976 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
977   if (!LegalOperations)
978     return SDValue();
979
980   EVT VT = Op.getValueType();
981   if (VT.isVector() || !VT.isInteger())
982     return SDValue();
983
984   // If operation type is 'undesirable', e.g. i16 on x86, consider
985   // promoting it.
986   unsigned Opc = Op.getOpcode();
987   if (TLI.isTypeDesirableForOp(Opc, VT))
988     return SDValue();
989
990   EVT PVT = VT;
991   // Consult target whether it is a good idea to promote this operation and
992   // what's the right type to promote it to.
993   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
994     assert(PVT != VT && "Don't know what type to promote to!");
995
996     bool Replace0 = false;
997     SDValue N0 = Op.getOperand(0);
998     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
999     if (!NN0.getNode())
1000       return SDValue();
1001
1002     bool Replace1 = false;
1003     SDValue N1 = Op.getOperand(1);
1004     SDValue NN1;
1005     if (N0 == N1)
1006       NN1 = NN0;
1007     else {
1008       NN1 = PromoteOperand(N1, PVT, Replace1);
1009       if (!NN1.getNode())
1010         return SDValue();
1011     }
1012
1013     AddToWorklist(NN0.getNode());
1014     if (NN1.getNode())
1015       AddToWorklist(NN1.getNode());
1016
1017     if (Replace0)
1018       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1019     if (Replace1)
1020       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1021
1022     DEBUG(dbgs() << "\nPromoting ";
1023           Op.getNode()->dump(&DAG));
1024     SDLoc dl(Op);
1025     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1026                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1027   }
1028   return SDValue();
1029 }
1030
1031 /// Promote the specified integer shift operation if the target indicates it is
1032 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1033 /// i32 since i16 instructions are longer.
1034 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1035   if (!LegalOperations)
1036     return SDValue();
1037
1038   EVT VT = Op.getValueType();
1039   if (VT.isVector() || !VT.isInteger())
1040     return SDValue();
1041
1042   // If operation type is 'undesirable', e.g. i16 on x86, consider
1043   // promoting it.
1044   unsigned Opc = Op.getOpcode();
1045   if (TLI.isTypeDesirableForOp(Opc, VT))
1046     return SDValue();
1047
1048   EVT PVT = VT;
1049   // Consult target whether it is a good idea to promote this operation and
1050   // what's the right type to promote it to.
1051   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052     assert(PVT != VT && "Don't know what type to promote to!");
1053
1054     bool Replace = false;
1055     SDValue N0 = Op.getOperand(0);
1056     if (Opc == ISD::SRA)
1057       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1058     else if (Opc == ISD::SRL)
1059       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1060     else
1061       N0 = PromoteOperand(N0, PVT, Replace);
1062     if (!N0.getNode())
1063       return SDValue();
1064
1065     AddToWorklist(N0.getNode());
1066     if (Replace)
1067       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1068
1069     DEBUG(dbgs() << "\nPromoting ";
1070           Op.getNode()->dump(&DAG));
1071     SDLoc dl(Op);
1072     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1073                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1074   }
1075   return SDValue();
1076 }
1077
1078 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1079   if (!LegalOperations)
1080     return SDValue();
1081
1082   EVT VT = Op.getValueType();
1083   if (VT.isVector() || !VT.isInteger())
1084     return SDValue();
1085
1086   // If operation type is 'undesirable', e.g. i16 on x86, consider
1087   // promoting it.
1088   unsigned Opc = Op.getOpcode();
1089   if (TLI.isTypeDesirableForOp(Opc, VT))
1090     return SDValue();
1091
1092   EVT PVT = VT;
1093   // Consult target whether it is a good idea to promote this operation and
1094   // what's the right type to promote it to.
1095   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1096     assert(PVT != VT && "Don't know what type to promote to!");
1097     // fold (aext (aext x)) -> (aext x)
1098     // fold (aext (zext x)) -> (zext x)
1099     // fold (aext (sext x)) -> (sext x)
1100     DEBUG(dbgs() << "\nPromoting ";
1101           Op.getNode()->dump(&DAG));
1102     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1103   }
1104   return SDValue();
1105 }
1106
1107 bool DAGCombiner::PromoteLoad(SDValue Op) {
1108   if (!LegalOperations)
1109     return false;
1110
1111   EVT VT = Op.getValueType();
1112   if (VT.isVector() || !VT.isInteger())
1113     return false;
1114
1115   // If operation type is 'undesirable', e.g. i16 on x86, consider
1116   // promoting it.
1117   unsigned Opc = Op.getOpcode();
1118   if (TLI.isTypeDesirableForOp(Opc, VT))
1119     return false;
1120
1121   EVT PVT = VT;
1122   // Consult target whether it is a good idea to promote this operation and
1123   // what's the right type to promote it to.
1124   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1125     assert(PVT != VT && "Don't know what type to promote to!");
1126
1127     SDLoc dl(Op);
1128     SDNode *N = Op.getNode();
1129     LoadSDNode *LD = cast<LoadSDNode>(N);
1130     EVT MemVT = LD->getMemoryVT();
1131     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1132       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1133                                                        : ISD::EXTLOAD)
1134       : LD->getExtensionType();
1135     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1136                                    LD->getChain(), LD->getBasePtr(),
1137                                    MemVT, LD->getMemOperand());
1138     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1139
1140     DEBUG(dbgs() << "\nPromoting ";
1141           N->dump(&DAG);
1142           dbgs() << "\nTo: ";
1143           Result.getNode()->dump(&DAG);
1144           dbgs() << '\n');
1145     WorklistRemover DeadNodes(*this);
1146     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1147     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1148     deleteAndRecombine(N);
1149     AddToWorklist(Result.getNode());
1150     return true;
1151   }
1152   return false;
1153 }
1154
1155 /// \brief Recursively delete a node which has no uses and any operands for
1156 /// which it is the only use.
1157 ///
1158 /// Note that this both deletes the nodes and removes them from the worklist.
1159 /// It also adds any nodes who have had a user deleted to the worklist as they
1160 /// may now have only one use and subject to other combines.
1161 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1162   if (!N->use_empty())
1163     return false;
1164
1165   SmallSetVector<SDNode *, 16> Nodes;
1166   Nodes.insert(N);
1167   do {
1168     N = Nodes.pop_back_val();
1169     if (!N)
1170       continue;
1171
1172     if (N->use_empty()) {
1173       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1174         Nodes.insert(N->getOperand(i).getNode());
1175
1176       removeFromWorklist(N);
1177       DAG.DeleteNode(N);
1178     } else {
1179       AddToWorklist(N);
1180     }
1181   } while (!Nodes.empty());
1182   return true;
1183 }
1184
1185 //===----------------------------------------------------------------------===//
1186 //  Main DAG Combiner implementation
1187 //===----------------------------------------------------------------------===//
1188
1189 void DAGCombiner::Run(CombineLevel AtLevel) {
1190   // set the instance variables, so that the various visit routines may use it.
1191   Level = AtLevel;
1192   LegalOperations = Level >= AfterLegalizeVectorOps;
1193   LegalTypes = Level >= AfterLegalizeTypes;
1194
1195   // Add all the dag nodes to the worklist.
1196   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1197        E = DAG.allnodes_end(); I != E; ++I)
1198     AddToWorklist(I);
1199
1200   // Create a dummy node (which is not added to allnodes), that adds a reference
1201   // to the root node, preventing it from being deleted, and tracking any
1202   // changes of the root.
1203   HandleSDNode Dummy(DAG.getRoot());
1204
1205   // while the worklist isn't empty, find a node and
1206   // try and combine it.
1207   while (!WorklistMap.empty()) {
1208     SDNode *N;
1209     // The Worklist holds the SDNodes in order, but it may contain null entries.
1210     do {
1211       N = Worklist.pop_back_val();
1212     } while (!N);
1213
1214     bool GoodWorklistEntry = WorklistMap.erase(N);
1215     (void)GoodWorklistEntry;
1216     assert(GoodWorklistEntry &&
1217            "Found a worklist entry without a corresponding map entry!");
1218
1219     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1220     // N is deleted from the DAG, since they too may now be dead or may have a
1221     // reduced number of uses, allowing other xforms.
1222     if (recursivelyDeleteUnusedNodes(N))
1223       continue;
1224
1225     WorklistRemover DeadNodes(*this);
1226
1227     // If this combine is running after legalizing the DAG, re-legalize any
1228     // nodes pulled off the worklist.
1229     if (Level == AfterLegalizeDAG) {
1230       SmallSetVector<SDNode *, 16> UpdatedNodes;
1231       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1232
1233       for (SDNode *LN : UpdatedNodes) {
1234         AddToWorklist(LN);
1235         AddUsersToWorklist(LN);
1236       }
1237       if (!NIsValid)
1238         continue;
1239     }
1240
1241     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1242
1243     // Add any operands of the new node which have not yet been combined to the
1244     // worklist as well. Because the worklist uniques things already, this
1245     // won't repeatedly process the same operand.
1246     CombinedNodes.insert(N);
1247     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1248       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1249         AddToWorklist(N->getOperand(i).getNode());
1250
1251     SDValue RV = combine(N);
1252
1253     if (!RV.getNode())
1254       continue;
1255
1256     ++NodesCombined;
1257
1258     // If we get back the same node we passed in, rather than a new node or
1259     // zero, we know that the node must have defined multiple values and
1260     // CombineTo was used.  Since CombineTo takes care of the worklist
1261     // mechanics for us, we have no work to do in this case.
1262     if (RV.getNode() == N)
1263       continue;
1264
1265     assert(N->getOpcode() != ISD::DELETED_NODE &&
1266            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1267            "Node was deleted but visit returned new node!");
1268
1269     DEBUG(dbgs() << " ... into: ";
1270           RV.getNode()->dump(&DAG));
1271
1272     // Transfer debug value.
1273     DAG.TransferDbgValues(SDValue(N, 0), RV);
1274     if (N->getNumValues() == RV.getNode()->getNumValues())
1275       DAG.ReplaceAllUsesWith(N, RV.getNode());
1276     else {
1277       assert(N->getValueType(0) == RV.getValueType() &&
1278              N->getNumValues() == 1 && "Type mismatch");
1279       SDValue OpV = RV;
1280       DAG.ReplaceAllUsesWith(N, &OpV);
1281     }
1282
1283     // Push the new node and any users onto the worklist
1284     AddToWorklist(RV.getNode());
1285     AddUsersToWorklist(RV.getNode());
1286
1287     // Finally, if the node is now dead, remove it from the graph.  The node
1288     // may not be dead if the replacement process recursively simplified to
1289     // something else needing this node. This will also take care of adding any
1290     // operands which have lost a user to the worklist.
1291     recursivelyDeleteUnusedNodes(N);
1292   }
1293
1294   // If the root changed (e.g. it was a dead load, update the root).
1295   DAG.setRoot(Dummy.getValue());
1296   DAG.RemoveDeadNodes();
1297 }
1298
1299 SDValue DAGCombiner::visit(SDNode *N) {
1300   switch (N->getOpcode()) {
1301   default: break;
1302   case ISD::TokenFactor:        return visitTokenFactor(N);
1303   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1304   case ISD::ADD:                return visitADD(N);
1305   case ISD::SUB:                return visitSUB(N);
1306   case ISD::ADDC:               return visitADDC(N);
1307   case ISD::SUBC:               return visitSUBC(N);
1308   case ISD::ADDE:               return visitADDE(N);
1309   case ISD::SUBE:               return visitSUBE(N);
1310   case ISD::MUL:                return visitMUL(N);
1311   case ISD::SDIV:               return visitSDIV(N);
1312   case ISD::UDIV:               return visitUDIV(N);
1313   case ISD::SREM:               return visitSREM(N);
1314   case ISD::UREM:               return visitUREM(N);
1315   case ISD::MULHU:              return visitMULHU(N);
1316   case ISD::MULHS:              return visitMULHS(N);
1317   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1318   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1319   case ISD::SMULO:              return visitSMULO(N);
1320   case ISD::UMULO:              return visitUMULO(N);
1321   case ISD::SDIVREM:            return visitSDIVREM(N);
1322   case ISD::UDIVREM:            return visitUDIVREM(N);
1323   case ISD::AND:                return visitAND(N);
1324   case ISD::OR:                 return visitOR(N);
1325   case ISD::XOR:                return visitXOR(N);
1326   case ISD::SHL:                return visitSHL(N);
1327   case ISD::SRA:                return visitSRA(N);
1328   case ISD::SRL:                return visitSRL(N);
1329   case ISD::ROTR:
1330   case ISD::ROTL:               return visitRotate(N);
1331   case ISD::CTLZ:               return visitCTLZ(N);
1332   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1333   case ISD::CTTZ:               return visitCTTZ(N);
1334   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1335   case ISD::CTPOP:              return visitCTPOP(N);
1336   case ISD::SELECT:             return visitSELECT(N);
1337   case ISD::VSELECT:            return visitVSELECT(N);
1338   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1339   case ISD::SETCC:              return visitSETCC(N);
1340   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1341   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1342   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1343   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1344   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1345   case ISD::BITCAST:            return visitBITCAST(N);
1346   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1347   case ISD::FADD:               return visitFADD(N);
1348   case ISD::FSUB:               return visitFSUB(N);
1349   case ISD::FMUL:               return visitFMUL(N);
1350   case ISD::FMA:                return visitFMA(N);
1351   case ISD::FDIV:               return visitFDIV(N);
1352   case ISD::FREM:               return visitFREM(N);
1353   case ISD::FSQRT:              return visitFSQRT(N);
1354   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1355   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1356   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1357   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1358   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1359   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1360   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1361   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1362   case ISD::FNEG:               return visitFNEG(N);
1363   case ISD::FABS:               return visitFABS(N);
1364   case ISD::FFLOOR:             return visitFFLOOR(N);
1365   case ISD::FMINNUM:            return visitFMINNUM(N);
1366   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1367   case ISD::FCEIL:              return visitFCEIL(N);
1368   case ISD::FTRUNC:             return visitFTRUNC(N);
1369   case ISD::BRCOND:             return visitBRCOND(N);
1370   case ISD::BR_CC:              return visitBR_CC(N);
1371   case ISD::LOAD:               return visitLOAD(N);
1372   case ISD::STORE:              return visitSTORE(N);
1373   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1374   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1375   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1376   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1377   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1378   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1379   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1380   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1381   case ISD::MLOAD:              return visitMLOAD(N);
1382   case ISD::MSTORE:             return visitMSTORE(N);
1383   }
1384   return SDValue();
1385 }
1386
1387 SDValue DAGCombiner::combine(SDNode *N) {
1388   SDValue RV = visit(N);
1389
1390   // If nothing happened, try a target-specific DAG combine.
1391   if (!RV.getNode()) {
1392     assert(N->getOpcode() != ISD::DELETED_NODE &&
1393            "Node was deleted but visit returned NULL!");
1394
1395     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1396         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1397
1398       // Expose the DAG combiner to the target combiner impls.
1399       TargetLowering::DAGCombinerInfo
1400         DagCombineInfo(DAG, Level, false, this);
1401
1402       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1403     }
1404   }
1405
1406   // If nothing happened still, try promoting the operation.
1407   if (!RV.getNode()) {
1408     switch (N->getOpcode()) {
1409     default: break;
1410     case ISD::ADD:
1411     case ISD::SUB:
1412     case ISD::MUL:
1413     case ISD::AND:
1414     case ISD::OR:
1415     case ISD::XOR:
1416       RV = PromoteIntBinOp(SDValue(N, 0));
1417       break;
1418     case ISD::SHL:
1419     case ISD::SRA:
1420     case ISD::SRL:
1421       RV = PromoteIntShiftOp(SDValue(N, 0));
1422       break;
1423     case ISD::SIGN_EXTEND:
1424     case ISD::ZERO_EXTEND:
1425     case ISD::ANY_EXTEND:
1426       RV = PromoteExtend(SDValue(N, 0));
1427       break;
1428     case ISD::LOAD:
1429       if (PromoteLoad(SDValue(N, 0)))
1430         RV = SDValue(N, 0);
1431       break;
1432     }
1433   }
1434
1435   // If N is a commutative binary node, try commuting it to enable more
1436   // sdisel CSE.
1437   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1438       N->getNumValues() == 1) {
1439     SDValue N0 = N->getOperand(0);
1440     SDValue N1 = N->getOperand(1);
1441
1442     // Constant operands are canonicalized to RHS.
1443     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1444       SDValue Ops[] = {N1, N0};
1445       SDNode *CSENode;
1446       if (const BinaryWithFlagsSDNode *BinNode =
1447               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1448         CSENode = DAG.getNodeIfExists(
1449             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1450             BinNode->hasNoSignedWrap(), BinNode->isExact());
1451       } else {
1452         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1453       }
1454       if (CSENode)
1455         return SDValue(CSENode, 0);
1456     }
1457   }
1458
1459   return RV;
1460 }
1461
1462 /// Given a node, return its input chain if it has one, otherwise return a null
1463 /// sd operand.
1464 static SDValue getInputChainForNode(SDNode *N) {
1465   if (unsigned NumOps = N->getNumOperands()) {
1466     if (N->getOperand(0).getValueType() == MVT::Other)
1467       return N->getOperand(0);
1468     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1469       return N->getOperand(NumOps-1);
1470     for (unsigned i = 1; i < NumOps-1; ++i)
1471       if (N->getOperand(i).getValueType() == MVT::Other)
1472         return N->getOperand(i);
1473   }
1474   return SDValue();
1475 }
1476
1477 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1478   // If N has two operands, where one has an input chain equal to the other,
1479   // the 'other' chain is redundant.
1480   if (N->getNumOperands() == 2) {
1481     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1482       return N->getOperand(0);
1483     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1484       return N->getOperand(1);
1485   }
1486
1487   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1488   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1489   SmallPtrSet<SDNode*, 16> SeenOps;
1490   bool Changed = false;             // If we should replace this token factor.
1491
1492   // Start out with this token factor.
1493   TFs.push_back(N);
1494
1495   // Iterate through token factors.  The TFs grows when new token factors are
1496   // encountered.
1497   for (unsigned i = 0; i < TFs.size(); ++i) {
1498     SDNode *TF = TFs[i];
1499
1500     // Check each of the operands.
1501     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1502       SDValue Op = TF->getOperand(i);
1503
1504       switch (Op.getOpcode()) {
1505       case ISD::EntryToken:
1506         // Entry tokens don't need to be added to the list. They are
1507         // redundant.
1508         Changed = true;
1509         break;
1510
1511       case ISD::TokenFactor:
1512         if (Op.hasOneUse() &&
1513             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1514           // Queue up for processing.
1515           TFs.push_back(Op.getNode());
1516           // Clean up in case the token factor is removed.
1517           AddToWorklist(Op.getNode());
1518           Changed = true;
1519           break;
1520         }
1521         // Fall thru
1522
1523       default:
1524         // Only add if it isn't already in the list.
1525         if (SeenOps.insert(Op.getNode()).second)
1526           Ops.push_back(Op);
1527         else
1528           Changed = true;
1529         break;
1530       }
1531     }
1532   }
1533
1534   SDValue Result;
1535
1536   // If we've changed things around then replace token factor.
1537   if (Changed) {
1538     if (Ops.empty()) {
1539       // The entry token is the only possible outcome.
1540       Result = DAG.getEntryNode();
1541     } else {
1542       // New and improved token factor.
1543       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1544     }
1545
1546     // Add users to worklist if AA is enabled, since it may introduce
1547     // a lot of new chained token factors while removing memory deps.
1548     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1549       : DAG.getSubtarget().useAA();
1550     return CombineTo(N, Result, UseAA /*add to worklist*/);
1551   }
1552
1553   return Result;
1554 }
1555
1556 /// MERGE_VALUES can always be eliminated.
1557 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1558   WorklistRemover DeadNodes(*this);
1559   // Replacing results may cause a different MERGE_VALUES to suddenly
1560   // be CSE'd with N, and carry its uses with it. Iterate until no
1561   // uses remain, to ensure that the node can be safely deleted.
1562   // First add the users of this node to the work list so that they
1563   // can be tried again once they have new operands.
1564   AddUsersToWorklist(N);
1565   do {
1566     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1567       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1568   } while (!N->use_empty());
1569   deleteAndRecombine(N);
1570   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1571 }
1572
1573 SDValue DAGCombiner::visitADD(SDNode *N) {
1574   SDValue N0 = N->getOperand(0);
1575   SDValue N1 = N->getOperand(1);
1576   EVT VT = N0.getValueType();
1577
1578   // fold vector ops
1579   if (VT.isVector()) {
1580     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1581       return FoldedVOp;
1582
1583     // fold (add x, 0) -> x, vector edition
1584     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1585       return N0;
1586     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1587       return N1;
1588   }
1589
1590   // fold (add x, undef) -> undef
1591   if (N0.getOpcode() == ISD::UNDEF)
1592     return N0;
1593   if (N1.getOpcode() == ISD::UNDEF)
1594     return N1;
1595   // fold (add c1, c2) -> c1+c2
1596   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1597   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1598   if (N0C && N1C)
1599     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1600   // canonicalize constant to RHS
1601   if (N0C && !N1C)
1602     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1603   // fold (add x, 0) -> x
1604   if (N1C && N1C->isNullValue())
1605     return N0;
1606   // fold (add Sym, c) -> Sym+c
1607   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1608     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1609         GA->getOpcode() == ISD::GlobalAddress)
1610       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1611                                   GA->getOffset() +
1612                                     (uint64_t)N1C->getSExtValue());
1613   // fold ((c1-A)+c2) -> (c1+c2)-A
1614   if (N1C && N0.getOpcode() == ISD::SUB)
1615     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1616       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1617                          DAG.getConstant(N1C->getAPIntValue()+
1618                                          N0C->getAPIntValue(), VT),
1619                          N0.getOperand(1));
1620   // reassociate add
1621   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1622     return RADD;
1623   // fold ((0-A) + B) -> B-A
1624   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1625       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1626     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1627   // fold (A + (0-B)) -> A-B
1628   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1629       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1630     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1631   // fold (A+(B-A)) -> B
1632   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1633     return N1.getOperand(0);
1634   // fold ((B-A)+A) -> B
1635   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1636     return N0.getOperand(0);
1637   // fold (A+(B-(A+C))) to (B-C)
1638   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1639       N0 == N1.getOperand(1).getOperand(0))
1640     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1641                        N1.getOperand(1).getOperand(1));
1642   // fold (A+(B-(C+A))) to (B-C)
1643   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1644       N0 == N1.getOperand(1).getOperand(1))
1645     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1646                        N1.getOperand(1).getOperand(0));
1647   // fold (A+((B-A)+or-C)) to (B+or-C)
1648   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1649       N1.getOperand(0).getOpcode() == ISD::SUB &&
1650       N0 == N1.getOperand(0).getOperand(1))
1651     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1652                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1653
1654   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1655   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1656     SDValue N00 = N0.getOperand(0);
1657     SDValue N01 = N0.getOperand(1);
1658     SDValue N10 = N1.getOperand(0);
1659     SDValue N11 = N1.getOperand(1);
1660
1661     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1662       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1663                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1664                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1665   }
1666
1667   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1668     return SDValue(N, 0);
1669
1670   // fold (a+b) -> (a|b) iff a and b share no bits.
1671   if (VT.isInteger() && !VT.isVector()) {
1672     APInt LHSZero, LHSOne;
1673     APInt RHSZero, RHSOne;
1674     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1675
1676     if (LHSZero.getBoolValue()) {
1677       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1678
1679       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1680       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1681       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1682         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1683           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1684       }
1685     }
1686   }
1687
1688   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1689   if (N1.getOpcode() == ISD::SHL &&
1690       N1.getOperand(0).getOpcode() == ISD::SUB)
1691     if (ConstantSDNode *C =
1692           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1693       if (C->getAPIntValue() == 0)
1694         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1695                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1696                                        N1.getOperand(0).getOperand(1),
1697                                        N1.getOperand(1)));
1698   if (N0.getOpcode() == ISD::SHL &&
1699       N0.getOperand(0).getOpcode() == ISD::SUB)
1700     if (ConstantSDNode *C =
1701           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1702       if (C->getAPIntValue() == 0)
1703         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1704                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1705                                        N0.getOperand(0).getOperand(1),
1706                                        N0.getOperand(1)));
1707
1708   if (N1.getOpcode() == ISD::AND) {
1709     SDValue AndOp0 = N1.getOperand(0);
1710     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1711     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1712     unsigned DestBits = VT.getScalarType().getSizeInBits();
1713
1714     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1715     // and similar xforms where the inner op is either ~0 or 0.
1716     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1717       SDLoc DL(N);
1718       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1719     }
1720   }
1721
1722   // add (sext i1), X -> sub X, (zext i1)
1723   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1724       N0.getOperand(0).getValueType() == MVT::i1 &&
1725       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1726     SDLoc DL(N);
1727     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1728     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1729   }
1730
1731   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1732   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1733     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1734     if (TN->getVT() == MVT::i1) {
1735       SDLoc DL(N);
1736       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1737                                  DAG.getConstant(1, VT));
1738       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1739     }
1740   }
1741
1742   return SDValue();
1743 }
1744
1745 SDValue DAGCombiner::visitADDC(SDNode *N) {
1746   SDValue N0 = N->getOperand(0);
1747   SDValue N1 = N->getOperand(1);
1748   EVT VT = N0.getValueType();
1749
1750   // If the flag result is dead, turn this into an ADD.
1751   if (!N->hasAnyUseOfValue(1))
1752     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1753                      DAG.getNode(ISD::CARRY_FALSE,
1754                                  SDLoc(N), MVT::Glue));
1755
1756   // canonicalize constant to RHS.
1757   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1758   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1759   if (N0C && !N1C)
1760     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1761
1762   // fold (addc x, 0) -> x + no carry out
1763   if (N1C && N1C->isNullValue())
1764     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1765                                         SDLoc(N), MVT::Glue));
1766
1767   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1768   APInt LHSZero, LHSOne;
1769   APInt RHSZero, RHSOne;
1770   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1771
1772   if (LHSZero.getBoolValue()) {
1773     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1774
1775     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1776     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1777     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1778       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1779                        DAG.getNode(ISD::CARRY_FALSE,
1780                                    SDLoc(N), MVT::Glue));
1781   }
1782
1783   return SDValue();
1784 }
1785
1786 SDValue DAGCombiner::visitADDE(SDNode *N) {
1787   SDValue N0 = N->getOperand(0);
1788   SDValue N1 = N->getOperand(1);
1789   SDValue CarryIn = N->getOperand(2);
1790
1791   // canonicalize constant to RHS
1792   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1793   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1794   if (N0C && !N1C)
1795     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1796                        N1, N0, CarryIn);
1797
1798   // fold (adde x, y, false) -> (addc x, y)
1799   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1800     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1801
1802   return SDValue();
1803 }
1804
1805 // Since it may not be valid to emit a fold to zero for vector initializers
1806 // check if we can before folding.
1807 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1808                              SelectionDAG &DAG,
1809                              bool LegalOperations, bool LegalTypes) {
1810   if (!VT.isVector())
1811     return DAG.getConstant(0, VT);
1812   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1813     return DAG.getConstant(0, VT);
1814   return SDValue();
1815 }
1816
1817 SDValue DAGCombiner::visitSUB(SDNode *N) {
1818   SDValue N0 = N->getOperand(0);
1819   SDValue N1 = N->getOperand(1);
1820   EVT VT = N0.getValueType();
1821
1822   // fold vector ops
1823   if (VT.isVector()) {
1824     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1825       return FoldedVOp;
1826
1827     // fold (sub x, 0) -> x, vector edition
1828     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1829       return N0;
1830   }
1831
1832   // fold (sub x, x) -> 0
1833   // FIXME: Refactor this and xor and other similar operations together.
1834   if (N0 == N1)
1835     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1836   // fold (sub c1, c2) -> c1-c2
1837   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1838   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1839   if (N0C && N1C)
1840     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1841   // fold (sub x, c) -> (add x, -c)
1842   if (N1C)
1843     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1844                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1845   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1846   if (N0C && N0C->isAllOnesValue())
1847     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1848   // fold A-(A-B) -> B
1849   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1850     return N1.getOperand(1);
1851   // fold (A+B)-A -> B
1852   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1853     return N0.getOperand(1);
1854   // fold (A+B)-B -> A
1855   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1856     return N0.getOperand(0);
1857   // fold C2-(A+C1) -> (C2-C1)-A
1858   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1859     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1860   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1861     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1862                                    VT);
1863     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1864                        N1.getOperand(0));
1865   }
1866   // fold ((A+(B+or-C))-B) -> A+or-C
1867   if (N0.getOpcode() == ISD::ADD &&
1868       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1869        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1870       N0.getOperand(1).getOperand(0) == N1)
1871     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1872                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1873   // fold ((A+(C+B))-B) -> A+C
1874   if (N0.getOpcode() == ISD::ADD &&
1875       N0.getOperand(1).getOpcode() == ISD::ADD &&
1876       N0.getOperand(1).getOperand(1) == N1)
1877     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1878                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1879   // fold ((A-(B-C))-C) -> A-B
1880   if (N0.getOpcode() == ISD::SUB &&
1881       N0.getOperand(1).getOpcode() == ISD::SUB &&
1882       N0.getOperand(1).getOperand(1) == N1)
1883     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1884                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1885
1886   // If either operand of a sub is undef, the result is undef
1887   if (N0.getOpcode() == ISD::UNDEF)
1888     return N0;
1889   if (N1.getOpcode() == ISD::UNDEF)
1890     return N1;
1891
1892   // If the relocation model supports it, consider symbol offsets.
1893   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1894     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1895       // fold (sub Sym, c) -> Sym-c
1896       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1897         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1898                                     GA->getOffset() -
1899                                       (uint64_t)N1C->getSExtValue());
1900       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1901       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1902         if (GA->getGlobal() == GB->getGlobal())
1903           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1904                                  VT);
1905     }
1906
1907   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1908   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1909     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1910     if (TN->getVT() == MVT::i1) {
1911       SDLoc DL(N);
1912       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1913                                  DAG.getConstant(1, VT));
1914       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1915     }
1916   }
1917
1918   return SDValue();
1919 }
1920
1921 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1922   SDValue N0 = N->getOperand(0);
1923   SDValue N1 = N->getOperand(1);
1924   EVT VT = N0.getValueType();
1925
1926   // If the flag result is dead, turn this into an SUB.
1927   if (!N->hasAnyUseOfValue(1))
1928     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1929                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1930                                  MVT::Glue));
1931
1932   // fold (subc x, x) -> 0 + no borrow
1933   if (N0 == N1)
1934     return CombineTo(N, DAG.getConstant(0, VT),
1935                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1936                                  MVT::Glue));
1937
1938   // fold (subc x, 0) -> x + no borrow
1939   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1940   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1941   if (N1C && N1C->isNullValue())
1942     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1943                                         MVT::Glue));
1944
1945   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1946   if (N0C && N0C->isAllOnesValue())
1947     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1948                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1949                                  MVT::Glue));
1950
1951   return SDValue();
1952 }
1953
1954 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1955   SDValue N0 = N->getOperand(0);
1956   SDValue N1 = N->getOperand(1);
1957   SDValue CarryIn = N->getOperand(2);
1958
1959   // fold (sube x, y, false) -> (subc x, y)
1960   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1961     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1962
1963   return SDValue();
1964 }
1965
1966 SDValue DAGCombiner::visitMUL(SDNode *N) {
1967   SDValue N0 = N->getOperand(0);
1968   SDValue N1 = N->getOperand(1);
1969   EVT VT = N0.getValueType();
1970
1971   // fold (mul x, undef) -> 0
1972   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1973     return DAG.getConstant(0, VT);
1974
1975   bool N0IsConst = false;
1976   bool N1IsConst = false;
1977   APInt ConstValue0, ConstValue1;
1978   // fold vector ops
1979   if (VT.isVector()) {
1980     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1981       return FoldedVOp;
1982
1983     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1984     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1985   } else {
1986     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1987     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1988                             : APInt();
1989     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1990     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1991                             : APInt();
1992   }
1993
1994   // fold (mul c1, c2) -> c1*c2
1995   if (N0IsConst && N1IsConst)
1996     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1997
1998   // canonicalize constant to RHS
1999   if (N0IsConst && !N1IsConst)
2000     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2001   // fold (mul x, 0) -> 0
2002   if (N1IsConst && ConstValue1 == 0)
2003     return N1;
2004   // We require a splat of the entire scalar bit width for non-contiguous
2005   // bit patterns.
2006   bool IsFullSplat =
2007     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2008   // fold (mul x, 1) -> x
2009   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2010     return N0;
2011   // fold (mul x, -1) -> 0-x
2012   if (N1IsConst && ConstValue1.isAllOnesValue())
2013     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2014                        DAG.getConstant(0, VT), N0);
2015   // fold (mul x, (1 << c)) -> x << c
2016   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2017     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2018                        DAG.getConstant(ConstValue1.logBase2(),
2019                                        getShiftAmountTy(N0.getValueType())));
2020   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2021   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2022     unsigned Log2Val = (-ConstValue1).logBase2();
2023     // FIXME: If the input is something that is easily negated (e.g. a
2024     // single-use add), we should put the negate there.
2025     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2026                        DAG.getConstant(0, VT),
2027                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2028                             DAG.getConstant(Log2Val,
2029                                       getShiftAmountTy(N0.getValueType()))));
2030   }
2031
2032   APInt Val;
2033   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2034   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2035       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2036                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2037     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2038                              N1, N0.getOperand(1));
2039     AddToWorklist(C3.getNode());
2040     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2041                        N0.getOperand(0), C3);
2042   }
2043
2044   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2045   // use.
2046   {
2047     SDValue Sh(nullptr,0), Y(nullptr,0);
2048     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2049     if (N0.getOpcode() == ISD::SHL &&
2050         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2051                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2052         N0.getNode()->hasOneUse()) {
2053       Sh = N0; Y = N1;
2054     } else if (N1.getOpcode() == ISD::SHL &&
2055                isa<ConstantSDNode>(N1.getOperand(1)) &&
2056                N1.getNode()->hasOneUse()) {
2057       Sh = N1; Y = N0;
2058     }
2059
2060     if (Sh.getNode()) {
2061       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2062                                 Sh.getOperand(0), Y);
2063       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2064                          Mul, Sh.getOperand(1));
2065     }
2066   }
2067
2068   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2069   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2070       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2071                      isa<ConstantSDNode>(N0.getOperand(1))))
2072     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2073                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2074                                    N0.getOperand(0), N1),
2075                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2076                                    N0.getOperand(1), N1));
2077
2078   // reassociate mul
2079   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2080     return RMUL;
2081
2082   return SDValue();
2083 }
2084
2085 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2086   SDValue N0 = N->getOperand(0);
2087   SDValue N1 = N->getOperand(1);
2088   EVT VT = N->getValueType(0);
2089
2090   // fold vector ops
2091   if (VT.isVector())
2092     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2093       return FoldedVOp;
2094
2095   // fold (sdiv c1, c2) -> c1/c2
2096   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2097   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2098   if (N0C && N1C && !N1C->isNullValue())
2099     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2100   // fold (sdiv X, 1) -> X
2101   if (N1C && N1C->getAPIntValue() == 1LL)
2102     return N0;
2103   // fold (sdiv X, -1) -> 0-X
2104   if (N1C && N1C->isAllOnesValue())
2105     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2106                        DAG.getConstant(0, VT), N0);
2107   // If we know the sign bits of both operands are zero, strength reduce to a
2108   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2109   if (!VT.isVector()) {
2110     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2111       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2112                          N0, N1);
2113   }
2114
2115   // fold (sdiv X, pow2) -> simple ops after legalize
2116   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2117                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2118     // If dividing by powers of two is cheap, then don't perform the following
2119     // fold.
2120     if (TLI.isPow2SDivCheap())
2121       return SDValue();
2122
2123     // Target-specific implementation of sdiv x, pow2.
2124     SDValue Res = BuildSDIVPow2(N);
2125     if (Res.getNode())
2126       return Res;
2127
2128     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2129
2130     // Splat the sign bit into the register
2131     SDValue SGN =
2132         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2133                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2134                                     getShiftAmountTy(N0.getValueType())));
2135     AddToWorklist(SGN.getNode());
2136
2137     // Add (N0 < 0) ? abs2 - 1 : 0;
2138     SDValue SRL =
2139         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2140                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2141                                     getShiftAmountTy(SGN.getValueType())));
2142     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2143     AddToWorklist(SRL.getNode());
2144     AddToWorklist(ADD.getNode());    // Divide by pow2
2145     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2146                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2147
2148     // If we're dividing by a positive value, we're done.  Otherwise, we must
2149     // negate the result.
2150     if (N1C->getAPIntValue().isNonNegative())
2151       return SRA;
2152
2153     AddToWorklist(SRA.getNode());
2154     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2155   }
2156
2157   // If integer divide is expensive and we satisfy the requirements, emit an
2158   // alternate sequence.
2159   if (N1C && !TLI.isIntDivCheap()) {
2160     SDValue Op = BuildSDIV(N);
2161     if (Op.getNode()) return Op;
2162   }
2163
2164   // undef / X -> 0
2165   if (N0.getOpcode() == ISD::UNDEF)
2166     return DAG.getConstant(0, VT);
2167   // X / undef -> undef
2168   if (N1.getOpcode() == ISD::UNDEF)
2169     return N1;
2170
2171   return SDValue();
2172 }
2173
2174 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2175   SDValue N0 = N->getOperand(0);
2176   SDValue N1 = N->getOperand(1);
2177   EVT VT = N->getValueType(0);
2178
2179   // fold vector ops
2180   if (VT.isVector())
2181     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2182       return FoldedVOp;
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 is twice as wide is legal, transform the mulhu to a wider
2453   // multiply 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 is twice as wide is legal, transform the mulhu to a wider
2483   // multiply 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     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2803       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   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2844     return RAND;
2845   // fold (and (or x, C), D) -> D if (C & D) == D
2846   if (N1C && N0.getOpcode() == ISD::OR)
2847     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2848       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2849         return N1;
2850   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2851   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2852     SDValue N0Op0 = N0.getOperand(0);
2853     APInt Mask = ~N1C->getAPIntValue();
2854     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2855     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2856       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2857                                  N0.getValueType(), N0Op0);
2858
2859       // Replace uses of the AND with uses of the Zero extend node.
2860       CombineTo(N, Zext);
2861
2862       // We actually want to replace all uses of the any_extend with the
2863       // zero_extend, to avoid duplicating things.  This will later cause this
2864       // AND to be folded.
2865       CombineTo(N0.getNode(), Zext);
2866       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2867     }
2868   }
2869   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2870   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2871   // already be zero by virtue of the width of the base type of the load.
2872   //
2873   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2874   // more cases.
2875   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2876        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2877       N0.getOpcode() == ISD::LOAD) {
2878     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2879                                          N0 : N0.getOperand(0) );
2880
2881     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2882     // This can be a pure constant or a vector splat, in which case we treat the
2883     // vector as a scalar and use the splat value.
2884     APInt Constant = APInt::getNullValue(1);
2885     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2886       Constant = C->getAPIntValue();
2887     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2888       APInt SplatValue, SplatUndef;
2889       unsigned SplatBitSize;
2890       bool HasAnyUndefs;
2891       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2892                                              SplatBitSize, HasAnyUndefs);
2893       if (IsSplat) {
2894         // Undef bits can contribute to a possible optimisation if set, so
2895         // set them.
2896         SplatValue |= SplatUndef;
2897
2898         // The splat value may be something like "0x00FFFFFF", which means 0 for
2899         // the first vector value and FF for the rest, repeating. We need a mask
2900         // that will apply equally to all members of the vector, so AND all the
2901         // lanes of the constant together.
2902         EVT VT = Vector->getValueType(0);
2903         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2904
2905         // If the splat value has been compressed to a bitlength lower
2906         // than the size of the vector lane, we need to re-expand it to
2907         // the lane size.
2908         if (BitWidth > SplatBitSize)
2909           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2910                SplatBitSize < BitWidth;
2911                SplatBitSize = SplatBitSize * 2)
2912             SplatValue |= SplatValue.shl(SplatBitSize);
2913
2914         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2915         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2916         if (SplatBitSize % BitWidth == 0) {
2917           Constant = APInt::getAllOnesValue(BitWidth);
2918           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2919             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2920         }
2921       }
2922     }
2923
2924     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2925     // actually legal and isn't going to get expanded, else this is a false
2926     // optimisation.
2927     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2928                                                     Load->getValueType(0),
2929                                                     Load->getMemoryVT());
2930
2931     // Resize the constant to the same size as the original memory access before
2932     // extension. If it is still the AllOnesValue then this AND is completely
2933     // unneeded.
2934     Constant =
2935       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2936
2937     bool B;
2938     switch (Load->getExtensionType()) {
2939     default: B = false; break;
2940     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2941     case ISD::ZEXTLOAD:
2942     case ISD::NON_EXTLOAD: B = true; break;
2943     }
2944
2945     if (B && Constant.isAllOnesValue()) {
2946       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2947       // preserve semantics once we get rid of the AND.
2948       SDValue NewLoad(Load, 0);
2949       if (Load->getExtensionType() == ISD::EXTLOAD) {
2950         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2951                               Load->getValueType(0), SDLoc(Load),
2952                               Load->getChain(), Load->getBasePtr(),
2953                               Load->getOffset(), Load->getMemoryVT(),
2954                               Load->getMemOperand());
2955         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2956         if (Load->getNumValues() == 3) {
2957           // PRE/POST_INC loads have 3 values.
2958           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2959                            NewLoad.getValue(2) };
2960           CombineTo(Load, To, 3, true);
2961         } else {
2962           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2963         }
2964       }
2965
2966       // Fold the AND away, taking care not to fold to the old load node if we
2967       // replaced it.
2968       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2969
2970       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2971     }
2972   }
2973
2974   // fold (and (load x), 255) -> (zextload x, i8)
2975   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2976   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2977   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2978               (N0.getOpcode() == ISD::ANY_EXTEND &&
2979                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2980     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2981     LoadSDNode *LN0 = HasAnyExt
2982       ? cast<LoadSDNode>(N0.getOperand(0))
2983       : cast<LoadSDNode>(N0);
2984     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2985         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2986       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2987       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2988         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2989         EVT LoadedVT = LN0->getMemoryVT();
2990         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2991
2992         if (ExtVT == LoadedVT &&
2993             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2994                                                     ExtVT))) {
2995
2996           SDValue NewLoad =
2997             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2998                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2999                            LN0->getMemOperand());
3000           AddToWorklist(N);
3001           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3002           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3003         }
3004
3005         // Do not change the width of a volatile load.
3006         // Do not generate loads of non-round integer types since these can
3007         // be expensive (and would be wrong if the type is not byte sized).
3008         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3009             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3010                                                     ExtVT))) {
3011           EVT PtrType = LN0->getOperand(1).getValueType();
3012
3013           unsigned Alignment = LN0->getAlignment();
3014           SDValue NewPtr = LN0->getBasePtr();
3015
3016           // For big endian targets, we need to add an offset to the pointer
3017           // to load the correct bytes.  For little endian systems, we merely
3018           // need to read fewer bytes from the same pointer.
3019           if (TLI.isBigEndian()) {
3020             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3021             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3022             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3023             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3024                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3025             Alignment = MinAlign(Alignment, PtrOff);
3026           }
3027
3028           AddToWorklist(NewPtr.getNode());
3029
3030           SDValue Load =
3031             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3032                            LN0->getChain(), NewPtr,
3033                            LN0->getPointerInfo(),
3034                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3035                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3036           AddToWorklist(N);
3037           CombineTo(LN0, Load, Load.getValue(1));
3038           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3039         }
3040       }
3041     }
3042   }
3043
3044   if (SDValue Combined = visitANDLike(N0, N1, N))
3045     return Combined;
3046
3047   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3048   if (N0.getOpcode() == N1.getOpcode()) {
3049     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3050     if (Tmp.getNode()) return Tmp;
3051   }
3052
3053   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3054   // fold (and (sra)) -> (and (srl)) when possible.
3055   if (!VT.isVector() &&
3056       SimplifyDemandedBits(SDValue(N, 0)))
3057     return SDValue(N, 0);
3058
3059   // fold (zext_inreg (extload x)) -> (zextload x)
3060   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3061     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3062     EVT MemVT = LN0->getMemoryVT();
3063     // If we zero all the possible extended bits, then we can turn this into
3064     // a zextload if we are running before legalize or the operation is legal.
3065     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3066     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3067                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3068         ((!LegalOperations && !LN0->isVolatile()) ||
3069          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3070       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3071                                        LN0->getChain(), LN0->getBasePtr(),
3072                                        MemVT, LN0->getMemOperand());
3073       AddToWorklist(N);
3074       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3075       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3076     }
3077   }
3078   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3079   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3080       N0.hasOneUse()) {
3081     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3082     EVT MemVT = LN0->getMemoryVT();
3083     // If we zero all the possible extended bits, then we can turn this into
3084     // a zextload if we are running before legalize or the operation is legal.
3085     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3086     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3087                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3088         ((!LegalOperations && !LN0->isVolatile()) ||
3089          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3090       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3091                                        LN0->getChain(), LN0->getBasePtr(),
3092                                        MemVT, LN0->getMemOperand());
3093       AddToWorklist(N);
3094       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3095       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3096     }
3097   }
3098   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3099   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3100     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3101                                        N0.getOperand(1), false);
3102     if (BSwap.getNode())
3103       return BSwap;
3104   }
3105
3106   return SDValue();
3107 }
3108
3109 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3110 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3111                                         bool DemandHighBits) {
3112   if (!LegalOperations)
3113     return SDValue();
3114
3115   EVT VT = N->getValueType(0);
3116   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3117     return SDValue();
3118   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3119     return SDValue();
3120
3121   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3122   bool LookPassAnd0 = false;
3123   bool LookPassAnd1 = false;
3124   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3125       std::swap(N0, N1);
3126   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3127       std::swap(N0, N1);
3128   if (N0.getOpcode() == ISD::AND) {
3129     if (!N0.getNode()->hasOneUse())
3130       return SDValue();
3131     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3132     if (!N01C || N01C->getZExtValue() != 0xFF00)
3133       return SDValue();
3134     N0 = N0.getOperand(0);
3135     LookPassAnd0 = true;
3136   }
3137
3138   if (N1.getOpcode() == ISD::AND) {
3139     if (!N1.getNode()->hasOneUse())
3140       return SDValue();
3141     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3142     if (!N11C || N11C->getZExtValue() != 0xFF)
3143       return SDValue();
3144     N1 = N1.getOperand(0);
3145     LookPassAnd1 = true;
3146   }
3147
3148   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3149     std::swap(N0, N1);
3150   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3151     return SDValue();
3152   if (!N0.getNode()->hasOneUse() ||
3153       !N1.getNode()->hasOneUse())
3154     return SDValue();
3155
3156   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3157   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3158   if (!N01C || !N11C)
3159     return SDValue();
3160   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3161     return SDValue();
3162
3163   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3164   SDValue N00 = N0->getOperand(0);
3165   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3166     if (!N00.getNode()->hasOneUse())
3167       return SDValue();
3168     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3169     if (!N001C || N001C->getZExtValue() != 0xFF)
3170       return SDValue();
3171     N00 = N00.getOperand(0);
3172     LookPassAnd0 = true;
3173   }
3174
3175   SDValue N10 = N1->getOperand(0);
3176   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3177     if (!N10.getNode()->hasOneUse())
3178       return SDValue();
3179     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3180     if (!N101C || N101C->getZExtValue() != 0xFF00)
3181       return SDValue();
3182     N10 = N10.getOperand(0);
3183     LookPassAnd1 = true;
3184   }
3185
3186   if (N00 != N10)
3187     return SDValue();
3188
3189   // Make sure everything beyond the low halfword gets set to zero since the SRL
3190   // 16 will clear the top bits.
3191   unsigned OpSizeInBits = VT.getSizeInBits();
3192   if (DemandHighBits && OpSizeInBits > 16) {
3193     // If the left-shift isn't masked out then the only way this is a bswap is
3194     // if all bits beyond the low 8 are 0. In that case the entire pattern
3195     // reduces to a left shift anyway: leave it for other parts of the combiner.
3196     if (!LookPassAnd0)
3197       return SDValue();
3198
3199     // However, if the right shift isn't masked out then it might be because
3200     // it's not needed. See if we can spot that too.
3201     if (!LookPassAnd1 &&
3202         !DAG.MaskedValueIsZero(
3203             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3204       return SDValue();
3205   }
3206
3207   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3208   if (OpSizeInBits > 16)
3209     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3210                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3211   return Res;
3212 }
3213
3214 /// Return true if the specified node is an element that makes up a 32-bit
3215 /// packed halfword byteswap.
3216 /// ((x & 0x000000ff) << 8) |
3217 /// ((x & 0x0000ff00) >> 8) |
3218 /// ((x & 0x00ff0000) << 8) |
3219 /// ((x & 0xff000000) >> 8)
3220 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3221   if (!N.getNode()->hasOneUse())
3222     return false;
3223
3224   unsigned Opc = N.getOpcode();
3225   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3226     return false;
3227
3228   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3229   if (!N1C)
3230     return false;
3231
3232   unsigned Num;
3233   switch (N1C->getZExtValue()) {
3234   default:
3235     return false;
3236   case 0xFF:       Num = 0; break;
3237   case 0xFF00:     Num = 1; break;
3238   case 0xFF0000:   Num = 2; break;
3239   case 0xFF000000: Num = 3; break;
3240   }
3241
3242   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3243   SDValue N0 = N.getOperand(0);
3244   if (Opc == ISD::AND) {
3245     if (Num == 0 || Num == 2) {
3246       // (x >> 8) & 0xff
3247       // (x >> 8) & 0xff0000
3248       if (N0.getOpcode() != ISD::SRL)
3249         return false;
3250       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3251       if (!C || C->getZExtValue() != 8)
3252         return false;
3253     } else {
3254       // (x << 8) & 0xff00
3255       // (x << 8) & 0xff000000
3256       if (N0.getOpcode() != ISD::SHL)
3257         return false;
3258       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3259       if (!C || C->getZExtValue() != 8)
3260         return false;
3261     }
3262   } else if (Opc == ISD::SHL) {
3263     // (x & 0xff) << 8
3264     // (x & 0xff0000) << 8
3265     if (Num != 0 && Num != 2)
3266       return false;
3267     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3268     if (!C || C->getZExtValue() != 8)
3269       return false;
3270   } else { // Opc == ISD::SRL
3271     // (x & 0xff00) >> 8
3272     // (x & 0xff000000) >> 8
3273     if (Num != 1 && Num != 3)
3274       return false;
3275     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276     if (!C || C->getZExtValue() != 8)
3277       return false;
3278   }
3279
3280   if (Parts[Num])
3281     return false;
3282
3283   Parts[Num] = N0.getOperand(0).getNode();
3284   return true;
3285 }
3286
3287 /// Match a 32-bit packed halfword bswap. That is
3288 /// ((x & 0x000000ff) << 8) |
3289 /// ((x & 0x0000ff00) >> 8) |
3290 /// ((x & 0x00ff0000) << 8) |
3291 /// ((x & 0xff000000) >> 8)
3292 /// => (rotl (bswap x), 16)
3293 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3294   if (!LegalOperations)
3295     return SDValue();
3296
3297   EVT VT = N->getValueType(0);
3298   if (VT != MVT::i32)
3299     return SDValue();
3300   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3301     return SDValue();
3302
3303   // Look for either
3304   // (or (or (and), (and)), (or (and), (and)))
3305   // (or (or (or (and), (and)), (and)), (and))
3306   if (N0.getOpcode() != ISD::OR)
3307     return SDValue();
3308   SDValue N00 = N0.getOperand(0);
3309   SDValue N01 = N0.getOperand(1);
3310   SDNode *Parts[4] = {};
3311
3312   if (N1.getOpcode() == ISD::OR &&
3313       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3314     // (or (or (and), (and)), (or (and), (and)))
3315     SDValue N000 = N00.getOperand(0);
3316     if (!isBSwapHWordElement(N000, Parts))
3317       return SDValue();
3318
3319     SDValue N001 = N00.getOperand(1);
3320     if (!isBSwapHWordElement(N001, Parts))
3321       return SDValue();
3322     SDValue N010 = N01.getOperand(0);
3323     if (!isBSwapHWordElement(N010, Parts))
3324       return SDValue();
3325     SDValue N011 = N01.getOperand(1);
3326     if (!isBSwapHWordElement(N011, Parts))
3327       return SDValue();
3328   } else {
3329     // (or (or (or (and), (and)), (and)), (and))
3330     if (!isBSwapHWordElement(N1, Parts))
3331       return SDValue();
3332     if (!isBSwapHWordElement(N01, Parts))
3333       return SDValue();
3334     if (N00.getOpcode() != ISD::OR)
3335       return SDValue();
3336     SDValue N000 = N00.getOperand(0);
3337     if (!isBSwapHWordElement(N000, Parts))
3338       return SDValue();
3339     SDValue N001 = N00.getOperand(1);
3340     if (!isBSwapHWordElement(N001, Parts))
3341       return SDValue();
3342   }
3343
3344   // Make sure the parts are all coming from the same node.
3345   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3346     return SDValue();
3347
3348   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3349                               SDValue(Parts[0],0));
3350
3351   // Result of the bswap should be rotated by 16. If it's not legal, then
3352   // do  (x << 16) | (x >> 16).
3353   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3354   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3355     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3356   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3357     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3358   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3359                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3360                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3361 }
3362
3363 /// This contains all DAGCombine rules which reduce two values combined by
3364 /// an Or operation to a single value \see visitANDLike().
3365 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3366   EVT VT = N1.getValueType();
3367   // fold (or x, undef) -> -1
3368   if (!LegalOperations &&
3369       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3370     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3371     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3372   }
3373   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3374   SDValue LL, LR, RL, RR, CC0, CC1;
3375   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3376     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3377     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3378
3379     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3380         LL.getValueType().isInteger()) {
3381       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3382       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3383       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3384           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3385         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3386                                      LR.getValueType(), LL, RL);
3387         AddToWorklist(ORNode.getNode());
3388         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3389       }
3390       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3391       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3392       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3393           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3394         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3395                                       LR.getValueType(), LL, RL);
3396         AddToWorklist(ANDNode.getNode());
3397         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3398       }
3399     }
3400     // canonicalize equivalent to ll == rl
3401     if (LL == RR && LR == RL) {
3402       Op1 = ISD::getSetCCSwappedOperands(Op1);
3403       std::swap(RL, RR);
3404     }
3405     if (LL == RL && LR == RR) {
3406       bool isInteger = LL.getValueType().isInteger();
3407       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3408       if (Result != ISD::SETCC_INVALID &&
3409           (!LegalOperations ||
3410            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3411             TLI.isOperationLegal(ISD::SETCC,
3412               getSetCCResultType(N0.getValueType())))))
3413         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3414                             LL, LR, Result);
3415     }
3416   }
3417
3418   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3419   if (N0.getOpcode() == ISD::AND &&
3420       N1.getOpcode() == ISD::AND &&
3421       N0.getOperand(1).getOpcode() == ISD::Constant &&
3422       N1.getOperand(1).getOpcode() == ISD::Constant &&
3423       // Don't increase # computations.
3424       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3425     // We can only do this xform if we know that bits from X that are set in C2
3426     // but not in C1 are already zero.  Likewise for Y.
3427     const APInt &LHSMask =
3428       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3429     const APInt &RHSMask =
3430       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3431
3432     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3433         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3434       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3435                               N0.getOperand(0), N1.getOperand(0));
3436       return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3437                          DAG.getConstant(LHSMask | RHSMask, VT));
3438     }
3439   }
3440
3441   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3442   if (N0.getOpcode() == ISD::AND &&
3443       N1.getOpcode() == ISD::AND &&
3444       N0.getOperand(0) == N1.getOperand(0) &&
3445       // Don't increase # computations.
3446       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3447     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3448                             N0.getOperand(1), N1.getOperand(1));
3449     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3450   }
3451
3452   return SDValue();
3453 }
3454
3455 SDValue DAGCombiner::visitOR(SDNode *N) {
3456   SDValue N0 = N->getOperand(0);
3457   SDValue N1 = N->getOperand(1);
3458   EVT VT = N1.getValueType();
3459
3460   // fold vector ops
3461   if (VT.isVector()) {
3462     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3463       return FoldedVOp;
3464
3465     // fold (or x, 0) -> x, vector edition
3466     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3467       return N1;
3468     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3469       return N0;
3470
3471     // fold (or x, -1) -> -1, vector edition
3472     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3473       // do not return N0, because undef node may exist in N0
3474       return DAG.getConstant(
3475           APInt::getAllOnesValue(
3476               N0.getValueType().getScalarType().getSizeInBits()),
3477           N0.getValueType());
3478     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3479       // do not return N1, because undef node may exist in N1
3480       return DAG.getConstant(
3481           APInt::getAllOnesValue(
3482               N1.getValueType().getScalarType().getSizeInBits()),
3483           N1.getValueType());
3484
3485     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3486     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3487     // Do this only if the resulting shuffle is legal.
3488     if (isa<ShuffleVectorSDNode>(N0) &&
3489         isa<ShuffleVectorSDNode>(N1) &&
3490         // Avoid folding a node with illegal type.
3491         TLI.isTypeLegal(VT) &&
3492         N0->getOperand(1) == N1->getOperand(1) &&
3493         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3494       bool CanFold = true;
3495       unsigned NumElts = VT.getVectorNumElements();
3496       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3497       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3498       // We construct two shuffle masks:
3499       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3500       // and N1 as the second operand.
3501       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3502       // and N0 as the second operand.
3503       // We do this because OR is commutable and therefore there might be
3504       // two ways to fold this node into a shuffle.
3505       SmallVector<int,4> Mask1;
3506       SmallVector<int,4> Mask2;
3507
3508       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3509         int M0 = SV0->getMaskElt(i);
3510         int M1 = SV1->getMaskElt(i);
3511
3512         // Both shuffle indexes are undef. Propagate Undef.
3513         if (M0 < 0 && M1 < 0) {
3514           Mask1.push_back(M0);
3515           Mask2.push_back(M0);
3516           continue;
3517         }
3518
3519         if (M0 < 0 || M1 < 0 ||
3520             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3521             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3522           CanFold = false;
3523           break;
3524         }
3525
3526         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3527         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3528       }
3529
3530       if (CanFold) {
3531         // Fold this sequence only if the resulting shuffle is 'legal'.
3532         if (TLI.isShuffleMaskLegal(Mask1, VT))
3533           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3534                                       N1->getOperand(0), &Mask1[0]);
3535         if (TLI.isShuffleMaskLegal(Mask2, VT))
3536           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3537                                       N0->getOperand(0), &Mask2[0]);
3538       }
3539     }
3540   }
3541
3542   // fold (or c1, c2) -> c1|c2
3543   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3544   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3545   if (N0C && N1C)
3546     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3547   // canonicalize constant to RHS
3548   if (N0C && !N1C)
3549     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3550   // fold (or x, 0) -> x
3551   if (N1C && N1C->isNullValue())
3552     return N0;
3553   // fold (or x, -1) -> -1
3554   if (N1C && N1C->isAllOnesValue())
3555     return N1;
3556   // fold (or x, c) -> c iff (x & ~c) == 0
3557   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3558     return N1;
3559
3560   if (SDValue Combined = visitORLike(N0, N1, N))
3561     return Combined;
3562
3563   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3564   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3565   if (BSwap.getNode())
3566     return BSwap;
3567   BSwap = MatchBSwapHWordLow(N, N0, N1);
3568   if (BSwap.getNode())
3569     return BSwap;
3570
3571   // reassociate or
3572   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3573     return ROR;
3574   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3575   // iff (c1 & c2) == 0.
3576   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3577              isa<ConstantSDNode>(N0.getOperand(1))) {
3578     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3579     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3580       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3581         return DAG.getNode(
3582             ISD::AND, SDLoc(N), VT,
3583             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3584       return SDValue();
3585     }
3586   }
3587   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3588   if (N0.getOpcode() == N1.getOpcode()) {
3589     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3590     if (Tmp.getNode()) return Tmp;
3591   }
3592
3593   // See if this is some rotate idiom.
3594   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3595     return SDValue(Rot, 0);
3596
3597   // Simplify the operands using demanded-bits information.
3598   if (!VT.isVector() &&
3599       SimplifyDemandedBits(SDValue(N, 0)))
3600     return SDValue(N, 0);
3601
3602   return SDValue();
3603 }
3604
3605 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3606 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3607   if (Op.getOpcode() == ISD::AND) {
3608     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3609       Mask = Op.getOperand(1);
3610       Op = Op.getOperand(0);
3611     } else {
3612       return false;
3613     }
3614   }
3615
3616   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3617     Shift = Op;
3618     return true;
3619   }
3620
3621   return false;
3622 }
3623
3624 // Return true if we can prove that, whenever Neg and Pos are both in the
3625 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3626 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3627 //
3628 //     (or (shift1 X, Neg), (shift2 X, Pos))
3629 //
3630 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3631 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3632 // to consider shift amounts with defined behavior.
3633 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3634   // If OpSize is a power of 2 then:
3635   //
3636   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3637   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3638   //
3639   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3640   // for the stronger condition:
3641   //
3642   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3643   //
3644   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3645   // we can just replace Neg with Neg' for the rest of the function.
3646   //
3647   // In other cases we check for the even stronger condition:
3648   //
3649   //     Neg == OpSize - Pos                                    [B]
3650   //
3651   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3652   // behavior if Pos == 0 (and consequently Neg == OpSize).
3653   //
3654   // We could actually use [A] whenever OpSize is a power of 2, but the
3655   // only extra cases that it would match are those uninteresting ones
3656   // where Neg and Pos are never in range at the same time.  E.g. for
3657   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3658   // as well as (sub 32, Pos), but:
3659   //
3660   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3661   //
3662   // always invokes undefined behavior for 32-bit X.
3663   //
3664   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3665   unsigned MaskLoBits = 0;
3666   if (Neg.getOpcode() == ISD::AND &&
3667       isPowerOf2_64(OpSize) &&
3668       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3669       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3670     Neg = Neg.getOperand(0);
3671     MaskLoBits = Log2_64(OpSize);
3672   }
3673
3674   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3675   if (Neg.getOpcode() != ISD::SUB)
3676     return 0;
3677   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3678   if (!NegC)
3679     return 0;
3680   SDValue NegOp1 = Neg.getOperand(1);
3681
3682   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3683   // Pos'.  The truncation is redundant for the purpose of the equality.
3684   if (MaskLoBits &&
3685       Pos.getOpcode() == ISD::AND &&
3686       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3687       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3688     Pos = Pos.getOperand(0);
3689
3690   // The condition we need is now:
3691   //
3692   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3693   //
3694   // If NegOp1 == Pos then we need:
3695   //
3696   //              OpSize & Mask == NegC & Mask
3697   //
3698   // (because "x & Mask" is a truncation and distributes through subtraction).
3699   APInt Width;
3700   if (Pos == NegOp1)
3701     Width = NegC->getAPIntValue();
3702   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3703   // Then the condition we want to prove becomes:
3704   //
3705   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3706   //
3707   // which, again because "x & Mask" is a truncation, becomes:
3708   //
3709   //                NegC & Mask == (OpSize - PosC) & Mask
3710   //              OpSize & Mask == (NegC + PosC) & Mask
3711   else if (Pos.getOpcode() == ISD::ADD &&
3712            Pos.getOperand(0) == NegOp1 &&
3713            Pos.getOperand(1).getOpcode() == ISD::Constant)
3714     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3715              NegC->getAPIntValue());
3716   else
3717     return false;
3718
3719   // Now we just need to check that OpSize & Mask == Width & Mask.
3720   if (MaskLoBits)
3721     // Opsize & Mask is 0 since Mask is Opsize - 1.
3722     return Width.getLoBits(MaskLoBits) == 0;
3723   return Width == OpSize;
3724 }
3725
3726 // A subroutine of MatchRotate used once we have found an OR of two opposite
3727 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3728 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3729 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3730 // Neg with outer conversions stripped away.
3731 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3732                                        SDValue Neg, SDValue InnerPos,
3733                                        SDValue InnerNeg, unsigned PosOpcode,
3734                                        unsigned NegOpcode, SDLoc DL) {
3735   // fold (or (shl x, (*ext y)),
3736   //          (srl x, (*ext (sub 32, y)))) ->
3737   //   (rotl x, y) or (rotr x, (sub 32, y))
3738   //
3739   // fold (or (shl x, (*ext (sub 32, y))),
3740   //          (srl x, (*ext y))) ->
3741   //   (rotr x, y) or (rotl x, (sub 32, y))
3742   EVT VT = Shifted.getValueType();
3743   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3744     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3745     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3746                        HasPos ? Pos : Neg).getNode();
3747   }
3748
3749   return nullptr;
3750 }
3751
3752 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3753 // idioms for rotate, and if the target supports rotation instructions, generate
3754 // a rot[lr].
3755 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3756   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3757   EVT VT = LHS.getValueType();
3758   if (!TLI.isTypeLegal(VT)) return nullptr;
3759
3760   // The target must have at least one rotate flavor.
3761   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3762   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3763   if (!HasROTL && !HasROTR) return nullptr;
3764
3765   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3766   SDValue LHSShift;   // The shift.
3767   SDValue LHSMask;    // AND value if any.
3768   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3769     return nullptr; // Not part of a rotate.
3770
3771   SDValue RHSShift;   // The shift.
3772   SDValue RHSMask;    // AND value if any.
3773   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3774     return nullptr; // Not part of a rotate.
3775
3776   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3777     return nullptr;   // Not shifting the same value.
3778
3779   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3780     return nullptr;   // Shifts must disagree.
3781
3782   // Canonicalize shl to left side in a shl/srl pair.
3783   if (RHSShift.getOpcode() == ISD::SHL) {
3784     std::swap(LHS, RHS);
3785     std::swap(LHSShift, RHSShift);
3786     std::swap(LHSMask , RHSMask );
3787   }
3788
3789   unsigned OpSizeInBits = VT.getSizeInBits();
3790   SDValue LHSShiftArg = LHSShift.getOperand(0);
3791   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3792   SDValue RHSShiftArg = RHSShift.getOperand(0);
3793   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3794
3795   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3796   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3797   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3798       RHSShiftAmt.getOpcode() == ISD::Constant) {
3799     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3800     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3801     if ((LShVal + RShVal) != OpSizeInBits)
3802       return nullptr;
3803
3804     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3805                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3806
3807     // If there is an AND of either shifted operand, apply it to the result.
3808     if (LHSMask.getNode() || RHSMask.getNode()) {
3809       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3810
3811       if (LHSMask.getNode()) {
3812         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3813         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3814       }
3815       if (RHSMask.getNode()) {
3816         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3817         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3818       }
3819
3820       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3821     }
3822
3823     return Rot.getNode();
3824   }
3825
3826   // If there is a mask here, and we have a variable shift, we can't be sure
3827   // that we're masking out the right stuff.
3828   if (LHSMask.getNode() || RHSMask.getNode())
3829     return nullptr;
3830
3831   // If the shift amount is sign/zext/any-extended just peel it off.
3832   SDValue LExtOp0 = LHSShiftAmt;
3833   SDValue RExtOp0 = RHSShiftAmt;
3834   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3835        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3836        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3837        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3838       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3839        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3840        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3841        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3842     LExtOp0 = LHSShiftAmt.getOperand(0);
3843     RExtOp0 = RHSShiftAmt.getOperand(0);
3844   }
3845
3846   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3847                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3848   if (TryL)
3849     return TryL;
3850
3851   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3852                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3853   if (TryR)
3854     return TryR;
3855
3856   return nullptr;
3857 }
3858
3859 SDValue DAGCombiner::visitXOR(SDNode *N) {
3860   SDValue N0 = N->getOperand(0);
3861   SDValue N1 = N->getOperand(1);
3862   EVT VT = N0.getValueType();
3863
3864   // fold vector ops
3865   if (VT.isVector()) {
3866     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3867       return FoldedVOp;
3868
3869     // fold (xor x, 0) -> x, vector edition
3870     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3871       return N1;
3872     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3873       return N0;
3874   }
3875
3876   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3877   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3878     return DAG.getConstant(0, VT);
3879   // fold (xor x, undef) -> undef
3880   if (N0.getOpcode() == ISD::UNDEF)
3881     return N0;
3882   if (N1.getOpcode() == ISD::UNDEF)
3883     return N1;
3884   // fold (xor c1, c2) -> c1^c2
3885   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3886   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3887   if (N0C && N1C)
3888     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3889   // canonicalize constant to RHS
3890   if (N0C && !N1C)
3891     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3892   // fold (xor x, 0) -> x
3893   if (N1C && N1C->isNullValue())
3894     return N0;
3895   // reassociate xor
3896   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3897     return RXOR;
3898
3899   // fold !(x cc y) -> (x !cc y)
3900   SDValue LHS, RHS, CC;
3901   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3902     bool isInt = LHS.getValueType().isInteger();
3903     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3904                                                isInt);
3905
3906     if (!LegalOperations ||
3907         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3908       switch (N0.getOpcode()) {
3909       default:
3910         llvm_unreachable("Unhandled SetCC Equivalent!");
3911       case ISD::SETCC:
3912         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3913       case ISD::SELECT_CC:
3914         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3915                                N0.getOperand(3), NotCC);
3916       }
3917     }
3918   }
3919
3920   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3921   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3922       N0.getNode()->hasOneUse() &&
3923       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3924     SDValue V = N0.getOperand(0);
3925     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3926                     DAG.getConstant(1, V.getValueType()));
3927     AddToWorklist(V.getNode());
3928     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3929   }
3930
3931   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3932   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3933       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3934     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3935     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3936       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3937       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3938       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3939       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3940       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3941     }
3942   }
3943   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3944   if (N1C && N1C->isAllOnesValue() &&
3945       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3946     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3947     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3948       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3949       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3950       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3951       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3952       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3953     }
3954   }
3955   // fold (xor (and x, y), y) -> (and (not x), y)
3956   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3957       N0->getOperand(1) == N1) {
3958     SDValue X = N0->getOperand(0);
3959     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3960     AddToWorklist(NotX.getNode());
3961     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3962   }
3963   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3964   if (N1C && N0.getOpcode() == ISD::XOR) {
3965     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3966     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3967     if (N00C)
3968       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3969                          DAG.getConstant(N1C->getAPIntValue() ^
3970                                          N00C->getAPIntValue(), VT));
3971     if (N01C)
3972       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3973                          DAG.getConstant(N1C->getAPIntValue() ^
3974                                          N01C->getAPIntValue(), VT));
3975   }
3976   // fold (xor x, x) -> 0
3977   if (N0 == N1)
3978     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3979
3980   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3981   // Here is a concrete example of this equivalence:
3982   // i16   x ==  14
3983   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
3984   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3985   //
3986   // =>
3987   //
3988   // i16     ~1      == 0b1111111111111110
3989   // i16 rol(~1, 14) == 0b1011111111111111
3990   //
3991   // Some additional tips to help conceptualize this transform:
3992   // - Try to see the operation as placing a single zero in a value of all ones.
3993   // - There exists no value for x which would allow the result to contain zero.
3994   // - Values of x larger than the bitwidth are undefined and do not require a
3995   //   consistent result.
3996   // - Pushing the zero left requires shifting one bits in from the right.
3997   // A rotate left of ~1 is a nice way of achieving the desired result.
3998   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3999     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4000       if (N0.getOpcode() == ISD::SHL)
4001         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4002           if (N1C->isAllOnesValue() && ShlLHS->isOne())
4003             return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4004                                N0.getOperand(1));
4005
4006   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4007   if (N0.getOpcode() == N1.getOpcode()) {
4008     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4009     if (Tmp.getNode()) return Tmp;
4010   }
4011
4012   // Simplify the expression using non-local knowledge.
4013   if (!VT.isVector() &&
4014       SimplifyDemandedBits(SDValue(N, 0)))
4015     return SDValue(N, 0);
4016
4017   return SDValue();
4018 }
4019
4020 /// Handle transforms common to the three shifts, when the shift amount is a
4021 /// constant.
4022 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4023   // We can't and shouldn't fold opaque constants.
4024   if (Amt->isOpaque())
4025     return SDValue();
4026
4027   SDNode *LHS = N->getOperand(0).getNode();
4028   if (!LHS->hasOneUse()) return SDValue();
4029
4030   // We want to pull some binops through shifts, so that we have (and (shift))
4031   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4032   // thing happens with address calculations, so it's important to canonicalize
4033   // it.
4034   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4035
4036   switch (LHS->getOpcode()) {
4037   default: return SDValue();
4038   case ISD::OR:
4039   case ISD::XOR:
4040     HighBitSet = false; // We can only transform sra if the high bit is clear.
4041     break;
4042   case ISD::AND:
4043     HighBitSet = true;  // We can only transform sra if the high bit is set.
4044     break;
4045   case ISD::ADD:
4046     if (N->getOpcode() != ISD::SHL)
4047       return SDValue(); // only shl(add) not sr[al](add).
4048     HighBitSet = false; // We can only transform sra if the high bit is clear.
4049     break;
4050   }
4051
4052   // We require the RHS of the binop to be a constant and not opaque as well.
4053   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4054   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4055
4056   // FIXME: disable this unless the input to the binop is a shift by a constant.
4057   // If it is not a shift, it pessimizes some common cases like:
4058   //
4059   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4060   //    int bar(int *X, int i) { return X[i & 255]; }
4061   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4062   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4063        BinOpLHSVal->getOpcode() != ISD::SRA &&
4064        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4065       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4066     return SDValue();
4067
4068   EVT VT = N->getValueType(0);
4069
4070   // If this is a signed shift right, and the high bit is modified by the
4071   // logical operation, do not perform the transformation. The highBitSet
4072   // boolean indicates the value of the high bit of the constant which would
4073   // cause it to be modified for this operation.
4074   if (N->getOpcode() == ISD::SRA) {
4075     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4076     if (BinOpRHSSignSet != HighBitSet)
4077       return SDValue();
4078   }
4079
4080   if (!TLI.isDesirableToCommuteWithShift(LHS))
4081     return SDValue();
4082
4083   // Fold the constants, shifting the binop RHS by the shift amount.
4084   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4085                                N->getValueType(0),
4086                                LHS->getOperand(1), N->getOperand(1));
4087   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4088
4089   // Create the new shift.
4090   SDValue NewShift = DAG.getNode(N->getOpcode(),
4091                                  SDLoc(LHS->getOperand(0)),
4092                                  VT, LHS->getOperand(0), N->getOperand(1));
4093
4094   // Create the new binop.
4095   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4096 }
4097
4098 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4099   assert(N->getOpcode() == ISD::TRUNCATE);
4100   assert(N->getOperand(0).getOpcode() == ISD::AND);
4101
4102   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4103   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4104     SDValue N01 = N->getOperand(0).getOperand(1);
4105
4106     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4107       EVT TruncVT = N->getValueType(0);
4108       SDValue N00 = N->getOperand(0).getOperand(0);
4109       APInt TruncC = N01C->getAPIntValue();
4110       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4111
4112       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4113                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4114                          DAG.getConstant(TruncC, TruncVT));
4115     }
4116   }
4117
4118   return SDValue();
4119 }
4120
4121 SDValue DAGCombiner::visitRotate(SDNode *N) {
4122   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4123   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4124       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4125     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4126     if (NewOp1.getNode())
4127       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4128                          N->getOperand(0), NewOp1);
4129   }
4130   return SDValue();
4131 }
4132
4133 SDValue DAGCombiner::visitSHL(SDNode *N) {
4134   SDValue N0 = N->getOperand(0);
4135   SDValue N1 = N->getOperand(1);
4136   EVT VT = N0.getValueType();
4137   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4138
4139   // fold vector ops
4140   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4141   if (VT.isVector()) {
4142     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4143       return FoldedVOp;
4144
4145     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4146     // If setcc produces all-one true value then:
4147     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4148     if (N1CV && N1CV->isConstant()) {
4149       if (N0.getOpcode() == ISD::AND) {
4150         SDValue N00 = N0->getOperand(0);
4151         SDValue N01 = N0->getOperand(1);
4152         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4153
4154         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4155             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4156                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4157           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4158             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4159         }
4160       } else {
4161         N1C = isConstOrConstSplat(N1);
4162       }
4163     }
4164   }
4165
4166   // fold (shl c1, c2) -> c1<<c2
4167   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4168   if (N0C && N1C)
4169     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4170   // fold (shl 0, x) -> 0
4171   if (N0C && N0C->isNullValue())
4172     return N0;
4173   // fold (shl x, c >= size(x)) -> undef
4174   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4175     return DAG.getUNDEF(VT);
4176   // fold (shl x, 0) -> x
4177   if (N1C && N1C->isNullValue())
4178     return N0;
4179   // fold (shl undef, x) -> 0
4180   if (N0.getOpcode() == ISD::UNDEF)
4181     return DAG.getConstant(0, VT);
4182   // if (shl x, c) is known to be zero, return 0
4183   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4184                             APInt::getAllOnesValue(OpSizeInBits)))
4185     return DAG.getConstant(0, VT);
4186   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4187   if (N1.getOpcode() == ISD::TRUNCATE &&
4188       N1.getOperand(0).getOpcode() == ISD::AND) {
4189     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4190     if (NewOp1.getNode())
4191       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4192   }
4193
4194   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4195     return SDValue(N, 0);
4196
4197   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4198   if (N1C && N0.getOpcode() == ISD::SHL) {
4199     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4200       uint64_t c1 = N0C1->getZExtValue();
4201       uint64_t c2 = N1C->getZExtValue();
4202       if (c1 + c2 >= OpSizeInBits)
4203         return DAG.getConstant(0, VT);
4204       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4205                          DAG.getConstant(c1 + c2, N1.getValueType()));
4206     }
4207   }
4208
4209   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4210   // For this to be valid, the second form must not preserve any of the bits
4211   // that are shifted out by the inner shift in the first form.  This means
4212   // the outer shift size must be >= the number of bits added by the ext.
4213   // As a corollary, we don't care what kind of ext it is.
4214   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4215               N0.getOpcode() == ISD::ANY_EXTEND ||
4216               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4217       N0.getOperand(0).getOpcode() == ISD::SHL) {
4218     SDValue N0Op0 = N0.getOperand(0);
4219     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4220       uint64_t c1 = N0Op0C1->getZExtValue();
4221       uint64_t c2 = N1C->getZExtValue();
4222       EVT InnerShiftVT = N0Op0.getValueType();
4223       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4224       if (c2 >= OpSizeInBits - InnerShiftSize) {
4225         if (c1 + c2 >= OpSizeInBits)
4226           return DAG.getConstant(0, VT);
4227         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4228                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4229                                        N0Op0->getOperand(0)),
4230                            DAG.getConstant(c1 + c2, N1.getValueType()));
4231       }
4232     }
4233   }
4234
4235   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4236   // Only fold this if the inner zext has no other uses to avoid increasing
4237   // the total number of instructions.
4238   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4239       N0.getOperand(0).getOpcode() == ISD::SRL) {
4240     SDValue N0Op0 = N0.getOperand(0);
4241     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4242       uint64_t c1 = N0Op0C1->getZExtValue();
4243       if (c1 < VT.getScalarSizeInBits()) {
4244         uint64_t c2 = N1C->getZExtValue();
4245         if (c1 == c2) {
4246           SDValue NewOp0 = N0.getOperand(0);
4247           EVT CountVT = NewOp0.getOperand(1).getValueType();
4248           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4249                                        NewOp0, DAG.getConstant(c2, CountVT));
4250           AddToWorklist(NewSHL.getNode());
4251           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4252         }
4253       }
4254     }
4255   }
4256
4257   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4258   //                               (and (srl x, (sub c1, c2), MASK)
4259   // Only fold this if the inner shift has no other uses -- if it does, folding
4260   // this will increase the total number of instructions.
4261   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4262     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4263       uint64_t c1 = N0C1->getZExtValue();
4264       if (c1 < OpSizeInBits) {
4265         uint64_t c2 = N1C->getZExtValue();
4266         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4267         SDValue Shift;
4268         if (c2 > c1) {
4269           Mask = Mask.shl(c2 - c1);
4270           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4271                               DAG.getConstant(c2 - c1, N1.getValueType()));
4272         } else {
4273           Mask = Mask.lshr(c1 - c2);
4274           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4275                               DAG.getConstant(c1 - c2, N1.getValueType()));
4276         }
4277         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4278                            DAG.getConstant(Mask, VT));
4279       }
4280     }
4281   }
4282   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4283   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4284     unsigned BitSize = VT.getScalarSizeInBits();
4285     SDValue HiBitsMask =
4286       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4287                                             BitSize - N1C->getZExtValue()), VT);
4288     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4289                        HiBitsMask);
4290   }
4291
4292   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4293   // Variant of version done on multiply, except mul by a power of 2 is turned
4294   // into a shift.
4295   APInt Val;
4296   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4297       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4298        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4299     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4300     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4301     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4302   }
4303
4304   if (N1C) {
4305     SDValue NewSHL = visitShiftByConstant(N, N1C);
4306     if (NewSHL.getNode())
4307       return NewSHL;
4308   }
4309
4310   return SDValue();
4311 }
4312
4313 SDValue DAGCombiner::visitSRA(SDNode *N) {
4314   SDValue N0 = N->getOperand(0);
4315   SDValue N1 = N->getOperand(1);
4316   EVT VT = N0.getValueType();
4317   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4318
4319   // fold vector ops
4320   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4321   if (VT.isVector()) {
4322     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4323       return FoldedVOp;
4324
4325     N1C = isConstOrConstSplat(N1);
4326   }
4327
4328   // fold (sra c1, c2) -> (sra c1, c2)
4329   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4330   if (N0C && N1C)
4331     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4332   // fold (sra 0, x) -> 0
4333   if (N0C && N0C->isNullValue())
4334     return N0;
4335   // fold (sra -1, x) -> -1
4336   if (N0C && N0C->isAllOnesValue())
4337     return N0;
4338   // fold (sra x, (setge c, size(x))) -> undef
4339   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4340     return DAG.getUNDEF(VT);
4341   // fold (sra x, 0) -> x
4342   if (N1C && N1C->isNullValue())
4343     return N0;
4344   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4345   // sext_inreg.
4346   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4347     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4348     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4349     if (VT.isVector())
4350       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4351                                ExtVT, VT.getVectorNumElements());
4352     if ((!LegalOperations ||
4353          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4354       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4355                          N0.getOperand(0), DAG.getValueType(ExtVT));
4356   }
4357
4358   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4359   if (N1C && N0.getOpcode() == ISD::SRA) {
4360     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4361       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4362       if (Sum >= OpSizeInBits)
4363         Sum = OpSizeInBits - 1;
4364       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4365                          DAG.getConstant(Sum, N1.getValueType()));
4366     }
4367   }
4368
4369   // fold (sra (shl X, m), (sub result_size, n))
4370   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4371   // result_size - n != m.
4372   // If truncate is free for the target sext(shl) is likely to result in better
4373   // code.
4374   if (N0.getOpcode() == ISD::SHL && N1C) {
4375     // Get the two constanst of the shifts, CN0 = m, CN = n.
4376     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4377     if (N01C) {
4378       LLVMContext &Ctx = *DAG.getContext();
4379       // Determine what the truncate's result bitsize and type would be.
4380       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4381
4382       if (VT.isVector())
4383         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4384
4385       // Determine the residual right-shift amount.
4386       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4387
4388       // If the shift is not a no-op (in which case this should be just a sign
4389       // extend already), the truncated to type is legal, sign_extend is legal
4390       // on that type, and the truncate to that type is both legal and free,
4391       // perform the transform.
4392       if ((ShiftAmt > 0) &&
4393           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4394           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4395           TLI.isTruncateFree(VT, TruncVT)) {
4396
4397           SDValue Amt = DAG.getConstant(ShiftAmt,
4398               getShiftAmountTy(N0.getOperand(0).getValueType()));
4399           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4400                                       N0.getOperand(0), Amt);
4401           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4402                                       Shift);
4403           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4404                              N->getValueType(0), Trunc);
4405       }
4406     }
4407   }
4408
4409   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4410   if (N1.getOpcode() == ISD::TRUNCATE &&
4411       N1.getOperand(0).getOpcode() == ISD::AND) {
4412     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4413     if (NewOp1.getNode())
4414       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4415   }
4416
4417   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4418   //      if c1 is equal to the number of bits the trunc removes
4419   if (N0.getOpcode() == ISD::TRUNCATE &&
4420       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4421        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4422       N0.getOperand(0).hasOneUse() &&
4423       N0.getOperand(0).getOperand(1).hasOneUse() &&
4424       N1C) {
4425     SDValue N0Op0 = N0.getOperand(0);
4426     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4427       unsigned LargeShiftVal = LargeShift->getZExtValue();
4428       EVT LargeVT = N0Op0.getValueType();
4429
4430       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4431         SDValue Amt =
4432           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4433                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4434         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4435                                   N0Op0.getOperand(0), Amt);
4436         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4437       }
4438     }
4439   }
4440
4441   // Simplify, based on bits shifted out of the LHS.
4442   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4443     return SDValue(N, 0);
4444
4445
4446   // If the sign bit is known to be zero, switch this to a SRL.
4447   if (DAG.SignBitIsZero(N0))
4448     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4449
4450   if (N1C) {
4451     SDValue NewSRA = visitShiftByConstant(N, N1C);
4452     if (NewSRA.getNode())
4453       return NewSRA;
4454   }
4455
4456   return SDValue();
4457 }
4458
4459 SDValue DAGCombiner::visitSRL(SDNode *N) {
4460   SDValue N0 = N->getOperand(0);
4461   SDValue N1 = N->getOperand(1);
4462   EVT VT = N0.getValueType();
4463   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4464
4465   // fold vector ops
4466   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4467   if (VT.isVector()) {
4468     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4469       return FoldedVOp;
4470
4471     N1C = isConstOrConstSplat(N1);
4472   }
4473
4474   // fold (srl c1, c2) -> c1 >>u c2
4475   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4476   if (N0C && N1C)
4477     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4478   // fold (srl 0, x) -> 0
4479   if (N0C && N0C->isNullValue())
4480     return N0;
4481   // fold (srl x, c >= size(x)) -> undef
4482   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4483     return DAG.getUNDEF(VT);
4484   // fold (srl x, 0) -> x
4485   if (N1C && N1C->isNullValue())
4486     return N0;
4487   // if (srl x, c) is known to be zero, return 0
4488   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4489                                    APInt::getAllOnesValue(OpSizeInBits)))
4490     return DAG.getConstant(0, VT);
4491
4492   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4493   if (N1C && N0.getOpcode() == ISD::SRL) {
4494     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4495       uint64_t c1 = N01C->getZExtValue();
4496       uint64_t c2 = N1C->getZExtValue();
4497       if (c1 + c2 >= OpSizeInBits)
4498         return DAG.getConstant(0, VT);
4499       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4500                          DAG.getConstant(c1 + c2, N1.getValueType()));
4501     }
4502   }
4503
4504   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4505   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4506       N0.getOperand(0).getOpcode() == ISD::SRL &&
4507       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4508     uint64_t c1 =
4509       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4510     uint64_t c2 = N1C->getZExtValue();
4511     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4512     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4513     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4514     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4515     if (c1 + OpSizeInBits == InnerShiftSize) {
4516       if (c1 + c2 >= InnerShiftSize)
4517         return DAG.getConstant(0, VT);
4518       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4519                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4520                                      N0.getOperand(0)->getOperand(0),
4521                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4522     }
4523   }
4524
4525   // fold (srl (shl x, c), c) -> (and x, cst2)
4526   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4527     unsigned BitSize = N0.getScalarValueSizeInBits();
4528     if (BitSize <= 64) {
4529       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4530       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4531                          DAG.getConstant(~0ULL >> ShAmt, VT));
4532     }
4533   }
4534
4535   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4536   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4537     // Shifting in all undef bits?
4538     EVT SmallVT = N0.getOperand(0).getValueType();
4539     unsigned BitSize = SmallVT.getScalarSizeInBits();
4540     if (N1C->getZExtValue() >= BitSize)
4541       return DAG.getUNDEF(VT);
4542
4543     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4544       uint64_t ShiftAmt = N1C->getZExtValue();
4545       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4546                                        N0.getOperand(0),
4547                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4548       AddToWorklist(SmallShift.getNode());
4549       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4550       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4551                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4552                          DAG.getConstant(Mask, VT));
4553     }
4554   }
4555
4556   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4557   // bit, which is unmodified by sra.
4558   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4559     if (N0.getOpcode() == ISD::SRA)
4560       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4561   }
4562
4563   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4564   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4565       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4566     APInt KnownZero, KnownOne;
4567     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4568
4569     // If any of the input bits are KnownOne, then the input couldn't be all
4570     // zeros, thus the result of the srl will always be zero.
4571     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4572
4573     // If all of the bits input the to ctlz node are known to be zero, then
4574     // the result of the ctlz is "32" and the result of the shift is one.
4575     APInt UnknownBits = ~KnownZero;
4576     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4577
4578     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4579     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4580       // Okay, we know that only that the single bit specified by UnknownBits
4581       // could be set on input to the CTLZ node. If this bit is set, the SRL
4582       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4583       // to an SRL/XOR pair, which is likely to simplify more.
4584       unsigned ShAmt = UnknownBits.countTrailingZeros();
4585       SDValue Op = N0.getOperand(0);
4586
4587       if (ShAmt) {
4588         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4589                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4590         AddToWorklist(Op.getNode());
4591       }
4592
4593       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4594                          Op, DAG.getConstant(1, VT));
4595     }
4596   }
4597
4598   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4599   if (N1.getOpcode() == ISD::TRUNCATE &&
4600       N1.getOperand(0).getOpcode() == ISD::AND) {
4601     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4602     if (NewOp1.getNode())
4603       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4604   }
4605
4606   // fold operands of srl based on knowledge that the low bits are not
4607   // demanded.
4608   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4609     return SDValue(N, 0);
4610
4611   if (N1C) {
4612     SDValue NewSRL = visitShiftByConstant(N, N1C);
4613     if (NewSRL.getNode())
4614       return NewSRL;
4615   }
4616
4617   // Attempt to convert a srl of a load into a narrower zero-extending load.
4618   SDValue NarrowLoad = ReduceLoadWidth(N);
4619   if (NarrowLoad.getNode())
4620     return NarrowLoad;
4621
4622   // Here is a common situation. We want to optimize:
4623   //
4624   //   %a = ...
4625   //   %b = and i32 %a, 2
4626   //   %c = srl i32 %b, 1
4627   //   brcond i32 %c ...
4628   //
4629   // into
4630   //
4631   //   %a = ...
4632   //   %b = and %a, 2
4633   //   %c = setcc eq %b, 0
4634   //   brcond %c ...
4635   //
4636   // However when after the source operand of SRL is optimized into AND, the SRL
4637   // itself may not be optimized further. Look for it and add the BRCOND into
4638   // the worklist.
4639   if (N->hasOneUse()) {
4640     SDNode *Use = *N->use_begin();
4641     if (Use->getOpcode() == ISD::BRCOND)
4642       AddToWorklist(Use);
4643     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4644       // Also look pass the truncate.
4645       Use = *Use->use_begin();
4646       if (Use->getOpcode() == ISD::BRCOND)
4647         AddToWorklist(Use);
4648     }
4649   }
4650
4651   return SDValue();
4652 }
4653
4654 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4655   SDValue N0 = N->getOperand(0);
4656   EVT VT = N->getValueType(0);
4657
4658   // fold (ctlz c1) -> c2
4659   if (isa<ConstantSDNode>(N0))
4660     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4661   return SDValue();
4662 }
4663
4664 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4665   SDValue N0 = N->getOperand(0);
4666   EVT VT = N->getValueType(0);
4667
4668   // fold (ctlz_zero_undef c1) -> c2
4669   if (isa<ConstantSDNode>(N0))
4670     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4671   return SDValue();
4672 }
4673
4674 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4675   SDValue N0 = N->getOperand(0);
4676   EVT VT = N->getValueType(0);
4677
4678   // fold (cttz c1) -> c2
4679   if (isa<ConstantSDNode>(N0))
4680     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4681   return SDValue();
4682 }
4683
4684 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4685   SDValue N0 = N->getOperand(0);
4686   EVT VT = N->getValueType(0);
4687
4688   // fold (cttz_zero_undef c1) -> c2
4689   if (isa<ConstantSDNode>(N0))
4690     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4691   return SDValue();
4692 }
4693
4694 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4695   SDValue N0 = N->getOperand(0);
4696   EVT VT = N->getValueType(0);
4697
4698   // fold (ctpop c1) -> c2
4699   if (isa<ConstantSDNode>(N0))
4700     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4701   return SDValue();
4702 }
4703
4704
4705 /// \brief Generate Min/Max node
4706 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4707                                    SDValue True, SDValue False,
4708                                    ISD::CondCode CC, const TargetLowering &TLI,
4709                                    SelectionDAG &DAG) {
4710   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4711     return SDValue();
4712
4713   switch (CC) {
4714   case ISD::SETOLT:
4715   case ISD::SETOLE:
4716   case ISD::SETLT:
4717   case ISD::SETLE:
4718   case ISD::SETULT:
4719   case ISD::SETULE: {
4720     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4721     if (TLI.isOperationLegal(Opcode, VT))
4722       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4723     return SDValue();
4724   }
4725   case ISD::SETOGT:
4726   case ISD::SETOGE:
4727   case ISD::SETGT:
4728   case ISD::SETGE:
4729   case ISD::SETUGT:
4730   case ISD::SETUGE: {
4731     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4732     if (TLI.isOperationLegal(Opcode, VT))
4733       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4734     return SDValue();
4735   }
4736   default:
4737     return SDValue();
4738   }
4739 }
4740
4741 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4742   SDValue N0 = N->getOperand(0);
4743   SDValue N1 = N->getOperand(1);
4744   SDValue N2 = N->getOperand(2);
4745   EVT VT = N->getValueType(0);
4746   EVT VT0 = N0.getValueType();
4747
4748   // fold (select C, X, X) -> X
4749   if (N1 == N2)
4750     return N1;
4751   // fold (select true, X, Y) -> X
4752   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4753   if (N0C && !N0C->isNullValue())
4754     return N1;
4755   // fold (select false, X, Y) -> Y
4756   if (N0C && N0C->isNullValue())
4757     return N2;
4758   // fold (select C, 1, X) -> (or C, X)
4759   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4760   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4761     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4762   // fold (select C, 0, 1) -> (xor C, 1)
4763   // We can't do this reliably if integer based booleans have different contents
4764   // to floating point based booleans. This is because we can't tell whether we
4765   // have an integer-based boolean or a floating-point-based boolean unless we
4766   // can find the SETCC that produced it and inspect its operands. This is
4767   // fairly easy if C is the SETCC node, but it can potentially be
4768   // undiscoverable (or not reasonably discoverable). For example, it could be
4769   // in another basic block or it could require searching a complicated
4770   // expression.
4771   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4772   if (VT.isInteger() &&
4773       (VT0 == MVT::i1 || (VT0.isInteger() &&
4774                           TLI.getBooleanContents(false, false) ==
4775                               TLI.getBooleanContents(false, true) &&
4776                           TLI.getBooleanContents(false, false) ==
4777                               TargetLowering::ZeroOrOneBooleanContent)) &&
4778       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4779     SDValue XORNode;
4780     if (VT == VT0)
4781       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4782                          N0, DAG.getConstant(1, VT0));
4783     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4784                           N0, DAG.getConstant(1, VT0));
4785     AddToWorklist(XORNode.getNode());
4786     if (VT.bitsGT(VT0))
4787       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4788     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4789   }
4790   // fold (select C, 0, X) -> (and (not C), X)
4791   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4792     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4793     AddToWorklist(NOTNode.getNode());
4794     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4795   }
4796   // fold (select C, X, 1) -> (or (not C), X)
4797   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4798     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4799     AddToWorklist(NOTNode.getNode());
4800     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4801   }
4802   // fold (select C, X, 0) -> (and C, X)
4803   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4804     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4805   // fold (select X, X, Y) -> (or X, Y)
4806   // fold (select X, 1, Y) -> (or X, Y)
4807   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4808     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4809   // fold (select X, Y, X) -> (and X, Y)
4810   // fold (select X, Y, 0) -> (and X, Y)
4811   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4812     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4813
4814   // If we can fold this based on the true/false value, do so.
4815   if (SimplifySelectOps(N, N1, N2))
4816     return SDValue(N, 0);  // Don't revisit N.
4817
4818   // fold selects based on a setcc into other things, such as min/max/abs
4819   if (N0.getOpcode() == ISD::SETCC) {
4820     // select x, y (fcmp lt x, y) -> fminnum x, y
4821     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4822     //
4823     // This is OK if we don't care about what happens if either operand is a
4824     // NaN.
4825     //
4826
4827     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4828     // no signed zeros as well as no nans.
4829     const TargetOptions &Options = DAG.getTarget().Options;
4830     if (Options.UnsafeFPMath &&
4831         VT.isFloatingPoint() && N0.hasOneUse() &&
4832         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4833       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4834
4835       SDValue FMinMax =
4836           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4837                               N1, N2, CC, TLI, DAG);
4838       if (FMinMax)
4839         return FMinMax;
4840     }
4841
4842     if ((!LegalOperations &&
4843          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4844         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4845       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4846                          N0.getOperand(0), N0.getOperand(1),
4847                          N1, N2, N0.getOperand(2));
4848     return SimplifySelect(SDLoc(N), N0, N1, N2);
4849   }
4850
4851   if (VT0 == MVT::i1) {
4852     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4853       // select (and Cond0, Cond1), X, Y
4854       //   -> select Cond0, (select Cond1, X, Y), Y
4855       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4856         SDValue Cond0 = N0->getOperand(0);
4857         SDValue Cond1 = N0->getOperand(1);
4858         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4859                                           N1.getValueType(), Cond1, N1, N2);
4860         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4861                            InnerSelect, N2);
4862       }
4863       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4864       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4865         SDValue Cond0 = N0->getOperand(0);
4866         SDValue Cond1 = N0->getOperand(1);
4867         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4868                                           N1.getValueType(), Cond1, N1, N2);
4869         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4870                            InnerSelect);
4871       }
4872     }
4873
4874     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4875     if (N1->getOpcode() == ISD::SELECT) {
4876       SDValue N1_0 = N1->getOperand(0);
4877       SDValue N1_1 = N1->getOperand(1);
4878       SDValue N1_2 = N1->getOperand(2);
4879       if (N1_2 == N2) {
4880         // Create the actual and node if we can generate good code for it.
4881         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4882           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4883                                     N0, N1_0);
4884           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4885                              N1_1, N2);
4886         }
4887         // Otherwise see if we can optimize the "and" to a better pattern.
4888         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4889           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4890                              N1_1, N2);
4891       }
4892     }
4893     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4894     if (N2->getOpcode() == ISD::SELECT) {
4895       SDValue N2_0 = N2->getOperand(0);
4896       SDValue N2_1 = N2->getOperand(1);
4897       SDValue N2_2 = N2->getOperand(2);
4898       if (N2_1 == N1) {
4899         // Create the actual or node if we can generate good code for it.
4900         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4901           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4902                                    N0, N2_0);
4903           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4904                              N1, N2_2);
4905         }
4906         // Otherwise see if we can optimize to a better pattern.
4907         if (SDValue Combined = visitORLike(N0, N2_0, N))
4908           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4909                              N1, N2_2);
4910       }
4911     }
4912   }
4913
4914   return SDValue();
4915 }
4916
4917 static
4918 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4919   SDLoc DL(N);
4920   EVT LoVT, HiVT;
4921   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4922
4923   // Split the inputs.
4924   SDValue Lo, Hi, LL, LH, RL, RH;
4925   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4926   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4927
4928   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4929   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4930
4931   return std::make_pair(Lo, Hi);
4932 }
4933
4934 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4935 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4936 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4937   SDLoc dl(N);
4938   SDValue Cond = N->getOperand(0);
4939   SDValue LHS = N->getOperand(1);
4940   SDValue RHS = N->getOperand(2);
4941   EVT VT = N->getValueType(0);
4942   int NumElems = VT.getVectorNumElements();
4943   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4944          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4945          Cond.getOpcode() == ISD::BUILD_VECTOR);
4946
4947   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4948   // binary ones here.
4949   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4950     return SDValue();
4951
4952   // We're sure we have an even number of elements due to the
4953   // concat_vectors we have as arguments to vselect.
4954   // Skip BV elements until we find one that's not an UNDEF
4955   // After we find an UNDEF element, keep looping until we get to half the
4956   // length of the BV and see if all the non-undef nodes are the same.
4957   ConstantSDNode *BottomHalf = nullptr;
4958   for (int i = 0; i < NumElems / 2; ++i) {
4959     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4960       continue;
4961
4962     if (BottomHalf == nullptr)
4963       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4964     else if (Cond->getOperand(i).getNode() != BottomHalf)
4965       return SDValue();
4966   }
4967
4968   // Do the same for the second half of the BuildVector
4969   ConstantSDNode *TopHalf = nullptr;
4970   for (int i = NumElems / 2; i < NumElems; ++i) {
4971     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4972       continue;
4973
4974     if (TopHalf == nullptr)
4975       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4976     else if (Cond->getOperand(i).getNode() != TopHalf)
4977       return SDValue();
4978   }
4979
4980   assert(TopHalf && BottomHalf &&
4981          "One half of the selector was all UNDEFs and the other was all the "
4982          "same value. This should have been addressed before this function.");
4983   return DAG.getNode(
4984       ISD::CONCAT_VECTORS, dl, VT,
4985       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4986       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4987 }
4988
4989 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4990
4991   if (Level >= AfterLegalizeTypes)
4992     return SDValue();
4993
4994   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4995   SDValue Mask = MST->getMask();
4996   SDValue Data  = MST->getValue();
4997   SDLoc DL(N);
4998
4999   // If the MSTORE data type requires splitting and the mask is provided by a
5000   // SETCC, then split both nodes and its operands before legalization. This
5001   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5002   // and enables future optimizations (e.g. min/max pattern matching on X86).
5003   if (Mask.getOpcode() == ISD::SETCC) {
5004
5005     // Check if any splitting is required.
5006     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5007         TargetLowering::TypeSplitVector)
5008       return SDValue();
5009
5010     SDValue MaskLo, MaskHi, Lo, Hi;
5011     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5012
5013     EVT LoVT, HiVT;
5014     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5015
5016     SDValue Chain = MST->getChain();
5017     SDValue Ptr   = MST->getBasePtr();
5018
5019     EVT MemoryVT = MST->getMemoryVT();
5020     unsigned Alignment = MST->getOriginalAlignment();
5021
5022     // if Alignment is equal to the vector size,
5023     // take the half of it for the second part
5024     unsigned SecondHalfAlignment =
5025       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5026          Alignment/2 : Alignment;
5027
5028     EVT LoMemVT, HiMemVT;
5029     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5030
5031     SDValue DataLo, DataHi;
5032     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5033
5034     MachineMemOperand *MMO = DAG.getMachineFunction().
5035       getMachineMemOperand(MST->getPointerInfo(),
5036                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5037                            Alignment, MST->getAAInfo(), MST->getRanges());
5038
5039     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5040                             MST->isTruncatingStore());
5041
5042     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5043     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5044                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5045
5046     MMO = DAG.getMachineFunction().
5047       getMachineMemOperand(MST->getPointerInfo(),
5048                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5049                            SecondHalfAlignment, MST->getAAInfo(),
5050                            MST->getRanges());
5051
5052     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5053                             MST->isTruncatingStore());
5054
5055     AddToWorklist(Lo.getNode());
5056     AddToWorklist(Hi.getNode());
5057
5058     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5059   }
5060   return SDValue();
5061 }
5062
5063 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5064
5065   if (Level >= AfterLegalizeTypes)
5066     return SDValue();
5067
5068   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5069   SDValue Mask = MLD->getMask();
5070   SDLoc DL(N);
5071
5072   // If the MLOAD result requires splitting and the mask is provided by a
5073   // SETCC, then split both nodes and its operands before legalization. This
5074   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5075   // and enables future optimizations (e.g. min/max pattern matching on X86).
5076
5077   if (Mask.getOpcode() == ISD::SETCC) {
5078     EVT VT = N->getValueType(0);
5079
5080     // Check if any splitting is required.
5081     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5082         TargetLowering::TypeSplitVector)
5083       return SDValue();
5084
5085     SDValue MaskLo, MaskHi, Lo, Hi;
5086     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5087
5088     SDValue Src0 = MLD->getSrc0();
5089     SDValue Src0Lo, Src0Hi;
5090     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5091
5092     EVT LoVT, HiVT;
5093     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5094
5095     SDValue Chain = MLD->getChain();
5096     SDValue Ptr   = MLD->getBasePtr();
5097     EVT MemoryVT = MLD->getMemoryVT();
5098     unsigned Alignment = MLD->getOriginalAlignment();
5099
5100     // if Alignment is equal to the vector size,
5101     // take the half of it for the second part
5102     unsigned SecondHalfAlignment =
5103       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5104          Alignment/2 : Alignment;
5105
5106     EVT LoMemVT, HiMemVT;
5107     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5108
5109     MachineMemOperand *MMO = DAG.getMachineFunction().
5110     getMachineMemOperand(MLD->getPointerInfo(),
5111                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5112                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5113
5114     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5115                            ISD::NON_EXTLOAD);
5116
5117     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5118     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5119                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5120
5121     MMO = DAG.getMachineFunction().
5122     getMachineMemOperand(MLD->getPointerInfo(),
5123                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5124                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5125
5126     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5127                            ISD::NON_EXTLOAD);
5128
5129     AddToWorklist(Lo.getNode());
5130     AddToWorklist(Hi.getNode());
5131
5132     // Build a factor node to remember that this load is independent of the
5133     // other one.
5134     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5135                         Hi.getValue(1));
5136
5137     // Legalized the chain result - switch anything that used the old chain to
5138     // use the new one.
5139     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5140
5141     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5142
5143     SDValue RetOps[] = { LoadRes, Chain };
5144     return DAG.getMergeValues(RetOps, DL);
5145   }
5146   return SDValue();
5147 }
5148
5149 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5150   SDValue N0 = N->getOperand(0);
5151   SDValue N1 = N->getOperand(1);
5152   SDValue N2 = N->getOperand(2);
5153   SDLoc DL(N);
5154
5155   // Canonicalize integer abs.
5156   // vselect (setg[te] X,  0),  X, -X ->
5157   // vselect (setgt    X, -1),  X, -X ->
5158   // vselect (setl[te] X,  0), -X,  X ->
5159   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5160   if (N0.getOpcode() == ISD::SETCC) {
5161     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5162     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5163     bool isAbs = false;
5164     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5165
5166     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5167          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5168         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5169       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5170     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5171              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5172       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5173
5174     if (isAbs) {
5175       EVT VT = LHS.getValueType();
5176       SDValue Shift = DAG.getNode(
5177           ISD::SRA, DL, VT, LHS,
5178           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5179       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5180       AddToWorklist(Shift.getNode());
5181       AddToWorklist(Add.getNode());
5182       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5183     }
5184   }
5185
5186   // If the VSELECT result requires splitting and the mask is provided by a
5187   // SETCC, then split both nodes and its operands before legalization. This
5188   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5189   // and enables future optimizations (e.g. min/max pattern matching on X86).
5190   if (N0.getOpcode() == ISD::SETCC) {
5191     EVT VT = N->getValueType(0);
5192
5193     // Check if any splitting is required.
5194     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5195         TargetLowering::TypeSplitVector)
5196       return SDValue();
5197
5198     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5199     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5200     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5201     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5202
5203     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5204     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5205
5206     // Add the new VSELECT nodes to the work list in case they need to be split
5207     // again.
5208     AddToWorklist(Lo.getNode());
5209     AddToWorklist(Hi.getNode());
5210
5211     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5212   }
5213
5214   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5215   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5216     return N1;
5217   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5218   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5219     return N2;
5220
5221   // The ConvertSelectToConcatVector function is assuming both the above
5222   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5223   // and addressed.
5224   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5225       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5226       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5227     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5228     if (CV.getNode())
5229       return CV;
5230   }
5231
5232   return SDValue();
5233 }
5234
5235 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5236   SDValue N0 = N->getOperand(0);
5237   SDValue N1 = N->getOperand(1);
5238   SDValue N2 = N->getOperand(2);
5239   SDValue N3 = N->getOperand(3);
5240   SDValue N4 = N->getOperand(4);
5241   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5242
5243   // fold select_cc lhs, rhs, x, x, cc -> x
5244   if (N2 == N3)
5245     return N2;
5246
5247   // Determine if the condition we're dealing with is constant
5248   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5249                               N0, N1, CC, SDLoc(N), false);
5250   if (SCC.getNode()) {
5251     AddToWorklist(SCC.getNode());
5252
5253     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5254       if (!SCCC->isNullValue())
5255         return N2;    // cond always true -> true val
5256       else
5257         return N3;    // cond always false -> false val
5258     } else if (SCC->getOpcode() == ISD::UNDEF) {
5259       // When the condition is UNDEF, just return the first operand. This is
5260       // coherent the DAG creation, no setcc node is created in this case
5261       return N2;
5262     } else if (SCC.getOpcode() == ISD::SETCC) {
5263       // Fold to a simpler select_cc
5264       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5265                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5266                          SCC.getOperand(2));
5267     }
5268   }
5269
5270   // If we can fold this based on the true/false value, do so.
5271   if (SimplifySelectOps(N, N2, N3))
5272     return SDValue(N, 0);  // Don't revisit N.
5273
5274   // fold select_cc into other things, such as min/max/abs
5275   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5276 }
5277
5278 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5279   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5280                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5281                        SDLoc(N));
5282 }
5283
5284 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5285 // dag node into a ConstantSDNode or a build_vector of constants.
5286 // This function is called by the DAGCombiner when visiting sext/zext/aext
5287 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5288 // Vector extends are not folded if operations are legal; this is to
5289 // avoid introducing illegal build_vector dag nodes.
5290 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5291                                          SelectionDAG &DAG, bool LegalTypes,
5292                                          bool LegalOperations) {
5293   unsigned Opcode = N->getOpcode();
5294   SDValue N0 = N->getOperand(0);
5295   EVT VT = N->getValueType(0);
5296
5297   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5298          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5299
5300   // fold (sext c1) -> c1
5301   // fold (zext c1) -> c1
5302   // fold (aext c1) -> c1
5303   if (isa<ConstantSDNode>(N0))
5304     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5305
5306   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5307   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5308   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5309   EVT SVT = VT.getScalarType();
5310   if (!(VT.isVector() &&
5311       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5312       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5313     return nullptr;
5314
5315   // We can fold this node into a build_vector.
5316   unsigned VTBits = SVT.getSizeInBits();
5317   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5318   unsigned ShAmt = VTBits - EVTBits;
5319   SmallVector<SDValue, 8> Elts;
5320   unsigned NumElts = N0->getNumOperands();
5321   SDLoc DL(N);
5322
5323   for (unsigned i=0; i != NumElts; ++i) {
5324     SDValue Op = N0->getOperand(i);
5325     if (Op->getOpcode() == ISD::UNDEF) {
5326       Elts.push_back(DAG.getUNDEF(SVT));
5327       continue;
5328     }
5329
5330     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5331     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5332     if (Opcode == ISD::SIGN_EXTEND)
5333       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5334                                      SVT));
5335     else
5336       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5337                                      SVT));
5338   }
5339
5340   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5341 }
5342
5343 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5344 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5345 // transformation. Returns true if extension are possible and the above
5346 // mentioned transformation is profitable.
5347 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5348                                     unsigned ExtOpc,
5349                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5350                                     const TargetLowering &TLI) {
5351   bool HasCopyToRegUses = false;
5352   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5353   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5354                             UE = N0.getNode()->use_end();
5355        UI != UE; ++UI) {
5356     SDNode *User = *UI;
5357     if (User == N)
5358       continue;
5359     if (UI.getUse().getResNo() != N0.getResNo())
5360       continue;
5361     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5362     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5363       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5364       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5365         // Sign bits will be lost after a zext.
5366         return false;
5367       bool Add = false;
5368       for (unsigned i = 0; i != 2; ++i) {
5369         SDValue UseOp = User->getOperand(i);
5370         if (UseOp == N0)
5371           continue;
5372         if (!isa<ConstantSDNode>(UseOp))
5373           return false;
5374         Add = true;
5375       }
5376       if (Add)
5377         ExtendNodes.push_back(User);
5378       continue;
5379     }
5380     // If truncates aren't free and there are users we can't
5381     // extend, it isn't worthwhile.
5382     if (!isTruncFree)
5383       return false;
5384     // Remember if this value is live-out.
5385     if (User->getOpcode() == ISD::CopyToReg)
5386       HasCopyToRegUses = true;
5387   }
5388
5389   if (HasCopyToRegUses) {
5390     bool BothLiveOut = false;
5391     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5392          UI != UE; ++UI) {
5393       SDUse &Use = UI.getUse();
5394       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5395         BothLiveOut = true;
5396         break;
5397       }
5398     }
5399     if (BothLiveOut)
5400       // Both unextended and extended values are live out. There had better be
5401       // a good reason for the transformation.
5402       return ExtendNodes.size();
5403   }
5404   return true;
5405 }
5406
5407 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5408                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5409                                   ISD::NodeType ExtType) {
5410   // Extend SetCC uses if necessary.
5411   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5412     SDNode *SetCC = SetCCs[i];
5413     SmallVector<SDValue, 4> Ops;
5414
5415     for (unsigned j = 0; j != 2; ++j) {
5416       SDValue SOp = SetCC->getOperand(j);
5417       if (SOp == Trunc)
5418         Ops.push_back(ExtLoad);
5419       else
5420         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5421     }
5422
5423     Ops.push_back(SetCC->getOperand(2));
5424     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5425   }
5426 }
5427
5428 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5429 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5430   SDValue N0 = N->getOperand(0);
5431   EVT DstVT = N->getValueType(0);
5432   EVT SrcVT = N0.getValueType();
5433
5434   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5435           N->getOpcode() == ISD::ZERO_EXTEND) &&
5436          "Unexpected node type (not an extend)!");
5437
5438   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5439   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5440   //   (v8i32 (sext (v8i16 (load x))))
5441   // into:
5442   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5443   //                          (v4i32 (sextload (x + 16)))))
5444   // Where uses of the original load, i.e.:
5445   //   (v8i16 (load x))
5446   // are replaced with:
5447   //   (v8i16 (truncate
5448   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5449   //                            (v4i32 (sextload (x + 16)))))))
5450   //
5451   // This combine is only applicable to illegal, but splittable, vectors.
5452   // All legal types, and illegal non-vector types, are handled elsewhere.
5453   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5454   //
5455   if (N0->getOpcode() != ISD::LOAD)
5456     return SDValue();
5457
5458   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5459
5460   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5461       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5462       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5463     return SDValue();
5464
5465   SmallVector<SDNode *, 4> SetCCs;
5466   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5467     return SDValue();
5468
5469   ISD::LoadExtType ExtType =
5470       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5471
5472   // Try to split the vector types to get down to legal types.
5473   EVT SplitSrcVT = SrcVT;
5474   EVT SplitDstVT = DstVT;
5475   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5476          SplitSrcVT.getVectorNumElements() > 1) {
5477     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5478     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5479   }
5480
5481   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5482     return SDValue();
5483
5484   SDLoc DL(N);
5485   const unsigned NumSplits =
5486       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5487   const unsigned Stride = SplitSrcVT.getStoreSize();
5488   SmallVector<SDValue, 4> Loads;
5489   SmallVector<SDValue, 4> Chains;
5490
5491   SDValue BasePtr = LN0->getBasePtr();
5492   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5493     const unsigned Offset = Idx * Stride;
5494     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5495
5496     SDValue SplitLoad = DAG.getExtLoad(
5497         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5498         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5499         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5500         Align, LN0->getAAInfo());
5501
5502     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5503                           DAG.getConstant(Stride, BasePtr.getValueType()));
5504
5505     Loads.push_back(SplitLoad.getValue(0));
5506     Chains.push_back(SplitLoad.getValue(1));
5507   }
5508
5509   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5510   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5511
5512   CombineTo(N, NewValue);
5513
5514   // Replace uses of the original load (before extension)
5515   // with a truncate of the concatenated sextloaded vectors.
5516   SDValue Trunc =
5517       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5518   CombineTo(N0.getNode(), Trunc, NewChain);
5519   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5520                   (ISD::NodeType)N->getOpcode());
5521   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5522 }
5523
5524 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5525   SDValue N0 = N->getOperand(0);
5526   EVT VT = N->getValueType(0);
5527
5528   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5529                                               LegalOperations))
5530     return SDValue(Res, 0);
5531
5532   // fold (sext (sext x)) -> (sext x)
5533   // fold (sext (aext x)) -> (sext x)
5534   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5535     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5536                        N0.getOperand(0));
5537
5538   if (N0.getOpcode() == ISD::TRUNCATE) {
5539     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5540     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5541     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5542     if (NarrowLoad.getNode()) {
5543       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5544       if (NarrowLoad.getNode() != N0.getNode()) {
5545         CombineTo(N0.getNode(), NarrowLoad);
5546         // CombineTo deleted the truncate, if needed, but not what's under it.
5547         AddToWorklist(oye);
5548       }
5549       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5550     }
5551
5552     // See if the value being truncated is already sign extended.  If so, just
5553     // eliminate the trunc/sext pair.
5554     SDValue Op = N0.getOperand(0);
5555     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5556     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5557     unsigned DestBits = VT.getScalarType().getSizeInBits();
5558     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5559
5560     if (OpBits == DestBits) {
5561       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5562       // bits, it is already ready.
5563       if (NumSignBits > DestBits-MidBits)
5564         return Op;
5565     } else if (OpBits < DestBits) {
5566       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5567       // bits, just sext from i32.
5568       if (NumSignBits > OpBits-MidBits)
5569         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5570     } else {
5571       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5572       // bits, just truncate to i32.
5573       if (NumSignBits > OpBits-MidBits)
5574         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5575     }
5576
5577     // fold (sext (truncate x)) -> (sextinreg x).
5578     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5579                                                  N0.getValueType())) {
5580       if (OpBits < DestBits)
5581         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5582       else if (OpBits > DestBits)
5583         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5584       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5585                          DAG.getValueType(N0.getValueType()));
5586     }
5587   }
5588
5589   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5590   // Only generate vector extloads when 1) they're legal, and 2) they are
5591   // deemed desirable by the target.
5592   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5593       ((!LegalOperations && !VT.isVector() &&
5594         !cast<LoadSDNode>(N0)->isVolatile()) ||
5595        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5596     bool DoXform = true;
5597     SmallVector<SDNode*, 4> SetCCs;
5598     if (!N0.hasOneUse())
5599       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5600     if (VT.isVector())
5601       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5602     if (DoXform) {
5603       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5604       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5605                                        LN0->getChain(),
5606                                        LN0->getBasePtr(), N0.getValueType(),
5607                                        LN0->getMemOperand());
5608       CombineTo(N, ExtLoad);
5609       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5610                                   N0.getValueType(), ExtLoad);
5611       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5612       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5613                       ISD::SIGN_EXTEND);
5614       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5615     }
5616   }
5617
5618   // fold (sext (load x)) to multiple smaller sextloads.
5619   // Only on illegal but splittable vectors.
5620   if (SDValue ExtLoad = CombineExtLoad(N))
5621     return ExtLoad;
5622
5623   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5624   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5625   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5626       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5627     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5628     EVT MemVT = LN0->getMemoryVT();
5629     if ((!LegalOperations && !LN0->isVolatile()) ||
5630         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5631       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5632                                        LN0->getChain(),
5633                                        LN0->getBasePtr(), MemVT,
5634                                        LN0->getMemOperand());
5635       CombineTo(N, ExtLoad);
5636       CombineTo(N0.getNode(),
5637                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5638                             N0.getValueType(), ExtLoad),
5639                 ExtLoad.getValue(1));
5640       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5641     }
5642   }
5643
5644   // fold (sext (and/or/xor (load x), cst)) ->
5645   //      (and/or/xor (sextload x), (sext cst))
5646   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5647        N0.getOpcode() == ISD::XOR) &&
5648       isa<LoadSDNode>(N0.getOperand(0)) &&
5649       N0.getOperand(1).getOpcode() == ISD::Constant &&
5650       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5651       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5652     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5653     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5654       bool DoXform = true;
5655       SmallVector<SDNode*, 4> SetCCs;
5656       if (!N0.hasOneUse())
5657         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5658                                           SetCCs, TLI);
5659       if (DoXform) {
5660         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5661                                          LN0->getChain(), LN0->getBasePtr(),
5662                                          LN0->getMemoryVT(),
5663                                          LN0->getMemOperand());
5664         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5665         Mask = Mask.sext(VT.getSizeInBits());
5666         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5667                                   ExtLoad, DAG.getConstant(Mask, VT));
5668         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5669                                     SDLoc(N0.getOperand(0)),
5670                                     N0.getOperand(0).getValueType(), ExtLoad);
5671         CombineTo(N, And);
5672         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5673         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5674                         ISD::SIGN_EXTEND);
5675         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5676       }
5677     }
5678   }
5679
5680   if (N0.getOpcode() == ISD::SETCC) {
5681     EVT N0VT = N0.getOperand(0).getValueType();
5682     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5683     // Only do this before legalize for now.
5684     if (VT.isVector() && !LegalOperations &&
5685         TLI.getBooleanContents(N0VT) ==
5686             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5687       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5688       // of the same size as the compared operands. Only optimize sext(setcc())
5689       // if this is the case.
5690       EVT SVT = getSetCCResultType(N0VT);
5691
5692       // We know that the # elements of the results is the same as the
5693       // # elements of the compare (and the # elements of the compare result
5694       // for that matter).  Check to see that they are the same size.  If so,
5695       // we know that the element size of the sext'd result matches the
5696       // element size of the compare operands.
5697       if (VT.getSizeInBits() == SVT.getSizeInBits())
5698         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5699                              N0.getOperand(1),
5700                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5701
5702       // If the desired elements are smaller or larger than the source
5703       // elements we can use a matching integer vector type and then
5704       // truncate/sign extend
5705       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5706       if (SVT == MatchingVectorType) {
5707         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5708                                N0.getOperand(0), N0.getOperand(1),
5709                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5710         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5711       }
5712     }
5713
5714     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5715     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5716     SDValue NegOne =
5717       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5718     SDValue SCC =
5719       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5720                        NegOne, DAG.getConstant(0, VT),
5721                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5722     if (SCC.getNode()) return SCC;
5723
5724     if (!VT.isVector()) {
5725       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5726       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5727         SDLoc DL(N);
5728         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5729         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5730                                      N0.getOperand(0), N0.getOperand(1), CC);
5731         return DAG.getSelect(DL, VT, SetCC,
5732                              NegOne, DAG.getConstant(0, VT));
5733       }
5734     }
5735   }
5736
5737   // fold (sext x) -> (zext x) if the sign bit is known zero.
5738   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5739       DAG.SignBitIsZero(N0))
5740     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5741
5742   return SDValue();
5743 }
5744
5745 // isTruncateOf - If N is a truncate of some other value, return true, record
5746 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5747 // This function computes KnownZero to avoid a duplicated call to
5748 // computeKnownBits in the caller.
5749 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5750                          APInt &KnownZero) {
5751   APInt KnownOne;
5752   if (N->getOpcode() == ISD::TRUNCATE) {
5753     Op = N->getOperand(0);
5754     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5755     return true;
5756   }
5757
5758   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5759       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5760     return false;
5761
5762   SDValue Op0 = N->getOperand(0);
5763   SDValue Op1 = N->getOperand(1);
5764   assert(Op0.getValueType() == Op1.getValueType());
5765
5766   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5767   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5768   if (COp0 && COp0->isNullValue())
5769     Op = Op1;
5770   else if (COp1 && COp1->isNullValue())
5771     Op = Op0;
5772   else
5773     return false;
5774
5775   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5776
5777   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5778     return false;
5779
5780   return true;
5781 }
5782
5783 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5784   SDValue N0 = N->getOperand(0);
5785   EVT VT = N->getValueType(0);
5786
5787   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5788                                               LegalOperations))
5789     return SDValue(Res, 0);
5790
5791   // fold (zext (zext x)) -> (zext x)
5792   // fold (zext (aext x)) -> (zext x)
5793   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5794     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5795                        N0.getOperand(0));
5796
5797   // fold (zext (truncate x)) -> (zext x) or
5798   //      (zext (truncate x)) -> (truncate x)
5799   // This is valid when the truncated bits of x are already zero.
5800   // FIXME: We should extend this to work for vectors too.
5801   SDValue Op;
5802   APInt KnownZero;
5803   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5804     APInt TruncatedBits =
5805       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5806       APInt(Op.getValueSizeInBits(), 0) :
5807       APInt::getBitsSet(Op.getValueSizeInBits(),
5808                         N0.getValueSizeInBits(),
5809                         std::min(Op.getValueSizeInBits(),
5810                                  VT.getSizeInBits()));
5811     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5812       if (VT.bitsGT(Op.getValueType()))
5813         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5814       if (VT.bitsLT(Op.getValueType()))
5815         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5816
5817       return Op;
5818     }
5819   }
5820
5821   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5822   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5823   if (N0.getOpcode() == ISD::TRUNCATE) {
5824     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5825     if (NarrowLoad.getNode()) {
5826       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5827       if (NarrowLoad.getNode() != N0.getNode()) {
5828         CombineTo(N0.getNode(), NarrowLoad);
5829         // CombineTo deleted the truncate, if needed, but not what's under it.
5830         AddToWorklist(oye);
5831       }
5832       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5833     }
5834   }
5835
5836   // fold (zext (truncate x)) -> (and x, mask)
5837   if (N0.getOpcode() == ISD::TRUNCATE &&
5838       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5839
5840     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5841     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5842     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5843     if (NarrowLoad.getNode()) {
5844       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5845       if (NarrowLoad.getNode() != N0.getNode()) {
5846         CombineTo(N0.getNode(), NarrowLoad);
5847         // CombineTo deleted the truncate, if needed, but not what's under it.
5848         AddToWorklist(oye);
5849       }
5850       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5851     }
5852
5853     SDValue Op = N0.getOperand(0);
5854     if (Op.getValueType().bitsLT(VT)) {
5855       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5856       AddToWorklist(Op.getNode());
5857     } else if (Op.getValueType().bitsGT(VT)) {
5858       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5859       AddToWorklist(Op.getNode());
5860     }
5861     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5862                                   N0.getValueType().getScalarType());
5863   }
5864
5865   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5866   // if either of the casts is not free.
5867   if (N0.getOpcode() == ISD::AND &&
5868       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5869       N0.getOperand(1).getOpcode() == ISD::Constant &&
5870       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5871                            N0.getValueType()) ||
5872        !TLI.isZExtFree(N0.getValueType(), VT))) {
5873     SDValue X = N0.getOperand(0).getOperand(0);
5874     if (X.getValueType().bitsLT(VT)) {
5875       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5876     } else if (X.getValueType().bitsGT(VT)) {
5877       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5878     }
5879     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5880     Mask = Mask.zext(VT.getSizeInBits());
5881     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5882                        X, DAG.getConstant(Mask, VT));
5883   }
5884
5885   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5886   // Only generate vector extloads when 1) they're legal, and 2) they are
5887   // deemed desirable by the target.
5888   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5889       ((!LegalOperations && !VT.isVector() &&
5890         !cast<LoadSDNode>(N0)->isVolatile()) ||
5891        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5892     bool DoXform = true;
5893     SmallVector<SDNode*, 4> SetCCs;
5894     if (!N0.hasOneUse())
5895       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5896     if (VT.isVector())
5897       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5898     if (DoXform) {
5899       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5900       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5901                                        LN0->getChain(),
5902                                        LN0->getBasePtr(), N0.getValueType(),
5903                                        LN0->getMemOperand());
5904       CombineTo(N, ExtLoad);
5905       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5906                                   N0.getValueType(), ExtLoad);
5907       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5908
5909       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5910                       ISD::ZERO_EXTEND);
5911       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5912     }
5913   }
5914
5915   // fold (zext (load x)) to multiple smaller zextloads.
5916   // Only on illegal but splittable vectors.
5917   if (SDValue ExtLoad = CombineExtLoad(N))
5918     return ExtLoad;
5919
5920   // fold (zext (and/or/xor (load x), cst)) ->
5921   //      (and/or/xor (zextload x), (zext cst))
5922   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5923        N0.getOpcode() == ISD::XOR) &&
5924       isa<LoadSDNode>(N0.getOperand(0)) &&
5925       N0.getOperand(1).getOpcode() == ISD::Constant &&
5926       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5927       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5928     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5929     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5930       bool DoXform = true;
5931       SmallVector<SDNode*, 4> SetCCs;
5932       if (!N0.hasOneUse())
5933         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5934                                           SetCCs, TLI);
5935       if (DoXform) {
5936         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5937                                          LN0->getChain(), LN0->getBasePtr(),
5938                                          LN0->getMemoryVT(),
5939                                          LN0->getMemOperand());
5940         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5941         Mask = Mask.zext(VT.getSizeInBits());
5942         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5943                                   ExtLoad, DAG.getConstant(Mask, VT));
5944         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5945                                     SDLoc(N0.getOperand(0)),
5946                                     N0.getOperand(0).getValueType(), ExtLoad);
5947         CombineTo(N, And);
5948         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5949         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5950                         ISD::ZERO_EXTEND);
5951         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5952       }
5953     }
5954   }
5955
5956   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5957   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5958   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5959       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5960     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5961     EVT MemVT = LN0->getMemoryVT();
5962     if ((!LegalOperations && !LN0->isVolatile()) ||
5963         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5964       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5965                                        LN0->getChain(),
5966                                        LN0->getBasePtr(), MemVT,
5967                                        LN0->getMemOperand());
5968       CombineTo(N, ExtLoad);
5969       CombineTo(N0.getNode(),
5970                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5971                             ExtLoad),
5972                 ExtLoad.getValue(1));
5973       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5974     }
5975   }
5976
5977   if (N0.getOpcode() == ISD::SETCC) {
5978     if (!LegalOperations && VT.isVector() &&
5979         N0.getValueType().getVectorElementType() == MVT::i1) {
5980       EVT N0VT = N0.getOperand(0).getValueType();
5981       if (getSetCCResultType(N0VT) == N0.getValueType())
5982         return SDValue();
5983
5984       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5985       // Only do this before legalize for now.
5986       EVT EltVT = VT.getVectorElementType();
5987       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5988                                     DAG.getConstant(1, EltVT));
5989       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5990         // We know that the # elements of the results is the same as the
5991         // # elements of the compare (and the # elements of the compare result
5992         // for that matter).  Check to see that they are the same size.  If so,
5993         // we know that the element size of the sext'd result matches the
5994         // element size of the compare operands.
5995         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5996                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5997                                          N0.getOperand(1),
5998                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5999                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
6000                                        OneOps));
6001
6002       // If the desired elements are smaller or larger than the source
6003       // elements we can use a matching integer vector type and then
6004       // truncate/sign extend
6005       EVT MatchingElementType =
6006         EVT::getIntegerVT(*DAG.getContext(),
6007                           N0VT.getScalarType().getSizeInBits());
6008       EVT MatchingVectorType =
6009         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6010                          N0VT.getVectorNumElements());
6011       SDValue VsetCC =
6012         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6013                       N0.getOperand(1),
6014                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6015       return DAG.getNode(ISD::AND, SDLoc(N), VT,
6016                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
6017                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
6018     }
6019
6020     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6021     SDValue SCC =
6022       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6023                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6024                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6025     if (SCC.getNode()) return SCC;
6026   }
6027
6028   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6029   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6030       isa<ConstantSDNode>(N0.getOperand(1)) &&
6031       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6032       N0.hasOneUse()) {
6033     SDValue ShAmt = N0.getOperand(1);
6034     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6035     if (N0.getOpcode() == ISD::SHL) {
6036       SDValue InnerZExt = N0.getOperand(0);
6037       // If the original shl may be shifting out bits, do not perform this
6038       // transformation.
6039       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6040         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6041       if (ShAmtVal > KnownZeroBits)
6042         return SDValue();
6043     }
6044
6045     SDLoc DL(N);
6046
6047     // Ensure that the shift amount is wide enough for the shifted value.
6048     if (VT.getSizeInBits() >= 256)
6049       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6050
6051     return DAG.getNode(N0.getOpcode(), DL, VT,
6052                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6053                        ShAmt);
6054   }
6055
6056   return SDValue();
6057 }
6058
6059 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6060   SDValue N0 = N->getOperand(0);
6061   EVT VT = N->getValueType(0);
6062
6063   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6064                                               LegalOperations))
6065     return SDValue(Res, 0);
6066
6067   // fold (aext (aext x)) -> (aext x)
6068   // fold (aext (zext x)) -> (zext x)
6069   // fold (aext (sext x)) -> (sext x)
6070   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6071       N0.getOpcode() == ISD::ZERO_EXTEND ||
6072       N0.getOpcode() == ISD::SIGN_EXTEND)
6073     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6074
6075   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6076   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6077   if (N0.getOpcode() == ISD::TRUNCATE) {
6078     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6079     if (NarrowLoad.getNode()) {
6080       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6081       if (NarrowLoad.getNode() != N0.getNode()) {
6082         CombineTo(N0.getNode(), NarrowLoad);
6083         // CombineTo deleted the truncate, if needed, but not what's under it.
6084         AddToWorklist(oye);
6085       }
6086       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6087     }
6088   }
6089
6090   // fold (aext (truncate x))
6091   if (N0.getOpcode() == ISD::TRUNCATE) {
6092     SDValue TruncOp = N0.getOperand(0);
6093     if (TruncOp.getValueType() == VT)
6094       return TruncOp; // x iff x size == zext size.
6095     if (TruncOp.getValueType().bitsGT(VT))
6096       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6097     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6098   }
6099
6100   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6101   // if the trunc is not free.
6102   if (N0.getOpcode() == ISD::AND &&
6103       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6104       N0.getOperand(1).getOpcode() == ISD::Constant &&
6105       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6106                           N0.getValueType())) {
6107     SDValue X = N0.getOperand(0).getOperand(0);
6108     if (X.getValueType().bitsLT(VT)) {
6109       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6110     } else if (X.getValueType().bitsGT(VT)) {
6111       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6112     }
6113     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6114     Mask = Mask.zext(VT.getSizeInBits());
6115     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6116                        X, DAG.getConstant(Mask, VT));
6117   }
6118
6119   // fold (aext (load x)) -> (aext (truncate (extload x)))
6120   // None of the supported targets knows how to perform load and any_ext
6121   // on vectors in one instruction.  We only perform this transformation on
6122   // scalars.
6123   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6124       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6125       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6126     bool DoXform = true;
6127     SmallVector<SDNode*, 4> SetCCs;
6128     if (!N0.hasOneUse())
6129       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6130     if (DoXform) {
6131       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6132       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6133                                        LN0->getChain(),
6134                                        LN0->getBasePtr(), N0.getValueType(),
6135                                        LN0->getMemOperand());
6136       CombineTo(N, ExtLoad);
6137       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6138                                   N0.getValueType(), ExtLoad);
6139       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6140       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6141                       ISD::ANY_EXTEND);
6142       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6143     }
6144   }
6145
6146   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6147   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6148   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6149   if (N0.getOpcode() == ISD::LOAD &&
6150       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6151       N0.hasOneUse()) {
6152     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6153     ISD::LoadExtType ExtType = LN0->getExtensionType();
6154     EVT MemVT = LN0->getMemoryVT();
6155     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6156       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6157                                        VT, LN0->getChain(), LN0->getBasePtr(),
6158                                        MemVT, LN0->getMemOperand());
6159       CombineTo(N, ExtLoad);
6160       CombineTo(N0.getNode(),
6161                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6162                             N0.getValueType(), ExtLoad),
6163                 ExtLoad.getValue(1));
6164       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6165     }
6166   }
6167
6168   if (N0.getOpcode() == ISD::SETCC) {
6169     // For vectors:
6170     // aext(setcc) -> vsetcc
6171     // aext(setcc) -> truncate(vsetcc)
6172     // aext(setcc) -> aext(vsetcc)
6173     // Only do this before legalize for now.
6174     if (VT.isVector() && !LegalOperations) {
6175       EVT N0VT = N0.getOperand(0).getValueType();
6176         // We know that the # elements of the results is the same as the
6177         // # elements of the compare (and the # elements of the compare result
6178         // for that matter).  Check to see that they are the same size.  If so,
6179         // we know that the element size of the sext'd result matches the
6180         // element size of the compare operands.
6181       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6182         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6183                              N0.getOperand(1),
6184                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6185       // If the desired elements are smaller or larger than the source
6186       // elements we can use a matching integer vector type and then
6187       // truncate/any extend
6188       else {
6189         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6190         SDValue VsetCC =
6191           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6192                         N0.getOperand(1),
6193                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6194         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6195       }
6196     }
6197
6198     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6199     SDValue SCC =
6200       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6201                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6202                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6203     if (SCC.getNode())
6204       return SCC;
6205   }
6206
6207   return SDValue();
6208 }
6209
6210 /// See if the specified operand can be simplified with the knowledge that only
6211 /// the bits specified by Mask are used.  If so, return the simpler operand,
6212 /// otherwise return a null SDValue.
6213 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6214   switch (V.getOpcode()) {
6215   default: break;
6216   case ISD::Constant: {
6217     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6218     assert(CV && "Const value should be ConstSDNode.");
6219     const APInt &CVal = CV->getAPIntValue();
6220     APInt NewVal = CVal & Mask;
6221     if (NewVal != CVal)
6222       return DAG.getConstant(NewVal, V.getValueType());
6223     break;
6224   }
6225   case ISD::OR:
6226   case ISD::XOR:
6227     // If the LHS or RHS don't contribute bits to the or, drop them.
6228     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6229       return V.getOperand(1);
6230     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6231       return V.getOperand(0);
6232     break;
6233   case ISD::SRL:
6234     // Only look at single-use SRLs.
6235     if (!V.getNode()->hasOneUse())
6236       break;
6237     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6238       // See if we can recursively simplify the LHS.
6239       unsigned Amt = RHSC->getZExtValue();
6240
6241       // Watch out for shift count overflow though.
6242       if (Amt >= Mask.getBitWidth()) break;
6243       APInt NewMask = Mask << Amt;
6244       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6245       if (SimplifyLHS.getNode())
6246         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6247                            SimplifyLHS, V.getOperand(1));
6248     }
6249   }
6250   return SDValue();
6251 }
6252
6253 /// If the result of a wider load is shifted to right of N  bits and then
6254 /// truncated to a narrower type and where N is a multiple of number of bits of
6255 /// the narrower type, transform it to a narrower load from address + N / num of
6256 /// bits of new type. If the result is to be extended, also fold the extension
6257 /// to form a extending load.
6258 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6259   unsigned Opc = N->getOpcode();
6260
6261   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6262   SDValue N0 = N->getOperand(0);
6263   EVT VT = N->getValueType(0);
6264   EVT ExtVT = VT;
6265
6266   // This transformation isn't valid for vector loads.
6267   if (VT.isVector())
6268     return SDValue();
6269
6270   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6271   // extended to VT.
6272   if (Opc == ISD::SIGN_EXTEND_INREG) {
6273     ExtType = ISD::SEXTLOAD;
6274     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6275   } else if (Opc == ISD::SRL) {
6276     // Another special-case: SRL is basically zero-extending a narrower value.
6277     ExtType = ISD::ZEXTLOAD;
6278     N0 = SDValue(N, 0);
6279     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6280     if (!N01) return SDValue();
6281     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6282                               VT.getSizeInBits() - N01->getZExtValue());
6283   }
6284   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6285     return SDValue();
6286
6287   unsigned EVTBits = ExtVT.getSizeInBits();
6288
6289   // Do not generate loads of non-round integer types since these can
6290   // be expensive (and would be wrong if the type is not byte sized).
6291   if (!ExtVT.isRound())
6292     return SDValue();
6293
6294   unsigned ShAmt = 0;
6295   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6296     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6297       ShAmt = N01->getZExtValue();
6298       // Is the shift amount a multiple of size of VT?
6299       if ((ShAmt & (EVTBits-1)) == 0) {
6300         N0 = N0.getOperand(0);
6301         // Is the load width a multiple of size of VT?
6302         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6303           return SDValue();
6304       }
6305
6306       // At this point, we must have a load or else we can't do the transform.
6307       if (!isa<LoadSDNode>(N0)) return SDValue();
6308
6309       // Because a SRL must be assumed to *need* to zero-extend the high bits
6310       // (as opposed to anyext the high bits), we can't combine the zextload
6311       // lowering of SRL and an sextload.
6312       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6313         return SDValue();
6314
6315       // If the shift amount is larger than the input type then we're not
6316       // accessing any of the loaded bytes.  If the load was a zextload/extload
6317       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6318       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6319         return SDValue();
6320     }
6321   }
6322
6323   // If the load is shifted left (and the result isn't shifted back right),
6324   // we can fold the truncate through the shift.
6325   unsigned ShLeftAmt = 0;
6326   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6327       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6328     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6329       ShLeftAmt = N01->getZExtValue();
6330       N0 = N0.getOperand(0);
6331     }
6332   }
6333
6334   // If we haven't found a load, we can't narrow it.  Don't transform one with
6335   // multiple uses, this would require adding a new load.
6336   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6337     return SDValue();
6338
6339   // Don't change the width of a volatile load.
6340   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6341   if (LN0->isVolatile())
6342     return SDValue();
6343
6344   // Verify that we are actually reducing a load width here.
6345   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6346     return SDValue();
6347
6348   // For the transform to be legal, the load must produce only two values
6349   // (the value loaded and the chain).  Don't transform a pre-increment
6350   // load, for example, which produces an extra value.  Otherwise the
6351   // transformation is not equivalent, and the downstream logic to replace
6352   // uses gets things wrong.
6353   if (LN0->getNumValues() > 2)
6354     return SDValue();
6355
6356   // If the load that we're shrinking is an extload and we're not just
6357   // discarding the extension we can't simply shrink the load. Bail.
6358   // TODO: It would be possible to merge the extensions in some cases.
6359   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6360       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6361     return SDValue();
6362
6363   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6364     return SDValue();
6365
6366   EVT PtrType = N0.getOperand(1).getValueType();
6367
6368   if (PtrType == MVT::Untyped || PtrType.isExtended())
6369     // It's not possible to generate a constant of extended or untyped type.
6370     return SDValue();
6371
6372   // For big endian targets, we need to adjust the offset to the pointer to
6373   // load the correct bytes.
6374   if (TLI.isBigEndian()) {
6375     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6376     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6377     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6378   }
6379
6380   uint64_t PtrOff = ShAmt / 8;
6381   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6382   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6383                                PtrType, LN0->getBasePtr(),
6384                                DAG.getConstant(PtrOff, PtrType));
6385   AddToWorklist(NewPtr.getNode());
6386
6387   SDValue Load;
6388   if (ExtType == ISD::NON_EXTLOAD)
6389     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6390                         LN0->getPointerInfo().getWithOffset(PtrOff),
6391                         LN0->isVolatile(), LN0->isNonTemporal(),
6392                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6393   else
6394     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6395                           LN0->getPointerInfo().getWithOffset(PtrOff),
6396                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6397                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6398
6399   // Replace the old load's chain with the new load's chain.
6400   WorklistRemover DeadNodes(*this);
6401   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6402
6403   // Shift the result left, if we've swallowed a left shift.
6404   SDValue Result = Load;
6405   if (ShLeftAmt != 0) {
6406     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6407     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6408       ShImmTy = VT;
6409     // If the shift amount is as large as the result size (but, presumably,
6410     // no larger than the source) then the useful bits of the result are
6411     // zero; we can't simply return the shortened shift, because the result
6412     // of that operation is undefined.
6413     if (ShLeftAmt >= VT.getSizeInBits())
6414       Result = DAG.getConstant(0, VT);
6415     else
6416       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6417                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6418   }
6419
6420   // Return the new loaded value.
6421   return Result;
6422 }
6423
6424 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6425   SDValue N0 = N->getOperand(0);
6426   SDValue N1 = N->getOperand(1);
6427   EVT VT = N->getValueType(0);
6428   EVT EVT = cast<VTSDNode>(N1)->getVT();
6429   unsigned VTBits = VT.getScalarType().getSizeInBits();
6430   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6431
6432   // fold (sext_in_reg c1) -> c1
6433   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6434     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6435
6436   // If the input is already sign extended, just drop the extension.
6437   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6438     return N0;
6439
6440   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6441   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6442       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6443     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6444                        N0.getOperand(0), N1);
6445
6446   // fold (sext_in_reg (sext x)) -> (sext x)
6447   // fold (sext_in_reg (aext x)) -> (sext x)
6448   // if x is small enough.
6449   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6450     SDValue N00 = N0.getOperand(0);
6451     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6452         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6453       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6454   }
6455
6456   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6457   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6458     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6459
6460   // fold operands of sext_in_reg based on knowledge that the top bits are not
6461   // demanded.
6462   if (SimplifyDemandedBits(SDValue(N, 0)))
6463     return SDValue(N, 0);
6464
6465   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6466   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6467   SDValue NarrowLoad = ReduceLoadWidth(N);
6468   if (NarrowLoad.getNode())
6469     return NarrowLoad;
6470
6471   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6472   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6473   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6474   if (N0.getOpcode() == ISD::SRL) {
6475     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6476       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6477         // We can turn this into an SRA iff the input to the SRL is already sign
6478         // extended enough.
6479         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6480         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6481           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6482                              N0.getOperand(0), N0.getOperand(1));
6483       }
6484   }
6485
6486   // fold (sext_inreg (extload x)) -> (sextload x)
6487   if (ISD::isEXTLoad(N0.getNode()) &&
6488       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6489       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6490       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6491        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6492     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6493     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6494                                      LN0->getChain(),
6495                                      LN0->getBasePtr(), EVT,
6496                                      LN0->getMemOperand());
6497     CombineTo(N, ExtLoad);
6498     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6499     AddToWorklist(ExtLoad.getNode());
6500     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6501   }
6502   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6503   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6504       N0.hasOneUse() &&
6505       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6506       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6507        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6508     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6509     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6510                                      LN0->getChain(),
6511                                      LN0->getBasePtr(), EVT,
6512                                      LN0->getMemOperand());
6513     CombineTo(N, ExtLoad);
6514     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6515     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6516   }
6517
6518   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6519   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6520     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6521                                        N0.getOperand(1), false);
6522     if (BSwap.getNode())
6523       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6524                          BSwap, N1);
6525   }
6526
6527   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6528   // into a build_vector.
6529   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6530     SmallVector<SDValue, 8> Elts;
6531     unsigned NumElts = N0->getNumOperands();
6532     unsigned ShAmt = VTBits - EVTBits;
6533
6534     for (unsigned i = 0; i != NumElts; ++i) {
6535       SDValue Op = N0->getOperand(i);
6536       if (Op->getOpcode() == ISD::UNDEF) {
6537         Elts.push_back(Op);
6538         continue;
6539       }
6540
6541       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6542       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6543       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6544                                      Op.getValueType()));
6545     }
6546
6547     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6548   }
6549
6550   return SDValue();
6551 }
6552
6553 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6554   SDValue N0 = N->getOperand(0);
6555   EVT VT = N->getValueType(0);
6556   bool isLE = TLI.isLittleEndian();
6557
6558   // noop truncate
6559   if (N0.getValueType() == N->getValueType(0))
6560     return N0;
6561   // fold (truncate c1) -> c1
6562   if (isConstantIntBuildVectorOrConstantInt(N0))
6563     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6564   // fold (truncate (truncate x)) -> (truncate x)
6565   if (N0.getOpcode() == ISD::TRUNCATE)
6566     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6567   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6568   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6569       N0.getOpcode() == ISD::SIGN_EXTEND ||
6570       N0.getOpcode() == ISD::ANY_EXTEND) {
6571     if (N0.getOperand(0).getValueType().bitsLT(VT))
6572       // if the source is smaller than the dest, we still need an extend
6573       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6574                          N0.getOperand(0));
6575     if (N0.getOperand(0).getValueType().bitsGT(VT))
6576       // if the source is larger than the dest, than we just need the truncate
6577       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6578     // if the source and dest are the same type, we can drop both the extend
6579     // and the truncate.
6580     return N0.getOperand(0);
6581   }
6582
6583   // Fold extract-and-trunc into a narrow extract. For example:
6584   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6585   //   i32 y = TRUNCATE(i64 x)
6586   //        -- becomes --
6587   //   v16i8 b = BITCAST (v2i64 val)
6588   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6589   //
6590   // Note: We only run this optimization after type legalization (which often
6591   // creates this pattern) and before operation legalization after which
6592   // we need to be more careful about the vector instructions that we generate.
6593   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6594       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6595
6596     EVT VecTy = N0.getOperand(0).getValueType();
6597     EVT ExTy = N0.getValueType();
6598     EVT TrTy = N->getValueType(0);
6599
6600     unsigned NumElem = VecTy.getVectorNumElements();
6601     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6602
6603     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6604     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6605
6606     SDValue EltNo = N0->getOperand(1);
6607     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6608       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6609       EVT IndexTy = TLI.getVectorIdxTy();
6610       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6611
6612       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6613                               NVT, N0.getOperand(0));
6614
6615       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6616                          SDLoc(N), TrTy, V,
6617                          DAG.getConstant(Index, IndexTy));
6618     }
6619   }
6620
6621   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6622   if (N0.getOpcode() == ISD::SELECT) {
6623     EVT SrcVT = N0.getValueType();
6624     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6625         TLI.isTruncateFree(SrcVT, VT)) {
6626       SDLoc SL(N0);
6627       SDValue Cond = N0.getOperand(0);
6628       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6629       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6630       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6631     }
6632   }
6633
6634   // Fold a series of buildvector, bitcast, and truncate if possible.
6635   // For example fold
6636   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6637   //   (2xi32 (buildvector x, y)).
6638   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6639       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6640       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6641       N0.getOperand(0).hasOneUse()) {
6642
6643     SDValue BuildVect = N0.getOperand(0);
6644     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6645     EVT TruncVecEltTy = VT.getVectorElementType();
6646
6647     // Check that the element types match.
6648     if (BuildVectEltTy == TruncVecEltTy) {
6649       // Now we only need to compute the offset of the truncated elements.
6650       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6651       unsigned TruncVecNumElts = VT.getVectorNumElements();
6652       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6653
6654       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6655              "Invalid number of elements");
6656
6657       SmallVector<SDValue, 8> Opnds;
6658       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6659         Opnds.push_back(BuildVect.getOperand(i));
6660
6661       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6662     }
6663   }
6664
6665   // See if we can simplify the input to this truncate through knowledge that
6666   // only the low bits are being used.
6667   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6668   // Currently we only perform this optimization on scalars because vectors
6669   // may have different active low bits.
6670   if (!VT.isVector()) {
6671     SDValue Shorter =
6672       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6673                                                VT.getSizeInBits()));
6674     if (Shorter.getNode())
6675       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6676   }
6677   // fold (truncate (load x)) -> (smaller load x)
6678   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6679   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6680     SDValue Reduced = ReduceLoadWidth(N);
6681     if (Reduced.getNode())
6682       return Reduced;
6683     // Handle the case where the load remains an extending load even
6684     // after truncation.
6685     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6686       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6687       if (!LN0->isVolatile() &&
6688           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6689         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6690                                          VT, LN0->getChain(), LN0->getBasePtr(),
6691                                          LN0->getMemoryVT(),
6692                                          LN0->getMemOperand());
6693         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6694         return NewLoad;
6695       }
6696     }
6697   }
6698   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6699   // where ... are all 'undef'.
6700   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6701     SmallVector<EVT, 8> VTs;
6702     SDValue V;
6703     unsigned Idx = 0;
6704     unsigned NumDefs = 0;
6705
6706     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6707       SDValue X = N0.getOperand(i);
6708       if (X.getOpcode() != ISD::UNDEF) {
6709         V = X;
6710         Idx = i;
6711         NumDefs++;
6712       }
6713       // Stop if more than one members are non-undef.
6714       if (NumDefs > 1)
6715         break;
6716       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6717                                      VT.getVectorElementType(),
6718                                      X.getValueType().getVectorNumElements()));
6719     }
6720
6721     if (NumDefs == 0)
6722       return DAG.getUNDEF(VT);
6723
6724     if (NumDefs == 1) {
6725       assert(V.getNode() && "The single defined operand is empty!");
6726       SmallVector<SDValue, 8> Opnds;
6727       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6728         if (i != Idx) {
6729           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6730           continue;
6731         }
6732         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6733         AddToWorklist(NV.getNode());
6734         Opnds.push_back(NV);
6735       }
6736       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6737     }
6738   }
6739
6740   // Simplify the operands using demanded-bits information.
6741   if (!VT.isVector() &&
6742       SimplifyDemandedBits(SDValue(N, 0)))
6743     return SDValue(N, 0);
6744
6745   return SDValue();
6746 }
6747
6748 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6749   SDValue Elt = N->getOperand(i);
6750   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6751     return Elt.getNode();
6752   return Elt.getOperand(Elt.getResNo()).getNode();
6753 }
6754
6755 /// build_pair (load, load) -> load
6756 /// if load locations are consecutive.
6757 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6758   assert(N->getOpcode() == ISD::BUILD_PAIR);
6759
6760   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6761   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6762   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6763       LD1->getAddressSpace() != LD2->getAddressSpace())
6764     return SDValue();
6765   EVT LD1VT = LD1->getValueType(0);
6766
6767   if (ISD::isNON_EXTLoad(LD2) &&
6768       LD2->hasOneUse() &&
6769       // If both are volatile this would reduce the number of volatile loads.
6770       // If one is volatile it might be ok, but play conservative and bail out.
6771       !LD1->isVolatile() &&
6772       !LD2->isVolatile() &&
6773       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6774     unsigned Align = LD1->getAlignment();
6775     unsigned NewAlign = TLI.getDataLayout()->
6776       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6777
6778     if (NewAlign <= Align &&
6779         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6780       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6781                          LD1->getBasePtr(), LD1->getPointerInfo(),
6782                          false, false, false, Align);
6783   }
6784
6785   return SDValue();
6786 }
6787
6788 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6789   SDValue N0 = N->getOperand(0);
6790   EVT VT = N->getValueType(0);
6791
6792   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6793   // Only do this before legalize, since afterward the target may be depending
6794   // on the bitconvert.
6795   // First check to see if this is all constant.
6796   if (!LegalTypes &&
6797       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6798       VT.isVector()) {
6799     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6800
6801     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6802     assert(!DestEltVT.isVector() &&
6803            "Element type of vector ValueType must not be vector!");
6804     if (isSimple)
6805       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6806   }
6807
6808   // If the input is a constant, let getNode fold it.
6809   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6810     // If we can't allow illegal operations, we need to check that this is just
6811     // a fp -> int or int -> conversion and that the resulting operation will
6812     // be legal.
6813     if (!LegalOperations ||
6814         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6815          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6816         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6817          TLI.isOperationLegal(ISD::Constant, VT)))
6818       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6819   }
6820
6821   // (conv (conv x, t1), t2) -> (conv x, t2)
6822   if (N0.getOpcode() == ISD::BITCAST)
6823     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6824                        N0.getOperand(0));
6825
6826   // fold (conv (load x)) -> (load (conv*)x)
6827   // If the resultant load doesn't need a higher alignment than the original!
6828   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6829       // Do not change the width of a volatile load.
6830       !cast<LoadSDNode>(N0)->isVolatile() &&
6831       // Do not remove the cast if the types differ in endian layout.
6832       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6833       TLI.hasBigEndianPartOrdering(VT) &&
6834       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6835       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6836     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6837     unsigned Align = TLI.getDataLayout()->
6838       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6839     unsigned OrigAlign = LN0->getAlignment();
6840
6841     if (Align <= OrigAlign) {
6842       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6843                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6844                                  LN0->isVolatile(), LN0->isNonTemporal(),
6845                                  LN0->isInvariant(), OrigAlign,
6846                                  LN0->getAAInfo());
6847       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6848       return Load;
6849     }
6850   }
6851
6852   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6853   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6854   // This often reduces constant pool loads.
6855   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6856        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6857       N0.getNode()->hasOneUse() && VT.isInteger() &&
6858       !VT.isVector() && !N0.getValueType().isVector()) {
6859     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6860                                   N0.getOperand(0));
6861     AddToWorklist(NewConv.getNode());
6862
6863     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6864     if (N0.getOpcode() == ISD::FNEG)
6865       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6866                          NewConv, DAG.getConstant(SignBit, VT));
6867     assert(N0.getOpcode() == ISD::FABS);
6868     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6869                        NewConv, DAG.getConstant(~SignBit, VT));
6870   }
6871
6872   // fold (bitconvert (fcopysign cst, x)) ->
6873   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6874   // Note that we don't handle (copysign x, cst) because this can always be
6875   // folded to an fneg or fabs.
6876   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6877       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6878       VT.isInteger() && !VT.isVector()) {
6879     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6880     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6881     if (isTypeLegal(IntXVT)) {
6882       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6883                               IntXVT, N0.getOperand(1));
6884       AddToWorklist(X.getNode());
6885
6886       // If X has a different width than the result/lhs, sext it or truncate it.
6887       unsigned VTWidth = VT.getSizeInBits();
6888       if (OrigXWidth < VTWidth) {
6889         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6890         AddToWorklist(X.getNode());
6891       } else if (OrigXWidth > VTWidth) {
6892         // To get the sign bit in the right place, we have to shift it right
6893         // before truncating.
6894         X = DAG.getNode(ISD::SRL, SDLoc(X),
6895                         X.getValueType(), X,
6896                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6897         AddToWorklist(X.getNode());
6898         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6899         AddToWorklist(X.getNode());
6900       }
6901
6902       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6903       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6904                       X, DAG.getConstant(SignBit, VT));
6905       AddToWorklist(X.getNode());
6906
6907       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6908                                 VT, N0.getOperand(0));
6909       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6910                         Cst, DAG.getConstant(~SignBit, VT));
6911       AddToWorklist(Cst.getNode());
6912
6913       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6914     }
6915   }
6916
6917   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6918   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6919     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6920     if (CombineLD.getNode())
6921       return CombineLD;
6922   }
6923
6924   return SDValue();
6925 }
6926
6927 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6928   EVT VT = N->getValueType(0);
6929   return CombineConsecutiveLoads(N, VT);
6930 }
6931
6932 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6933 /// operands. DstEltVT indicates the destination element value type.
6934 SDValue DAGCombiner::
6935 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6936   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6937
6938   // If this is already the right type, we're done.
6939   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6940
6941   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6942   unsigned DstBitSize = DstEltVT.getSizeInBits();
6943
6944   // If this is a conversion of N elements of one type to N elements of another
6945   // type, convert each element.  This handles FP<->INT cases.
6946   if (SrcBitSize == DstBitSize) {
6947     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6948                               BV->getValueType(0).getVectorNumElements());
6949
6950     // Due to the FP element handling below calling this routine recursively,
6951     // we can end up with a scalar-to-vector node here.
6952     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6953       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6954                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6955                                      DstEltVT, BV->getOperand(0)));
6956
6957     SmallVector<SDValue, 8> Ops;
6958     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6959       SDValue Op = BV->getOperand(i);
6960       // If the vector element type is not legal, the BUILD_VECTOR operands
6961       // are promoted and implicitly truncated.  Make that explicit here.
6962       if (Op.getValueType() != SrcEltVT)
6963         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6964       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6965                                 DstEltVT, Op));
6966       AddToWorklist(Ops.back().getNode());
6967     }
6968     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6969   }
6970
6971   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6972   // handle annoying details of growing/shrinking FP values, we convert them to
6973   // int first.
6974   if (SrcEltVT.isFloatingPoint()) {
6975     // Convert the input float vector to a int vector where the elements are the
6976     // same sizes.
6977     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6978     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6979     SrcEltVT = IntVT;
6980   }
6981
6982   // Now we know the input is an integer vector.  If the output is a FP type,
6983   // convert to integer first, then to FP of the right size.
6984   if (DstEltVT.isFloatingPoint()) {
6985     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6986     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6987
6988     // Next, convert to FP elements of the same size.
6989     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6990   }
6991
6992   // Okay, we know the src/dst types are both integers of differing types.
6993   // Handling growing first.
6994   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6995   if (SrcBitSize < DstBitSize) {
6996     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6997
6998     SmallVector<SDValue, 8> Ops;
6999     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7000          i += NumInputsPerOutput) {
7001       bool isLE = TLI.isLittleEndian();
7002       APInt NewBits = APInt(DstBitSize, 0);
7003       bool EltIsUndef = true;
7004       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7005         // Shift the previously computed bits over.
7006         NewBits <<= SrcBitSize;
7007         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7008         if (Op.getOpcode() == ISD::UNDEF) continue;
7009         EltIsUndef = false;
7010
7011         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7012                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7013       }
7014
7015       if (EltIsUndef)
7016         Ops.push_back(DAG.getUNDEF(DstEltVT));
7017       else
7018         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7019     }
7020
7021     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7022     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7023   }
7024
7025   // Finally, this must be the case where we are shrinking elements: each input
7026   // turns into multiple outputs.
7027   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7028   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7029                             NumOutputsPerInput*BV->getNumOperands());
7030   SmallVector<SDValue, 8> Ops;
7031
7032   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7033     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7034       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7035       continue;
7036     }
7037
7038     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7039                   getAPIntValue().zextOrTrunc(SrcBitSize);
7040
7041     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7042       APInt ThisVal = OpVal.trunc(DstBitSize);
7043       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7044       OpVal = OpVal.lshr(DstBitSize);
7045     }
7046
7047     // For big endian targets, swap the order of the pieces of each element.
7048     if (TLI.isBigEndian())
7049       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7050   }
7051
7052   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7053 }
7054
7055 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7056 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7057                                        bool Aggressive,
7058                                        SDNode *N,
7059                                        const TargetLowering &TLI,
7060                                        SelectionDAG &DAG) {
7061   SDValue N0 = N->getOperand(0);
7062   SDValue N1 = N->getOperand(1);
7063   EVT VT = N->getValueType(0);
7064
7065   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7066   if (N0.getOpcode() == ISD::FMUL &&
7067       (Aggressive || N0->hasOneUse())) {
7068     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7069                        N0.getOperand(0), N0.getOperand(1), N1);
7070   }
7071
7072   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7073   // Note: Commutes FADD operands.
7074   if (N1.getOpcode() == ISD::FMUL &&
7075       (Aggressive || N1->hasOneUse())) {
7076     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7077                        N1.getOperand(0), N1.getOperand(1), N0);
7078   }
7079
7080   // More folding opportunities when target permits.
7081   if (Aggressive) {
7082     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7083     if (N0.getOpcode() == ISD::FMA &&
7084         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7085       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7086                          N0.getOperand(0), N0.getOperand(1),
7087                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7088                                      N0.getOperand(2).getOperand(0),
7089                                      N0.getOperand(2).getOperand(1),
7090                                      N1));
7091     }
7092
7093     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7094     if (N1->getOpcode() == ISD::FMA &&
7095         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7096       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7097                          N1.getOperand(0), N1.getOperand(1),
7098                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7099                                      N1.getOperand(2).getOperand(0),
7100                                      N1.getOperand(2).getOperand(1),
7101                                      N0));
7102     }
7103   }
7104
7105   return SDValue();
7106 }
7107
7108 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7109                                        bool Aggressive,
7110                                        SDNode *N,
7111                                        const TargetLowering &TLI,
7112                                        SelectionDAG &DAG) {
7113   SDValue N0 = N->getOperand(0);
7114   SDValue N1 = N->getOperand(1);
7115   EVT VT = N->getValueType(0);
7116
7117   SDLoc SL(N);
7118
7119   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7120   if (N0.getOpcode() == ISD::FMUL &&
7121       (Aggressive || N0->hasOneUse())) {
7122     return DAG.getNode(FusedOpcode, SL, VT,
7123                        N0.getOperand(0), N0.getOperand(1),
7124                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7125   }
7126
7127   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7128   // Note: Commutes FSUB operands.
7129   if (N1.getOpcode() == ISD::FMUL &&
7130       (Aggressive || N1->hasOneUse()))
7131     return DAG.getNode(FusedOpcode, SL, VT,
7132                        DAG.getNode(ISD::FNEG, SL, VT,
7133                                    N1.getOperand(0)),
7134                        N1.getOperand(1), N0);
7135
7136   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7137   if (N0.getOpcode() == ISD::FNEG &&
7138       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7139       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7140     SDValue N00 = N0.getOperand(0).getOperand(0);
7141     SDValue N01 = N0.getOperand(0).getOperand(1);
7142     return DAG.getNode(FusedOpcode, SL, VT,
7143                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7144                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7145   }
7146
7147   // More folding opportunities when target permits.
7148   if (Aggressive) {
7149     // fold (fsub (fma x, y, (fmul u, v)), z)
7150     //   -> (fma x, y (fma u, v, (fneg z)))
7151     if (N0.getOpcode() == FusedOpcode &&
7152         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7153       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7154                          N0.getOperand(0), N0.getOperand(1),
7155                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7156                                      N0.getOperand(2).getOperand(0),
7157                                      N0.getOperand(2).getOperand(1),
7158                                      DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7159                                                  N1)));
7160     }
7161
7162     // fold (fsub x, (fma y, z, (fmul u, v)))
7163     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7164     if (N1.getOpcode() == FusedOpcode &&
7165         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7166       SDValue N20 = N1.getOperand(2).getOperand(0);
7167       SDValue N21 = N1.getOperand(2).getOperand(1);
7168       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7169                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7170                                      N1.getOperand(0)),
7171                          N1.getOperand(1),
7172                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7173                                      DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7174                                                  N20),
7175                                      N21, N0));
7176     }
7177   }
7178
7179   return SDValue();
7180 }
7181
7182 SDValue DAGCombiner::visitFADD(SDNode *N) {
7183   SDValue N0 = N->getOperand(0);
7184   SDValue N1 = N->getOperand(1);
7185   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7186   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7187   EVT VT = N->getValueType(0);
7188   const TargetOptions &Options = DAG.getTarget().Options;
7189
7190   // fold vector ops
7191   if (VT.isVector())
7192     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7193       return FoldedVOp;
7194
7195   // fold (fadd c1, c2) -> c1 + c2
7196   if (N0CFP && N1CFP)
7197     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7198
7199   // canonicalize constant to RHS
7200   if (N0CFP && !N1CFP)
7201     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7202
7203   // fold (fadd A, (fneg B)) -> (fsub A, B)
7204   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7205       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7206     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7207                        GetNegatedExpression(N1, DAG, LegalOperations));
7208
7209   // fold (fadd (fneg A), B) -> (fsub B, A)
7210   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7211       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7212     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7213                        GetNegatedExpression(N0, DAG, LegalOperations));
7214
7215   // If 'unsafe math' is enabled, fold lots of things.
7216   if (Options.UnsafeFPMath) {
7217     // No FP constant should be created after legalization as Instruction
7218     // Selection pass has a hard time dealing with FP constants.
7219     bool AllowNewConst = (Level < AfterLegalizeDAG);
7220
7221     // fold (fadd A, 0) -> A
7222     if (N1CFP && N1CFP->getValueAPF().isZero())
7223       return N0;
7224
7225     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7226     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7227         isa<ConstantFPSDNode>(N0.getOperand(1)))
7228       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7229                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7230                                      N0.getOperand(1), N1));
7231
7232     // If allowed, fold (fadd (fneg x), x) -> 0.0
7233     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7234       return DAG.getConstantFP(0.0, VT);
7235
7236     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7237     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7238       return DAG.getConstantFP(0.0, VT);
7239
7240     // We can fold chains of FADD's of the same value into multiplications.
7241     // This transform is not safe in general because we are reducing the number
7242     // of rounding steps.
7243     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7244       if (N0.getOpcode() == ISD::FMUL) {
7245         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7246         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7247
7248         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7249         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7250           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7251                                        SDValue(CFP01, 0),
7252                                        DAG.getConstantFP(1.0, VT));
7253           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7254         }
7255
7256         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7257         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7258             N1.getOperand(0) == N1.getOperand(1) &&
7259             N0.getOperand(0) == N1.getOperand(0)) {
7260           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7261                                        SDValue(CFP01, 0),
7262                                        DAG.getConstantFP(2.0, VT));
7263           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7264                              N0.getOperand(0), NewCFP);
7265         }
7266       }
7267
7268       if (N1.getOpcode() == ISD::FMUL) {
7269         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7270         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7271
7272         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7273         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7274           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7275                                        SDValue(CFP11, 0),
7276                                        DAG.getConstantFP(1.0, VT));
7277           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7278         }
7279
7280         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7281         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7282             N0.getOperand(0) == N0.getOperand(1) &&
7283             N1.getOperand(0) == N0.getOperand(0)) {
7284           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7285                                        SDValue(CFP11, 0),
7286                                        DAG.getConstantFP(2.0, VT));
7287           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7288         }
7289       }
7290
7291       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7292         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7293         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7294         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7295             (N0.getOperand(0) == N1))
7296           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7297                              N1, DAG.getConstantFP(3.0, VT));
7298       }
7299
7300       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7301         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7302         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7303         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7304             N1.getOperand(0) == N0)
7305           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7306                              N0, DAG.getConstantFP(3.0, VT));
7307       }
7308
7309       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7310       if (AllowNewConst &&
7311           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7312           N0.getOperand(0) == N0.getOperand(1) &&
7313           N1.getOperand(0) == N1.getOperand(1) &&
7314           N0.getOperand(0) == N1.getOperand(0))
7315         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7316                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7317     }
7318   } // enable-unsafe-fp-math
7319
7320   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7321     // Assume if there is an fmad instruction that it should be aggressively
7322     // used.
7323     if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7324       return Fused;
7325   }
7326
7327   // FADD -> FMA combines:
7328   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7329       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7330       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7331
7332     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7333       // Don't form FMA if we are preferring FMAD.
7334       if (SDValue Fused
7335           = performFaddFmulCombines(ISD::FMA,
7336                                     TLI.enableAggressiveFMAFusion(VT),
7337                                     N, TLI, DAG)) {
7338         return Fused;
7339       }
7340     }
7341
7342     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7343     // to combine into FMA, arrange such nodes accordingly.
7344     if (TLI.isFPExtFree(VT)) {
7345
7346       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7347       if (N0.getOpcode() == ISD::FP_EXTEND) {
7348         SDValue N00 = N0.getOperand(0);
7349         if (N00.getOpcode() == ISD::FMUL)
7350           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7351                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7352                                          N00.getOperand(0)),
7353                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7354                                          N00.getOperand(1)), N1);
7355       }
7356
7357       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7358       // Note: Commutes FADD operands.
7359       if (N1.getOpcode() == ISD::FP_EXTEND) {
7360         SDValue N10 = N1.getOperand(0);
7361         if (N10.getOpcode() == ISD::FMUL)
7362           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7363                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7364                                          N10.getOperand(0)),
7365                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7366                                          N10.getOperand(1)), N0);
7367       }
7368     }
7369   }
7370
7371   return SDValue();
7372 }
7373
7374 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7375   SDValue N0 = N->getOperand(0);
7376   SDValue N1 = N->getOperand(1);
7377   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7378   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7379   EVT VT = N->getValueType(0);
7380   SDLoc dl(N);
7381   const TargetOptions &Options = DAG.getTarget().Options;
7382
7383   // fold vector ops
7384   if (VT.isVector())
7385     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7386       return FoldedVOp;
7387
7388   // fold (fsub c1, c2) -> c1-c2
7389   if (N0CFP && N1CFP)
7390     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7391
7392   // fold (fsub A, (fneg B)) -> (fadd A, B)
7393   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7394     return DAG.getNode(ISD::FADD, dl, VT, N0,
7395                        GetNegatedExpression(N1, DAG, LegalOperations));
7396
7397   // If 'unsafe math' is enabled, fold lots of things.
7398   if (Options.UnsafeFPMath) {
7399     // (fsub A, 0) -> A
7400     if (N1CFP && N1CFP->getValueAPF().isZero())
7401       return N0;
7402
7403     // (fsub 0, B) -> -B
7404     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7405       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7406         return GetNegatedExpression(N1, DAG, LegalOperations);
7407       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7408         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7409     }
7410
7411     // (fsub x, x) -> 0.0
7412     if (N0 == N1)
7413       return DAG.getConstantFP(0.0f, VT);
7414
7415     // (fsub x, (fadd x, y)) -> (fneg y)
7416     // (fsub x, (fadd y, x)) -> (fneg y)
7417     if (N1.getOpcode() == ISD::FADD) {
7418       SDValue N10 = N1->getOperand(0);
7419       SDValue N11 = N1->getOperand(1);
7420
7421       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7422         return GetNegatedExpression(N11, DAG, LegalOperations);
7423
7424       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7425         return GetNegatedExpression(N10, DAG, LegalOperations);
7426     }
7427   }
7428
7429   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7430     // Assume if there is an fmad instruction that it should be aggressively
7431     // used.
7432     if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7433       return Fused;
7434   }
7435
7436   // FSUB -> FMA combines:
7437   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7438       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7439       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7440
7441     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7442       // Don't form FMA if we are preferring FMAD.
7443
7444       if (SDValue Fused
7445           = performFsubFmulCombines(ISD::FMA,
7446                                     TLI.enableAggressiveFMAFusion(VT),
7447                                     N, TLI, DAG)) {
7448         return Fused;
7449       }
7450     }
7451
7452     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7453     // to combine into FMA, arrange such nodes accordingly.
7454     if (TLI.isFPExtFree(VT)) {
7455       // fold (fsub (fpext (fmul x, y)), z)
7456       //   -> (fma (fpext x), (fpext y), (fneg z))
7457       if (N0.getOpcode() == ISD::FP_EXTEND) {
7458         SDValue N00 = N0.getOperand(0);
7459         if (N00.getOpcode() == ISD::FMUL)
7460           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7461                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7462                                          N00.getOperand(0)),
7463                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7464                                          N00.getOperand(1)),
7465                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7466       }
7467
7468       // fold (fsub x, (fpext (fmul y, z)))
7469       //   -> (fma (fneg (fpext y)), (fpext z), x)
7470       // Note: Commutes FSUB operands.
7471       if (N1.getOpcode() == ISD::FP_EXTEND) {
7472         SDValue N10 = N1.getOperand(0);
7473         if (N10.getOpcode() == ISD::FMUL)
7474           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7475                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7476                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7477                                                      VT, N10.getOperand(0))),
7478                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7479                                          N10.getOperand(1)),
7480                              N0);
7481       }
7482
7483       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7484       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7485       if (N0.getOpcode() == ISD::FP_EXTEND) {
7486         SDValue N00 = N0.getOperand(0);
7487         if (N00.getOpcode() == ISD::FNEG) {
7488           SDValue N000 = N00.getOperand(0);
7489           if (N000.getOpcode() == ISD::FMUL) {
7490             return DAG.getNode(ISD::FMA, dl, VT,
7491                                DAG.getNode(ISD::FNEG, dl, VT,
7492                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7493                                                        VT, N000.getOperand(0))),
7494                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7495                                            N000.getOperand(1)),
7496                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7497           }
7498         }
7499       }
7500
7501       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7502       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7503       if (N0.getOpcode() == ISD::FNEG) {
7504         SDValue N00 = N0.getOperand(0);
7505         if (N00.getOpcode() == ISD::FP_EXTEND) {
7506           SDValue N000 = N00.getOperand(0);
7507           if (N000.getOpcode() == ISD::FMUL) {
7508             return DAG.getNode(ISD::FMA, dl, VT,
7509                                DAG.getNode(ISD::FNEG, dl, VT,
7510                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7511                                            VT, N000.getOperand(0))),
7512                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7513                                            N000.getOperand(1)),
7514                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7515           }
7516         }
7517       }
7518     }
7519   }
7520
7521   return SDValue();
7522 }
7523
7524 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7525   SDValue N0 = N->getOperand(0);
7526   SDValue N1 = N->getOperand(1);
7527   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7528   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7529   EVT VT = N->getValueType(0);
7530   const TargetOptions &Options = DAG.getTarget().Options;
7531
7532   // fold vector ops
7533   if (VT.isVector()) {
7534     // This just handles C1 * C2 for vectors. Other vector folds are below.
7535     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7536       return FoldedVOp;
7537
7538     // Canonicalize vector constant to RHS.
7539     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7540         N1.getOpcode() != ISD::BUILD_VECTOR)
7541       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7542         if (BV0->isConstant())
7543           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7544   }
7545
7546   // fold (fmul c1, c2) -> c1*c2
7547   if (N0CFP && N1CFP)
7548     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7549
7550   // canonicalize constant to RHS
7551   if (N0CFP && !N1CFP)
7552     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7553
7554   // fold (fmul A, 1.0) -> A
7555   if (N1CFP && N1CFP->isExactlyValue(1.0))
7556     return N0;
7557
7558   if (Options.UnsafeFPMath) {
7559     // fold (fmul A, 0) -> 0
7560     if (N1CFP && N1CFP->getValueAPF().isZero())
7561       return N1;
7562
7563     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7564     if (N0.getOpcode() == ISD::FMUL) {
7565       // Fold scalars or any vector constants (not just splats).
7566       // This fold is done in general by InstCombine, but extra fmul insts
7567       // may have been generated during lowering.
7568       SDValue N00 = N0.getOperand(0);
7569       SDValue N01 = N0.getOperand(1);
7570       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7571       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7572       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7573       
7574       // Check 1: Make sure that the first operand of the inner multiply is NOT
7575       // a constant. Otherwise, we may induce infinite looping.
7576       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7577         // Check 2: Make sure that the second operand of the inner multiply and
7578         // the second operand of the outer multiply are constants.
7579         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7580             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7581           SDLoc SL(N);
7582           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7583           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7584         }
7585       }
7586     }
7587
7588     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7589     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7590     // during an early run of DAGCombiner can prevent folding with fmuls
7591     // inserted during lowering.
7592     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7593       SDLoc SL(N);
7594       const SDValue Two = DAG.getConstantFP(2.0, VT);
7595       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7596       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7597     }
7598   }
7599
7600   // fold (fmul X, 2.0) -> (fadd X, X)
7601   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7602     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7603
7604   // fold (fmul X, -1.0) -> (fneg X)
7605   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7606     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7607       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7608
7609   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7610   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7611     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7612       // Both can be negated for free, check to see if at least one is cheaper
7613       // negated.
7614       if (LHSNeg == 2 || RHSNeg == 2)
7615         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7616                            GetNegatedExpression(N0, DAG, LegalOperations),
7617                            GetNegatedExpression(N1, DAG, LegalOperations));
7618     }
7619   }
7620
7621   return SDValue();
7622 }
7623
7624 SDValue DAGCombiner::visitFMA(SDNode *N) {
7625   SDValue N0 = N->getOperand(0);
7626   SDValue N1 = N->getOperand(1);
7627   SDValue N2 = N->getOperand(2);
7628   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7629   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7630   EVT VT = N->getValueType(0);
7631   SDLoc dl(N);
7632   const TargetOptions &Options = DAG.getTarget().Options;
7633
7634   // Constant fold FMA.
7635   if (isa<ConstantFPSDNode>(N0) &&
7636       isa<ConstantFPSDNode>(N1) &&
7637       isa<ConstantFPSDNode>(N2)) {
7638     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7639   }
7640
7641   if (Options.UnsafeFPMath) {
7642     if (N0CFP && N0CFP->isZero())
7643       return N2;
7644     if (N1CFP && N1CFP->isZero())
7645       return N2;
7646   }
7647   if (N0CFP && N0CFP->isExactlyValue(1.0))
7648     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7649   if (N1CFP && N1CFP->isExactlyValue(1.0))
7650     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7651
7652   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7653   if (N0CFP && !N1CFP)
7654     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7655
7656   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7657   if (Options.UnsafeFPMath && N1CFP &&
7658       N2.getOpcode() == ISD::FMUL &&
7659       N0 == N2.getOperand(0) &&
7660       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7661     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7662                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7663   }
7664
7665
7666   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7667   if (Options.UnsafeFPMath &&
7668       N0.getOpcode() == ISD::FMUL && N1CFP &&
7669       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7670     return DAG.getNode(ISD::FMA, dl, VT,
7671                        N0.getOperand(0),
7672                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7673                        N2);
7674   }
7675
7676   // (fma x, 1, y) -> (fadd x, y)
7677   // (fma x, -1, y) -> (fadd (fneg x), y)
7678   if (N1CFP) {
7679     if (N1CFP->isExactlyValue(1.0))
7680       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7681
7682     if (N1CFP->isExactlyValue(-1.0) &&
7683         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7684       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7685       AddToWorklist(RHSNeg.getNode());
7686       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7687     }
7688   }
7689
7690   // (fma x, c, x) -> (fmul x, (c+1))
7691   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7692     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7693                        DAG.getNode(ISD::FADD, dl, VT,
7694                                    N1, DAG.getConstantFP(1.0, VT)));
7695
7696   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7697   if (Options.UnsafeFPMath && N1CFP &&
7698       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7699     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7700                        DAG.getNode(ISD::FADD, dl, VT,
7701                                    N1, DAG.getConstantFP(-1.0, VT)));
7702
7703
7704   return SDValue();
7705 }
7706
7707 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7708   SDValue N0 = N->getOperand(0);
7709   SDValue N1 = N->getOperand(1);
7710   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7711   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7712   EVT VT = N->getValueType(0);
7713   SDLoc DL(N);
7714   const TargetOptions &Options = DAG.getTarget().Options;
7715
7716   // fold vector ops
7717   if (VT.isVector())
7718     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7719       return FoldedVOp;
7720
7721   // fold (fdiv c1, c2) -> c1/c2
7722   if (N0CFP && N1CFP)
7723     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7724
7725   if (Options.UnsafeFPMath) {
7726     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7727     if (N1CFP) {
7728       // Compute the reciprocal 1.0 / c2.
7729       APFloat N1APF = N1CFP->getValueAPF();
7730       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7731       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7732       // Only do the transform if the reciprocal is a legal fp immediate that
7733       // isn't too nasty (eg NaN, denormal, ...).
7734       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7735           (!LegalOperations ||
7736            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7737            // backend)... we should handle this gracefully after Legalize.
7738            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7739            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7740            TLI.isFPImmLegal(Recip, VT)))
7741         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7742                            DAG.getConstantFP(Recip, VT));
7743     }
7744
7745     // If this FDIV is part of a reciprocal square root, it may be folded
7746     // into a target-specific square root estimate instruction.
7747     if (N1.getOpcode() == ISD::FSQRT) {
7748       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7749         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7750       }
7751     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7752                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7753       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7754         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7755         AddToWorklist(RV.getNode());
7756         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7757       }
7758     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7759                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7760       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7761         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7762         AddToWorklist(RV.getNode());
7763         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7764       }
7765     } else if (N1.getOpcode() == ISD::FMUL) {
7766       // Look through an FMUL. Even though this won't remove the FDIV directly,
7767       // it's still worthwhile to get rid of the FSQRT if possible.
7768       SDValue SqrtOp;
7769       SDValue OtherOp;
7770       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7771         SqrtOp = N1.getOperand(0);
7772         OtherOp = N1.getOperand(1);
7773       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7774         SqrtOp = N1.getOperand(1);
7775         OtherOp = N1.getOperand(0);
7776       }
7777       if (SqrtOp.getNode()) {
7778         // We found a FSQRT, so try to make this fold:
7779         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7780         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7781           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7782           AddToWorklist(RV.getNode());
7783           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7784         }
7785       }
7786     }
7787
7788     // Fold into a reciprocal estimate and multiply instead of a real divide.
7789     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7790       AddToWorklist(RV.getNode());
7791       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7792     }
7793   }
7794
7795   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7796   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7797     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7798       // Both can be negated for free, check to see if at least one is cheaper
7799       // negated.
7800       if (LHSNeg == 2 || RHSNeg == 2)
7801         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7802                            GetNegatedExpression(N0, DAG, LegalOperations),
7803                            GetNegatedExpression(N1, DAG, LegalOperations));
7804     }
7805   }
7806
7807   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7808   // reciprocal.
7809   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7810   // Notice that this is not always beneficial. One reason is different target
7811   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7812   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7813   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7814   if (Options.UnsafeFPMath) {
7815     // Skip if current node is a reciprocal.
7816     if (N0CFP && N0CFP->isExactlyValue(1.0))
7817       return SDValue();
7818
7819     SmallVector<SDNode *, 4> Users;
7820     // Find all FDIV users of the same divisor.
7821     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7822                               UE = N1.getNode()->use_end();
7823          UI != UE; ++UI) {
7824       SDNode *User = UI.getUse().getUser();
7825       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7826         Users.push_back(User);
7827     }
7828
7829     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7830       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7831       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7832
7833       // Dividend / Divisor -> Dividend * Reciprocal
7834       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7835         if ((*I)->getOperand(0) != FPOne) {
7836           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7837                                         (*I)->getOperand(0), Reciprocal);
7838           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7839         }
7840       }
7841       return SDValue();
7842     }
7843   }
7844
7845   return SDValue();
7846 }
7847
7848 SDValue DAGCombiner::visitFREM(SDNode *N) {
7849   SDValue N0 = N->getOperand(0);
7850   SDValue N1 = N->getOperand(1);
7851   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7852   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7853   EVT VT = N->getValueType(0);
7854
7855   // fold (frem c1, c2) -> fmod(c1,c2)
7856   if (N0CFP && N1CFP)
7857     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7858
7859   return SDValue();
7860 }
7861
7862 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7863   if (DAG.getTarget().Options.UnsafeFPMath &&
7864       !TLI.isFsqrtCheap()) {
7865     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7866     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7867       EVT VT = RV.getValueType();
7868       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7869       AddToWorklist(RV.getNode());
7870
7871       // Unfortunately, RV is now NaN if the input was exactly 0.
7872       // Select out this case and force the answer to 0.
7873       SDValue Zero = DAG.getConstantFP(0.0, VT);
7874       SDValue ZeroCmp =
7875         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7876                      N->getOperand(0), Zero, ISD::SETEQ);
7877       AddToWorklist(ZeroCmp.getNode());
7878       AddToWorklist(RV.getNode());
7879
7880       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7881                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7882       return RV;
7883     }
7884   }
7885   return SDValue();
7886 }
7887
7888 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7889   SDValue N0 = N->getOperand(0);
7890   SDValue N1 = N->getOperand(1);
7891   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7892   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7893   EVT VT = N->getValueType(0);
7894
7895   if (N0CFP && N1CFP)  // Constant fold
7896     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7897
7898   if (N1CFP) {
7899     const APFloat& V = N1CFP->getValueAPF();
7900     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7901     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7902     if (!V.isNegative()) {
7903       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7904         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7905     } else {
7906       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7907         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7908                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7909     }
7910   }
7911
7912   // copysign(fabs(x), y) -> copysign(x, y)
7913   // copysign(fneg(x), y) -> copysign(x, y)
7914   // copysign(copysign(x,z), y) -> copysign(x, y)
7915   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7916       N0.getOpcode() == ISD::FCOPYSIGN)
7917     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7918                        N0.getOperand(0), N1);
7919
7920   // copysign(x, abs(y)) -> abs(x)
7921   if (N1.getOpcode() == ISD::FABS)
7922     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7923
7924   // copysign(x, copysign(y,z)) -> copysign(x, z)
7925   if (N1.getOpcode() == ISD::FCOPYSIGN)
7926     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7927                        N0, N1.getOperand(1));
7928
7929   // copysign(x, fp_extend(y)) -> copysign(x, y)
7930   // copysign(x, fp_round(y)) -> copysign(x, y)
7931   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7932     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7933                        N0, N1.getOperand(0));
7934
7935   return SDValue();
7936 }
7937
7938 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7939   SDValue N0 = N->getOperand(0);
7940   EVT VT = N->getValueType(0);
7941   EVT OpVT = N0.getValueType();
7942
7943   // fold (sint_to_fp c1) -> c1fp
7944   if (isConstantIntBuildVectorOrConstantInt(N0) &&
7945       // ...but only if the target supports immediate floating-point values
7946       (!LegalOperations ||
7947        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7948     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7949
7950   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7951   // but UINT_TO_FP is legal on this target, try to convert.
7952   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7953       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7954     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7955     if (DAG.SignBitIsZero(N0))
7956       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7957   }
7958
7959   // The next optimizations are desirable only if SELECT_CC can be lowered.
7960   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7961     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7962     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7963         !VT.isVector() &&
7964         (!LegalOperations ||
7965          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7966       SDValue Ops[] =
7967         { N0.getOperand(0), N0.getOperand(1),
7968           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7969           N0.getOperand(2) };
7970       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7971     }
7972
7973     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7974     //      (select_cc x, y, 1.0, 0.0,, cc)
7975     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7976         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7977         (!LegalOperations ||
7978          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7979       SDValue Ops[] =
7980         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7981           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7982           N0.getOperand(0).getOperand(2) };
7983       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7984     }
7985   }
7986
7987   return SDValue();
7988 }
7989
7990 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7991   SDValue N0 = N->getOperand(0);
7992   EVT VT = N->getValueType(0);
7993   EVT OpVT = N0.getValueType();
7994
7995   // fold (uint_to_fp c1) -> c1fp
7996   if (isConstantIntBuildVectorOrConstantInt(N0) &&
7997       // ...but only if the target supports immediate floating-point values
7998       (!LegalOperations ||
7999        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8000     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8001
8002   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8003   // but SINT_TO_FP is legal on this target, try to convert.
8004   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8005       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8006     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8007     if (DAG.SignBitIsZero(N0))
8008       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8009   }
8010
8011   // The next optimizations are desirable only if SELECT_CC can be lowered.
8012   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8013     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8014
8015     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8016         (!LegalOperations ||
8017          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8018       SDValue Ops[] =
8019         { N0.getOperand(0), N0.getOperand(1),
8020           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
8021           N0.getOperand(2) };
8022       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8023     }
8024   }
8025
8026   return SDValue();
8027 }
8028
8029 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8030 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8031   SDValue N0 = N->getOperand(0);
8032   EVT VT = N->getValueType(0);
8033
8034   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8035     return SDValue();
8036
8037   SDValue Src = N0.getOperand(0);
8038   EVT SrcVT = Src.getValueType();
8039   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8040   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8041
8042   // We can safely assume the conversion won't overflow the output range,
8043   // because (for example) (uint8_t)18293.f is undefined behavior.
8044
8045   // Since we can assume the conversion won't overflow, our decision as to
8046   // whether the input will fit in the float should depend on the minimum
8047   // of the input range and output range.
8048
8049   // This means this is also safe for a signed input and unsigned output, since
8050   // a negative input would lead to undefined behavior.
8051   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8052   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8053   unsigned ActualSize = std::min(InputSize, OutputSize);
8054   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8055
8056   // We can only fold away the float conversion if the input range can be
8057   // represented exactly in the float range.
8058   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8059     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8060       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8061                                                        : ISD::ZERO_EXTEND;
8062       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8063     }
8064     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8065       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8066     if (SrcVT == VT)
8067       return Src;
8068     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8069   }
8070   return SDValue();
8071 }
8072
8073 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8074   SDValue N0 = N->getOperand(0);
8075   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8076   EVT VT = N->getValueType(0);
8077
8078   // fold (fp_to_sint c1fp) -> c1
8079   if (N0CFP)
8080     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8081
8082   return FoldIntToFPToInt(N, DAG);
8083 }
8084
8085 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8086   SDValue N0 = N->getOperand(0);
8087   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8088   EVT VT = N->getValueType(0);
8089
8090   // fold (fp_to_uint c1fp) -> c1
8091   if (N0CFP)
8092     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8093
8094   return FoldIntToFPToInt(N, DAG);
8095 }
8096
8097 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8098   SDValue N0 = N->getOperand(0);
8099   SDValue N1 = N->getOperand(1);
8100   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8101   EVT VT = N->getValueType(0);
8102
8103   // fold (fp_round c1fp) -> c1fp
8104   if (N0CFP)
8105     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8106
8107   // fold (fp_round (fp_extend x)) -> x
8108   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8109     return N0.getOperand(0);
8110
8111   // fold (fp_round (fp_round x)) -> (fp_round x)
8112   if (N0.getOpcode() == ISD::FP_ROUND) {
8113     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8114     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8115     // If the first fp_round isn't a value preserving truncation, it might
8116     // introduce a tie in the second fp_round, that wouldn't occur in the
8117     // single-step fp_round we want to fold to.
8118     // In other words, double rounding isn't the same as rounding.
8119     // Also, this is a value preserving truncation iff both fp_round's are.
8120     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8121       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8122                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8123   }
8124
8125   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8126   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8127     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8128                               N0.getOperand(0), N1);
8129     AddToWorklist(Tmp.getNode());
8130     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8131                        Tmp, N0.getOperand(1));
8132   }
8133
8134   return SDValue();
8135 }
8136
8137 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8138   SDValue N0 = N->getOperand(0);
8139   EVT VT = N->getValueType(0);
8140   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8141   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8142
8143   // fold (fp_round_inreg c1fp) -> c1fp
8144   if (N0CFP && isTypeLegal(EVT)) {
8145     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8146     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8147   }
8148
8149   return SDValue();
8150 }
8151
8152 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8153   SDValue N0 = N->getOperand(0);
8154   EVT VT = N->getValueType(0);
8155
8156   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8157   if (N->hasOneUse() &&
8158       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8159     return SDValue();
8160
8161   // fold (fp_extend c1fp) -> c1fp
8162   if (isConstantFPBuildVectorOrConstantFP(N0))
8163     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8164
8165   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8166   // value of X.
8167   if (N0.getOpcode() == ISD::FP_ROUND
8168       && N0.getNode()->getConstantOperandVal(1) == 1) {
8169     SDValue In = N0.getOperand(0);
8170     if (In.getValueType() == VT) return In;
8171     if (VT.bitsLT(In.getValueType()))
8172       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8173                          In, N0.getOperand(1));
8174     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8175   }
8176
8177   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8178   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8179        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8180     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8181     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8182                                      LN0->getChain(),
8183                                      LN0->getBasePtr(), N0.getValueType(),
8184                                      LN0->getMemOperand());
8185     CombineTo(N, ExtLoad);
8186     CombineTo(N0.getNode(),
8187               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8188                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8189               ExtLoad.getValue(1));
8190     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8191   }
8192
8193   return SDValue();
8194 }
8195
8196 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8197   SDValue N0 = N->getOperand(0);
8198   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8199   EVT VT = N->getValueType(0);
8200
8201   // fold (fceil c1) -> fceil(c1)
8202   if (N0CFP)
8203     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8204
8205   return SDValue();
8206 }
8207
8208 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8209   SDValue N0 = N->getOperand(0);
8210   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8211   EVT VT = N->getValueType(0);
8212
8213   // fold (ftrunc c1) -> ftrunc(c1)
8214   if (N0CFP)
8215     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8216
8217   return SDValue();
8218 }
8219
8220 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8221   SDValue N0 = N->getOperand(0);
8222   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8223   EVT VT = N->getValueType(0);
8224
8225   // fold (ffloor c1) -> ffloor(c1)
8226   if (N0CFP)
8227     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8228
8229   return SDValue();
8230 }
8231
8232 // FIXME: FNEG and FABS have a lot in common; refactor.
8233 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8234   SDValue N0 = N->getOperand(0);
8235   EVT VT = N->getValueType(0);
8236
8237   // Constant fold FNEG.
8238   if (isConstantFPBuildVectorOrConstantFP(N0))
8239     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8240
8241   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8242                          &DAG.getTarget().Options))
8243     return GetNegatedExpression(N0, DAG, LegalOperations);
8244
8245   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8246   // constant pool values.
8247   if (!TLI.isFNegFree(VT) &&
8248       N0.getOpcode() == ISD::BITCAST &&
8249       N0.getNode()->hasOneUse()) {
8250     SDValue Int = N0.getOperand(0);
8251     EVT IntVT = Int.getValueType();
8252     if (IntVT.isInteger() && !IntVT.isVector()) {
8253       APInt SignMask;
8254       if (N0.getValueType().isVector()) {
8255         // For a vector, get a mask such as 0x80... per scalar element
8256         // and splat it.
8257         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8258         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8259       } else {
8260         // For a scalar, just generate 0x80...
8261         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8262       }
8263       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8264                         DAG.getConstant(SignMask, IntVT));
8265       AddToWorklist(Int.getNode());
8266       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8267     }
8268   }
8269
8270   // (fneg (fmul c, x)) -> (fmul -c, x)
8271   if (N0.getOpcode() == ISD::FMUL) {
8272     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8273     if (CFP1) {
8274       APFloat CVal = CFP1->getValueAPF();
8275       CVal.changeSign();
8276       if (Level >= AfterLegalizeDAG &&
8277           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8278            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8279         return DAG.getNode(
8280             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8281             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8282     }
8283   }
8284
8285   return SDValue();
8286 }
8287
8288 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8289   SDValue N0 = N->getOperand(0);
8290   SDValue N1 = N->getOperand(1);
8291   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8292   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8293
8294   if (N0CFP && N1CFP) {
8295     const APFloat &C0 = N0CFP->getValueAPF();
8296     const APFloat &C1 = N1CFP->getValueAPF();
8297     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8298   }
8299
8300   if (N0CFP) {
8301     EVT VT = N->getValueType(0);
8302     // Canonicalize to constant on RHS.
8303     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8304   }
8305
8306   return SDValue();
8307 }
8308
8309 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8310   SDValue N0 = N->getOperand(0);
8311   SDValue N1 = N->getOperand(1);
8312   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8313   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8314
8315   if (N0CFP && N1CFP) {
8316     const APFloat &C0 = N0CFP->getValueAPF();
8317     const APFloat &C1 = N1CFP->getValueAPF();
8318     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8319   }
8320
8321   if (N0CFP) {
8322     EVT VT = N->getValueType(0);
8323     // Canonicalize to constant on RHS.
8324     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8325   }
8326
8327   return SDValue();
8328 }
8329
8330 SDValue DAGCombiner::visitFABS(SDNode *N) {
8331   SDValue N0 = N->getOperand(0);
8332   EVT VT = N->getValueType(0);
8333
8334   // fold (fabs c1) -> fabs(c1)
8335   if (isConstantFPBuildVectorOrConstantFP(N0))
8336     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8337
8338   // fold (fabs (fabs x)) -> (fabs x)
8339   if (N0.getOpcode() == ISD::FABS)
8340     return N->getOperand(0);
8341
8342   // fold (fabs (fneg x)) -> (fabs x)
8343   // fold (fabs (fcopysign x, y)) -> (fabs x)
8344   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8345     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8346
8347   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8348   // constant pool values.
8349   if (!TLI.isFAbsFree(VT) &&
8350       N0.getOpcode() == ISD::BITCAST &&
8351       N0.getNode()->hasOneUse()) {
8352     SDValue Int = N0.getOperand(0);
8353     EVT IntVT = Int.getValueType();
8354     if (IntVT.isInteger() && !IntVT.isVector()) {
8355       APInt SignMask;
8356       if (N0.getValueType().isVector()) {
8357         // For a vector, get a mask such as 0x7f... per scalar element
8358         // and splat it.
8359         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8360         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8361       } else {
8362         // For a scalar, just generate 0x7f...
8363         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8364       }
8365       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8366                         DAG.getConstant(SignMask, IntVT));
8367       AddToWorklist(Int.getNode());
8368       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8369     }
8370   }
8371
8372   return SDValue();
8373 }
8374
8375 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8376   SDValue Chain = N->getOperand(0);
8377   SDValue N1 = N->getOperand(1);
8378   SDValue N2 = N->getOperand(2);
8379
8380   // If N is a constant we could fold this into a fallthrough or unconditional
8381   // branch. However that doesn't happen very often in normal code, because
8382   // Instcombine/SimplifyCFG should have handled the available opportunities.
8383   // If we did this folding here, it would be necessary to update the
8384   // MachineBasicBlock CFG, which is awkward.
8385
8386   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8387   // on the target.
8388   if (N1.getOpcode() == ISD::SETCC &&
8389       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8390                                    N1.getOperand(0).getValueType())) {
8391     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8392                        Chain, N1.getOperand(2),
8393                        N1.getOperand(0), N1.getOperand(1), N2);
8394   }
8395
8396   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8397       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8398        (N1.getOperand(0).hasOneUse() &&
8399         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8400     SDNode *Trunc = nullptr;
8401     if (N1.getOpcode() == ISD::TRUNCATE) {
8402       // Look pass the truncate.
8403       Trunc = N1.getNode();
8404       N1 = N1.getOperand(0);
8405     }
8406
8407     // Match this pattern so that we can generate simpler code:
8408     //
8409     //   %a = ...
8410     //   %b = and i32 %a, 2
8411     //   %c = srl i32 %b, 1
8412     //   brcond i32 %c ...
8413     //
8414     // into
8415     //
8416     //   %a = ...
8417     //   %b = and i32 %a, 2
8418     //   %c = setcc eq %b, 0
8419     //   brcond %c ...
8420     //
8421     // This applies only when the AND constant value has one bit set and the
8422     // SRL constant is equal to the log2 of the AND constant. The back-end is
8423     // smart enough to convert the result into a TEST/JMP sequence.
8424     SDValue Op0 = N1.getOperand(0);
8425     SDValue Op1 = N1.getOperand(1);
8426
8427     if (Op0.getOpcode() == ISD::AND &&
8428         Op1.getOpcode() == ISD::Constant) {
8429       SDValue AndOp1 = Op0.getOperand(1);
8430
8431       if (AndOp1.getOpcode() == ISD::Constant) {
8432         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8433
8434         if (AndConst.isPowerOf2() &&
8435             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8436           SDValue SetCC =
8437             DAG.getSetCC(SDLoc(N),
8438                          getSetCCResultType(Op0.getValueType()),
8439                          Op0, DAG.getConstant(0, Op0.getValueType()),
8440                          ISD::SETNE);
8441
8442           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8443                                           MVT::Other, Chain, SetCC, N2);
8444           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8445           // will convert it back to (X & C1) >> C2.
8446           CombineTo(N, NewBRCond, false);
8447           // Truncate is dead.
8448           if (Trunc)
8449             deleteAndRecombine(Trunc);
8450           // Replace the uses of SRL with SETCC
8451           WorklistRemover DeadNodes(*this);
8452           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8453           deleteAndRecombine(N1.getNode());
8454           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8455         }
8456       }
8457     }
8458
8459     if (Trunc)
8460       // Restore N1 if the above transformation doesn't match.
8461       N1 = N->getOperand(1);
8462   }
8463
8464   // Transform br(xor(x, y)) -> br(x != y)
8465   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8466   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8467     SDNode *TheXor = N1.getNode();
8468     SDValue Op0 = TheXor->getOperand(0);
8469     SDValue Op1 = TheXor->getOperand(1);
8470     if (Op0.getOpcode() == Op1.getOpcode()) {
8471       // Avoid missing important xor optimizations.
8472       SDValue Tmp = visitXOR(TheXor);
8473       if (Tmp.getNode()) {
8474         if (Tmp.getNode() != TheXor) {
8475           DEBUG(dbgs() << "\nReplacing.8 ";
8476                 TheXor->dump(&DAG);
8477                 dbgs() << "\nWith: ";
8478                 Tmp.getNode()->dump(&DAG);
8479                 dbgs() << '\n');
8480           WorklistRemover DeadNodes(*this);
8481           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8482           deleteAndRecombine(TheXor);
8483           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8484                              MVT::Other, Chain, Tmp, N2);
8485         }
8486
8487         // visitXOR has changed XOR's operands or replaced the XOR completely,
8488         // bail out.
8489         return SDValue(N, 0);
8490       }
8491     }
8492
8493     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8494       bool Equal = false;
8495       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8496         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8497             Op0.getOpcode() == ISD::XOR) {
8498           TheXor = Op0.getNode();
8499           Equal = true;
8500         }
8501
8502       EVT SetCCVT = N1.getValueType();
8503       if (LegalTypes)
8504         SetCCVT = getSetCCResultType(SetCCVT);
8505       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8506                                    SetCCVT,
8507                                    Op0, Op1,
8508                                    Equal ? ISD::SETEQ : ISD::SETNE);
8509       // Replace the uses of XOR with SETCC
8510       WorklistRemover DeadNodes(*this);
8511       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8512       deleteAndRecombine(N1.getNode());
8513       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8514                          MVT::Other, Chain, SetCC, N2);
8515     }
8516   }
8517
8518   return SDValue();
8519 }
8520
8521 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8522 //
8523 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8524   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8525   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8526
8527   // If N is a constant we could fold this into a fallthrough or unconditional
8528   // branch. However that doesn't happen very often in normal code, because
8529   // Instcombine/SimplifyCFG should have handled the available opportunities.
8530   // If we did this folding here, it would be necessary to update the
8531   // MachineBasicBlock CFG, which is awkward.
8532
8533   // Use SimplifySetCC to simplify SETCC's.
8534   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8535                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8536                                false);
8537   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8538
8539   // fold to a simpler setcc
8540   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8541     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8542                        N->getOperand(0), Simp.getOperand(2),
8543                        Simp.getOperand(0), Simp.getOperand(1),
8544                        N->getOperand(4));
8545
8546   return SDValue();
8547 }
8548
8549 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8550 /// and that N may be folded in the load / store addressing mode.
8551 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8552                                     SelectionDAG &DAG,
8553                                     const TargetLowering &TLI) {
8554   EVT VT;
8555   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8556     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8557       return false;
8558     VT = Use->getValueType(0);
8559   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8560     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8561       return false;
8562     VT = ST->getValue().getValueType();
8563   } else
8564     return false;
8565
8566   TargetLowering::AddrMode AM;
8567   if (N->getOpcode() == ISD::ADD) {
8568     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8569     if (Offset)
8570       // [reg +/- imm]
8571       AM.BaseOffs = Offset->getSExtValue();
8572     else
8573       // [reg +/- reg]
8574       AM.Scale = 1;
8575   } else if (N->getOpcode() == ISD::SUB) {
8576     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8577     if (Offset)
8578       // [reg +/- imm]
8579       AM.BaseOffs = -Offset->getSExtValue();
8580     else
8581       // [reg +/- reg]
8582       AM.Scale = 1;
8583   } else
8584     return false;
8585
8586   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8587 }
8588
8589 /// Try turning a load/store into a pre-indexed load/store when the base
8590 /// pointer is an add or subtract and it has other uses besides the load/store.
8591 /// After the transformation, the new indexed load/store has effectively folded
8592 /// the add/subtract in and all of its other uses are redirected to the
8593 /// new load/store.
8594 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8595   if (Level < AfterLegalizeDAG)
8596     return false;
8597
8598   bool isLoad = true;
8599   SDValue Ptr;
8600   EVT VT;
8601   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8602     if (LD->isIndexed())
8603       return false;
8604     VT = LD->getMemoryVT();
8605     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8606         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8607       return false;
8608     Ptr = LD->getBasePtr();
8609   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8610     if (ST->isIndexed())
8611       return false;
8612     VT = ST->getMemoryVT();
8613     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8614         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8615       return false;
8616     Ptr = ST->getBasePtr();
8617     isLoad = false;
8618   } else {
8619     return false;
8620   }
8621
8622   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8623   // out.  There is no reason to make this a preinc/predec.
8624   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8625       Ptr.getNode()->hasOneUse())
8626     return false;
8627
8628   // Ask the target to do addressing mode selection.
8629   SDValue BasePtr;
8630   SDValue Offset;
8631   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8632   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8633     return false;
8634
8635   // Backends without true r+i pre-indexed forms may need to pass a
8636   // constant base with a variable offset so that constant coercion
8637   // will work with the patterns in canonical form.
8638   bool Swapped = false;
8639   if (isa<ConstantSDNode>(BasePtr)) {
8640     std::swap(BasePtr, Offset);
8641     Swapped = true;
8642   }
8643
8644   // Don't create a indexed load / store with zero offset.
8645   if (isa<ConstantSDNode>(Offset) &&
8646       cast<ConstantSDNode>(Offset)->isNullValue())
8647     return false;
8648
8649   // Try turning it into a pre-indexed load / store except when:
8650   // 1) The new base ptr is a frame index.
8651   // 2) If N is a store and the new base ptr is either the same as or is a
8652   //    predecessor of the value being stored.
8653   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8654   //    that would create a cycle.
8655   // 4) All uses are load / store ops that use it as old base ptr.
8656
8657   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8658   // (plus the implicit offset) to a register to preinc anyway.
8659   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8660     return false;
8661
8662   // Check #2.
8663   if (!isLoad) {
8664     SDValue Val = cast<StoreSDNode>(N)->getValue();
8665     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8666       return false;
8667   }
8668
8669   // If the offset is a constant, there may be other adds of constants that
8670   // can be folded with this one. We should do this to avoid having to keep
8671   // a copy of the original base pointer.
8672   SmallVector<SDNode *, 16> OtherUses;
8673   if (isa<ConstantSDNode>(Offset))
8674     for (SDNode *Use : BasePtr.getNode()->uses()) {
8675       if (Use == Ptr.getNode())
8676         continue;
8677
8678       if (Use->isPredecessorOf(N))
8679         continue;
8680
8681       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8682         OtherUses.clear();
8683         break;
8684       }
8685
8686       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8687       if (Op1.getNode() == BasePtr.getNode())
8688         std::swap(Op0, Op1);
8689       assert(Op0.getNode() == BasePtr.getNode() &&
8690              "Use of ADD/SUB but not an operand");
8691
8692       if (!isa<ConstantSDNode>(Op1)) {
8693         OtherUses.clear();
8694         break;
8695       }
8696
8697       // FIXME: In some cases, we can be smarter about this.
8698       if (Op1.getValueType() != Offset.getValueType()) {
8699         OtherUses.clear();
8700         break;
8701       }
8702
8703       OtherUses.push_back(Use);
8704     }
8705
8706   if (Swapped)
8707     std::swap(BasePtr, Offset);
8708
8709   // Now check for #3 and #4.
8710   bool RealUse = false;
8711
8712   // Caches for hasPredecessorHelper
8713   SmallPtrSet<const SDNode *, 32> Visited;
8714   SmallVector<const SDNode *, 16> Worklist;
8715
8716   for (SDNode *Use : Ptr.getNode()->uses()) {
8717     if (Use == N)
8718       continue;
8719     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8720       return false;
8721
8722     // If Ptr may be folded in addressing mode of other use, then it's
8723     // not profitable to do this transformation.
8724     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8725       RealUse = true;
8726   }
8727
8728   if (!RealUse)
8729     return false;
8730
8731   SDValue Result;
8732   if (isLoad)
8733     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8734                                 BasePtr, Offset, AM);
8735   else
8736     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8737                                  BasePtr, Offset, AM);
8738   ++PreIndexedNodes;
8739   ++NodesCombined;
8740   DEBUG(dbgs() << "\nReplacing.4 ";
8741         N->dump(&DAG);
8742         dbgs() << "\nWith: ";
8743         Result.getNode()->dump(&DAG);
8744         dbgs() << '\n');
8745   WorklistRemover DeadNodes(*this);
8746   if (isLoad) {
8747     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8748     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8749   } else {
8750     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8751   }
8752
8753   // Finally, since the node is now dead, remove it from the graph.
8754   deleteAndRecombine(N);
8755
8756   if (Swapped)
8757     std::swap(BasePtr, Offset);
8758
8759   // Replace other uses of BasePtr that can be updated to use Ptr
8760   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8761     unsigned OffsetIdx = 1;
8762     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8763       OffsetIdx = 0;
8764     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8765            BasePtr.getNode() && "Expected BasePtr operand");
8766
8767     // We need to replace ptr0 in the following expression:
8768     //   x0 * offset0 + y0 * ptr0 = t0
8769     // knowing that
8770     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8771     //
8772     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8773     // indexed load/store and the expresion that needs to be re-written.
8774     //
8775     // Therefore, we have:
8776     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8777
8778     ConstantSDNode *CN =
8779       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8780     int X0, X1, Y0, Y1;
8781     APInt Offset0 = CN->getAPIntValue();
8782     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8783
8784     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8785     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8786     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8787     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8788
8789     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8790
8791     APInt CNV = Offset0;
8792     if (X0 < 0) CNV = -CNV;
8793     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8794     else CNV = CNV - Offset1;
8795
8796     // We can now generate the new expression.
8797     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8798     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8799
8800     SDValue NewUse = DAG.getNode(Opcode,
8801                                  SDLoc(OtherUses[i]),
8802                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8803     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8804     deleteAndRecombine(OtherUses[i]);
8805   }
8806
8807   // Replace the uses of Ptr with uses of the updated base value.
8808   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8809   deleteAndRecombine(Ptr.getNode());
8810
8811   return true;
8812 }
8813
8814 /// Try to combine a load/store with a add/sub of the base pointer node into a
8815 /// post-indexed load/store. The transformation folded the add/subtract into the
8816 /// new indexed load/store effectively and all of its uses are redirected to the
8817 /// new load/store.
8818 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8819   if (Level < AfterLegalizeDAG)
8820     return false;
8821
8822   bool isLoad = true;
8823   SDValue Ptr;
8824   EVT VT;
8825   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8826     if (LD->isIndexed())
8827       return false;
8828     VT = LD->getMemoryVT();
8829     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8830         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8831       return false;
8832     Ptr = LD->getBasePtr();
8833   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8834     if (ST->isIndexed())
8835       return false;
8836     VT = ST->getMemoryVT();
8837     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8838         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8839       return false;
8840     Ptr = ST->getBasePtr();
8841     isLoad = false;
8842   } else {
8843     return false;
8844   }
8845
8846   if (Ptr.getNode()->hasOneUse())
8847     return false;
8848
8849   for (SDNode *Op : Ptr.getNode()->uses()) {
8850     if (Op == N ||
8851         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8852       continue;
8853
8854     SDValue BasePtr;
8855     SDValue Offset;
8856     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8857     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8858       // Don't create a indexed load / store with zero offset.
8859       if (isa<ConstantSDNode>(Offset) &&
8860           cast<ConstantSDNode>(Offset)->isNullValue())
8861         continue;
8862
8863       // Try turning it into a post-indexed load / store except when
8864       // 1) All uses are load / store ops that use it as base ptr (and
8865       //    it may be folded as addressing mmode).
8866       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8867       //    nor a successor of N. Otherwise, if Op is folded that would
8868       //    create a cycle.
8869
8870       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8871         continue;
8872
8873       // Check for #1.
8874       bool TryNext = false;
8875       for (SDNode *Use : BasePtr.getNode()->uses()) {
8876         if (Use == Ptr.getNode())
8877           continue;
8878
8879         // If all the uses are load / store addresses, then don't do the
8880         // transformation.
8881         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8882           bool RealUse = false;
8883           for (SDNode *UseUse : Use->uses()) {
8884             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8885               RealUse = true;
8886           }
8887
8888           if (!RealUse) {
8889             TryNext = true;
8890             break;
8891           }
8892         }
8893       }
8894
8895       if (TryNext)
8896         continue;
8897
8898       // Check for #2
8899       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8900         SDValue Result = isLoad
8901           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8902                                BasePtr, Offset, AM)
8903           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8904                                 BasePtr, Offset, AM);
8905         ++PostIndexedNodes;
8906         ++NodesCombined;
8907         DEBUG(dbgs() << "\nReplacing.5 ";
8908               N->dump(&DAG);
8909               dbgs() << "\nWith: ";
8910               Result.getNode()->dump(&DAG);
8911               dbgs() << '\n');
8912         WorklistRemover DeadNodes(*this);
8913         if (isLoad) {
8914           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8915           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8916         } else {
8917           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8918         }
8919
8920         // Finally, since the node is now dead, remove it from the graph.
8921         deleteAndRecombine(N);
8922
8923         // Replace the uses of Use with uses of the updated base value.
8924         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8925                                       Result.getValue(isLoad ? 1 : 0));
8926         deleteAndRecombine(Op);
8927         return true;
8928       }
8929     }
8930   }
8931
8932   return false;
8933 }
8934
8935 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8936 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8937   ISD::MemIndexedMode AM = LD->getAddressingMode();
8938   assert(AM != ISD::UNINDEXED);
8939   SDValue BP = LD->getOperand(1);
8940   SDValue Inc = LD->getOperand(2);
8941
8942   // Some backends use TargetConstants for load offsets, but don't expect
8943   // TargetConstants in general ADD nodes. We can convert these constants into
8944   // regular Constants (if the constant is not opaque).
8945   assert((Inc.getOpcode() != ISD::TargetConstant ||
8946           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8947          "Cannot split out indexing using opaque target constants");
8948   if (Inc.getOpcode() == ISD::TargetConstant) {
8949     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8950     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8951                           ConstInc->getValueType(0));
8952   }
8953
8954   unsigned Opc =
8955       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8956   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8957 }
8958
8959 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8960   LoadSDNode *LD  = cast<LoadSDNode>(N);
8961   SDValue Chain = LD->getChain();
8962   SDValue Ptr   = LD->getBasePtr();
8963
8964   // If load is not volatile and there are no uses of the loaded value (and
8965   // the updated indexed value in case of indexed loads), change uses of the
8966   // chain value into uses of the chain input (i.e. delete the dead load).
8967   if (!LD->isVolatile()) {
8968     if (N->getValueType(1) == MVT::Other) {
8969       // Unindexed loads.
8970       if (!N->hasAnyUseOfValue(0)) {
8971         // It's not safe to use the two value CombineTo variant here. e.g.
8972         // v1, chain2 = load chain1, loc
8973         // v2, chain3 = load chain2, loc
8974         // v3         = add v2, c
8975         // Now we replace use of chain2 with chain1.  This makes the second load
8976         // isomorphic to the one we are deleting, and thus makes this load live.
8977         DEBUG(dbgs() << "\nReplacing.6 ";
8978               N->dump(&DAG);
8979               dbgs() << "\nWith chain: ";
8980               Chain.getNode()->dump(&DAG);
8981               dbgs() << "\n");
8982         WorklistRemover DeadNodes(*this);
8983         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8984
8985         if (N->use_empty())
8986           deleteAndRecombine(N);
8987
8988         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8989       }
8990     } else {
8991       // Indexed loads.
8992       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8993
8994       // If this load has an opaque TargetConstant offset, then we cannot split
8995       // the indexing into an add/sub directly (that TargetConstant may not be
8996       // valid for a different type of node, and we cannot convert an opaque
8997       // target constant into a regular constant).
8998       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8999                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9000
9001       if (!N->hasAnyUseOfValue(0) &&
9002           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9003         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9004         SDValue Index;
9005         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9006           Index = SplitIndexingFromLoad(LD);
9007           // Try to fold the base pointer arithmetic into subsequent loads and
9008           // stores.
9009           AddUsersToWorklist(N);
9010         } else
9011           Index = DAG.getUNDEF(N->getValueType(1));
9012         DEBUG(dbgs() << "\nReplacing.7 ";
9013               N->dump(&DAG);
9014               dbgs() << "\nWith: ";
9015               Undef.getNode()->dump(&DAG);
9016               dbgs() << " and 2 other values\n");
9017         WorklistRemover DeadNodes(*this);
9018         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9019         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9020         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9021         deleteAndRecombine(N);
9022         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9023       }
9024     }
9025   }
9026
9027   // If this load is directly stored, replace the load value with the stored
9028   // value.
9029   // TODO: Handle store large -> read small portion.
9030   // TODO: Handle TRUNCSTORE/LOADEXT
9031   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9032     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9033       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9034       if (PrevST->getBasePtr() == Ptr &&
9035           PrevST->getValue().getValueType() == N->getValueType(0))
9036       return CombineTo(N, Chain.getOperand(1), Chain);
9037     }
9038   }
9039
9040   // Try to infer better alignment information than the load already has.
9041   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9042     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9043       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9044         SDValue NewLoad =
9045                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9046                               LD->getValueType(0),
9047                               Chain, Ptr, LD->getPointerInfo(),
9048                               LD->getMemoryVT(),
9049                               LD->isVolatile(), LD->isNonTemporal(),
9050                               LD->isInvariant(), Align, LD->getAAInfo());
9051         if (NewLoad.getNode() != N)
9052           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9053       }
9054     }
9055   }
9056
9057   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9058                                                   : DAG.getSubtarget().useAA();
9059 #ifndef NDEBUG
9060   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9061       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9062     UseAA = false;
9063 #endif
9064   if (UseAA && LD->isUnindexed()) {
9065     // Walk up chain skipping non-aliasing memory nodes.
9066     SDValue BetterChain = FindBetterChain(N, Chain);
9067
9068     // If there is a better chain.
9069     if (Chain != BetterChain) {
9070       SDValue ReplLoad;
9071
9072       // Replace the chain to void dependency.
9073       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9074         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9075                                BetterChain, Ptr, LD->getMemOperand());
9076       } else {
9077         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9078                                   LD->getValueType(0),
9079                                   BetterChain, Ptr, LD->getMemoryVT(),
9080                                   LD->getMemOperand());
9081       }
9082
9083       // Create token factor to keep old chain connected.
9084       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9085                                   MVT::Other, Chain, ReplLoad.getValue(1));
9086
9087       // Make sure the new and old chains are cleaned up.
9088       AddToWorklist(Token.getNode());
9089
9090       // Replace uses with load result and token factor. Don't add users
9091       // to work list.
9092       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9093     }
9094   }
9095
9096   // Try transforming N to an indexed load.
9097   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9098     return SDValue(N, 0);
9099
9100   // Try to slice up N to more direct loads if the slices are mapped to
9101   // different register banks or pairing can take place.
9102   if (SliceUpLoad(N))
9103     return SDValue(N, 0);
9104
9105   return SDValue();
9106 }
9107
9108 namespace {
9109 /// \brief Helper structure used to slice a load in smaller loads.
9110 /// Basically a slice is obtained from the following sequence:
9111 /// Origin = load Ty1, Base
9112 /// Shift = srl Ty1 Origin, CstTy Amount
9113 /// Inst = trunc Shift to Ty2
9114 ///
9115 /// Then, it will be rewriten into:
9116 /// Slice = load SliceTy, Base + SliceOffset
9117 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9118 ///
9119 /// SliceTy is deduced from the number of bits that are actually used to
9120 /// build Inst.
9121 struct LoadedSlice {
9122   /// \brief Helper structure used to compute the cost of a slice.
9123   struct Cost {
9124     /// Are we optimizing for code size.
9125     bool ForCodeSize;
9126     /// Various cost.
9127     unsigned Loads;
9128     unsigned Truncates;
9129     unsigned CrossRegisterBanksCopies;
9130     unsigned ZExts;
9131     unsigned Shift;
9132
9133     Cost(bool ForCodeSize = false)
9134         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9135           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9136
9137     /// \brief Get the cost of one isolated slice.
9138     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9139         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9140           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9141       EVT TruncType = LS.Inst->getValueType(0);
9142       EVT LoadedType = LS.getLoadedType();
9143       if (TruncType != LoadedType &&
9144           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9145         ZExts = 1;
9146     }
9147
9148     /// \brief Account for slicing gain in the current cost.
9149     /// Slicing provide a few gains like removing a shift or a
9150     /// truncate. This method allows to grow the cost of the original
9151     /// load with the gain from this slice.
9152     void addSliceGain(const LoadedSlice &LS) {
9153       // Each slice saves a truncate.
9154       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9155       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9156                               LS.Inst->getOperand(0).getValueType()))
9157         ++Truncates;
9158       // If there is a shift amount, this slice gets rid of it.
9159       if (LS.Shift)
9160         ++Shift;
9161       // If this slice can merge a cross register bank copy, account for it.
9162       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9163         ++CrossRegisterBanksCopies;
9164     }
9165
9166     Cost &operator+=(const Cost &RHS) {
9167       Loads += RHS.Loads;
9168       Truncates += RHS.Truncates;
9169       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9170       ZExts += RHS.ZExts;
9171       Shift += RHS.Shift;
9172       return *this;
9173     }
9174
9175     bool operator==(const Cost &RHS) const {
9176       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9177              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9178              ZExts == RHS.ZExts && Shift == RHS.Shift;
9179     }
9180
9181     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9182
9183     bool operator<(const Cost &RHS) const {
9184       // Assume cross register banks copies are as expensive as loads.
9185       // FIXME: Do we want some more target hooks?
9186       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9187       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9188       // Unless we are optimizing for code size, consider the
9189       // expensive operation first.
9190       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9191         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9192       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9193              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9194     }
9195
9196     bool operator>(const Cost &RHS) const { return RHS < *this; }
9197
9198     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9199
9200     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9201   };
9202   // The last instruction that represent the slice. This should be a
9203   // truncate instruction.
9204   SDNode *Inst;
9205   // The original load instruction.
9206   LoadSDNode *Origin;
9207   // The right shift amount in bits from the original load.
9208   unsigned Shift;
9209   // The DAG from which Origin came from.
9210   // This is used to get some contextual information about legal types, etc.
9211   SelectionDAG *DAG;
9212
9213   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9214               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9215       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9216
9217   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9218   /// \return Result is \p BitWidth and has used bits set to 1 and
9219   ///         not used bits set to 0.
9220   APInt getUsedBits() const {
9221     // Reproduce the trunc(lshr) sequence:
9222     // - Start from the truncated value.
9223     // - Zero extend to the desired bit width.
9224     // - Shift left.
9225     assert(Origin && "No original load to compare against.");
9226     unsigned BitWidth = Origin->getValueSizeInBits(0);
9227     assert(Inst && "This slice is not bound to an instruction");
9228     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9229            "Extracted slice is bigger than the whole type!");
9230     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9231     UsedBits.setAllBits();
9232     UsedBits = UsedBits.zext(BitWidth);
9233     UsedBits <<= Shift;
9234     return UsedBits;
9235   }
9236
9237   /// \brief Get the size of the slice to be loaded in bytes.
9238   unsigned getLoadedSize() const {
9239     unsigned SliceSize = getUsedBits().countPopulation();
9240     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9241     return SliceSize / 8;
9242   }
9243
9244   /// \brief Get the type that will be loaded for this slice.
9245   /// Note: This may not be the final type for the slice.
9246   EVT getLoadedType() const {
9247     assert(DAG && "Missing context");
9248     LLVMContext &Ctxt = *DAG->getContext();
9249     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9250   }
9251
9252   /// \brief Get the alignment of the load used for this slice.
9253   unsigned getAlignment() const {
9254     unsigned Alignment = Origin->getAlignment();
9255     unsigned Offset = getOffsetFromBase();
9256     if (Offset != 0)
9257       Alignment = MinAlign(Alignment, Alignment + Offset);
9258     return Alignment;
9259   }
9260
9261   /// \brief Check if this slice can be rewritten with legal operations.
9262   bool isLegal() const {
9263     // An invalid slice is not legal.
9264     if (!Origin || !Inst || !DAG)
9265       return false;
9266
9267     // Offsets are for indexed load only, we do not handle that.
9268     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9269       return false;
9270
9271     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9272
9273     // Check that the type is legal.
9274     EVT SliceType = getLoadedType();
9275     if (!TLI.isTypeLegal(SliceType))
9276       return false;
9277
9278     // Check that the load is legal for this type.
9279     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9280       return false;
9281
9282     // Check that the offset can be computed.
9283     // 1. Check its type.
9284     EVT PtrType = Origin->getBasePtr().getValueType();
9285     if (PtrType == MVT::Untyped || PtrType.isExtended())
9286       return false;
9287
9288     // 2. Check that it fits in the immediate.
9289     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9290       return false;
9291
9292     // 3. Check that the computation is legal.
9293     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9294       return false;
9295
9296     // Check that the zext is legal if it needs one.
9297     EVT TruncateType = Inst->getValueType(0);
9298     if (TruncateType != SliceType &&
9299         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9300       return false;
9301
9302     return true;
9303   }
9304
9305   /// \brief Get the offset in bytes of this slice in the original chunk of
9306   /// bits.
9307   /// \pre DAG != nullptr.
9308   uint64_t getOffsetFromBase() const {
9309     assert(DAG && "Missing context.");
9310     bool IsBigEndian =
9311         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9312     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9313     uint64_t Offset = Shift / 8;
9314     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9315     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9316            "The size of the original loaded type is not a multiple of a"
9317            " byte.");
9318     // If Offset is bigger than TySizeInBytes, it means we are loading all
9319     // zeros. This should have been optimized before in the process.
9320     assert(TySizeInBytes > Offset &&
9321            "Invalid shift amount for given loaded size");
9322     if (IsBigEndian)
9323       Offset = TySizeInBytes - Offset - getLoadedSize();
9324     return Offset;
9325   }
9326
9327   /// \brief Generate the sequence of instructions to load the slice
9328   /// represented by this object and redirect the uses of this slice to
9329   /// this new sequence of instructions.
9330   /// \pre this->Inst && this->Origin are valid Instructions and this
9331   /// object passed the legal check: LoadedSlice::isLegal returned true.
9332   /// \return The last instruction of the sequence used to load the slice.
9333   SDValue loadSlice() const {
9334     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9335     const SDValue &OldBaseAddr = Origin->getBasePtr();
9336     SDValue BaseAddr = OldBaseAddr;
9337     // Get the offset in that chunk of bytes w.r.t. the endianess.
9338     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9339     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9340     if (Offset) {
9341       // BaseAddr = BaseAddr + Offset.
9342       EVT ArithType = BaseAddr.getValueType();
9343       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9344                               DAG->getConstant(Offset, ArithType));
9345     }
9346
9347     // Create the type of the loaded slice according to its size.
9348     EVT SliceType = getLoadedType();
9349
9350     // Create the load for the slice.
9351     SDValue LastInst = DAG->getLoad(
9352         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9353         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9354         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9355     // If the final type is not the same as the loaded type, this means that
9356     // we have to pad with zero. Create a zero extend for that.
9357     EVT FinalType = Inst->getValueType(0);
9358     if (SliceType != FinalType)
9359       LastInst =
9360           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9361     return LastInst;
9362   }
9363
9364   /// \brief Check if this slice can be merged with an expensive cross register
9365   /// bank copy. E.g.,
9366   /// i = load i32
9367   /// f = bitcast i32 i to float
9368   bool canMergeExpensiveCrossRegisterBankCopy() const {
9369     if (!Inst || !Inst->hasOneUse())
9370       return false;
9371     SDNode *Use = *Inst->use_begin();
9372     if (Use->getOpcode() != ISD::BITCAST)
9373       return false;
9374     assert(DAG && "Missing context");
9375     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9376     EVT ResVT = Use->getValueType(0);
9377     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9378     const TargetRegisterClass *ArgRC =
9379         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9380     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9381       return false;
9382
9383     // At this point, we know that we perform a cross-register-bank copy.
9384     // Check if it is expensive.
9385     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9386     // Assume bitcasts are cheap, unless both register classes do not
9387     // explicitly share a common sub class.
9388     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9389       return false;
9390
9391     // Check if it will be merged with the load.
9392     // 1. Check the alignment constraint.
9393     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9394         ResVT.getTypeForEVT(*DAG->getContext()));
9395
9396     if (RequiredAlignment > getAlignment())
9397       return false;
9398
9399     // 2. Check that the load is a legal operation for that type.
9400     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9401       return false;
9402
9403     // 3. Check that we do not have a zext in the way.
9404     if (Inst->getValueType(0) != getLoadedType())
9405       return false;
9406
9407     return true;
9408   }
9409 };
9410 }
9411
9412 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9413 /// \p UsedBits looks like 0..0 1..1 0..0.
9414 static bool areUsedBitsDense(const APInt &UsedBits) {
9415   // If all the bits are one, this is dense!
9416   if (UsedBits.isAllOnesValue())
9417     return true;
9418
9419   // Get rid of the unused bits on the right.
9420   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9421   // Get rid of the unused bits on the left.
9422   if (NarrowedUsedBits.countLeadingZeros())
9423     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9424   // Check that the chunk of bits is completely used.
9425   return NarrowedUsedBits.isAllOnesValue();
9426 }
9427
9428 /// \brief Check whether or not \p First and \p Second are next to each other
9429 /// in memory. This means that there is no hole between the bits loaded
9430 /// by \p First and the bits loaded by \p Second.
9431 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9432                                      const LoadedSlice &Second) {
9433   assert(First.Origin == Second.Origin && First.Origin &&
9434          "Unable to match different memory origins.");
9435   APInt UsedBits = First.getUsedBits();
9436   assert((UsedBits & Second.getUsedBits()) == 0 &&
9437          "Slices are not supposed to overlap.");
9438   UsedBits |= Second.getUsedBits();
9439   return areUsedBitsDense(UsedBits);
9440 }
9441
9442 /// \brief Adjust the \p GlobalLSCost according to the target
9443 /// paring capabilities and the layout of the slices.
9444 /// \pre \p GlobalLSCost should account for at least as many loads as
9445 /// there is in the slices in \p LoadedSlices.
9446 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9447                                  LoadedSlice::Cost &GlobalLSCost) {
9448   unsigned NumberOfSlices = LoadedSlices.size();
9449   // If there is less than 2 elements, no pairing is possible.
9450   if (NumberOfSlices < 2)
9451     return;
9452
9453   // Sort the slices so that elements that are likely to be next to each
9454   // other in memory are next to each other in the list.
9455   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9456             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9457     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9458     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9459   });
9460   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9461   // First (resp. Second) is the first (resp. Second) potentially candidate
9462   // to be placed in a paired load.
9463   const LoadedSlice *First = nullptr;
9464   const LoadedSlice *Second = nullptr;
9465   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9466                 // Set the beginning of the pair.
9467                                                            First = Second) {
9468
9469     Second = &LoadedSlices[CurrSlice];
9470
9471     // If First is NULL, it means we start a new pair.
9472     // Get to the next slice.
9473     if (!First)
9474       continue;
9475
9476     EVT LoadedType = First->getLoadedType();
9477
9478     // If the types of the slices are different, we cannot pair them.
9479     if (LoadedType != Second->getLoadedType())
9480       continue;
9481
9482     // Check if the target supplies paired loads for this type.
9483     unsigned RequiredAlignment = 0;
9484     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9485       // move to the next pair, this type is hopeless.
9486       Second = nullptr;
9487       continue;
9488     }
9489     // Check if we meet the alignment requirement.
9490     if (RequiredAlignment > First->getAlignment())
9491       continue;
9492
9493     // Check that both loads are next to each other in memory.
9494     if (!areSlicesNextToEachOther(*First, *Second))
9495       continue;
9496
9497     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9498     --GlobalLSCost.Loads;
9499     // Move to the next pair.
9500     Second = nullptr;
9501   }
9502 }
9503
9504 /// \brief Check the profitability of all involved LoadedSlice.
9505 /// Currently, it is considered profitable if there is exactly two
9506 /// involved slices (1) which are (2) next to each other in memory, and
9507 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9508 ///
9509 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9510 /// the elements themselves.
9511 ///
9512 /// FIXME: When the cost model will be mature enough, we can relax
9513 /// constraints (1) and (2).
9514 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9515                                 const APInt &UsedBits, bool ForCodeSize) {
9516   unsigned NumberOfSlices = LoadedSlices.size();
9517   if (StressLoadSlicing)
9518     return NumberOfSlices > 1;
9519
9520   // Check (1).
9521   if (NumberOfSlices != 2)
9522     return false;
9523
9524   // Check (2).
9525   if (!areUsedBitsDense(UsedBits))
9526     return false;
9527
9528   // Check (3).
9529   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9530   // The original code has one big load.
9531   OrigCost.Loads = 1;
9532   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9533     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9534     // Accumulate the cost of all the slices.
9535     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9536     GlobalSlicingCost += SliceCost;
9537
9538     // Account as cost in the original configuration the gain obtained
9539     // with the current slices.
9540     OrigCost.addSliceGain(LS);
9541   }
9542
9543   // If the target supports paired load, adjust the cost accordingly.
9544   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9545   return OrigCost > GlobalSlicingCost;
9546 }
9547
9548 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9549 /// operations, split it in the various pieces being extracted.
9550 ///
9551 /// This sort of thing is introduced by SROA.
9552 /// This slicing takes care not to insert overlapping loads.
9553 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9554 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9555   if (Level < AfterLegalizeDAG)
9556     return false;
9557
9558   LoadSDNode *LD = cast<LoadSDNode>(N);
9559   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9560       !LD->getValueType(0).isInteger())
9561     return false;
9562
9563   // Keep track of already used bits to detect overlapping values.
9564   // In that case, we will just abort the transformation.
9565   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9566
9567   SmallVector<LoadedSlice, 4> LoadedSlices;
9568
9569   // Check if this load is used as several smaller chunks of bits.
9570   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9571   // of computation for each trunc.
9572   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9573        UI != UIEnd; ++UI) {
9574     // Skip the uses of the chain.
9575     if (UI.getUse().getResNo() != 0)
9576       continue;
9577
9578     SDNode *User = *UI;
9579     unsigned Shift = 0;
9580
9581     // Check if this is a trunc(lshr).
9582     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9583         isa<ConstantSDNode>(User->getOperand(1))) {
9584       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9585       User = *User->use_begin();
9586     }
9587
9588     // At this point, User is a Truncate, iff we encountered, trunc or
9589     // trunc(lshr).
9590     if (User->getOpcode() != ISD::TRUNCATE)
9591       return false;
9592
9593     // The width of the type must be a power of 2 and greater than 8-bits.
9594     // Otherwise the load cannot be represented in LLVM IR.
9595     // Moreover, if we shifted with a non-8-bits multiple, the slice
9596     // will be across several bytes. We do not support that.
9597     unsigned Width = User->getValueSizeInBits(0);
9598     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9599       return 0;
9600
9601     // Build the slice for this chain of computations.
9602     LoadedSlice LS(User, LD, Shift, &DAG);
9603     APInt CurrentUsedBits = LS.getUsedBits();
9604
9605     // Check if this slice overlaps with another.
9606     if ((CurrentUsedBits & UsedBits) != 0)
9607       return false;
9608     // Update the bits used globally.
9609     UsedBits |= CurrentUsedBits;
9610
9611     // Check if the new slice would be legal.
9612     if (!LS.isLegal())
9613       return false;
9614
9615     // Record the slice.
9616     LoadedSlices.push_back(LS);
9617   }
9618
9619   // Abort slicing if it does not seem to be profitable.
9620   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9621     return false;
9622
9623   ++SlicedLoads;
9624
9625   // Rewrite each chain to use an independent load.
9626   // By construction, each chain can be represented by a unique load.
9627
9628   // Prepare the argument for the new token factor for all the slices.
9629   SmallVector<SDValue, 8> ArgChains;
9630   for (SmallVectorImpl<LoadedSlice>::const_iterator
9631            LSIt = LoadedSlices.begin(),
9632            LSItEnd = LoadedSlices.end();
9633        LSIt != LSItEnd; ++LSIt) {
9634     SDValue SliceInst = LSIt->loadSlice();
9635     CombineTo(LSIt->Inst, SliceInst, true);
9636     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9637       SliceInst = SliceInst.getOperand(0);
9638     assert(SliceInst->getOpcode() == ISD::LOAD &&
9639            "It takes more than a zext to get to the loaded slice!!");
9640     ArgChains.push_back(SliceInst.getValue(1));
9641   }
9642
9643   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9644                               ArgChains);
9645   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9646   return true;
9647 }
9648
9649 /// Check to see if V is (and load (ptr), imm), where the load is having
9650 /// specific bytes cleared out.  If so, return the byte size being masked out
9651 /// and the shift amount.
9652 static std::pair<unsigned, unsigned>
9653 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9654   std::pair<unsigned, unsigned> Result(0, 0);
9655
9656   // Check for the structure we're looking for.
9657   if (V->getOpcode() != ISD::AND ||
9658       !isa<ConstantSDNode>(V->getOperand(1)) ||
9659       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9660     return Result;
9661
9662   // Check the chain and pointer.
9663   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9664   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9665
9666   // The store should be chained directly to the load or be an operand of a
9667   // tokenfactor.
9668   if (LD == Chain.getNode())
9669     ; // ok.
9670   else if (Chain->getOpcode() != ISD::TokenFactor)
9671     return Result; // Fail.
9672   else {
9673     bool isOk = false;
9674     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9675       if (Chain->getOperand(i).getNode() == LD) {
9676         isOk = true;
9677         break;
9678       }
9679     if (!isOk) return Result;
9680   }
9681
9682   // This only handles simple types.
9683   if (V.getValueType() != MVT::i16 &&
9684       V.getValueType() != MVT::i32 &&
9685       V.getValueType() != MVT::i64)
9686     return Result;
9687
9688   // Check the constant mask.  Invert it so that the bits being masked out are
9689   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9690   // follow the sign bit for uniformity.
9691   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9692   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9693   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9694   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9695   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9696   if (NotMaskLZ == 64) return Result;  // All zero mask.
9697
9698   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9699   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9700     return Result;
9701
9702   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9703   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9704     NotMaskLZ -= 64-V.getValueSizeInBits();
9705
9706   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9707   switch (MaskedBytes) {
9708   case 1:
9709   case 2:
9710   case 4: break;
9711   default: return Result; // All one mask, or 5-byte mask.
9712   }
9713
9714   // Verify that the first bit starts at a multiple of mask so that the access
9715   // is aligned the same as the access width.
9716   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9717
9718   Result.first = MaskedBytes;
9719   Result.second = NotMaskTZ/8;
9720   return Result;
9721 }
9722
9723
9724 /// Check to see if IVal is something that provides a value as specified by
9725 /// MaskInfo. If so, replace the specified store with a narrower store of
9726 /// truncated IVal.
9727 static SDNode *
9728 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9729                                 SDValue IVal, StoreSDNode *St,
9730                                 DAGCombiner *DC) {
9731   unsigned NumBytes = MaskInfo.first;
9732   unsigned ByteShift = MaskInfo.second;
9733   SelectionDAG &DAG = DC->getDAG();
9734
9735   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9736   // that uses this.  If not, this is not a replacement.
9737   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9738                                   ByteShift*8, (ByteShift+NumBytes)*8);
9739   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9740
9741   // Check that it is legal on the target to do this.  It is legal if the new
9742   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9743   // legalization.
9744   MVT VT = MVT::getIntegerVT(NumBytes*8);
9745   if (!DC->isTypeLegal(VT))
9746     return nullptr;
9747
9748   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9749   // shifted by ByteShift and truncated down to NumBytes.
9750   if (ByteShift)
9751     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9752                        DAG.getConstant(ByteShift*8,
9753                                     DC->getShiftAmountTy(IVal.getValueType())));
9754
9755   // Figure out the offset for the store and the alignment of the access.
9756   unsigned StOffset;
9757   unsigned NewAlign = St->getAlignment();
9758
9759   if (DAG.getTargetLoweringInfo().isLittleEndian())
9760     StOffset = ByteShift;
9761   else
9762     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9763
9764   SDValue Ptr = St->getBasePtr();
9765   if (StOffset) {
9766     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9767                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9768     NewAlign = MinAlign(NewAlign, StOffset);
9769   }
9770
9771   // Truncate down to the new size.
9772   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9773
9774   ++OpsNarrowed;
9775   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9776                       St->getPointerInfo().getWithOffset(StOffset),
9777                       false, false, NewAlign).getNode();
9778 }
9779
9780
9781 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9782 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9783 /// narrowing the load and store if it would end up being a win for performance
9784 /// or code size.
9785 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9786   StoreSDNode *ST  = cast<StoreSDNode>(N);
9787   if (ST->isVolatile())
9788     return SDValue();
9789
9790   SDValue Chain = ST->getChain();
9791   SDValue Value = ST->getValue();
9792   SDValue Ptr   = ST->getBasePtr();
9793   EVT VT = Value.getValueType();
9794
9795   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9796     return SDValue();
9797
9798   unsigned Opc = Value.getOpcode();
9799
9800   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9801   // is a byte mask indicating a consecutive number of bytes, check to see if
9802   // Y is known to provide just those bytes.  If so, we try to replace the
9803   // load + replace + store sequence with a single (narrower) store, which makes
9804   // the load dead.
9805   if (Opc == ISD::OR) {
9806     std::pair<unsigned, unsigned> MaskedLoad;
9807     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9808     if (MaskedLoad.first)
9809       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9810                                                   Value.getOperand(1), ST,this))
9811         return SDValue(NewST, 0);
9812
9813     // Or is commutative, so try swapping X and Y.
9814     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9815     if (MaskedLoad.first)
9816       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9817                                                   Value.getOperand(0), ST,this))
9818         return SDValue(NewST, 0);
9819   }
9820
9821   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9822       Value.getOperand(1).getOpcode() != ISD::Constant)
9823     return SDValue();
9824
9825   SDValue N0 = Value.getOperand(0);
9826   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9827       Chain == SDValue(N0.getNode(), 1)) {
9828     LoadSDNode *LD = cast<LoadSDNode>(N0);
9829     if (LD->getBasePtr() != Ptr ||
9830         LD->getPointerInfo().getAddrSpace() !=
9831         ST->getPointerInfo().getAddrSpace())
9832       return SDValue();
9833
9834     // Find the type to narrow it the load / op / store to.
9835     SDValue N1 = Value.getOperand(1);
9836     unsigned BitWidth = N1.getValueSizeInBits();
9837     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9838     if (Opc == ISD::AND)
9839       Imm ^= APInt::getAllOnesValue(BitWidth);
9840     if (Imm == 0 || Imm.isAllOnesValue())
9841       return SDValue();
9842     unsigned ShAmt = Imm.countTrailingZeros();
9843     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9844     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9845     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9846     // The narrowing should be profitable, the load/store operation should be
9847     // legal (or custom) and the store size should be equal to the NewVT width.
9848     while (NewBW < BitWidth &&
9849            (NewVT.getStoreSizeInBits() != NewBW ||
9850             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9851             !TLI.isNarrowingProfitable(VT, NewVT))) {
9852       NewBW = NextPowerOf2(NewBW);
9853       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9854     }
9855     if (NewBW >= BitWidth)
9856       return SDValue();
9857
9858     // If the lsb changed does not start at the type bitwidth boundary,
9859     // start at the previous one.
9860     if (ShAmt % NewBW)
9861       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9862     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9863                                    std::min(BitWidth, ShAmt + NewBW));
9864     if ((Imm & Mask) == Imm) {
9865       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9866       if (Opc == ISD::AND)
9867         NewImm ^= APInt::getAllOnesValue(NewBW);
9868       uint64_t PtrOff = ShAmt / 8;
9869       // For big endian targets, we need to adjust the offset to the pointer to
9870       // load the correct bytes.
9871       if (TLI.isBigEndian())
9872         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9873
9874       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9875       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9876       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9877         return SDValue();
9878
9879       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9880                                    Ptr.getValueType(), Ptr,
9881                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9882       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9883                                   LD->getChain(), NewPtr,
9884                                   LD->getPointerInfo().getWithOffset(PtrOff),
9885                                   LD->isVolatile(), LD->isNonTemporal(),
9886                                   LD->isInvariant(), NewAlign,
9887                                   LD->getAAInfo());
9888       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9889                                    DAG.getConstant(NewImm, NewVT));
9890       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9891                                    NewVal, NewPtr,
9892                                    ST->getPointerInfo().getWithOffset(PtrOff),
9893                                    false, false, NewAlign);
9894
9895       AddToWorklist(NewPtr.getNode());
9896       AddToWorklist(NewLD.getNode());
9897       AddToWorklist(NewVal.getNode());
9898       WorklistRemover DeadNodes(*this);
9899       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9900       ++OpsNarrowed;
9901       return NewST;
9902     }
9903   }
9904
9905   return SDValue();
9906 }
9907
9908 /// For a given floating point load / store pair, if the load value isn't used
9909 /// by any other operations, then consider transforming the pair to integer
9910 /// load / store operations if the target deems the transformation profitable.
9911 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9912   StoreSDNode *ST  = cast<StoreSDNode>(N);
9913   SDValue Chain = ST->getChain();
9914   SDValue Value = ST->getValue();
9915   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9916       Value.hasOneUse() &&
9917       Chain == SDValue(Value.getNode(), 1)) {
9918     LoadSDNode *LD = cast<LoadSDNode>(Value);
9919     EVT VT = LD->getMemoryVT();
9920     if (!VT.isFloatingPoint() ||
9921         VT != ST->getMemoryVT() ||
9922         LD->isNonTemporal() ||
9923         ST->isNonTemporal() ||
9924         LD->getPointerInfo().getAddrSpace() != 0 ||
9925         ST->getPointerInfo().getAddrSpace() != 0)
9926       return SDValue();
9927
9928     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9929     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9930         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9931         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9932         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9933       return SDValue();
9934
9935     unsigned LDAlign = LD->getAlignment();
9936     unsigned STAlign = ST->getAlignment();
9937     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9938     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9939     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9940       return SDValue();
9941
9942     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9943                                 LD->getChain(), LD->getBasePtr(),
9944                                 LD->getPointerInfo(),
9945                                 false, false, false, LDAlign);
9946
9947     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9948                                  NewLD, ST->getBasePtr(),
9949                                  ST->getPointerInfo(),
9950                                  false, false, STAlign);
9951
9952     AddToWorklist(NewLD.getNode());
9953     AddToWorklist(NewST.getNode());
9954     WorklistRemover DeadNodes(*this);
9955     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9956     ++LdStFP2Int;
9957     return NewST;
9958   }
9959
9960   return SDValue();
9961 }
9962
9963 namespace {
9964 /// Helper struct to parse and store a memory address as base + index + offset.
9965 /// We ignore sign extensions when it is safe to do so.
9966 /// The following two expressions are not equivalent. To differentiate we need
9967 /// to store whether there was a sign extension involved in the index
9968 /// computation.
9969 ///  (load (i64 add (i64 copyfromreg %c)
9970 ///                 (i64 signextend (add (i8 load %index)
9971 ///                                      (i8 1))))
9972 /// vs
9973 ///
9974 /// (load (i64 add (i64 copyfromreg %c)
9975 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9976 ///                                         (i32 1)))))
9977 struct BaseIndexOffset {
9978   SDValue Base;
9979   SDValue Index;
9980   int64_t Offset;
9981   bool IsIndexSignExt;
9982
9983   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9984
9985   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9986                   bool IsIndexSignExt) :
9987     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9988
9989   bool equalBaseIndex(const BaseIndexOffset &Other) {
9990     return Other.Base == Base && Other.Index == Index &&
9991       Other.IsIndexSignExt == IsIndexSignExt;
9992   }
9993
9994   /// Parses tree in Ptr for base, index, offset addresses.
9995   static BaseIndexOffset match(SDValue Ptr) {
9996     bool IsIndexSignExt = false;
9997
9998     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9999     // instruction, then it could be just the BASE or everything else we don't
10000     // know how to handle. Just use Ptr as BASE and give up.
10001     if (Ptr->getOpcode() != ISD::ADD)
10002       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10003
10004     // We know that we have at least an ADD instruction. Try to pattern match
10005     // the simple case of BASE + OFFSET.
10006     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10007       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10008       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10009                               IsIndexSignExt);
10010     }
10011
10012     // Inside a loop the current BASE pointer is calculated using an ADD and a
10013     // MUL instruction. In this case Ptr is the actual BASE pointer.
10014     // (i64 add (i64 %array_ptr)
10015     //          (i64 mul (i64 %induction_var)
10016     //                   (i64 %element_size)))
10017     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10018       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10019
10020     // Look at Base + Index + Offset cases.
10021     SDValue Base = Ptr->getOperand(0);
10022     SDValue IndexOffset = Ptr->getOperand(1);
10023
10024     // Skip signextends.
10025     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10026       IndexOffset = IndexOffset->getOperand(0);
10027       IsIndexSignExt = true;
10028     }
10029
10030     // Either the case of Base + Index (no offset) or something else.
10031     if (IndexOffset->getOpcode() != ISD::ADD)
10032       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10033
10034     // Now we have the case of Base + Index + offset.
10035     SDValue Index = IndexOffset->getOperand(0);
10036     SDValue Offset = IndexOffset->getOperand(1);
10037
10038     if (!isa<ConstantSDNode>(Offset))
10039       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10040
10041     // Ignore signextends.
10042     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10043       Index = Index->getOperand(0);
10044       IsIndexSignExt = true;
10045     } else IsIndexSignExt = false;
10046
10047     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10048     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10049   }
10050 };
10051 } // namespace
10052
10053 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10054                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10055                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10056   // Make sure we have something to merge.
10057   if (NumElem < 2)
10058     return false;
10059
10060   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10061   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10062   unsigned EarliestNodeUsed = 0;
10063
10064   for (unsigned i=0; i < NumElem; ++i) {
10065     // Find a chain for the new wide-store operand. Notice that some
10066     // of the store nodes that we found may not be selected for inclusion
10067     // in the wide store. The chain we use needs to be the chain of the
10068     // earliest store node which is *used* and replaced by the wide store.
10069     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10070       EarliestNodeUsed = i;
10071   }
10072
10073   // The earliest Node in the DAG.
10074   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10075   SDLoc DL(StoreNodes[0].MemNode);
10076
10077   SDValue StoredVal;
10078   if (UseVector) {
10079     // Find a legal type for the vector store.
10080     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10081     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10082     if (IsConstantSrc) {
10083       // A vector store with a constant source implies that the constant is
10084       // zero; we only handle merging stores of constant zeros because the zero
10085       // can be materialized without a load.
10086       // It may be beneficial to loosen this restriction to allow non-zero
10087       // store merging.
10088       StoredVal = DAG.getConstant(0, Ty);
10089     } else {
10090       SmallVector<SDValue, 8> Ops;
10091       for (unsigned i = 0; i < NumElem ; ++i) {
10092         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10093         SDValue Val = St->getValue();
10094         // All of the operands of a BUILD_VECTOR must have the same type.
10095         if (Val.getValueType() != MemVT)
10096           return false;
10097         Ops.push_back(Val);
10098       }
10099
10100       // Build the extracted vector elements back into a vector.
10101       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10102     }
10103   } else {
10104     // We should always use a vector store when merging extracted vector
10105     // elements, so this path implies a store of constants.
10106     assert(IsConstantSrc && "Merged vector elements should use vector store");
10107
10108     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10109     APInt StoreInt(StoreBW, 0);
10110
10111     // Construct a single integer constant which is made of the smaller
10112     // constant inputs.
10113     bool IsLE = TLI.isLittleEndian();
10114     for (unsigned i = 0; i < NumElem ; ++i) {
10115       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10116       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10117       SDValue Val = St->getValue();
10118       StoreInt <<= ElementSizeBytes*8;
10119       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10120         StoreInt |= C->getAPIntValue().zext(StoreBW);
10121       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10122         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10123       } else {
10124         llvm_unreachable("Invalid constant element type");
10125       }
10126     }
10127
10128     // Create the new Load and Store operations.
10129     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10130     StoredVal = DAG.getConstant(StoreInt, StoreTy);
10131   }
10132
10133   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10134                                   FirstInChain->getBasePtr(),
10135                                   FirstInChain->getPointerInfo(),
10136                                   false, false,
10137                                   FirstInChain->getAlignment());
10138
10139   // Replace the first store with the new store
10140   CombineTo(EarliestOp, NewStore);
10141   // Erase all other stores.
10142   for (unsigned i = 0; i < NumElem ; ++i) {
10143     if (StoreNodes[i].MemNode == EarliestOp)
10144       continue;
10145     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10146     // ReplaceAllUsesWith will replace all uses that existed when it was
10147     // called, but graph optimizations may cause new ones to appear. For
10148     // example, the case in pr14333 looks like
10149     //
10150     //  St's chain -> St -> another store -> X
10151     //
10152     // And the only difference from St to the other store is the chain.
10153     // When we change it's chain to be St's chain they become identical,
10154     // get CSEed and the net result is that X is now a use of St.
10155     // Since we know that St is redundant, just iterate.
10156     while (!St->use_empty())
10157       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10158     deleteAndRecombine(St);
10159   }
10160
10161   return true;
10162 }
10163
10164 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10165   if (OptLevel == CodeGenOpt::None)
10166     return false;
10167
10168   EVT MemVT = St->getMemoryVT();
10169   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10170   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10171       Attribute::NoImplicitFloat);
10172
10173   // Don't merge vectors into wider inputs.
10174   if (MemVT.isVector() || !MemVT.isSimple())
10175     return false;
10176
10177   // Perform an early exit check. Do not bother looking at stored values that
10178   // are not constants, loads, or extracted vector elements.
10179   SDValue StoredVal = St->getValue();
10180   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10181   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10182                        isa<ConstantFPSDNode>(StoredVal);
10183   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10184
10185   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10186     return false;
10187
10188   // Only look at ends of store sequences.
10189   SDValue Chain = SDValue(St, 0);
10190   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10191     return false;
10192
10193   // This holds the base pointer, index, and the offset in bytes from the base
10194   // pointer.
10195   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10196
10197   // We must have a base and an offset.
10198   if (!BasePtr.Base.getNode())
10199     return false;
10200
10201   // Do not handle stores to undef base pointers.
10202   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10203     return false;
10204
10205   // Save the LoadSDNodes that we find in the chain.
10206   // We need to make sure that these nodes do not interfere with
10207   // any of the store nodes.
10208   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10209
10210   // Save the StoreSDNodes that we find in the chain.
10211   SmallVector<MemOpLink, 8> StoreNodes;
10212
10213   // Walk up the chain and look for nodes with offsets from the same
10214   // base pointer. Stop when reaching an instruction with a different kind
10215   // or instruction which has a different base pointer.
10216   unsigned Seq = 0;
10217   StoreSDNode *Index = St;
10218   while (Index) {
10219     // If the chain has more than one use, then we can't reorder the mem ops.
10220     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10221       break;
10222
10223     // Find the base pointer and offset for this memory node.
10224     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10225
10226     // Check that the base pointer is the same as the original one.
10227     if (!Ptr.equalBaseIndex(BasePtr))
10228       break;
10229
10230     // Check that the alignment is the same.
10231     if (Index->getAlignment() != St->getAlignment())
10232       break;
10233
10234     // The memory operands must not be volatile.
10235     if (Index->isVolatile() || Index->isIndexed())
10236       break;
10237
10238     // No truncation.
10239     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10240       if (St->isTruncatingStore())
10241         break;
10242
10243     // The stored memory type must be the same.
10244     if (Index->getMemoryVT() != MemVT)
10245       break;
10246
10247     // We do not allow unaligned stores because we want to prevent overriding
10248     // stores.
10249     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10250       break;
10251
10252     // We found a potential memory operand to merge.
10253     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10254
10255     // Find the next memory operand in the chain. If the next operand in the
10256     // chain is a store then move up and continue the scan with the next
10257     // memory operand. If the next operand is a load save it and use alias
10258     // information to check if it interferes with anything.
10259     SDNode *NextInChain = Index->getChain().getNode();
10260     while (1) {
10261       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10262         // We found a store node. Use it for the next iteration.
10263         Index = STn;
10264         break;
10265       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10266         if (Ldn->isVolatile()) {
10267           Index = nullptr;
10268           break;
10269         }
10270
10271         // Save the load node for later. Continue the scan.
10272         AliasLoadNodes.push_back(Ldn);
10273         NextInChain = Ldn->getChain().getNode();
10274         continue;
10275       } else {
10276         Index = nullptr;
10277         break;
10278       }
10279     }
10280   }
10281
10282   // Check if there is anything to merge.
10283   if (StoreNodes.size() < 2)
10284     return false;
10285
10286   // Sort the memory operands according to their distance from the base pointer.
10287   std::sort(StoreNodes.begin(), StoreNodes.end(),
10288             [](MemOpLink LHS, MemOpLink RHS) {
10289     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10290            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10291             LHS.SequenceNum > RHS.SequenceNum);
10292   });
10293
10294   // Scan the memory operations on the chain and find the first non-consecutive
10295   // store memory address.
10296   unsigned LastConsecutiveStore = 0;
10297   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10298   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10299
10300     // Check that the addresses are consecutive starting from the second
10301     // element in the list of stores.
10302     if (i > 0) {
10303       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10304       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10305         break;
10306     }
10307
10308     bool Alias = false;
10309     // Check if this store interferes with any of the loads that we found.
10310     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10311       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10312         Alias = true;
10313         break;
10314       }
10315     // We found a load that alias with this store. Stop the sequence.
10316     if (Alias)
10317       break;
10318
10319     // Mark this node as useful.
10320     LastConsecutiveStore = i;
10321   }
10322
10323   // The node with the lowest store address.
10324   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10325
10326   // Store the constants into memory as one consecutive store.
10327   if (IsConstantSrc) {
10328     unsigned LastLegalType = 0;
10329     unsigned LastLegalVectorType = 0;
10330     bool NonZero = false;
10331     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10332       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10333       SDValue StoredVal = St->getValue();
10334
10335       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10336         NonZero |= !C->isNullValue();
10337       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10338         NonZero |= !C->getConstantFPValue()->isNullValue();
10339       } else {
10340         // Non-constant.
10341         break;
10342       }
10343
10344       // Find a legal type for the constant store.
10345       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10346       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10347       if (TLI.isTypeLegal(StoreTy))
10348         LastLegalType = i+1;
10349       // Or check whether a truncstore is legal.
10350       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10351                TargetLowering::TypePromoteInteger) {
10352         EVT LegalizedStoredValueTy =
10353           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10354         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10355           LastLegalType = i+1;
10356       }
10357
10358       // Find a legal type for the vector store.
10359       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10360       if (TLI.isTypeLegal(Ty))
10361         LastLegalVectorType = i + 1;
10362     }
10363
10364     // We only use vectors if the constant is known to be zero and the
10365     // function is not marked with the noimplicitfloat attribute.
10366     if (NonZero || NoVectors)
10367       LastLegalVectorType = 0;
10368
10369     // Check if we found a legal integer type to store.
10370     if (LastLegalType == 0 && LastLegalVectorType == 0)
10371       return false;
10372
10373     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10374     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10375
10376     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10377                                            true, UseVector);
10378   }
10379
10380   // When extracting multiple vector elements, try to store them
10381   // in one vector store rather than a sequence of scalar stores.
10382   if (IsExtractVecEltSrc) {
10383     unsigned NumElem = 0;
10384     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10385       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10386       SDValue StoredVal = St->getValue();
10387       // This restriction could be loosened.
10388       // Bail out if any stored values are not elements extracted from a vector.
10389       // It should be possible to handle mixed sources, but load sources need
10390       // more careful handling (see the block of code below that handles
10391       // consecutive loads).
10392       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10393         return false;
10394
10395       // Find a legal type for the vector store.
10396       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10397       if (TLI.isTypeLegal(Ty))
10398         NumElem = i + 1;
10399     }
10400
10401     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10402                                            false, true);
10403   }
10404
10405   // Below we handle the case of multiple consecutive stores that
10406   // come from multiple consecutive loads. We merge them into a single
10407   // wide load and a single wide store.
10408
10409   // Look for load nodes which are used by the stored values.
10410   SmallVector<MemOpLink, 8> LoadNodes;
10411
10412   // Find acceptable loads. Loads need to have the same chain (token factor),
10413   // must not be zext, volatile, indexed, and they must be consecutive.
10414   BaseIndexOffset LdBasePtr;
10415   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10416     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10417     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10418     if (!Ld) break;
10419
10420     // Loads must only have one use.
10421     if (!Ld->hasNUsesOfValue(1, 0))
10422       break;
10423
10424     // Check that the alignment is the same as the stores.
10425     if (Ld->getAlignment() != St->getAlignment())
10426       break;
10427
10428     // The memory operands must not be volatile.
10429     if (Ld->isVolatile() || Ld->isIndexed())
10430       break;
10431
10432     // We do not accept ext loads.
10433     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10434       break;
10435
10436     // The stored memory type must be the same.
10437     if (Ld->getMemoryVT() != MemVT)
10438       break;
10439
10440     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10441     // If this is not the first ptr that we check.
10442     if (LdBasePtr.Base.getNode()) {
10443       // The base ptr must be the same.
10444       if (!LdPtr.equalBaseIndex(LdBasePtr))
10445         break;
10446     } else {
10447       // Check that all other base pointers are the same as this one.
10448       LdBasePtr = LdPtr;
10449     }
10450
10451     // We found a potential memory operand to merge.
10452     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10453   }
10454
10455   if (LoadNodes.size() < 2)
10456     return false;
10457
10458   // If we have load/store pair instructions and we only have two values,
10459   // don't bother.
10460   unsigned RequiredAlignment;
10461   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10462       St->getAlignment() >= RequiredAlignment)
10463     return false;
10464
10465   // Scan the memory operations on the chain and find the first non-consecutive
10466   // load memory address. These variables hold the index in the store node
10467   // array.
10468   unsigned LastConsecutiveLoad = 0;
10469   // This variable refers to the size and not index in the array.
10470   unsigned LastLegalVectorType = 0;
10471   unsigned LastLegalIntegerType = 0;
10472   StartAddress = LoadNodes[0].OffsetFromBase;
10473   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10474   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10475     // All loads much share the same chain.
10476     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10477       break;
10478
10479     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10480     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10481       break;
10482     LastConsecutiveLoad = i;
10483
10484     // Find a legal type for the vector store.
10485     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10486     if (TLI.isTypeLegal(StoreTy))
10487       LastLegalVectorType = i + 1;
10488
10489     // Find a legal type for the integer store.
10490     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10491     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10492     if (TLI.isTypeLegal(StoreTy))
10493       LastLegalIntegerType = i + 1;
10494     // Or check whether a truncstore and extload is legal.
10495     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10496              TargetLowering::TypePromoteInteger) {
10497       EVT LegalizedStoredValueTy =
10498         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10499       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10500           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10501           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10502           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10503         LastLegalIntegerType = i+1;
10504     }
10505   }
10506
10507   // Only use vector types if the vector type is larger than the integer type.
10508   // If they are the same, use integers.
10509   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10510   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10511
10512   // We add +1 here because the LastXXX variables refer to location while
10513   // the NumElem refers to array/index size.
10514   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10515   NumElem = std::min(LastLegalType, NumElem);
10516
10517   if (NumElem < 2)
10518     return false;
10519
10520   // The earliest Node in the DAG.
10521   unsigned EarliestNodeUsed = 0;
10522   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10523   for (unsigned i=1; i<NumElem; ++i) {
10524     // Find a chain for the new wide-store operand. Notice that some
10525     // of the store nodes that we found may not be selected for inclusion
10526     // in the wide store. The chain we use needs to be the chain of the
10527     // earliest store node which is *used* and replaced by the wide store.
10528     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10529       EarliestNodeUsed = i;
10530   }
10531
10532   // Find if it is better to use vectors or integers to load and store
10533   // to memory.
10534   EVT JointMemOpVT;
10535   if (UseVectorTy) {
10536     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10537   } else {
10538     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10539     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10540   }
10541
10542   SDLoc LoadDL(LoadNodes[0].MemNode);
10543   SDLoc StoreDL(StoreNodes[0].MemNode);
10544
10545   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10546   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10547                                 FirstLoad->getChain(),
10548                                 FirstLoad->getBasePtr(),
10549                                 FirstLoad->getPointerInfo(),
10550                                 false, false, false,
10551                                 FirstLoad->getAlignment());
10552
10553   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10554                                   FirstInChain->getBasePtr(),
10555                                   FirstInChain->getPointerInfo(), false, false,
10556                                   FirstInChain->getAlignment());
10557
10558   // Replace one of the loads with the new load.
10559   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10560   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10561                                 SDValue(NewLoad.getNode(), 1));
10562
10563   // Remove the rest of the load chains.
10564   for (unsigned i = 1; i < NumElem ; ++i) {
10565     // Replace all chain users of the old load nodes with the chain of the new
10566     // load node.
10567     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10568     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10569   }
10570
10571   // Replace the first store with the new store.
10572   CombineTo(EarliestOp, NewStore);
10573   // Erase all other stores.
10574   for (unsigned i = 0; i < NumElem ; ++i) {
10575     // Remove all Store nodes.
10576     if (StoreNodes[i].MemNode == EarliestOp)
10577       continue;
10578     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10579     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10580     deleteAndRecombine(St);
10581   }
10582
10583   return true;
10584 }
10585
10586 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10587   StoreSDNode *ST  = cast<StoreSDNode>(N);
10588   SDValue Chain = ST->getChain();
10589   SDValue Value = ST->getValue();
10590   SDValue Ptr   = ST->getBasePtr();
10591
10592   // If this is a store of a bit convert, store the input value if the
10593   // resultant store does not need a higher alignment than the original.
10594   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10595       ST->isUnindexed()) {
10596     unsigned OrigAlign = ST->getAlignment();
10597     EVT SVT = Value.getOperand(0).getValueType();
10598     unsigned Align = TLI.getDataLayout()->
10599       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10600     if (Align <= OrigAlign &&
10601         ((!LegalOperations && !ST->isVolatile()) ||
10602          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10603       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10604                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10605                           ST->isNonTemporal(), OrigAlign,
10606                           ST->getAAInfo());
10607   }
10608
10609   // Turn 'store undef, Ptr' -> nothing.
10610   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10611     return Chain;
10612
10613   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10614   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10615     // NOTE: If the original store is volatile, this transform must not increase
10616     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10617     // processor operation but an i64 (which is not legal) requires two.  So the
10618     // transform should not be done in this case.
10619     if (Value.getOpcode() != ISD::TargetConstantFP) {
10620       SDValue Tmp;
10621       switch (CFP->getSimpleValueType(0).SimpleTy) {
10622       default: llvm_unreachable("Unknown FP type");
10623       case MVT::f16:    // We don't do this for these yet.
10624       case MVT::f80:
10625       case MVT::f128:
10626       case MVT::ppcf128:
10627         break;
10628       case MVT::f32:
10629         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10630             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10631           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10632                               bitcastToAPInt().getZExtValue(), MVT::i32);
10633           return DAG.getStore(Chain, SDLoc(N), Tmp,
10634                               Ptr, ST->getMemOperand());
10635         }
10636         break;
10637       case MVT::f64:
10638         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10639              !ST->isVolatile()) ||
10640             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10641           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10642                                 getZExtValue(), MVT::i64);
10643           return DAG.getStore(Chain, SDLoc(N), Tmp,
10644                               Ptr, ST->getMemOperand());
10645         }
10646
10647         if (!ST->isVolatile() &&
10648             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10649           // Many FP stores are not made apparent until after legalize, e.g. for
10650           // argument passing.  Since this is so common, custom legalize the
10651           // 64-bit integer store into two 32-bit stores.
10652           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10653           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10654           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10655           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10656
10657           unsigned Alignment = ST->getAlignment();
10658           bool isVolatile = ST->isVolatile();
10659           bool isNonTemporal = ST->isNonTemporal();
10660           AAMDNodes AAInfo = ST->getAAInfo();
10661
10662           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10663                                      Ptr, ST->getPointerInfo(),
10664                                      isVolatile, isNonTemporal,
10665                                      ST->getAlignment(), AAInfo);
10666           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10667                             DAG.getConstant(4, Ptr.getValueType()));
10668           Alignment = MinAlign(Alignment, 4U);
10669           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10670                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10671                                      isVolatile, isNonTemporal,
10672                                      Alignment, AAInfo);
10673           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10674                              St0, St1);
10675         }
10676
10677         break;
10678       }
10679     }
10680   }
10681
10682   // Try to infer better alignment information than the store already has.
10683   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10684     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10685       if (Align > ST->getAlignment()) {
10686         SDValue NewStore =
10687                DAG.getTruncStore(Chain, SDLoc(N), Value,
10688                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10689                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10690                                  ST->getAAInfo());
10691         if (NewStore.getNode() != N)
10692           return CombineTo(ST, NewStore, true);
10693       }
10694     }
10695   }
10696
10697   // Try transforming a pair floating point load / store ops to integer
10698   // load / store ops.
10699   SDValue NewST = TransformFPLoadStorePair(N);
10700   if (NewST.getNode())
10701     return NewST;
10702
10703   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10704                                                   : DAG.getSubtarget().useAA();
10705 #ifndef NDEBUG
10706   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10707       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10708     UseAA = false;
10709 #endif
10710   if (UseAA && ST->isUnindexed()) {
10711     // Walk up chain skipping non-aliasing memory nodes.
10712     SDValue BetterChain = FindBetterChain(N, Chain);
10713
10714     // If there is a better chain.
10715     if (Chain != BetterChain) {
10716       SDValue ReplStore;
10717
10718       // Replace the chain to avoid dependency.
10719       if (ST->isTruncatingStore()) {
10720         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10721                                       ST->getMemoryVT(), ST->getMemOperand());
10722       } else {
10723         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10724                                  ST->getMemOperand());
10725       }
10726
10727       // Create token to keep both nodes around.
10728       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10729                                   MVT::Other, Chain, ReplStore);
10730
10731       // Make sure the new and old chains are cleaned up.
10732       AddToWorklist(Token.getNode());
10733
10734       // Don't add users to work list.
10735       return CombineTo(N, Token, false);
10736     }
10737   }
10738
10739   // Try transforming N to an indexed store.
10740   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10741     return SDValue(N, 0);
10742
10743   // FIXME: is there such a thing as a truncating indexed store?
10744   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10745       Value.getValueType().isInteger()) {
10746     // See if we can simplify the input to this truncstore with knowledge that
10747     // only the low bits are being used.  For example:
10748     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10749     SDValue Shorter =
10750       GetDemandedBits(Value,
10751                       APInt::getLowBitsSet(
10752                         Value.getValueType().getScalarType().getSizeInBits(),
10753                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10754     AddToWorklist(Value.getNode());
10755     if (Shorter.getNode())
10756       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10757                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10758
10759     // Otherwise, see if we can simplify the operation with
10760     // SimplifyDemandedBits, which only works if the value has a single use.
10761     if (SimplifyDemandedBits(Value,
10762                         APInt::getLowBitsSet(
10763                           Value.getValueType().getScalarType().getSizeInBits(),
10764                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10765       return SDValue(N, 0);
10766   }
10767
10768   // If this is a load followed by a store to the same location, then the store
10769   // is dead/noop.
10770   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10771     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10772         ST->isUnindexed() && !ST->isVolatile() &&
10773         // There can't be any side effects between the load and store, such as
10774         // a call or store.
10775         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10776       // The store is dead, remove it.
10777       return Chain;
10778     }
10779   }
10780
10781   // If this is a store followed by a store with the same value to the same
10782   // location, then the store is dead/noop.
10783   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10784     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10785         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10786         ST1->isUnindexed() && !ST1->isVolatile()) {
10787       // The store is dead, remove it.
10788       return Chain;
10789     }
10790   }
10791
10792   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10793   // truncating store.  We can do this even if this is already a truncstore.
10794   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10795       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10796       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10797                             ST->getMemoryVT())) {
10798     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10799                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10800   }
10801
10802   // Only perform this optimization before the types are legal, because we
10803   // don't want to perform this optimization on every DAGCombine invocation.
10804   if (!LegalTypes) {
10805     bool EverChanged = false;
10806
10807     do {
10808       // There can be multiple store sequences on the same chain.
10809       // Keep trying to merge store sequences until we are unable to do so
10810       // or until we merge the last store on the chain.
10811       bool Changed = MergeConsecutiveStores(ST);
10812       EverChanged |= Changed;
10813       if (!Changed) break;
10814     } while (ST->getOpcode() != ISD::DELETED_NODE);
10815
10816     if (EverChanged)
10817       return SDValue(N, 0);
10818   }
10819
10820   return ReduceLoadOpStoreWidth(N);
10821 }
10822
10823 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10824   SDValue InVec = N->getOperand(0);
10825   SDValue InVal = N->getOperand(1);
10826   SDValue EltNo = N->getOperand(2);
10827   SDLoc dl(N);
10828
10829   // If the inserted element is an UNDEF, just use the input vector.
10830   if (InVal.getOpcode() == ISD::UNDEF)
10831     return InVec;
10832
10833   EVT VT = InVec.getValueType();
10834
10835   // If we can't generate a legal BUILD_VECTOR, exit
10836   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10837     return SDValue();
10838
10839   // Check that we know which element is being inserted
10840   if (!isa<ConstantSDNode>(EltNo))
10841     return SDValue();
10842   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10843
10844   // Canonicalize insert_vector_elt dag nodes.
10845   // Example:
10846   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10847   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10848   //
10849   // Do this only if the child insert_vector node has one use; also
10850   // do this only if indices are both constants and Idx1 < Idx0.
10851   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10852       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10853     unsigned OtherElt =
10854       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10855     if (Elt < OtherElt) {
10856       // Swap nodes.
10857       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10858                                   InVec.getOperand(0), InVal, EltNo);
10859       AddToWorklist(NewOp.getNode());
10860       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10861                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10862     }
10863   }
10864
10865   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10866   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10867   // vector elements.
10868   SmallVector<SDValue, 8> Ops;
10869   // Do not combine these two vectors if the output vector will not replace
10870   // the input vector.
10871   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10872     Ops.append(InVec.getNode()->op_begin(),
10873                InVec.getNode()->op_end());
10874   } else if (InVec.getOpcode() == ISD::UNDEF) {
10875     unsigned NElts = VT.getVectorNumElements();
10876     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10877   } else {
10878     return SDValue();
10879   }
10880
10881   // Insert the element
10882   if (Elt < Ops.size()) {
10883     // All the operands of BUILD_VECTOR must have the same type;
10884     // we enforce that here.
10885     EVT OpVT = Ops[0].getValueType();
10886     if (InVal.getValueType() != OpVT)
10887       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10888                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10889                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10890     Ops[Elt] = InVal;
10891   }
10892
10893   // Return the new vector
10894   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10895 }
10896
10897 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10898     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10899   EVT ResultVT = EVE->getValueType(0);
10900   EVT VecEltVT = InVecVT.getVectorElementType();
10901   unsigned Align = OriginalLoad->getAlignment();
10902   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10903       VecEltVT.getTypeForEVT(*DAG.getContext()));
10904
10905   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10906     return SDValue();
10907
10908   Align = NewAlign;
10909
10910   SDValue NewPtr = OriginalLoad->getBasePtr();
10911   SDValue Offset;
10912   EVT PtrType = NewPtr.getValueType();
10913   MachinePointerInfo MPI;
10914   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10915     int Elt = ConstEltNo->getZExtValue();
10916     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10917     if (TLI.isBigEndian())
10918       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10919     Offset = DAG.getConstant(PtrOff, PtrType);
10920     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10921   } else {
10922     Offset = DAG.getNode(
10923         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10924         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10925     if (TLI.isBigEndian())
10926       Offset = DAG.getNode(
10927           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10928           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10929     MPI = OriginalLoad->getPointerInfo();
10930   }
10931   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10932
10933   // The replacement we need to do here is a little tricky: we need to
10934   // replace an extractelement of a load with a load.
10935   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10936   // Note that this replacement assumes that the extractvalue is the only
10937   // use of the load; that's okay because we don't want to perform this
10938   // transformation in other cases anyway.
10939   SDValue Load;
10940   SDValue Chain;
10941   if (ResultVT.bitsGT(VecEltVT)) {
10942     // If the result type of vextract is wider than the load, then issue an
10943     // extending load instead.
10944     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10945                                                   VecEltVT)
10946                                    ? ISD::ZEXTLOAD
10947                                    : ISD::EXTLOAD;
10948     Load = DAG.getExtLoad(
10949         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10950         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10951         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10952     Chain = Load.getValue(1);
10953   } else {
10954     Load = DAG.getLoad(
10955         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10956         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10957         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10958     Chain = Load.getValue(1);
10959     if (ResultVT.bitsLT(VecEltVT))
10960       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10961     else
10962       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10963   }
10964   WorklistRemover DeadNodes(*this);
10965   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10966   SDValue To[] = { Load, Chain };
10967   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10968   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10969   // worklist explicitly as well.
10970   AddToWorklist(Load.getNode());
10971   AddUsersToWorklist(Load.getNode()); // Add users too
10972   // Make sure to revisit this node to clean it up; it will usually be dead.
10973   AddToWorklist(EVE);
10974   ++OpsNarrowed;
10975   return SDValue(EVE, 0);
10976 }
10977
10978 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10979   // (vextract (scalar_to_vector val, 0) -> val
10980   SDValue InVec = N->getOperand(0);
10981   EVT VT = InVec.getValueType();
10982   EVT NVT = N->getValueType(0);
10983
10984   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10985     // Check if the result type doesn't match the inserted element type. A
10986     // SCALAR_TO_VECTOR may truncate the inserted element and the
10987     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10988     SDValue InOp = InVec.getOperand(0);
10989     if (InOp.getValueType() != NVT) {
10990       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10991       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10992     }
10993     return InOp;
10994   }
10995
10996   SDValue EltNo = N->getOperand(1);
10997   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10998
10999   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11000   // We only perform this optimization before the op legalization phase because
11001   // we may introduce new vector instructions which are not backed by TD
11002   // patterns. For example on AVX, extracting elements from a wide vector
11003   // without using extract_subvector. However, if we can find an underlying
11004   // scalar value, then we can always use that.
11005   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11006       && ConstEltNo) {
11007     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11008     int NumElem = VT.getVectorNumElements();
11009     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11010     // Find the new index to extract from.
11011     int OrigElt = SVOp->getMaskElt(Elt);
11012
11013     // Extracting an undef index is undef.
11014     if (OrigElt == -1)
11015       return DAG.getUNDEF(NVT);
11016
11017     // Select the right vector half to extract from.
11018     SDValue SVInVec;
11019     if (OrigElt < NumElem) {
11020       SVInVec = InVec->getOperand(0);
11021     } else {
11022       SVInVec = InVec->getOperand(1);
11023       OrigElt -= NumElem;
11024     }
11025
11026     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11027       SDValue InOp = SVInVec.getOperand(OrigElt);
11028       if (InOp.getValueType() != NVT) {
11029         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11030         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11031       }
11032
11033       return InOp;
11034     }
11035
11036     // FIXME: We should handle recursing on other vector shuffles and
11037     // scalar_to_vector here as well.
11038
11039     if (!LegalOperations) {
11040       EVT IndexTy = TLI.getVectorIdxTy();
11041       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11042                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
11043     }
11044   }
11045
11046   bool BCNumEltsChanged = false;
11047   EVT ExtVT = VT.getVectorElementType();
11048   EVT LVT = ExtVT;
11049
11050   // If the result of load has to be truncated, then it's not necessarily
11051   // profitable.
11052   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11053     return SDValue();
11054
11055   if (InVec.getOpcode() == ISD::BITCAST) {
11056     // Don't duplicate a load with other uses.
11057     if (!InVec.hasOneUse())
11058       return SDValue();
11059
11060     EVT BCVT = InVec.getOperand(0).getValueType();
11061     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11062       return SDValue();
11063     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11064       BCNumEltsChanged = true;
11065     InVec = InVec.getOperand(0);
11066     ExtVT = BCVT.getVectorElementType();
11067   }
11068
11069   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11070   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11071       ISD::isNormalLoad(InVec.getNode()) &&
11072       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11073     SDValue Index = N->getOperand(1);
11074     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11075       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11076                                                            OrigLoad);
11077   }
11078
11079   // Perform only after legalization to ensure build_vector / vector_shuffle
11080   // optimizations have already been done.
11081   if (!LegalOperations) return SDValue();
11082
11083   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11084   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11085   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11086
11087   if (ConstEltNo) {
11088     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11089
11090     LoadSDNode *LN0 = nullptr;
11091     const ShuffleVectorSDNode *SVN = nullptr;
11092     if (ISD::isNormalLoad(InVec.getNode())) {
11093       LN0 = cast<LoadSDNode>(InVec);
11094     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11095                InVec.getOperand(0).getValueType() == ExtVT &&
11096                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11097       // Don't duplicate a load with other uses.
11098       if (!InVec.hasOneUse())
11099         return SDValue();
11100
11101       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11102     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11103       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11104       // =>
11105       // (load $addr+1*size)
11106
11107       // Don't duplicate a load with other uses.
11108       if (!InVec.hasOneUse())
11109         return SDValue();
11110
11111       // If the bit convert changed the number of elements, it is unsafe
11112       // to examine the mask.
11113       if (BCNumEltsChanged)
11114         return SDValue();
11115
11116       // Select the input vector, guarding against out of range extract vector.
11117       unsigned NumElems = VT.getVectorNumElements();
11118       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11119       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11120
11121       if (InVec.getOpcode() == ISD::BITCAST) {
11122         // Don't duplicate a load with other uses.
11123         if (!InVec.hasOneUse())
11124           return SDValue();
11125
11126         InVec = InVec.getOperand(0);
11127       }
11128       if (ISD::isNormalLoad(InVec.getNode())) {
11129         LN0 = cast<LoadSDNode>(InVec);
11130         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11131         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11132       }
11133     }
11134
11135     // Make sure we found a non-volatile load and the extractelement is
11136     // the only use.
11137     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11138       return SDValue();
11139
11140     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11141     if (Elt == -1)
11142       return DAG.getUNDEF(LVT);
11143
11144     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11145   }
11146
11147   return SDValue();
11148 }
11149
11150 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11151 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11152   // We perform this optimization post type-legalization because
11153   // the type-legalizer often scalarizes integer-promoted vectors.
11154   // Performing this optimization before may create bit-casts which
11155   // will be type-legalized to complex code sequences.
11156   // We perform this optimization only before the operation legalizer because we
11157   // may introduce illegal operations.
11158   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11159     return SDValue();
11160
11161   unsigned NumInScalars = N->getNumOperands();
11162   SDLoc dl(N);
11163   EVT VT = N->getValueType(0);
11164
11165   // Check to see if this is a BUILD_VECTOR of a bunch of values
11166   // which come from any_extend or zero_extend nodes. If so, we can create
11167   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11168   // optimizations. We do not handle sign-extend because we can't fill the sign
11169   // using shuffles.
11170   EVT SourceType = MVT::Other;
11171   bool AllAnyExt = true;
11172
11173   for (unsigned i = 0; i != NumInScalars; ++i) {
11174     SDValue In = N->getOperand(i);
11175     // Ignore undef inputs.
11176     if (In.getOpcode() == ISD::UNDEF) continue;
11177
11178     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11179     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11180
11181     // Abort if the element is not an extension.
11182     if (!ZeroExt && !AnyExt) {
11183       SourceType = MVT::Other;
11184       break;
11185     }
11186
11187     // The input is a ZeroExt or AnyExt. Check the original type.
11188     EVT InTy = In.getOperand(0).getValueType();
11189
11190     // Check that all of the widened source types are the same.
11191     if (SourceType == MVT::Other)
11192       // First time.
11193       SourceType = InTy;
11194     else if (InTy != SourceType) {
11195       // Multiple income types. Abort.
11196       SourceType = MVT::Other;
11197       break;
11198     }
11199
11200     // Check if all of the extends are ANY_EXTENDs.
11201     AllAnyExt &= AnyExt;
11202   }
11203
11204   // In order to have valid types, all of the inputs must be extended from the
11205   // same source type and all of the inputs must be any or zero extend.
11206   // Scalar sizes must be a power of two.
11207   EVT OutScalarTy = VT.getScalarType();
11208   bool ValidTypes = SourceType != MVT::Other &&
11209                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11210                  isPowerOf2_32(SourceType.getSizeInBits());
11211
11212   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11213   // turn into a single shuffle instruction.
11214   if (!ValidTypes)
11215     return SDValue();
11216
11217   bool isLE = TLI.isLittleEndian();
11218   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11219   assert(ElemRatio > 1 && "Invalid element size ratio");
11220   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11221                                DAG.getConstant(0, SourceType);
11222
11223   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11224   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11225
11226   // Populate the new build_vector
11227   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11228     SDValue Cast = N->getOperand(i);
11229     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11230             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11231             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11232     SDValue In;
11233     if (Cast.getOpcode() == ISD::UNDEF)
11234       In = DAG.getUNDEF(SourceType);
11235     else
11236       In = Cast->getOperand(0);
11237     unsigned Index = isLE ? (i * ElemRatio) :
11238                             (i * ElemRatio + (ElemRatio - 1));
11239
11240     assert(Index < Ops.size() && "Invalid index");
11241     Ops[Index] = In;
11242   }
11243
11244   // The type of the new BUILD_VECTOR node.
11245   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11246   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11247          "Invalid vector size");
11248   // Check if the new vector type is legal.
11249   if (!isTypeLegal(VecVT)) return SDValue();
11250
11251   // Make the new BUILD_VECTOR.
11252   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11253
11254   // The new BUILD_VECTOR node has the potential to be further optimized.
11255   AddToWorklist(BV.getNode());
11256   // Bitcast to the desired type.
11257   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11258 }
11259
11260 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11261   EVT VT = N->getValueType(0);
11262
11263   unsigned NumInScalars = N->getNumOperands();
11264   SDLoc dl(N);
11265
11266   EVT SrcVT = MVT::Other;
11267   unsigned Opcode = ISD::DELETED_NODE;
11268   unsigned NumDefs = 0;
11269
11270   for (unsigned i = 0; i != NumInScalars; ++i) {
11271     SDValue In = N->getOperand(i);
11272     unsigned Opc = In.getOpcode();
11273
11274     if (Opc == ISD::UNDEF)
11275       continue;
11276
11277     // If all scalar values are floats and converted from integers.
11278     if (Opcode == ISD::DELETED_NODE &&
11279         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11280       Opcode = Opc;
11281     }
11282
11283     if (Opc != Opcode)
11284       return SDValue();
11285
11286     EVT InVT = In.getOperand(0).getValueType();
11287
11288     // If all scalar values are typed differently, bail out. It's chosen to
11289     // simplify BUILD_VECTOR of integer types.
11290     if (SrcVT == MVT::Other)
11291       SrcVT = InVT;
11292     if (SrcVT != InVT)
11293       return SDValue();
11294     NumDefs++;
11295   }
11296
11297   // If the vector has just one element defined, it's not worth to fold it into
11298   // a vectorized one.
11299   if (NumDefs < 2)
11300     return SDValue();
11301
11302   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11303          && "Should only handle conversion from integer to float.");
11304   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11305
11306   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11307
11308   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11309     return SDValue();
11310
11311   // Just because the floating-point vector type is legal does not necessarily
11312   // mean that the corresponding integer vector type is.
11313   if (!isTypeLegal(NVT))
11314     return SDValue();
11315
11316   SmallVector<SDValue, 8> Opnds;
11317   for (unsigned i = 0; i != NumInScalars; ++i) {
11318     SDValue In = N->getOperand(i);
11319
11320     if (In.getOpcode() == ISD::UNDEF)
11321       Opnds.push_back(DAG.getUNDEF(SrcVT));
11322     else
11323       Opnds.push_back(In.getOperand(0));
11324   }
11325   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11326   AddToWorklist(BV.getNode());
11327
11328   return DAG.getNode(Opcode, dl, VT, BV);
11329 }
11330
11331 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11332   unsigned NumInScalars = N->getNumOperands();
11333   SDLoc dl(N);
11334   EVT VT = N->getValueType(0);
11335
11336   // A vector built entirely of undefs is undef.
11337   if (ISD::allOperandsUndef(N))
11338     return DAG.getUNDEF(VT);
11339
11340   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11341     return V;
11342
11343   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11344     return V;
11345
11346   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11347   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11348   // at most two distinct vectors, turn this into a shuffle node.
11349
11350   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11351   if (!isTypeLegal(VT))
11352     return SDValue();
11353
11354   // May only combine to shuffle after legalize if shuffle is legal.
11355   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11356     return SDValue();
11357
11358   SDValue VecIn1, VecIn2;
11359   bool UsesZeroVector = false;
11360   for (unsigned i = 0; i != NumInScalars; ++i) {
11361     SDValue Op = N->getOperand(i);
11362     // Ignore undef inputs.
11363     if (Op.getOpcode() == ISD::UNDEF) continue;
11364
11365     // See if we can combine this build_vector into a blend with a zero vector.
11366     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11367         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11368         (Op.getOpcode() == ISD::ConstantFP &&
11369         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11370       UsesZeroVector = true;
11371       continue;
11372     }
11373
11374     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11375     // constant index, bail out.
11376     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11377         !isa<ConstantSDNode>(Op.getOperand(1))) {
11378       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11379       break;
11380     }
11381
11382     // We allow up to two distinct input vectors.
11383     SDValue ExtractedFromVec = Op.getOperand(0);
11384     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11385       continue;
11386
11387     if (!VecIn1.getNode()) {
11388       VecIn1 = ExtractedFromVec;
11389     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11390       VecIn2 = ExtractedFromVec;
11391     } else {
11392       // Too many inputs.
11393       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11394       break;
11395     }
11396   }
11397
11398   // If everything is good, we can make a shuffle operation.
11399   if (VecIn1.getNode()) {
11400     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11401     SmallVector<int, 8> Mask;
11402     for (unsigned i = 0; i != NumInScalars; ++i) {
11403       unsigned Opcode = N->getOperand(i).getOpcode();
11404       if (Opcode == ISD::UNDEF) {
11405         Mask.push_back(-1);
11406         continue;
11407       }
11408
11409       // Operands can also be zero.
11410       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11411         assert(UsesZeroVector &&
11412                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11413                "Unexpected node found!");
11414         Mask.push_back(NumInScalars+i);
11415         continue;
11416       }
11417
11418       // If extracting from the first vector, just use the index directly.
11419       SDValue Extract = N->getOperand(i);
11420       SDValue ExtVal = Extract.getOperand(1);
11421       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11422       if (Extract.getOperand(0) == VecIn1) {
11423         Mask.push_back(ExtIndex);
11424         continue;
11425       }
11426
11427       // Otherwise, use InIdx + InputVecSize
11428       Mask.push_back(InNumElements + ExtIndex);
11429     }
11430
11431     // Avoid introducing illegal shuffles with zero.
11432     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11433       return SDValue();
11434
11435     // We can't generate a shuffle node with mismatched input and output types.
11436     // Attempt to transform a single input vector to the correct type.
11437     if ((VT != VecIn1.getValueType())) {
11438       // If the input vector type has a different base type to the output
11439       // vector type, bail out.
11440       EVT VTElemType = VT.getVectorElementType();
11441       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11442           (VecIn2.getNode() &&
11443            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11444         return SDValue();
11445
11446       // If the input vector is too small, widen it.
11447       // We only support widening of vectors which are half the size of the
11448       // output registers. For example XMM->YMM widening on X86 with AVX.
11449       EVT VecInT = VecIn1.getValueType();
11450       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11451         // If we only have one small input, widen it by adding undef values.
11452         if (!VecIn2.getNode())
11453           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11454                                DAG.getUNDEF(VecIn1.getValueType()));
11455         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11456           // If we have two small inputs of the same type, try to concat them.
11457           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11458           VecIn2 = SDValue(nullptr, 0);
11459         } else
11460           return SDValue();
11461       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11462         // If the input vector is too large, try to split it.
11463         // We don't support having two input vectors that are too large.
11464         // If the zero vector was used, we can not split the vector,
11465         // since we'd need 3 inputs.
11466         if (UsesZeroVector || VecIn2.getNode())
11467           return SDValue();
11468
11469         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11470           return SDValue();
11471
11472         // Try to replace VecIn1 with two extract_subvectors
11473         // No need to update the masks, they should still be correct.
11474         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11475           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11476         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11477           DAG.getConstant(0, TLI.getVectorIdxTy()));
11478       } else
11479         return SDValue();
11480     }
11481
11482     if (UsesZeroVector)
11483       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11484                                 DAG.getConstantFP(0.0, VT);
11485     else
11486       // If VecIn2 is unused then change it to undef.
11487       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11488
11489     // Check that we were able to transform all incoming values to the same
11490     // type.
11491     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11492         VecIn1.getValueType() != VT)
11493           return SDValue();
11494
11495     // Return the new VECTOR_SHUFFLE node.
11496     SDValue Ops[2];
11497     Ops[0] = VecIn1;
11498     Ops[1] = VecIn2;
11499     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11500   }
11501
11502   return SDValue();
11503 }
11504
11505 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11506   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11507   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11508   // inputs come from at most two distinct vectors, turn this into a shuffle
11509   // node.
11510
11511   // If we only have one input vector, we don't need to do any concatenation.
11512   if (N->getNumOperands() == 1)
11513     return N->getOperand(0);
11514
11515   // Check if all of the operands are undefs.
11516   EVT VT = N->getValueType(0);
11517   if (ISD::allOperandsUndef(N))
11518     return DAG.getUNDEF(VT);
11519
11520   // Optimize concat_vectors where one of the vectors is undef.
11521   if (N->getNumOperands() == 2 &&
11522       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11523     SDValue In = N->getOperand(0);
11524     assert(In.getValueType().isVector() && "Must concat vectors");
11525
11526     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11527     if (In->getOpcode() == ISD::BITCAST &&
11528         !In->getOperand(0)->getValueType(0).isVector()) {
11529       SDValue Scalar = In->getOperand(0);
11530       EVT SclTy = Scalar->getValueType(0);
11531
11532       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11533         return SDValue();
11534
11535       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11536                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11537       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11538         return SDValue();
11539
11540       SDLoc dl = SDLoc(N);
11541       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11542       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11543     }
11544   }
11545
11546   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11547   // We have already tested above for an UNDEF only concatenation.
11548   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11549   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11550   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11551     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11552   };
11553   bool AllBuildVectorsOrUndefs =
11554       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11555   if (AllBuildVectorsOrUndefs) {
11556     SmallVector<SDValue, 8> Opnds;
11557     EVT SVT = VT.getScalarType();
11558
11559     EVT MinVT = SVT;
11560     if (!SVT.isFloatingPoint()) {
11561       // If BUILD_VECTOR are from built from integer, they may have different
11562       // operand types. Get the smallest type and truncate all operands to it.
11563       bool FoundMinVT = false;
11564       for (const SDValue &Op : N->ops())
11565         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11566           EVT OpSVT = Op.getOperand(0)->getValueType(0);
11567           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11568           FoundMinVT = true;
11569         }
11570       assert(FoundMinVT && "Concat vector type mismatch");
11571     }
11572
11573     for (const SDValue &Op : N->ops()) {
11574       EVT OpVT = Op.getValueType();
11575       unsigned NumElts = OpVT.getVectorNumElements();
11576
11577       if (ISD::UNDEF == Op.getOpcode())
11578         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11579
11580       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11581         if (SVT.isFloatingPoint()) {
11582           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11583           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11584         } else {
11585           for (unsigned i = 0; i != NumElts; ++i)
11586             Opnds.push_back(
11587                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11588         }
11589       }
11590     }
11591
11592     assert(VT.getVectorNumElements() == Opnds.size() &&
11593            "Concat vector type mismatch");
11594     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11595   }
11596
11597   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11598   // nodes often generate nop CONCAT_VECTOR nodes.
11599   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11600   // place the incoming vectors at the exact same location.
11601   SDValue SingleSource = SDValue();
11602   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11603
11604   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11605     SDValue Op = N->getOperand(i);
11606
11607     if (Op.getOpcode() == ISD::UNDEF)
11608       continue;
11609
11610     // Check if this is the identity extract:
11611     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11612       return SDValue();
11613
11614     // Find the single incoming vector for the extract_subvector.
11615     if (SingleSource.getNode()) {
11616       if (Op.getOperand(0) != SingleSource)
11617         return SDValue();
11618     } else {
11619       SingleSource = Op.getOperand(0);
11620
11621       // Check the source type is the same as the type of the result.
11622       // If not, this concat may extend the vector, so we can not
11623       // optimize it away.
11624       if (SingleSource.getValueType() != N->getValueType(0))
11625         return SDValue();
11626     }
11627
11628     unsigned IdentityIndex = i * PartNumElem;
11629     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11630     // The extract index must be constant.
11631     if (!CS)
11632       return SDValue();
11633
11634     // Check that we are reading from the identity index.
11635     if (CS->getZExtValue() != IdentityIndex)
11636       return SDValue();
11637   }
11638
11639   if (SingleSource.getNode())
11640     return SingleSource;
11641
11642   return SDValue();
11643 }
11644
11645 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11646   EVT NVT = N->getValueType(0);
11647   SDValue V = N->getOperand(0);
11648
11649   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11650     // Combine:
11651     //    (extract_subvec (concat V1, V2, ...), i)
11652     // Into:
11653     //    Vi if possible
11654     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11655     // type.
11656     if (V->getOperand(0).getValueType() != NVT)
11657       return SDValue();
11658     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11659     unsigned NumElems = NVT.getVectorNumElements();
11660     assert((Idx % NumElems) == 0 &&
11661            "IDX in concat is not a multiple of the result vector length.");
11662     return V->getOperand(Idx / NumElems);
11663   }
11664
11665   // Skip bitcasting
11666   if (V->getOpcode() == ISD::BITCAST)
11667     V = V.getOperand(0);
11668
11669   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11670     SDLoc dl(N);
11671     // Handle only simple case where vector being inserted and vector
11672     // being extracted are of same type, and are half size of larger vectors.
11673     EVT BigVT = V->getOperand(0).getValueType();
11674     EVT SmallVT = V->getOperand(1).getValueType();
11675     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11676       return SDValue();
11677
11678     // Only handle cases where both indexes are constants with the same type.
11679     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11680     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11681
11682     if (InsIdx && ExtIdx &&
11683         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11684         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11685       // Combine:
11686       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11687       // Into:
11688       //    indices are equal or bit offsets are equal => V1
11689       //    otherwise => (extract_subvec V1, ExtIdx)
11690       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11691           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11692         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11693       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11694                          DAG.getNode(ISD::BITCAST, dl,
11695                                      N->getOperand(0).getValueType(),
11696                                      V->getOperand(0)), N->getOperand(1));
11697     }
11698   }
11699
11700   return SDValue();
11701 }
11702
11703 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11704                                                  SDValue V, SelectionDAG &DAG) {
11705   SDLoc DL(V);
11706   EVT VT = V.getValueType();
11707
11708   switch (V.getOpcode()) {
11709   default:
11710     return V;
11711
11712   case ISD::CONCAT_VECTORS: {
11713     EVT OpVT = V->getOperand(0).getValueType();
11714     int OpSize = OpVT.getVectorNumElements();
11715     SmallBitVector OpUsedElements(OpSize, false);
11716     bool FoundSimplification = false;
11717     SmallVector<SDValue, 4> NewOps;
11718     NewOps.reserve(V->getNumOperands());
11719     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11720       SDValue Op = V->getOperand(i);
11721       bool OpUsed = false;
11722       for (int j = 0; j < OpSize; ++j)
11723         if (UsedElements[i * OpSize + j]) {
11724           OpUsedElements[j] = true;
11725           OpUsed = true;
11726         }
11727       NewOps.push_back(
11728           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11729                  : DAG.getUNDEF(OpVT));
11730       FoundSimplification |= Op == NewOps.back();
11731       OpUsedElements.reset();
11732     }
11733     if (FoundSimplification)
11734       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11735     return V;
11736   }
11737
11738   case ISD::INSERT_SUBVECTOR: {
11739     SDValue BaseV = V->getOperand(0);
11740     SDValue SubV = V->getOperand(1);
11741     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11742     if (!IdxN)
11743       return V;
11744
11745     int SubSize = SubV.getValueType().getVectorNumElements();
11746     int Idx = IdxN->getZExtValue();
11747     bool SubVectorUsed = false;
11748     SmallBitVector SubUsedElements(SubSize, false);
11749     for (int i = 0; i < SubSize; ++i)
11750       if (UsedElements[i + Idx]) {
11751         SubVectorUsed = true;
11752         SubUsedElements[i] = true;
11753         UsedElements[i + Idx] = false;
11754       }
11755
11756     // Now recurse on both the base and sub vectors.
11757     SDValue SimplifiedSubV =
11758         SubVectorUsed
11759             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11760             : DAG.getUNDEF(SubV.getValueType());
11761     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11762     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11763       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11764                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11765     return V;
11766   }
11767   }
11768 }
11769
11770 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11771                                        SDValue N1, SelectionDAG &DAG) {
11772   EVT VT = SVN->getValueType(0);
11773   int NumElts = VT.getVectorNumElements();
11774   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11775   for (int M : SVN->getMask())
11776     if (M >= 0 && M < NumElts)
11777       N0UsedElements[M] = true;
11778     else if (M >= NumElts)
11779       N1UsedElements[M - NumElts] = true;
11780
11781   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11782   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11783   if (S0 == N0 && S1 == N1)
11784     return SDValue();
11785
11786   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11787 }
11788
11789 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11790 // or turn a shuffle of a single concat into simpler shuffle then concat.
11791 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11792   EVT VT = N->getValueType(0);
11793   unsigned NumElts = VT.getVectorNumElements();
11794
11795   SDValue N0 = N->getOperand(0);
11796   SDValue N1 = N->getOperand(1);
11797   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11798
11799   SmallVector<SDValue, 4> Ops;
11800   EVT ConcatVT = N0.getOperand(0).getValueType();
11801   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11802   unsigned NumConcats = NumElts / NumElemsPerConcat;
11803
11804   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11805   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11806   // half vector elements.
11807   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11808       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11809                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11810     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11811                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11812     N1 = DAG.getUNDEF(ConcatVT);
11813     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11814   }
11815
11816   // Look at every vector that's inserted. We're looking for exact
11817   // subvector-sized copies from a concatenated vector
11818   for (unsigned I = 0; I != NumConcats; ++I) {
11819     // Make sure we're dealing with a copy.
11820     unsigned Begin = I * NumElemsPerConcat;
11821     bool AllUndef = true, NoUndef = true;
11822     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11823       if (SVN->getMaskElt(J) >= 0)
11824         AllUndef = false;
11825       else
11826         NoUndef = false;
11827     }
11828
11829     if (NoUndef) {
11830       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11831         return SDValue();
11832
11833       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11834         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11835           return SDValue();
11836
11837       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11838       if (FirstElt < N0.getNumOperands())
11839         Ops.push_back(N0.getOperand(FirstElt));
11840       else
11841         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11842
11843     } else if (AllUndef) {
11844       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11845     } else { // Mixed with general masks and undefs, can't do optimization.
11846       return SDValue();
11847     }
11848   }
11849
11850   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11851 }
11852
11853 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11854   EVT VT = N->getValueType(0);
11855   unsigned NumElts = VT.getVectorNumElements();
11856
11857   SDValue N0 = N->getOperand(0);
11858   SDValue N1 = N->getOperand(1);
11859
11860   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11861
11862   // Canonicalize shuffle undef, undef -> undef
11863   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11864     return DAG.getUNDEF(VT);
11865
11866   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11867
11868   // Canonicalize shuffle v, v -> v, undef
11869   if (N0 == N1) {
11870     SmallVector<int, 8> NewMask;
11871     for (unsigned i = 0; i != NumElts; ++i) {
11872       int Idx = SVN->getMaskElt(i);
11873       if (Idx >= (int)NumElts) Idx -= NumElts;
11874       NewMask.push_back(Idx);
11875     }
11876     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11877                                 &NewMask[0]);
11878   }
11879
11880   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11881   if (N0.getOpcode() == ISD::UNDEF) {
11882     SmallVector<int, 8> NewMask;
11883     for (unsigned i = 0; i != NumElts; ++i) {
11884       int Idx = SVN->getMaskElt(i);
11885       if (Idx >= 0) {
11886         if (Idx >= (int)NumElts)
11887           Idx -= NumElts;
11888         else
11889           Idx = -1; // remove reference to lhs
11890       }
11891       NewMask.push_back(Idx);
11892     }
11893     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11894                                 &NewMask[0]);
11895   }
11896
11897   // Remove references to rhs if it is undef
11898   if (N1.getOpcode() == ISD::UNDEF) {
11899     bool Changed = false;
11900     SmallVector<int, 8> NewMask;
11901     for (unsigned i = 0; i != NumElts; ++i) {
11902       int Idx = SVN->getMaskElt(i);
11903       if (Idx >= (int)NumElts) {
11904         Idx = -1;
11905         Changed = true;
11906       }
11907       NewMask.push_back(Idx);
11908     }
11909     if (Changed)
11910       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11911   }
11912
11913   // If it is a splat, check if the argument vector is another splat or a
11914   // build_vector.
11915   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11916     SDNode *V = N0.getNode();
11917
11918     // If this is a bit convert that changes the element type of the vector but
11919     // not the number of vector elements, look through it.  Be careful not to
11920     // look though conversions that change things like v4f32 to v2f64.
11921     if (V->getOpcode() == ISD::BITCAST) {
11922       SDValue ConvInput = V->getOperand(0);
11923       if (ConvInput.getValueType().isVector() &&
11924           ConvInput.getValueType().getVectorNumElements() == NumElts)
11925         V = ConvInput.getNode();
11926     }
11927
11928     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11929       assert(V->getNumOperands() == NumElts &&
11930              "BUILD_VECTOR has wrong number of operands");
11931       SDValue Base;
11932       bool AllSame = true;
11933       for (unsigned i = 0; i != NumElts; ++i) {
11934         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11935           Base = V->getOperand(i);
11936           break;
11937         }
11938       }
11939       // Splat of <u, u, u, u>, return <u, u, u, u>
11940       if (!Base.getNode())
11941         return N0;
11942       for (unsigned i = 0; i != NumElts; ++i) {
11943         if (V->getOperand(i) != Base) {
11944           AllSame = false;
11945           break;
11946         }
11947       }
11948       // Splat of <x, x, x, x>, return <x, x, x, x>
11949       if (AllSame)
11950         return N0;
11951
11952       // Canonicalize any other splat as a build_vector.
11953       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11954       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11955       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11956                                   V->getValueType(0), Ops);
11957
11958       // We may have jumped through bitcasts, so the type of the
11959       // BUILD_VECTOR may not match the type of the shuffle.
11960       if (V->getValueType(0) != VT)
11961         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11962       return NewBV;
11963     }
11964   }
11965
11966   // There are various patterns used to build up a vector from smaller vectors,
11967   // subvectors, or elements. Scan chains of these and replace unused insertions
11968   // or components with undef.
11969   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11970     return S;
11971
11972   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11973       Level < AfterLegalizeVectorOps &&
11974       (N1.getOpcode() == ISD::UNDEF ||
11975       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11976        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11977     SDValue V = partitionShuffleOfConcats(N, DAG);
11978
11979     if (V.getNode())
11980       return V;
11981   }
11982
11983   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
11984   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
11985   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
11986     SmallVector<SDValue, 8> Ops;
11987     for (int M : SVN->getMask()) {
11988       SDValue Op = DAG.getUNDEF(VT.getScalarType());
11989       if (M >= 0) {
11990         int Idx = M % NumElts;
11991         SDValue &S = (M < (int)NumElts ? N0 : N1);
11992         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
11993           Op = S.getOperand(Idx);
11994         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
11995           if (Idx == 0)
11996             Op = S.getOperand(0);
11997         } else {
11998           // Operand can't be combined - bail out.
11999           break;
12000         }
12001       }
12002       Ops.push_back(Op);
12003     }
12004     if (Ops.size() == VT.getVectorNumElements()) {
12005       // BUILD_VECTOR requires all inputs to be of the same type, find the
12006       // maximum type and extend them all.
12007       EVT SVT = VT.getScalarType();
12008       if (SVT.isInteger())
12009         for (SDValue &Op : Ops)
12010           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12011       if (SVT != VT.getScalarType())
12012         for (SDValue &Op : Ops)
12013           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12014                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12015                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12016       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12017     }
12018   }
12019
12020   // If this shuffle only has a single input that is a bitcasted shuffle,
12021   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12022   // back to their original types.
12023   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12024       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12025       TLI.isTypeLegal(VT)) {
12026
12027     // Peek through the bitcast only if there is one user.
12028     SDValue BC0 = N0;
12029     while (BC0.getOpcode() == ISD::BITCAST) {
12030       if (!BC0.hasOneUse())
12031         break;
12032       BC0 = BC0.getOperand(0);
12033     }
12034
12035     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12036       if (Scale == 1)
12037         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12038
12039       SmallVector<int, 8> NewMask;
12040       for (int M : Mask)
12041         for (int s = 0; s != Scale; ++s)
12042           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12043       return NewMask;
12044     };
12045
12046     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12047       EVT SVT = VT.getScalarType();
12048       EVT InnerVT = BC0->getValueType(0);
12049       EVT InnerSVT = InnerVT.getScalarType();
12050
12051       // Determine which shuffle works with the smaller scalar type.
12052       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12053       EVT ScaleSVT = ScaleVT.getScalarType();
12054
12055       if (TLI.isTypeLegal(ScaleVT) &&
12056           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12057           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12058
12059         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12060         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12061
12062         // Scale the shuffle masks to the smaller scalar type.
12063         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12064         SmallVector<int, 8> InnerMask =
12065             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12066         SmallVector<int, 8> OuterMask =
12067             ScaleShuffleMask(SVN->getMask(), OuterScale);
12068
12069         // Merge the shuffle masks.
12070         SmallVector<int, 8> NewMask;
12071         for (int M : OuterMask)
12072           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12073
12074         // Test for shuffle mask legality over both commutations.
12075         SDValue SV0 = BC0->getOperand(0);
12076         SDValue SV1 = BC0->getOperand(1);
12077         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12078         if (!LegalMask) {
12079           std::swap(SV0, SV1);
12080           ShuffleVectorSDNode::commuteMask(NewMask);
12081           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12082         }
12083
12084         if (LegalMask) {
12085           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12086           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12087           return DAG.getNode(
12088               ISD::BITCAST, SDLoc(N), VT,
12089               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12090         }
12091       }
12092     }
12093   }
12094
12095   // Canonicalize shuffles according to rules:
12096   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12097   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12098   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12099   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12100       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12101       TLI.isTypeLegal(VT)) {
12102     // The incoming shuffle must be of the same type as the result of the
12103     // current shuffle.
12104     assert(N1->getOperand(0).getValueType() == VT &&
12105            "Shuffle types don't match");
12106
12107     SDValue SV0 = N1->getOperand(0);
12108     SDValue SV1 = N1->getOperand(1);
12109     bool HasSameOp0 = N0 == SV0;
12110     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12111     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12112       // Commute the operands of this shuffle so that next rule
12113       // will trigger.
12114       return DAG.getCommutedVectorShuffle(*SVN);
12115   }
12116
12117   // Try to fold according to rules:
12118   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12119   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12120   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12121   // Don't try to fold shuffles with illegal type.
12122   // Only fold if this shuffle is the only user of the other shuffle.
12123   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12124       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12125     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12126
12127     // The incoming shuffle must be of the same type as the result of the
12128     // current shuffle.
12129     assert(OtherSV->getOperand(0).getValueType() == VT &&
12130            "Shuffle types don't match");
12131
12132     SDValue SV0, SV1;
12133     SmallVector<int, 4> Mask;
12134     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12135     // operand, and SV1 as the second operand.
12136     for (unsigned i = 0; i != NumElts; ++i) {
12137       int Idx = SVN->getMaskElt(i);
12138       if (Idx < 0) {
12139         // Propagate Undef.
12140         Mask.push_back(Idx);
12141         continue;
12142       }
12143
12144       SDValue CurrentVec;
12145       if (Idx < (int)NumElts) {
12146         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12147         // shuffle mask to identify which vector is actually referenced.
12148         Idx = OtherSV->getMaskElt(Idx);
12149         if (Idx < 0) {
12150           // Propagate Undef.
12151           Mask.push_back(Idx);
12152           continue;
12153         }
12154
12155         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12156                                            : OtherSV->getOperand(1);
12157       } else {
12158         // This shuffle index references an element within N1.
12159         CurrentVec = N1;
12160       }
12161
12162       // Simple case where 'CurrentVec' is UNDEF.
12163       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12164         Mask.push_back(-1);
12165         continue;
12166       }
12167
12168       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12169       // will be the first or second operand of the combined shuffle.
12170       Idx = Idx % NumElts;
12171       if (!SV0.getNode() || SV0 == CurrentVec) {
12172         // Ok. CurrentVec is the left hand side.
12173         // Update the mask accordingly.
12174         SV0 = CurrentVec;
12175         Mask.push_back(Idx);
12176         continue;
12177       }
12178
12179       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12180       if (SV1.getNode() && SV1 != CurrentVec)
12181         return SDValue();
12182
12183       // Ok. CurrentVec is the right hand side.
12184       // Update the mask accordingly.
12185       SV1 = CurrentVec;
12186       Mask.push_back(Idx + NumElts);
12187     }
12188
12189     // Check if all indices in Mask are Undef. In case, propagate Undef.
12190     bool isUndefMask = true;
12191     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12192       isUndefMask &= Mask[i] < 0;
12193
12194     if (isUndefMask)
12195       return DAG.getUNDEF(VT);
12196
12197     if (!SV0.getNode())
12198       SV0 = DAG.getUNDEF(VT);
12199     if (!SV1.getNode())
12200       SV1 = DAG.getUNDEF(VT);
12201
12202     // Avoid introducing shuffles with illegal mask.
12203     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12204       ShuffleVectorSDNode::commuteMask(Mask);
12205
12206       if (!TLI.isShuffleMaskLegal(Mask, VT))
12207         return SDValue();
12208
12209       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12210       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12211       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12212       std::swap(SV0, SV1);
12213     }
12214
12215     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12216     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12217     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12218     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12219   }
12220
12221   return SDValue();
12222 }
12223
12224 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12225   SDValue InVal = N->getOperand(0);
12226   EVT VT = N->getValueType(0);
12227
12228   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12229   // with a VECTOR_SHUFFLE.
12230   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12231     SDValue InVec = InVal->getOperand(0);
12232     SDValue EltNo = InVal->getOperand(1);
12233
12234     // FIXME: We could support implicit truncation if the shuffle can be
12235     // scaled to a smaller vector scalar type.
12236     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12237     if (C0 && VT == InVec.getValueType() &&
12238         VT.getScalarType() == InVal.getValueType()) {
12239       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12240       int Elt = C0->getZExtValue();
12241       NewMask[0] = Elt;
12242
12243       if (TLI.isShuffleMaskLegal(NewMask, VT))
12244         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12245                                     NewMask);
12246     }
12247   }
12248
12249   return SDValue();
12250 }
12251
12252 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12253   SDValue N0 = N->getOperand(0);
12254   SDValue N2 = N->getOperand(2);
12255
12256   // If the input vector is a concatenation, and the insert replaces
12257   // one of the halves, we can optimize into a single concat_vectors.
12258   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12259       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12260     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12261     EVT VT = N->getValueType(0);
12262
12263     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12264     // (concat_vectors Z, Y)
12265     if (InsIdx == 0)
12266       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12267                          N->getOperand(1), N0.getOperand(1));
12268
12269     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12270     // (concat_vectors X, Z)
12271     if (InsIdx == VT.getVectorNumElements()/2)
12272       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12273                          N0.getOperand(0), N->getOperand(1));
12274   }
12275
12276   return SDValue();
12277 }
12278
12279 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12280 /// with the destination vector and a zero vector.
12281 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12282 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12283 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12284   EVT VT = N->getValueType(0);
12285   SDValue LHS = N->getOperand(0);
12286   SDValue RHS = N->getOperand(1);
12287   SDLoc dl(N);
12288
12289   // Make sure we're not running after operation legalization where it 
12290   // may have custom lowered the vector shuffles.
12291   if (LegalOperations)
12292     return SDValue();
12293
12294   if (N->getOpcode() != ISD::AND)
12295     return SDValue();
12296
12297   if (RHS.getOpcode() == ISD::BITCAST)
12298     RHS = RHS.getOperand(0);
12299
12300   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12301     SmallVector<int, 8> Indices;
12302     unsigned NumElts = RHS.getNumOperands();
12303
12304     for (unsigned i = 0; i != NumElts; ++i) {
12305       SDValue Elt = RHS.getOperand(i);
12306       if (!isa<ConstantSDNode>(Elt))
12307         return SDValue();
12308
12309       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12310         Indices.push_back(i);
12311       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12312         Indices.push_back(NumElts+i);
12313       else
12314         return SDValue();
12315     }
12316
12317     // Let's see if the target supports this vector_shuffle.
12318     EVT RVT = RHS.getValueType();
12319     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12320       return SDValue();
12321
12322     // Return the new VECTOR_SHUFFLE node.
12323     EVT EltVT = RVT.getVectorElementType();
12324     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12325                                    DAG.getConstant(0, EltVT));
12326     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12327     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12328     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12329     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12330   }
12331
12332   return SDValue();
12333 }
12334
12335 /// Visit a binary vector operation, like ADD.
12336 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12337   assert(N->getValueType(0).isVector() &&
12338          "SimplifyVBinOp only works on vectors!");
12339
12340   SDValue LHS = N->getOperand(0);
12341   SDValue RHS = N->getOperand(1);
12342
12343   if (SDValue Shuffle = XformToShuffleWithZero(N))
12344     return Shuffle;
12345
12346   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12347   // this operation.
12348   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12349       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12350     // Check if both vectors are constants. If not bail out.
12351     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12352           cast<BuildVectorSDNode>(RHS)->isConstant()))
12353       return SDValue();
12354
12355     SmallVector<SDValue, 8> Ops;
12356     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12357       SDValue LHSOp = LHS.getOperand(i);
12358       SDValue RHSOp = RHS.getOperand(i);
12359
12360       // Can't fold divide by zero.
12361       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12362           N->getOpcode() == ISD::FDIV) {
12363         if ((RHSOp.getOpcode() == ISD::Constant &&
12364              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12365             (RHSOp.getOpcode() == ISD::ConstantFP &&
12366              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12367           break;
12368       }
12369
12370       EVT VT = LHSOp.getValueType();
12371       EVT RVT = RHSOp.getValueType();
12372       if (RVT != VT) {
12373         // Integer BUILD_VECTOR operands may have types larger than the element
12374         // size (e.g., when the element type is not legal).  Prior to type
12375         // legalization, the types may not match between the two BUILD_VECTORS.
12376         // Truncate one of the operands to make them match.
12377         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12378           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12379         } else {
12380           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12381           VT = RVT;
12382         }
12383       }
12384       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12385                                    LHSOp, RHSOp);
12386       if (FoldOp.getOpcode() != ISD::UNDEF &&
12387           FoldOp.getOpcode() != ISD::Constant &&
12388           FoldOp.getOpcode() != ISD::ConstantFP)
12389         break;
12390       Ops.push_back(FoldOp);
12391       AddToWorklist(FoldOp.getNode());
12392     }
12393
12394     if (Ops.size() == LHS.getNumOperands())
12395       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12396   }
12397
12398   // Type legalization might introduce new shuffles in the DAG.
12399   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12400   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12401   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12402       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12403       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12404       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12405     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12406     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12407
12408     if (SVN0->getMask().equals(SVN1->getMask())) {
12409       EVT VT = N->getValueType(0);
12410       SDValue UndefVector = LHS.getOperand(1);
12411       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12412                                      LHS.getOperand(0), RHS.getOperand(0));
12413       AddUsersToWorklist(N);
12414       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12415                                   &SVN0->getMask()[0]);
12416     }
12417   }
12418
12419   return SDValue();
12420 }
12421
12422 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12423                                     SDValue N1, SDValue N2){
12424   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12425
12426   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12427                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12428
12429   // If we got a simplified select_cc node back from SimplifySelectCC, then
12430   // break it down into a new SETCC node, and a new SELECT node, and then return
12431   // the SELECT node, since we were called with a SELECT node.
12432   if (SCC.getNode()) {
12433     // Check to see if we got a select_cc back (to turn into setcc/select).
12434     // Otherwise, just return whatever node we got back, like fabs.
12435     if (SCC.getOpcode() == ISD::SELECT_CC) {
12436       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12437                                   N0.getValueType(),
12438                                   SCC.getOperand(0), SCC.getOperand(1),
12439                                   SCC.getOperand(4));
12440       AddToWorklist(SETCC.getNode());
12441       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12442                            SCC.getOperand(2), SCC.getOperand(3));
12443     }
12444
12445     return SCC;
12446   }
12447   return SDValue();
12448 }
12449
12450 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12451 /// being selected between, see if we can simplify the select.  Callers of this
12452 /// should assume that TheSelect is deleted if this returns true.  As such, they
12453 /// should return the appropriate thing (e.g. the node) back to the top-level of
12454 /// the DAG combiner loop to avoid it being looked at.
12455 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12456                                     SDValue RHS) {
12457
12458   // Cannot simplify select with vector condition
12459   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12460
12461   // If this is a select from two identical things, try to pull the operation
12462   // through the select.
12463   if (LHS.getOpcode() != RHS.getOpcode() ||
12464       !LHS.hasOneUse() || !RHS.hasOneUse())
12465     return false;
12466
12467   // If this is a load and the token chain is identical, replace the select
12468   // of two loads with a load through a select of the address to load from.
12469   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12470   // constants have been dropped into the constant pool.
12471   if (LHS.getOpcode() == ISD::LOAD) {
12472     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12473     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12474
12475     // Token chains must be identical.
12476     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12477         // Do not let this transformation reduce the number of volatile loads.
12478         LLD->isVolatile() || RLD->isVolatile() ||
12479         // If this is an EXTLOAD, the VT's must match.
12480         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12481         // If this is an EXTLOAD, the kind of extension must match.
12482         (LLD->getExtensionType() != RLD->getExtensionType() &&
12483          // The only exception is if one of the extensions is anyext.
12484          LLD->getExtensionType() != ISD::EXTLOAD &&
12485          RLD->getExtensionType() != ISD::EXTLOAD) ||
12486         // FIXME: this discards src value information.  This is
12487         // over-conservative. It would be beneficial to be able to remember
12488         // both potential memory locations.  Since we are discarding
12489         // src value info, don't do the transformation if the memory
12490         // locations are not in the default address space.
12491         LLD->getPointerInfo().getAddrSpace() != 0 ||
12492         RLD->getPointerInfo().getAddrSpace() != 0 ||
12493         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12494                                       LLD->getBasePtr().getValueType()))
12495       return false;
12496
12497     // Check that the select condition doesn't reach either load.  If so,
12498     // folding this will induce a cycle into the DAG.  If not, this is safe to
12499     // xform, so create a select of the addresses.
12500     SDValue Addr;
12501     if (TheSelect->getOpcode() == ISD::SELECT) {
12502       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12503       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12504           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12505         return false;
12506       // The loads must not depend on one another.
12507       if (LLD->isPredecessorOf(RLD) ||
12508           RLD->isPredecessorOf(LLD))
12509         return false;
12510       Addr = DAG.getSelect(SDLoc(TheSelect),
12511                            LLD->getBasePtr().getValueType(),
12512                            TheSelect->getOperand(0), LLD->getBasePtr(),
12513                            RLD->getBasePtr());
12514     } else {  // Otherwise SELECT_CC
12515       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12516       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12517
12518       if ((LLD->hasAnyUseOfValue(1) &&
12519            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12520           (RLD->hasAnyUseOfValue(1) &&
12521            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12522         return false;
12523
12524       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12525                          LLD->getBasePtr().getValueType(),
12526                          TheSelect->getOperand(0),
12527                          TheSelect->getOperand(1),
12528                          LLD->getBasePtr(), RLD->getBasePtr(),
12529                          TheSelect->getOperand(4));
12530     }
12531
12532     SDValue Load;
12533     // It is safe to replace the two loads if they have different alignments,
12534     // but the new load must be the minimum (most restrictive) alignment of the
12535     // inputs.
12536     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12537     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12538     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12539       Load = DAG.getLoad(TheSelect->getValueType(0),
12540                          SDLoc(TheSelect),
12541                          // FIXME: Discards pointer and AA info.
12542                          LLD->getChain(), Addr, MachinePointerInfo(),
12543                          LLD->isVolatile(), LLD->isNonTemporal(),
12544                          isInvariant, Alignment);
12545     } else {
12546       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12547                             RLD->getExtensionType() : LLD->getExtensionType(),
12548                             SDLoc(TheSelect),
12549                             TheSelect->getValueType(0),
12550                             // FIXME: Discards pointer and AA info.
12551                             LLD->getChain(), Addr, MachinePointerInfo(),
12552                             LLD->getMemoryVT(), LLD->isVolatile(),
12553                             LLD->isNonTemporal(), isInvariant, Alignment);
12554     }
12555
12556     // Users of the select now use the result of the load.
12557     CombineTo(TheSelect, Load);
12558
12559     // Users of the old loads now use the new load's chain.  We know the
12560     // old-load value is dead now.
12561     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12562     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12563     return true;
12564   }
12565
12566   return false;
12567 }
12568
12569 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12570 /// where 'cond' is the comparison specified by CC.
12571 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12572                                       SDValue N2, SDValue N3,
12573                                       ISD::CondCode CC, bool NotExtCompare) {
12574   // (x ? y : y) -> y.
12575   if (N2 == N3) return N2;
12576
12577   EVT VT = N2.getValueType();
12578   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12579   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12580   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12581
12582   // Determine if the condition we're dealing with is constant
12583   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12584                               N0, N1, CC, DL, false);
12585   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12586   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12587
12588   // fold select_cc true, x, y -> x
12589   if (SCCC && !SCCC->isNullValue())
12590     return N2;
12591   // fold select_cc false, x, y -> y
12592   if (SCCC && SCCC->isNullValue())
12593     return N3;
12594
12595   // Check to see if we can simplify the select into an fabs node
12596   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12597     // Allow either -0.0 or 0.0
12598     if (CFP->getValueAPF().isZero()) {
12599       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12600       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12601           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12602           N2 == N3.getOperand(0))
12603         return DAG.getNode(ISD::FABS, DL, VT, N0);
12604
12605       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12606       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12607           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12608           N2.getOperand(0) == N3)
12609         return DAG.getNode(ISD::FABS, DL, VT, N3);
12610     }
12611   }
12612
12613   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12614   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12615   // in it.  This is a win when the constant is not otherwise available because
12616   // it replaces two constant pool loads with one.  We only do this if the FP
12617   // type is known to be legal, because if it isn't, then we are before legalize
12618   // types an we want the other legalization to happen first (e.g. to avoid
12619   // messing with soft float) and if the ConstantFP is not legal, because if
12620   // it is legal, we may not need to store the FP constant in a constant pool.
12621   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12622     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12623       if (TLI.isTypeLegal(N2.getValueType()) &&
12624           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12625                TargetLowering::Legal &&
12626            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12627            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12628           // If both constants have multiple uses, then we won't need to do an
12629           // extra load, they are likely around in registers for other users.
12630           (TV->hasOneUse() || FV->hasOneUse())) {
12631         Constant *Elts[] = {
12632           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12633           const_cast<ConstantFP*>(TV->getConstantFPValue())
12634         };
12635         Type *FPTy = Elts[0]->getType();
12636         const DataLayout &TD = *TLI.getDataLayout();
12637
12638         // Create a ConstantArray of the two constants.
12639         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12640         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12641                                             TD.getPrefTypeAlignment(FPTy));
12642         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12643
12644         // Get the offsets to the 0 and 1 element of the array so that we can
12645         // select between them.
12646         SDValue Zero = DAG.getIntPtrConstant(0);
12647         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12648         SDValue One = DAG.getIntPtrConstant(EltSize);
12649
12650         SDValue Cond = DAG.getSetCC(DL,
12651                                     getSetCCResultType(N0.getValueType()),
12652                                     N0, N1, CC);
12653         AddToWorklist(Cond.getNode());
12654         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12655                                           Cond, One, Zero);
12656         AddToWorklist(CstOffset.getNode());
12657         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12658                             CstOffset);
12659         AddToWorklist(CPIdx.getNode());
12660         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12661                            MachinePointerInfo::getConstantPool(), false,
12662                            false, false, Alignment);
12663
12664       }
12665     }
12666
12667   // Check to see if we can perform the "gzip trick", transforming
12668   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12669   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12670       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12671        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12672     EVT XType = N0.getValueType();
12673     EVT AType = N2.getValueType();
12674     if (XType.bitsGE(AType)) {
12675       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12676       // single-bit constant.
12677       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12678         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12679         ShCtV = XType.getSizeInBits()-ShCtV-1;
12680         SDValue ShCt = DAG.getConstant(ShCtV,
12681                                        getShiftAmountTy(N0.getValueType()));
12682         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12683                                     XType, N0, ShCt);
12684         AddToWorklist(Shift.getNode());
12685
12686         if (XType.bitsGT(AType)) {
12687           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12688           AddToWorklist(Shift.getNode());
12689         }
12690
12691         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12692       }
12693
12694       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12695                                   XType, N0,
12696                                   DAG.getConstant(XType.getSizeInBits()-1,
12697                                          getShiftAmountTy(N0.getValueType())));
12698       AddToWorklist(Shift.getNode());
12699
12700       if (XType.bitsGT(AType)) {
12701         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12702         AddToWorklist(Shift.getNode());
12703       }
12704
12705       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12706     }
12707   }
12708
12709   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12710   // where y is has a single bit set.
12711   // A plaintext description would be, we can turn the SELECT_CC into an AND
12712   // when the condition can be materialized as an all-ones register.  Any
12713   // single bit-test can be materialized as an all-ones register with
12714   // shift-left and shift-right-arith.
12715   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12716       N0->getValueType(0) == VT &&
12717       N1C && N1C->isNullValue() &&
12718       N2C && N2C->isNullValue()) {
12719     SDValue AndLHS = N0->getOperand(0);
12720     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12721     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12722       // Shift the tested bit over the sign bit.
12723       APInt AndMask = ConstAndRHS->getAPIntValue();
12724       SDValue ShlAmt =
12725         DAG.getConstant(AndMask.countLeadingZeros(),
12726                         getShiftAmountTy(AndLHS.getValueType()));
12727       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12728
12729       // Now arithmetic right shift it all the way over, so the result is either
12730       // all-ones, or zero.
12731       SDValue ShrAmt =
12732         DAG.getConstant(AndMask.getBitWidth()-1,
12733                         getShiftAmountTy(Shl.getValueType()));
12734       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12735
12736       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12737     }
12738   }
12739
12740   // fold select C, 16, 0 -> shl C, 4
12741   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12742       TLI.getBooleanContents(N0.getValueType()) ==
12743           TargetLowering::ZeroOrOneBooleanContent) {
12744
12745     // If the caller doesn't want us to simplify this into a zext of a compare,
12746     // don't do it.
12747     if (NotExtCompare && N2C->getAPIntValue() == 1)
12748       return SDValue();
12749
12750     // Get a SetCC of the condition
12751     // NOTE: Don't create a SETCC if it's not legal on this target.
12752     if (!LegalOperations ||
12753         TLI.isOperationLegal(ISD::SETCC,
12754           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12755       SDValue Temp, SCC;
12756       // cast from setcc result type to select result type
12757       if (LegalTypes) {
12758         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12759                             N0, N1, CC);
12760         if (N2.getValueType().bitsLT(SCC.getValueType()))
12761           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12762                                         N2.getValueType());
12763         else
12764           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12765                              N2.getValueType(), SCC);
12766       } else {
12767         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12768         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12769                            N2.getValueType(), SCC);
12770       }
12771
12772       AddToWorklist(SCC.getNode());
12773       AddToWorklist(Temp.getNode());
12774
12775       if (N2C->getAPIntValue() == 1)
12776         return Temp;
12777
12778       // shl setcc result by log2 n2c
12779       return DAG.getNode(
12780           ISD::SHL, DL, N2.getValueType(), Temp,
12781           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12782                           getShiftAmountTy(Temp.getValueType())));
12783     }
12784   }
12785
12786   // Check to see if this is the equivalent of setcc
12787   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12788   // otherwise, go ahead with the folds.
12789   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12790     EVT XType = N0.getValueType();
12791     if (!LegalOperations ||
12792         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12793       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12794       if (Res.getValueType() != VT)
12795         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12796       return Res;
12797     }
12798
12799     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12800     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12801         (!LegalOperations ||
12802          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12803       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12804       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12805                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12806                                        getShiftAmountTy(Ctlz.getValueType())));
12807     }
12808     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12809     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12810       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12811                                   XType, DAG.getConstant(0, XType), N0);
12812       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12813       return DAG.getNode(ISD::SRL, DL, XType,
12814                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12815                          DAG.getConstant(XType.getSizeInBits()-1,
12816                                          getShiftAmountTy(XType)));
12817     }
12818     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12819     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12820       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12821                                  DAG.getConstant(XType.getSizeInBits()-1,
12822                                          getShiftAmountTy(N0.getValueType())));
12823       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12824     }
12825   }
12826
12827   // Check to see if this is an integer abs.
12828   // select_cc setg[te] X,  0,  X, -X ->
12829   // select_cc setgt    X, -1,  X, -X ->
12830   // select_cc setl[te] X,  0, -X,  X ->
12831   // select_cc setlt    X,  1, -X,  X ->
12832   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12833   if (N1C) {
12834     ConstantSDNode *SubC = nullptr;
12835     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12836          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12837         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12838       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12839     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12840               (N1C->isOne() && CC == ISD::SETLT)) &&
12841              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12842       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12843
12844     EVT XType = N0.getValueType();
12845     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12846       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12847                                   N0,
12848                                   DAG.getConstant(XType.getSizeInBits()-1,
12849                                          getShiftAmountTy(N0.getValueType())));
12850       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12851                                 XType, N0, Shift);
12852       AddToWorklist(Shift.getNode());
12853       AddToWorklist(Add.getNode());
12854       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12855     }
12856   }
12857
12858   return SDValue();
12859 }
12860
12861 /// This is a stub for TargetLowering::SimplifySetCC.
12862 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12863                                    SDValue N1, ISD::CondCode Cond,
12864                                    SDLoc DL, bool foldBooleans) {
12865   TargetLowering::DAGCombinerInfo
12866     DagCombineInfo(DAG, Level, false, this);
12867   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12868 }
12869
12870 /// Given an ISD::SDIV node expressing a divide by constant, return
12871 /// a DAG expression to select that will generate the same value by multiplying
12872 /// by a magic number.
12873 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12874 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12875   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12876   if (!C)
12877     return SDValue();
12878
12879   // Avoid division by zero.
12880   if (!C->getAPIntValue())
12881     return SDValue();
12882
12883   std::vector<SDNode*> Built;
12884   SDValue S =
12885       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12886
12887   for (SDNode *N : Built)
12888     AddToWorklist(N);
12889   return S;
12890 }
12891
12892 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12893 /// DAG expression that will generate the same value by right shifting.
12894 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12895   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12896   if (!C)
12897     return SDValue();
12898
12899   // Avoid division by zero.
12900   if (!C->getAPIntValue())
12901     return SDValue();
12902
12903   std::vector<SDNode *> Built;
12904   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12905
12906   for (SDNode *N : Built)
12907     AddToWorklist(N);
12908   return S;
12909 }
12910
12911 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12912 /// expression that will generate the same value by multiplying by a magic
12913 /// number.
12914 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12915 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12916   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12917   if (!C)
12918     return SDValue();
12919
12920   // Avoid division by zero.
12921   if (!C->getAPIntValue())
12922     return SDValue();
12923
12924   std::vector<SDNode*> Built;
12925   SDValue S =
12926       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12927
12928   for (SDNode *N : Built)
12929     AddToWorklist(N);
12930   return S;
12931 }
12932
12933 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12934   if (Level >= AfterLegalizeDAG)
12935     return SDValue();
12936
12937   // Expose the DAG combiner to the target combiner implementations.
12938   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12939
12940   unsigned Iterations = 0;
12941   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12942     if (Iterations) {
12943       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12944       // For the reciprocal, we need to find the zero of the function:
12945       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12946       //     =>
12947       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12948       //     does not require additional intermediate precision]
12949       EVT VT = Op.getValueType();
12950       SDLoc DL(Op);
12951       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12952
12953       AddToWorklist(Est.getNode());
12954
12955       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12956       for (unsigned i = 0; i < Iterations; ++i) {
12957         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12958         AddToWorklist(NewEst.getNode());
12959
12960         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12961         AddToWorklist(NewEst.getNode());
12962
12963         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12964         AddToWorklist(NewEst.getNode());
12965
12966         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12967         AddToWorklist(Est.getNode());
12968       }
12969     }
12970     return Est;
12971   }
12972
12973   return SDValue();
12974 }
12975
12976 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12977 /// For the reciprocal sqrt, we need to find the zero of the function:
12978 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12979 ///     =>
12980 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12981 /// As a result, we precompute A/2 prior to the iteration loop.
12982 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12983                                           unsigned Iterations) {
12984   EVT VT = Arg.getValueType();
12985   SDLoc DL(Arg);
12986   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12987
12988   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12989   // this entire sequence requires only one FP constant.
12990   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12991   AddToWorklist(HalfArg.getNode());
12992
12993   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12994   AddToWorklist(HalfArg.getNode());
12995
12996   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12997   for (unsigned i = 0; i < Iterations; ++i) {
12998     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12999     AddToWorklist(NewEst.getNode());
13000
13001     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13002     AddToWorklist(NewEst.getNode());
13003
13004     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13005     AddToWorklist(NewEst.getNode());
13006
13007     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13008     AddToWorklist(Est.getNode());
13009   }
13010   return Est;
13011 }
13012
13013 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13014 /// For the reciprocal sqrt, we need to find the zero of the function:
13015 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13016 ///     =>
13017 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13018 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13019                                           unsigned Iterations) {
13020   EVT VT = Arg.getValueType();
13021   SDLoc DL(Arg);
13022   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13023   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13024
13025   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13026   for (unsigned i = 0; i < Iterations; ++i) {
13027     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13028     AddToWorklist(HalfEst.getNode());
13029
13030     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13031     AddToWorklist(Est.getNode());
13032
13033     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13034     AddToWorklist(Est.getNode());
13035
13036     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13037     AddToWorklist(Est.getNode());
13038
13039     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13040     AddToWorklist(Est.getNode());
13041   }
13042   return Est;
13043 }
13044
13045 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13046   if (Level >= AfterLegalizeDAG)
13047     return SDValue();
13048
13049   // Expose the DAG combiner to the target combiner implementations.
13050   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13051   unsigned Iterations = 0;
13052   bool UseOneConstNR = false;
13053   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13054     AddToWorklist(Est.getNode());
13055     if (Iterations) {
13056       Est = UseOneConstNR ?
13057         BuildRsqrtNROneConst(Op, Est, Iterations) :
13058         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13059     }
13060     return Est;
13061   }
13062
13063   return SDValue();
13064 }
13065
13066 /// Return true if base is a frame index, which is known not to alias with
13067 /// anything but itself.  Provides base object and offset as results.
13068 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13069                            const GlobalValue *&GV, const void *&CV) {
13070   // Assume it is a primitive operation.
13071   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13072
13073   // If it's an adding a simple constant then integrate the offset.
13074   if (Base.getOpcode() == ISD::ADD) {
13075     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13076       Base = Base.getOperand(0);
13077       Offset += C->getZExtValue();
13078     }
13079   }
13080
13081   // Return the underlying GlobalValue, and update the Offset.  Return false
13082   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13083   // by multiple nodes with different offsets.
13084   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13085     GV = G->getGlobal();
13086     Offset += G->getOffset();
13087     return false;
13088   }
13089
13090   // Return the underlying Constant value, and update the Offset.  Return false
13091   // for ConstantSDNodes since the same constant pool entry may be represented
13092   // by multiple nodes with different offsets.
13093   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13094     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13095                                          : (const void *)C->getConstVal();
13096     Offset += C->getOffset();
13097     return false;
13098   }
13099   // If it's any of the following then it can't alias with anything but itself.
13100   return isa<FrameIndexSDNode>(Base);
13101 }
13102
13103 /// Return true if there is any possibility that the two addresses overlap.
13104 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13105   // If they are the same then they must be aliases.
13106   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13107
13108   // If they are both volatile then they cannot be reordered.
13109   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13110
13111   // Gather base node and offset information.
13112   SDValue Base1, Base2;
13113   int64_t Offset1, Offset2;
13114   const GlobalValue *GV1, *GV2;
13115   const void *CV1, *CV2;
13116   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13117                                       Base1, Offset1, GV1, CV1);
13118   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13119                                       Base2, Offset2, GV2, CV2);
13120
13121   // If they have a same base address then check to see if they overlap.
13122   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13123     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13124              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13125
13126   // It is possible for different frame indices to alias each other, mostly
13127   // when tail call optimization reuses return address slots for arguments.
13128   // To catch this case, look up the actual index of frame indices to compute
13129   // the real alias relationship.
13130   if (isFrameIndex1 && isFrameIndex2) {
13131     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13132     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13133     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13134     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13135              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13136   }
13137
13138   // Otherwise, if we know what the bases are, and they aren't identical, then
13139   // we know they cannot alias.
13140   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13141     return false;
13142
13143   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13144   // compared to the size and offset of the access, we may be able to prove they
13145   // do not alias.  This check is conservative for now to catch cases created by
13146   // splitting vector types.
13147   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13148       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13149       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13150        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13151       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13152     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13153     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13154
13155     // There is no overlap between these relatively aligned accesses of similar
13156     // size, return no alias.
13157     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13158         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13159       return false;
13160   }
13161
13162   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13163                    ? CombinerGlobalAA
13164                    : DAG.getSubtarget().useAA();
13165 #ifndef NDEBUG
13166   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13167       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13168     UseAA = false;
13169 #endif
13170   if (UseAA &&
13171       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13172     // Use alias analysis information.
13173     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13174                                  Op1->getSrcValueOffset());
13175     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13176         Op0->getSrcValueOffset() - MinOffset;
13177     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13178         Op1->getSrcValueOffset() - MinOffset;
13179     AliasAnalysis::AliasResult AAResult =
13180         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13181                                          Overlap1,
13182                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13183                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13184                                          Overlap2,
13185                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13186     if (AAResult == AliasAnalysis::NoAlias)
13187       return false;
13188   }
13189
13190   // Otherwise we have to assume they alias.
13191   return true;
13192 }
13193
13194 /// Walk up chain skipping non-aliasing memory nodes,
13195 /// looking for aliasing nodes and adding them to the Aliases vector.
13196 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13197                                    SmallVectorImpl<SDValue> &Aliases) {
13198   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13199   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13200
13201   // Get alias information for node.
13202   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13203
13204   // Starting off.
13205   Chains.push_back(OriginalChain);
13206   unsigned Depth = 0;
13207
13208   // Look at each chain and determine if it is an alias.  If so, add it to the
13209   // aliases list.  If not, then continue up the chain looking for the next
13210   // candidate.
13211   while (!Chains.empty()) {
13212     SDValue Chain = Chains.back();
13213     Chains.pop_back();
13214
13215     // For TokenFactor nodes, look at each operand and only continue up the
13216     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13217     // find more and revert to original chain since the xform is unlikely to be
13218     // profitable.
13219     //
13220     // FIXME: The depth check could be made to return the last non-aliasing
13221     // chain we found before we hit a tokenfactor rather than the original
13222     // chain.
13223     if (Depth > 6 || Aliases.size() == 2) {
13224       Aliases.clear();
13225       Aliases.push_back(OriginalChain);
13226       return;
13227     }
13228
13229     // Don't bother if we've been before.
13230     if (!Visited.insert(Chain.getNode()).second)
13231       continue;
13232
13233     switch (Chain.getOpcode()) {
13234     case ISD::EntryToken:
13235       // Entry token is ideal chain operand, but handled in FindBetterChain.
13236       break;
13237
13238     case ISD::LOAD:
13239     case ISD::STORE: {
13240       // Get alias information for Chain.
13241       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13242           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13243
13244       // If chain is alias then stop here.
13245       if (!(IsLoad && IsOpLoad) &&
13246           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13247         Aliases.push_back(Chain);
13248       } else {
13249         // Look further up the chain.
13250         Chains.push_back(Chain.getOperand(0));
13251         ++Depth;
13252       }
13253       break;
13254     }
13255
13256     case ISD::TokenFactor:
13257       // We have to check each of the operands of the token factor for "small"
13258       // token factors, so we queue them up.  Adding the operands to the queue
13259       // (stack) in reverse order maintains the original order and increases the
13260       // likelihood that getNode will find a matching token factor (CSE.)
13261       if (Chain.getNumOperands() > 16) {
13262         Aliases.push_back(Chain);
13263         break;
13264       }
13265       for (unsigned n = Chain.getNumOperands(); n;)
13266         Chains.push_back(Chain.getOperand(--n));
13267       ++Depth;
13268       break;
13269
13270     default:
13271       // For all other instructions we will just have to take what we can get.
13272       Aliases.push_back(Chain);
13273       break;
13274     }
13275   }
13276
13277   // We need to be careful here to also search for aliases through the
13278   // value operand of a store, etc. Consider the following situation:
13279   //   Token1 = ...
13280   //   L1 = load Token1, %52
13281   //   S1 = store Token1, L1, %51
13282   //   L2 = load Token1, %52+8
13283   //   S2 = store Token1, L2, %51+8
13284   //   Token2 = Token(S1, S2)
13285   //   L3 = load Token2, %53
13286   //   S3 = store Token2, L3, %52
13287   //   L4 = load Token2, %53+8
13288   //   S4 = store Token2, L4, %52+8
13289   // If we search for aliases of S3 (which loads address %52), and we look
13290   // only through the chain, then we'll miss the trivial dependence on L1
13291   // (which also loads from %52). We then might change all loads and
13292   // stores to use Token1 as their chain operand, which could result in
13293   // copying %53 into %52 before copying %52 into %51 (which should
13294   // happen first).
13295   //
13296   // The problem is, however, that searching for such data dependencies
13297   // can become expensive, and the cost is not directly related to the
13298   // chain depth. Instead, we'll rule out such configurations here by
13299   // insisting that we've visited all chain users (except for users
13300   // of the original chain, which is not necessary). When doing this,
13301   // we need to look through nodes we don't care about (otherwise, things
13302   // like register copies will interfere with trivial cases).
13303
13304   SmallVector<const SDNode *, 16> Worklist;
13305   for (const SDNode *N : Visited)
13306     if (N != OriginalChain.getNode())
13307       Worklist.push_back(N);
13308
13309   while (!Worklist.empty()) {
13310     const SDNode *M = Worklist.pop_back_val();
13311
13312     // We have already visited M, and want to make sure we've visited any uses
13313     // of M that we care about. For uses that we've not visisted, and don't
13314     // care about, queue them to the worklist.
13315
13316     for (SDNode::use_iterator UI = M->use_begin(),
13317          UIE = M->use_end(); UI != UIE; ++UI)
13318       if (UI.getUse().getValueType() == MVT::Other &&
13319           Visited.insert(*UI).second) {
13320         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13321           // We've not visited this use, and we care about it (it could have an
13322           // ordering dependency with the original node).
13323           Aliases.clear();
13324           Aliases.push_back(OriginalChain);
13325           return;
13326         }
13327
13328         // We've not visited this use, but we don't care about it. Mark it as
13329         // visited and enqueue it to the worklist.
13330         Worklist.push_back(*UI);
13331       }
13332   }
13333 }
13334
13335 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13336 /// (aliasing node.)
13337 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13338   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13339
13340   // Accumulate all the aliases to this node.
13341   GatherAllAliases(N, OldChain, Aliases);
13342
13343   // If no operands then chain to entry token.
13344   if (Aliases.size() == 0)
13345     return DAG.getEntryNode();
13346
13347   // If a single operand then chain to it.  We don't need to revisit it.
13348   if (Aliases.size() == 1)
13349     return Aliases[0];
13350
13351   // Construct a custom tailored token factor.
13352   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13353 }
13354
13355 /// This is the entry point for the file.
13356 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13357                            CodeGenOpt::Level OptLevel) {
13358   /// This is the main entry point to this class.
13359   DAGCombiner(*this, AA, OptLevel).Run(Level);
13360 }