DAGCombiner: Factor out some and/or combines.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue SimplifyVUnaryOp(SDNode *N);
255     SDValue visitSHL(SDNode *N);
256     SDValue visitSRA(SDNode *N);
257     SDValue visitSRL(SDNode *N);
258     SDValue visitRotate(SDNode *N);
259     SDValue visitCTLZ(SDNode *N);
260     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTTZ(SDNode *N);
262     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTPOP(SDNode *N);
264     SDValue visitSELECT(SDNode *N);
265     SDValue visitVSELECT(SDNode *N);
266     SDValue visitSELECT_CC(SDNode *N);
267     SDValue visitSETCC(SDNode *N);
268     SDValue visitSIGN_EXTEND(SDNode *N);
269     SDValue visitZERO_EXTEND(SDNode *N);
270     SDValue visitANY_EXTEND(SDNode *N);
271     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272     SDValue visitTRUNCATE(SDNode *N);
273     SDValue visitBITCAST(SDNode *N);
274     SDValue visitBUILD_PAIR(SDNode *N);
275     SDValue visitFADD(SDNode *N);
276     SDValue visitFSUB(SDNode *N);
277     SDValue visitFMUL(SDNode *N);
278     SDValue visitFMA(SDNode *N);
279     SDValue visitFDIV(SDNode *N);
280     SDValue visitFREM(SDNode *N);
281     SDValue visitFSQRT(SDNode *N);
282     SDValue visitFCOPYSIGN(SDNode *N);
283     SDValue visitSINT_TO_FP(SDNode *N);
284     SDValue visitUINT_TO_FP(SDNode *N);
285     SDValue visitFP_TO_SINT(SDNode *N);
286     SDValue visitFP_TO_UINT(SDNode *N);
287     SDValue visitFP_ROUND(SDNode *N);
288     SDValue visitFP_ROUND_INREG(SDNode *N);
289     SDValue visitFP_EXTEND(SDNode *N);
290     SDValue visitFNEG(SDNode *N);
291     SDValue visitFABS(SDNode *N);
292     SDValue visitFCEIL(SDNode *N);
293     SDValue visitFTRUNC(SDNode *N);
294     SDValue visitFFLOOR(SDNode *N);
295     SDValue visitFMINNUM(SDNode *N);
296     SDValue visitFMAXNUM(SDNode *N);
297     SDValue visitBRCOND(SDNode *N);
298     SDValue visitBR_CC(SDNode *N);
299     SDValue visitLOAD(SDNode *N);
300     SDValue visitSTORE(SDNode *N);
301     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
302     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
303     SDValue visitBUILD_VECTOR(SDNode *N);
304     SDValue visitCONCAT_VECTORS(SDNode *N);
305     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
306     SDValue visitVECTOR_SHUFFLE(SDNode *N);
307     SDValue 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 BuildVector or constant.
709 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
710   if (isa<ConstantSDNode>(N))
711     return N.getNode();
712   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
713   if (BV && BV->isConstant())
714     return BV;
715   return nullptr;
716 }
717
718 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
719 // int.
720 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
721   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
722     return CN;
723
724   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
725     BitVector UndefElements;
726     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
727
728     // BuildVectors can truncate their operands. Ignore that case here.
729     // FIXME: We blindly ignore splats which include undef which is overly
730     // pessimistic.
731     if (CN && UndefElements.none() &&
732         CN->getValueType(0) == N.getValueType().getScalarType())
733       return CN;
734   }
735
736   return nullptr;
737 }
738
739 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
740 // float.
741 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
742   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
743     return CN;
744
745   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
746     BitVector UndefElements;
747     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
748
749     if (CN && UndefElements.none())
750       return CN;
751   }
752
753   return nullptr;
754 }
755
756 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
757                                     SDValue N0, SDValue N1) {
758   EVT VT = N0.getValueType();
759   if (N0.getOpcode() == Opc) {
760     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
761       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
762         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
763         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
764           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
765         return SDValue();
766       }
767       if (N0.hasOneUse()) {
768         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
769         // use
770         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
771         if (!OpNode.getNode())
772           return SDValue();
773         AddToWorklist(OpNode.getNode());
774         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
775       }
776     }
777   }
778
779   if (N1.getOpcode() == Opc) {
780     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
781       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
782         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
783         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
784           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
785         return SDValue();
786       }
787       if (N1.hasOneUse()) {
788         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
789         // use
790         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
791         if (!OpNode.getNode())
792           return SDValue();
793         AddToWorklist(OpNode.getNode());
794         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
795       }
796     }
797   }
798
799   return SDValue();
800 }
801
802 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
803                                bool AddTo) {
804   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
805   ++NodesCombined;
806   DEBUG(dbgs() << "\nReplacing.1 ";
807         N->dump(&DAG);
808         dbgs() << "\nWith: ";
809         To[0].getNode()->dump(&DAG);
810         dbgs() << " and " << NumTo-1 << " other values\n");
811   for (unsigned i = 0, e = NumTo; i != e; ++i)
812     assert((!To[i].getNode() ||
813             N->getValueType(i) == To[i].getValueType()) &&
814            "Cannot combine value to value of different type!");
815
816   WorklistRemover DeadNodes(*this);
817   DAG.ReplaceAllUsesWith(N, To);
818   if (AddTo) {
819     // Push the new nodes and any users onto the worklist
820     for (unsigned i = 0, e = NumTo; i != e; ++i) {
821       if (To[i].getNode()) {
822         AddToWorklist(To[i].getNode());
823         AddUsersToWorklist(To[i].getNode());
824       }
825     }
826   }
827
828   // Finally, if the node is now dead, remove it from the graph.  The node
829   // may not be dead if the replacement process recursively simplified to
830   // something else needing this node.
831   if (N->use_empty())
832     deleteAndRecombine(N);
833   return SDValue(N, 0);
834 }
835
836 void DAGCombiner::
837 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
838   // Replace all uses.  If any nodes become isomorphic to other nodes and
839   // are deleted, make sure to remove them from our worklist.
840   WorklistRemover DeadNodes(*this);
841   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
842
843   // Push the new node and any (possibly new) users onto the worklist.
844   AddToWorklist(TLO.New.getNode());
845   AddUsersToWorklist(TLO.New.getNode());
846
847   // Finally, if the node is now dead, remove it from the graph.  The node
848   // may not be dead if the replacement process recursively simplified to
849   // something else needing this node.
850   if (TLO.Old.getNode()->use_empty())
851     deleteAndRecombine(TLO.Old.getNode());
852 }
853
854 /// Check the specified integer node value to see if it can be simplified or if
855 /// things it uses can be simplified by bit propagation. If so, return true.
856 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
857   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
858   APInt KnownZero, KnownOne;
859   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
860     return false;
861
862   // Revisit the node.
863   AddToWorklist(Op.getNode());
864
865   // Replace the old value with the new one.
866   ++NodesCombined;
867   DEBUG(dbgs() << "\nReplacing.2 ";
868         TLO.Old.getNode()->dump(&DAG);
869         dbgs() << "\nWith: ";
870         TLO.New.getNode()->dump(&DAG);
871         dbgs() << '\n');
872
873   CommitTargetLoweringOpt(TLO);
874   return true;
875 }
876
877 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
878   SDLoc dl(Load);
879   EVT VT = Load->getValueType(0);
880   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
881
882   DEBUG(dbgs() << "\nReplacing.9 ";
883         Load->dump(&DAG);
884         dbgs() << "\nWith: ";
885         Trunc.getNode()->dump(&DAG);
886         dbgs() << '\n');
887   WorklistRemover DeadNodes(*this);
888   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
889   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
890   deleteAndRecombine(Load);
891   AddToWorklist(Trunc.getNode());
892 }
893
894 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
895   Replace = false;
896   SDLoc dl(Op);
897   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
898     EVT MemVT = LD->getMemoryVT();
899     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
900       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
901                                                        : ISD::EXTLOAD)
902       : LD->getExtensionType();
903     Replace = true;
904     return DAG.getExtLoad(ExtType, dl, PVT,
905                           LD->getChain(), LD->getBasePtr(),
906                           MemVT, LD->getMemOperand());
907   }
908
909   unsigned Opc = Op.getOpcode();
910   switch (Opc) {
911   default: break;
912   case ISD::AssertSext:
913     return DAG.getNode(ISD::AssertSext, dl, PVT,
914                        SExtPromoteOperand(Op.getOperand(0), PVT),
915                        Op.getOperand(1));
916   case ISD::AssertZext:
917     return DAG.getNode(ISD::AssertZext, dl, PVT,
918                        ZExtPromoteOperand(Op.getOperand(0), PVT),
919                        Op.getOperand(1));
920   case ISD::Constant: {
921     unsigned ExtOpc =
922       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
923     return DAG.getNode(ExtOpc, dl, PVT, Op);
924   }
925   }
926
927   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
928     return SDValue();
929   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
930 }
931
932 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
933   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
934     return SDValue();
935   EVT OldVT = Op.getValueType();
936   SDLoc dl(Op);
937   bool Replace = false;
938   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
939   if (!NewOp.getNode())
940     return SDValue();
941   AddToWorklist(NewOp.getNode());
942
943   if (Replace)
944     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
945   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
946                      DAG.getValueType(OldVT));
947 }
948
949 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
950   EVT OldVT = Op.getValueType();
951   SDLoc dl(Op);
952   bool Replace = false;
953   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
954   if (!NewOp.getNode())
955     return SDValue();
956   AddToWorklist(NewOp.getNode());
957
958   if (Replace)
959     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
960   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
961 }
962
963 /// Promote the specified integer binary operation if the target indicates it is
964 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
965 /// i32 since i16 instructions are longer.
966 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
967   if (!LegalOperations)
968     return SDValue();
969
970   EVT VT = Op.getValueType();
971   if (VT.isVector() || !VT.isInteger())
972     return SDValue();
973
974   // If operation type is 'undesirable', e.g. i16 on x86, consider
975   // promoting it.
976   unsigned Opc = Op.getOpcode();
977   if (TLI.isTypeDesirableForOp(Opc, VT))
978     return SDValue();
979
980   EVT PVT = VT;
981   // Consult target whether it is a good idea to promote this operation and
982   // what's the right type to promote it to.
983   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
984     assert(PVT != VT && "Don't know what type to promote to!");
985
986     bool Replace0 = false;
987     SDValue N0 = Op.getOperand(0);
988     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
989     if (!NN0.getNode())
990       return SDValue();
991
992     bool Replace1 = false;
993     SDValue N1 = Op.getOperand(1);
994     SDValue NN1;
995     if (N0 == N1)
996       NN1 = NN0;
997     else {
998       NN1 = PromoteOperand(N1, PVT, Replace1);
999       if (!NN1.getNode())
1000         return SDValue();
1001     }
1002
1003     AddToWorklist(NN0.getNode());
1004     if (NN1.getNode())
1005       AddToWorklist(NN1.getNode());
1006
1007     if (Replace0)
1008       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1009     if (Replace1)
1010       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1011
1012     DEBUG(dbgs() << "\nPromoting ";
1013           Op.getNode()->dump(&DAG));
1014     SDLoc dl(Op);
1015     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1016                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1017   }
1018   return SDValue();
1019 }
1020
1021 /// Promote the specified integer shift operation if the target indicates it is
1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1023 /// i32 since i16 instructions are longer.
1024 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1025   if (!LegalOperations)
1026     return SDValue();
1027
1028   EVT VT = Op.getValueType();
1029   if (VT.isVector() || !VT.isInteger())
1030     return SDValue();
1031
1032   // If operation type is 'undesirable', e.g. i16 on x86, consider
1033   // promoting it.
1034   unsigned Opc = Op.getOpcode();
1035   if (TLI.isTypeDesirableForOp(Opc, VT))
1036     return SDValue();
1037
1038   EVT PVT = VT;
1039   // Consult target whether it is a good idea to promote this operation and
1040   // what's the right type to promote it to.
1041   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1042     assert(PVT != VT && "Don't know what type to promote to!");
1043
1044     bool Replace = false;
1045     SDValue N0 = Op.getOperand(0);
1046     if (Opc == ISD::SRA)
1047       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1048     else if (Opc == ISD::SRL)
1049       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1050     else
1051       N0 = PromoteOperand(N0, PVT, Replace);
1052     if (!N0.getNode())
1053       return SDValue();
1054
1055     AddToWorklist(N0.getNode());
1056     if (Replace)
1057       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1058
1059     DEBUG(dbgs() << "\nPromoting ";
1060           Op.getNode()->dump(&DAG));
1061     SDLoc dl(Op);
1062     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1063                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1064   }
1065   return SDValue();
1066 }
1067
1068 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1069   if (!LegalOperations)
1070     return SDValue();
1071
1072   EVT VT = Op.getValueType();
1073   if (VT.isVector() || !VT.isInteger())
1074     return SDValue();
1075
1076   // If operation type is 'undesirable', e.g. i16 on x86, consider
1077   // promoting it.
1078   unsigned Opc = Op.getOpcode();
1079   if (TLI.isTypeDesirableForOp(Opc, VT))
1080     return SDValue();
1081
1082   EVT PVT = VT;
1083   // Consult target whether it is a good idea to promote this operation and
1084   // what's the right type to promote it to.
1085   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1086     assert(PVT != VT && "Don't know what type to promote to!");
1087     // fold (aext (aext x)) -> (aext x)
1088     // fold (aext (zext x)) -> (zext x)
1089     // fold (aext (sext x)) -> (sext x)
1090     DEBUG(dbgs() << "\nPromoting ";
1091           Op.getNode()->dump(&DAG));
1092     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1093   }
1094   return SDValue();
1095 }
1096
1097 bool DAGCombiner::PromoteLoad(SDValue Op) {
1098   if (!LegalOperations)
1099     return false;
1100
1101   EVT VT = Op.getValueType();
1102   if (VT.isVector() || !VT.isInteger())
1103     return false;
1104
1105   // If operation type is 'undesirable', e.g. i16 on x86, consider
1106   // promoting it.
1107   unsigned Opc = Op.getOpcode();
1108   if (TLI.isTypeDesirableForOp(Opc, VT))
1109     return false;
1110
1111   EVT PVT = VT;
1112   // Consult target whether it is a good idea to promote this operation and
1113   // what's the right type to promote it to.
1114   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1115     assert(PVT != VT && "Don't know what type to promote to!");
1116
1117     SDLoc dl(Op);
1118     SDNode *N = Op.getNode();
1119     LoadSDNode *LD = cast<LoadSDNode>(N);
1120     EVT MemVT = LD->getMemoryVT();
1121     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1122       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1123                                                        : ISD::EXTLOAD)
1124       : LD->getExtensionType();
1125     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1126                                    LD->getChain(), LD->getBasePtr(),
1127                                    MemVT, LD->getMemOperand());
1128     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1129
1130     DEBUG(dbgs() << "\nPromoting ";
1131           N->dump(&DAG);
1132           dbgs() << "\nTo: ";
1133           Result.getNode()->dump(&DAG);
1134           dbgs() << '\n');
1135     WorklistRemover DeadNodes(*this);
1136     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1137     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1138     deleteAndRecombine(N);
1139     AddToWorklist(Result.getNode());
1140     return true;
1141   }
1142   return false;
1143 }
1144
1145 /// \brief Recursively delete a node which has no uses and any operands for
1146 /// which it is the only use.
1147 ///
1148 /// Note that this both deletes the nodes and removes them from the worklist.
1149 /// It also adds any nodes who have had a user deleted to the worklist as they
1150 /// may now have only one use and subject to other combines.
1151 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1152   if (!N->use_empty())
1153     return false;
1154
1155   SmallSetVector<SDNode *, 16> Nodes;
1156   Nodes.insert(N);
1157   do {
1158     N = Nodes.pop_back_val();
1159     if (!N)
1160       continue;
1161
1162     if (N->use_empty()) {
1163       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1164         Nodes.insert(N->getOperand(i).getNode());
1165
1166       removeFromWorklist(N);
1167       DAG.DeleteNode(N);
1168     } else {
1169       AddToWorklist(N);
1170     }
1171   } while (!Nodes.empty());
1172   return true;
1173 }
1174
1175 //===----------------------------------------------------------------------===//
1176 //  Main DAG Combiner implementation
1177 //===----------------------------------------------------------------------===//
1178
1179 void DAGCombiner::Run(CombineLevel AtLevel) {
1180   // set the instance variables, so that the various visit routines may use it.
1181   Level = AtLevel;
1182   LegalOperations = Level >= AfterLegalizeVectorOps;
1183   LegalTypes = Level >= AfterLegalizeTypes;
1184
1185   // Early exit if this basic block is in an optnone function.
1186   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
1187           Attribute::OptimizeNone))
1188     return;
1189
1190   // Add all the dag nodes to the worklist.
1191   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1192        E = DAG.allnodes_end(); I != E; ++I)
1193     AddToWorklist(I);
1194
1195   // Create a dummy node (which is not added to allnodes), that adds a reference
1196   // to the root node, preventing it from being deleted, and tracking any
1197   // changes of the root.
1198   HandleSDNode Dummy(DAG.getRoot());
1199
1200   // while the worklist isn't empty, find a node and
1201   // try and combine it.
1202   while (!WorklistMap.empty()) {
1203     SDNode *N;
1204     // The Worklist holds the SDNodes in order, but it may contain null entries.
1205     do {
1206       N = Worklist.pop_back_val();
1207     } while (!N);
1208
1209     bool GoodWorklistEntry = WorklistMap.erase(N);
1210     (void)GoodWorklistEntry;
1211     assert(GoodWorklistEntry &&
1212            "Found a worklist entry without a corresponding map entry!");
1213
1214     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1215     // N is deleted from the DAG, since they too may now be dead or may have a
1216     // reduced number of uses, allowing other xforms.
1217     if (recursivelyDeleteUnusedNodes(N))
1218       continue;
1219
1220     WorklistRemover DeadNodes(*this);
1221
1222     // If this combine is running after legalizing the DAG, re-legalize any
1223     // nodes pulled off the worklist.
1224     if (Level == AfterLegalizeDAG) {
1225       SmallSetVector<SDNode *, 16> UpdatedNodes;
1226       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1227
1228       for (SDNode *LN : UpdatedNodes) {
1229         AddToWorklist(LN);
1230         AddUsersToWorklist(LN);
1231       }
1232       if (!NIsValid)
1233         continue;
1234     }
1235
1236     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1237
1238     // Add any operands of the new node which have not yet been combined to the
1239     // worklist as well. Because the worklist uniques things already, this
1240     // won't repeatedly process the same operand.
1241     CombinedNodes.insert(N);
1242     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1243       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1244         AddToWorklist(N->getOperand(i).getNode());
1245
1246     SDValue RV = combine(N);
1247
1248     if (!RV.getNode())
1249       continue;
1250
1251     ++NodesCombined;
1252
1253     // If we get back the same node we passed in, rather than a new node or
1254     // zero, we know that the node must have defined multiple values and
1255     // CombineTo was used.  Since CombineTo takes care of the worklist
1256     // mechanics for us, we have no work to do in this case.
1257     if (RV.getNode() == N)
1258       continue;
1259
1260     assert(N->getOpcode() != ISD::DELETED_NODE &&
1261            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1262            "Node was deleted but visit returned new node!");
1263
1264     DEBUG(dbgs() << " ... into: ";
1265           RV.getNode()->dump(&DAG));
1266
1267     // Transfer debug value.
1268     DAG.TransferDbgValues(SDValue(N, 0), RV);
1269     if (N->getNumValues() == RV.getNode()->getNumValues())
1270       DAG.ReplaceAllUsesWith(N, RV.getNode());
1271     else {
1272       assert(N->getValueType(0) == RV.getValueType() &&
1273              N->getNumValues() == 1 && "Type mismatch");
1274       SDValue OpV = RV;
1275       DAG.ReplaceAllUsesWith(N, &OpV);
1276     }
1277
1278     // Push the new node and any users onto the worklist
1279     AddToWorklist(RV.getNode());
1280     AddUsersToWorklist(RV.getNode());
1281
1282     // Finally, if the node is now dead, remove it from the graph.  The node
1283     // may not be dead if the replacement process recursively simplified to
1284     // something else needing this node. This will also take care of adding any
1285     // operands which have lost a user to the worklist.
1286     recursivelyDeleteUnusedNodes(N);
1287   }
1288
1289   // If the root changed (e.g. it was a dead load, update the root).
1290   DAG.setRoot(Dummy.getValue());
1291   DAG.RemoveDeadNodes();
1292 }
1293
1294 SDValue DAGCombiner::visit(SDNode *N) {
1295   switch (N->getOpcode()) {
1296   default: break;
1297   case ISD::TokenFactor:        return visitTokenFactor(N);
1298   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1299   case ISD::ADD:                return visitADD(N);
1300   case ISD::SUB:                return visitSUB(N);
1301   case ISD::ADDC:               return visitADDC(N);
1302   case ISD::SUBC:               return visitSUBC(N);
1303   case ISD::ADDE:               return visitADDE(N);
1304   case ISD::SUBE:               return visitSUBE(N);
1305   case ISD::MUL:                return visitMUL(N);
1306   case ISD::SDIV:               return visitSDIV(N);
1307   case ISD::UDIV:               return visitUDIV(N);
1308   case ISD::SREM:               return visitSREM(N);
1309   case ISD::UREM:               return visitUREM(N);
1310   case ISD::MULHU:              return visitMULHU(N);
1311   case ISD::MULHS:              return visitMULHS(N);
1312   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1313   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1314   case ISD::SMULO:              return visitSMULO(N);
1315   case ISD::UMULO:              return visitUMULO(N);
1316   case ISD::SDIVREM:            return visitSDIVREM(N);
1317   case ISD::UDIVREM:            return visitUDIVREM(N);
1318   case ISD::AND:                return visitAND(N);
1319   case ISD::OR:                 return visitOR(N);
1320   case ISD::XOR:                return visitXOR(N);
1321   case ISD::SHL:                return visitSHL(N);
1322   case ISD::SRA:                return visitSRA(N);
1323   case ISD::SRL:                return visitSRL(N);
1324   case ISD::ROTR:
1325   case ISD::ROTL:               return visitRotate(N);
1326   case ISD::CTLZ:               return visitCTLZ(N);
1327   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1328   case ISD::CTTZ:               return visitCTTZ(N);
1329   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1330   case ISD::CTPOP:              return visitCTPOP(N);
1331   case ISD::SELECT:             return visitSELECT(N);
1332   case ISD::VSELECT:            return visitVSELECT(N);
1333   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1334   case ISD::SETCC:              return visitSETCC(N);
1335   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1336   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1337   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1338   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1339   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1340   case ISD::BITCAST:            return visitBITCAST(N);
1341   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1342   case ISD::FADD:               return visitFADD(N);
1343   case ISD::FSUB:               return visitFSUB(N);
1344   case ISD::FMUL:               return visitFMUL(N);
1345   case ISD::FMA:                return visitFMA(N);
1346   case ISD::FDIV:               return visitFDIV(N);
1347   case ISD::FREM:               return visitFREM(N);
1348   case ISD::FSQRT:              return visitFSQRT(N);
1349   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1350   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1351   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1352   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1353   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1354   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1355   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1356   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1357   case ISD::FNEG:               return visitFNEG(N);
1358   case ISD::FABS:               return visitFABS(N);
1359   case ISD::FFLOOR:             return visitFFLOOR(N);
1360   case ISD::FMINNUM:            return visitFMINNUM(N);
1361   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1362   case ISD::FCEIL:              return visitFCEIL(N);
1363   case ISD::FTRUNC:             return visitFTRUNC(N);
1364   case ISD::BRCOND:             return visitBRCOND(N);
1365   case ISD::BR_CC:              return visitBR_CC(N);
1366   case ISD::LOAD:               return visitLOAD(N);
1367   case ISD::STORE:              return visitSTORE(N);
1368   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1369   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1370   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1371   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1372   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1373   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1374   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1375   case ISD::MLOAD:              return visitMLOAD(N);
1376   case ISD::MSTORE:             return visitMSTORE(N);
1377   }
1378   return SDValue();
1379 }
1380
1381 SDValue DAGCombiner::combine(SDNode *N) {
1382   SDValue RV = visit(N);
1383
1384   // If nothing happened, try a target-specific DAG combine.
1385   if (!RV.getNode()) {
1386     assert(N->getOpcode() != ISD::DELETED_NODE &&
1387            "Node was deleted but visit returned NULL!");
1388
1389     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1390         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1391
1392       // Expose the DAG combiner to the target combiner impls.
1393       TargetLowering::DAGCombinerInfo
1394         DagCombineInfo(DAG, Level, false, this);
1395
1396       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1397     }
1398   }
1399
1400   // If nothing happened still, try promoting the operation.
1401   if (!RV.getNode()) {
1402     switch (N->getOpcode()) {
1403     default: break;
1404     case ISD::ADD:
1405     case ISD::SUB:
1406     case ISD::MUL:
1407     case ISD::AND:
1408     case ISD::OR:
1409     case ISD::XOR:
1410       RV = PromoteIntBinOp(SDValue(N, 0));
1411       break;
1412     case ISD::SHL:
1413     case ISD::SRA:
1414     case ISD::SRL:
1415       RV = PromoteIntShiftOp(SDValue(N, 0));
1416       break;
1417     case ISD::SIGN_EXTEND:
1418     case ISD::ZERO_EXTEND:
1419     case ISD::ANY_EXTEND:
1420       RV = PromoteExtend(SDValue(N, 0));
1421       break;
1422     case ISD::LOAD:
1423       if (PromoteLoad(SDValue(N, 0)))
1424         RV = SDValue(N, 0);
1425       break;
1426     }
1427   }
1428
1429   // If N is a commutative binary node, try commuting it to enable more
1430   // sdisel CSE.
1431   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1432       N->getNumValues() == 1) {
1433     SDValue N0 = N->getOperand(0);
1434     SDValue N1 = N->getOperand(1);
1435
1436     // Constant operands are canonicalized to RHS.
1437     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1438       SDValue Ops[] = {N1, N0};
1439       SDNode *CSENode;
1440       if (const BinaryWithFlagsSDNode *BinNode =
1441               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1442         CSENode = DAG.getNodeIfExists(
1443             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1444             BinNode->hasNoSignedWrap(), BinNode->isExact());
1445       } else {
1446         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1447       }
1448       if (CSENode)
1449         return SDValue(CSENode, 0);
1450     }
1451   }
1452
1453   return RV;
1454 }
1455
1456 /// Given a node, return its input chain if it has one, otherwise return a null
1457 /// sd operand.
1458 static SDValue getInputChainForNode(SDNode *N) {
1459   if (unsigned NumOps = N->getNumOperands()) {
1460     if (N->getOperand(0).getValueType() == MVT::Other)
1461       return N->getOperand(0);
1462     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1463       return N->getOperand(NumOps-1);
1464     for (unsigned i = 1; i < NumOps-1; ++i)
1465       if (N->getOperand(i).getValueType() == MVT::Other)
1466         return N->getOperand(i);
1467   }
1468   return SDValue();
1469 }
1470
1471 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1472   // If N has two operands, where one has an input chain equal to the other,
1473   // the 'other' chain is redundant.
1474   if (N->getNumOperands() == 2) {
1475     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1476       return N->getOperand(0);
1477     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1478       return N->getOperand(1);
1479   }
1480
1481   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1482   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1483   SmallPtrSet<SDNode*, 16> SeenOps;
1484   bool Changed = false;             // If we should replace this token factor.
1485
1486   // Start out with this token factor.
1487   TFs.push_back(N);
1488
1489   // Iterate through token factors.  The TFs grows when new token factors are
1490   // encountered.
1491   for (unsigned i = 0; i < TFs.size(); ++i) {
1492     SDNode *TF = TFs[i];
1493
1494     // Check each of the operands.
1495     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1496       SDValue Op = TF->getOperand(i);
1497
1498       switch (Op.getOpcode()) {
1499       case ISD::EntryToken:
1500         // Entry tokens don't need to be added to the list. They are
1501         // redundant.
1502         Changed = true;
1503         break;
1504
1505       case ISD::TokenFactor:
1506         if (Op.hasOneUse() &&
1507             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1508           // Queue up for processing.
1509           TFs.push_back(Op.getNode());
1510           // Clean up in case the token factor is removed.
1511           AddToWorklist(Op.getNode());
1512           Changed = true;
1513           break;
1514         }
1515         // Fall thru
1516
1517       default:
1518         // Only add if it isn't already in the list.
1519         if (SeenOps.insert(Op.getNode()).second)
1520           Ops.push_back(Op);
1521         else
1522           Changed = true;
1523         break;
1524       }
1525     }
1526   }
1527
1528   SDValue Result;
1529
1530   // If we've changed things around then replace token factor.
1531   if (Changed) {
1532     if (Ops.empty()) {
1533       // The entry token is the only possible outcome.
1534       Result = DAG.getEntryNode();
1535     } else {
1536       // New and improved token factor.
1537       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1538     }
1539
1540     // Add users to worklist if AA is enabled, since it may introduce
1541     // a lot of new chained token factors while removing memory deps.
1542     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1543       : DAG.getSubtarget().useAA();
1544     return CombineTo(N, Result, UseAA /*add to worklist*/);
1545   }
1546
1547   return Result;
1548 }
1549
1550 /// MERGE_VALUES can always be eliminated.
1551 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1552   WorklistRemover DeadNodes(*this);
1553   // Replacing results may cause a different MERGE_VALUES to suddenly
1554   // be CSE'd with N, and carry its uses with it. Iterate until no
1555   // uses remain, to ensure that the node can be safely deleted.
1556   // First add the users of this node to the work list so that they
1557   // can be tried again once they have new operands.
1558   AddUsersToWorklist(N);
1559   do {
1560     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1561       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1562   } while (!N->use_empty());
1563   deleteAndRecombine(N);
1564   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1565 }
1566
1567 SDValue DAGCombiner::visitADD(SDNode *N) {
1568   SDValue N0 = N->getOperand(0);
1569   SDValue N1 = N->getOperand(1);
1570   EVT VT = N0.getValueType();
1571
1572   // fold vector ops
1573   if (VT.isVector()) {
1574     SDValue FoldedVOp = SimplifyVBinOp(N);
1575     if (FoldedVOp.getNode()) return FoldedVOp;
1576
1577     // fold (add x, 0) -> x, vector edition
1578     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1579       return N0;
1580     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1581       return N1;
1582   }
1583
1584   // fold (add x, undef) -> undef
1585   if (N0.getOpcode() == ISD::UNDEF)
1586     return N0;
1587   if (N1.getOpcode() == ISD::UNDEF)
1588     return N1;
1589   // fold (add c1, c2) -> c1+c2
1590   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1591   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1592   if (N0C && N1C)
1593     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1594   // canonicalize constant to RHS
1595   if (N0C && !N1C)
1596     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1597   // fold (add x, 0) -> x
1598   if (N1C && N1C->isNullValue())
1599     return N0;
1600   // fold (add Sym, c) -> Sym+c
1601   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1602     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1603         GA->getOpcode() == ISD::GlobalAddress)
1604       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1605                                   GA->getOffset() +
1606                                     (uint64_t)N1C->getSExtValue());
1607   // fold ((c1-A)+c2) -> (c1+c2)-A
1608   if (N1C && N0.getOpcode() == ISD::SUB)
1609     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1610       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1611                          DAG.getConstant(N1C->getAPIntValue()+
1612                                          N0C->getAPIntValue(), VT),
1613                          N0.getOperand(1));
1614   // reassociate add
1615   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1616   if (RADD.getNode())
1617     return RADD;
1618   // fold ((0-A) + B) -> B-A
1619   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1620       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1621     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1622   // fold (A + (0-B)) -> A-B
1623   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1624       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1625     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1626   // fold (A+(B-A)) -> B
1627   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1628     return N1.getOperand(0);
1629   // fold ((B-A)+A) -> B
1630   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1631     return N0.getOperand(0);
1632   // fold (A+(B-(A+C))) to (B-C)
1633   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1634       N0 == N1.getOperand(1).getOperand(0))
1635     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1636                        N1.getOperand(1).getOperand(1));
1637   // fold (A+(B-(C+A))) to (B-C)
1638   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1639       N0 == N1.getOperand(1).getOperand(1))
1640     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1641                        N1.getOperand(1).getOperand(0));
1642   // fold (A+((B-A)+or-C)) to (B+or-C)
1643   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1644       N1.getOperand(0).getOpcode() == ISD::SUB &&
1645       N0 == N1.getOperand(0).getOperand(1))
1646     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1647                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1648
1649   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1650   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1651     SDValue N00 = N0.getOperand(0);
1652     SDValue N01 = N0.getOperand(1);
1653     SDValue N10 = N1.getOperand(0);
1654     SDValue N11 = N1.getOperand(1);
1655
1656     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1657       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1658                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1659                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1660   }
1661
1662   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1663     return SDValue(N, 0);
1664
1665   // fold (a+b) -> (a|b) iff a and b share no bits.
1666   if (VT.isInteger() && !VT.isVector()) {
1667     APInt LHSZero, LHSOne;
1668     APInt RHSZero, RHSOne;
1669     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1670
1671     if (LHSZero.getBoolValue()) {
1672       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1673
1674       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1675       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1676       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1677         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1678           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1679       }
1680     }
1681   }
1682
1683   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1684   if (N1.getOpcode() == ISD::SHL &&
1685       N1.getOperand(0).getOpcode() == ISD::SUB)
1686     if (ConstantSDNode *C =
1687           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1688       if (C->getAPIntValue() == 0)
1689         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1690                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1691                                        N1.getOperand(0).getOperand(1),
1692                                        N1.getOperand(1)));
1693   if (N0.getOpcode() == ISD::SHL &&
1694       N0.getOperand(0).getOpcode() == ISD::SUB)
1695     if (ConstantSDNode *C =
1696           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1697       if (C->getAPIntValue() == 0)
1698         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1699                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1700                                        N0.getOperand(0).getOperand(1),
1701                                        N0.getOperand(1)));
1702
1703   if (N1.getOpcode() == ISD::AND) {
1704     SDValue AndOp0 = N1.getOperand(0);
1705     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1706     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1707     unsigned DestBits = VT.getScalarType().getSizeInBits();
1708
1709     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1710     // and similar xforms where the inner op is either ~0 or 0.
1711     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1712       SDLoc DL(N);
1713       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1714     }
1715   }
1716
1717   // add (sext i1), X -> sub X, (zext i1)
1718   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1719       N0.getOperand(0).getValueType() == MVT::i1 &&
1720       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1721     SDLoc DL(N);
1722     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1723     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1724   }
1725
1726   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1727   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1728     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1729     if (TN->getVT() == MVT::i1) {
1730       SDLoc DL(N);
1731       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1732                                  DAG.getConstant(1, VT));
1733       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1734     }
1735   }
1736
1737   return SDValue();
1738 }
1739
1740 SDValue DAGCombiner::visitADDC(SDNode *N) {
1741   SDValue N0 = N->getOperand(0);
1742   SDValue N1 = N->getOperand(1);
1743   EVT VT = N0.getValueType();
1744
1745   // If the flag result is dead, turn this into an ADD.
1746   if (!N->hasAnyUseOfValue(1))
1747     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1748                      DAG.getNode(ISD::CARRY_FALSE,
1749                                  SDLoc(N), MVT::Glue));
1750
1751   // canonicalize constant to RHS.
1752   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1753   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1754   if (N0C && !N1C)
1755     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1756
1757   // fold (addc x, 0) -> x + no carry out
1758   if (N1C && N1C->isNullValue())
1759     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1760                                         SDLoc(N), MVT::Glue));
1761
1762   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1763   APInt LHSZero, LHSOne;
1764   APInt RHSZero, RHSOne;
1765   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1766
1767   if (LHSZero.getBoolValue()) {
1768     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1769
1770     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1771     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1772     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1773       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1774                        DAG.getNode(ISD::CARRY_FALSE,
1775                                    SDLoc(N), MVT::Glue));
1776   }
1777
1778   return SDValue();
1779 }
1780
1781 SDValue DAGCombiner::visitADDE(SDNode *N) {
1782   SDValue N0 = N->getOperand(0);
1783   SDValue N1 = N->getOperand(1);
1784   SDValue CarryIn = N->getOperand(2);
1785
1786   // canonicalize constant to RHS
1787   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1788   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1789   if (N0C && !N1C)
1790     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1791                        N1, N0, CarryIn);
1792
1793   // fold (adde x, y, false) -> (addc x, y)
1794   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1795     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1796
1797   return SDValue();
1798 }
1799
1800 // Since it may not be valid to emit a fold to zero for vector initializers
1801 // check if we can before folding.
1802 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1803                              SelectionDAG &DAG,
1804                              bool LegalOperations, bool LegalTypes) {
1805   if (!VT.isVector())
1806     return DAG.getConstant(0, VT);
1807   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1808     return DAG.getConstant(0, VT);
1809   return SDValue();
1810 }
1811
1812 SDValue DAGCombiner::visitSUB(SDNode *N) {
1813   SDValue N0 = N->getOperand(0);
1814   SDValue N1 = N->getOperand(1);
1815   EVT VT = N0.getValueType();
1816
1817   // fold vector ops
1818   if (VT.isVector()) {
1819     SDValue FoldedVOp = SimplifyVBinOp(N);
1820     if (FoldedVOp.getNode()) return FoldedVOp;
1821
1822     // fold (sub x, 0) -> x, vector edition
1823     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1824       return N0;
1825   }
1826
1827   // fold (sub x, x) -> 0
1828   // FIXME: Refactor this and xor and other similar operations together.
1829   if (N0 == N1)
1830     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1831   // fold (sub c1, c2) -> c1-c2
1832   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1833   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1834   if (N0C && N1C)
1835     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1836   // fold (sub x, c) -> (add x, -c)
1837   if (N1C)
1838     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1839                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1840   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1841   if (N0C && N0C->isAllOnesValue())
1842     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1843   // fold A-(A-B) -> B
1844   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1845     return N1.getOperand(1);
1846   // fold (A+B)-A -> B
1847   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1848     return N0.getOperand(1);
1849   // fold (A+B)-B -> A
1850   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1851     return N0.getOperand(0);
1852   // fold C2-(A+C1) -> (C2-C1)-A
1853   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1854     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1855   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1856     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1857                                    VT);
1858     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1859                        N1.getOperand(0));
1860   }
1861   // fold ((A+(B+or-C))-B) -> A+or-C
1862   if (N0.getOpcode() == ISD::ADD &&
1863       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1864        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1865       N0.getOperand(1).getOperand(0) == N1)
1866     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1867                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1868   // fold ((A+(C+B))-B) -> A+C
1869   if (N0.getOpcode() == ISD::ADD &&
1870       N0.getOperand(1).getOpcode() == ISD::ADD &&
1871       N0.getOperand(1).getOperand(1) == N1)
1872     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1873                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1874   // fold ((A-(B-C))-C) -> A-B
1875   if (N0.getOpcode() == ISD::SUB &&
1876       N0.getOperand(1).getOpcode() == ISD::SUB &&
1877       N0.getOperand(1).getOperand(1) == N1)
1878     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1879                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1880
1881   // If either operand of a sub is undef, the result is undef
1882   if (N0.getOpcode() == ISD::UNDEF)
1883     return N0;
1884   if (N1.getOpcode() == ISD::UNDEF)
1885     return N1;
1886
1887   // If the relocation model supports it, consider symbol offsets.
1888   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1889     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1890       // fold (sub Sym, c) -> Sym-c
1891       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1892         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1893                                     GA->getOffset() -
1894                                       (uint64_t)N1C->getSExtValue());
1895       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1896       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1897         if (GA->getGlobal() == GB->getGlobal())
1898           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1899                                  VT);
1900     }
1901
1902   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1903   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1904     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1905     if (TN->getVT() == MVT::i1) {
1906       SDLoc DL(N);
1907       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1908                                  DAG.getConstant(1, VT));
1909       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1910     }
1911   }
1912
1913   return SDValue();
1914 }
1915
1916 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1917   SDValue N0 = N->getOperand(0);
1918   SDValue N1 = N->getOperand(1);
1919   EVT VT = N0.getValueType();
1920
1921   // If the flag result is dead, turn this into an SUB.
1922   if (!N->hasAnyUseOfValue(1))
1923     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1924                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1925                                  MVT::Glue));
1926
1927   // fold (subc x, x) -> 0 + no borrow
1928   if (N0 == N1)
1929     return CombineTo(N, DAG.getConstant(0, VT),
1930                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1931                                  MVT::Glue));
1932
1933   // fold (subc x, 0) -> x + no borrow
1934   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1935   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1936   if (N1C && N1C->isNullValue())
1937     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1938                                         MVT::Glue));
1939
1940   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1941   if (N0C && N0C->isAllOnesValue())
1942     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1943                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1944                                  MVT::Glue));
1945
1946   return SDValue();
1947 }
1948
1949 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1950   SDValue N0 = N->getOperand(0);
1951   SDValue N1 = N->getOperand(1);
1952   SDValue CarryIn = N->getOperand(2);
1953
1954   // fold (sube x, y, false) -> (subc x, y)
1955   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1956     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1957
1958   return SDValue();
1959 }
1960
1961 SDValue DAGCombiner::visitMUL(SDNode *N) {
1962   SDValue N0 = N->getOperand(0);
1963   SDValue N1 = N->getOperand(1);
1964   EVT VT = N0.getValueType();
1965
1966   // fold (mul x, undef) -> 0
1967   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1968     return DAG.getConstant(0, VT);
1969
1970   bool N0IsConst = false;
1971   bool N1IsConst = false;
1972   APInt ConstValue0, ConstValue1;
1973   // fold vector ops
1974   if (VT.isVector()) {
1975     SDValue FoldedVOp = SimplifyVBinOp(N);
1976     if (FoldedVOp.getNode()) return FoldedVOp;
1977
1978     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1979     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1980   } else {
1981     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1982     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1983                             : APInt();
1984     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1985     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1986                             : APInt();
1987   }
1988
1989   // fold (mul c1, c2) -> c1*c2
1990   if (N0IsConst && N1IsConst)
1991     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1992
1993   // canonicalize constant to RHS
1994   if (N0IsConst && !N1IsConst)
1995     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1996   // fold (mul x, 0) -> 0
1997   if (N1IsConst && ConstValue1 == 0)
1998     return N1;
1999   // We require a splat of the entire scalar bit width for non-contiguous
2000   // bit patterns.
2001   bool IsFullSplat =
2002     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2003   // fold (mul x, 1) -> x
2004   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2005     return N0;
2006   // fold (mul x, -1) -> 0-x
2007   if (N1IsConst && ConstValue1.isAllOnesValue())
2008     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2009                        DAG.getConstant(0, VT), N0);
2010   // fold (mul x, (1 << c)) -> x << c
2011   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2012     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2013                        DAG.getConstant(ConstValue1.logBase2(),
2014                                        getShiftAmountTy(N0.getValueType())));
2015   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2016   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2017     unsigned Log2Val = (-ConstValue1).logBase2();
2018     // FIXME: If the input is something that is easily negated (e.g. a
2019     // single-use add), we should put the negate there.
2020     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021                        DAG.getConstant(0, VT),
2022                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2023                             DAG.getConstant(Log2Val,
2024                                       getShiftAmountTy(N0.getValueType()))));
2025   }
2026
2027   APInt Val;
2028   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2029   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2030       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2031                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2032     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2033                              N1, N0.getOperand(1));
2034     AddToWorklist(C3.getNode());
2035     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2036                        N0.getOperand(0), C3);
2037   }
2038
2039   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2040   // use.
2041   {
2042     SDValue Sh(nullptr,0), Y(nullptr,0);
2043     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2044     if (N0.getOpcode() == ISD::SHL &&
2045         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2046                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2047         N0.getNode()->hasOneUse()) {
2048       Sh = N0; Y = N1;
2049     } else if (N1.getOpcode() == ISD::SHL &&
2050                isa<ConstantSDNode>(N1.getOperand(1)) &&
2051                N1.getNode()->hasOneUse()) {
2052       Sh = N1; Y = N0;
2053     }
2054
2055     if (Sh.getNode()) {
2056       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2057                                 Sh.getOperand(0), Y);
2058       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2059                          Mul, Sh.getOperand(1));
2060     }
2061   }
2062
2063   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2064   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2065       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2066                      isa<ConstantSDNode>(N0.getOperand(1))))
2067     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2068                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2069                                    N0.getOperand(0), N1),
2070                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2071                                    N0.getOperand(1), N1));
2072
2073   // reassociate mul
2074   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2075   if (RMUL.getNode())
2076     return RMUL;
2077
2078   return SDValue();
2079 }
2080
2081 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2082   SDValue N0 = N->getOperand(0);
2083   SDValue N1 = N->getOperand(1);
2084   EVT VT = N->getValueType(0);
2085
2086   // fold vector ops
2087   if (VT.isVector()) {
2088     SDValue FoldedVOp = SimplifyVBinOp(N);
2089     if (FoldedVOp.getNode()) return FoldedVOp;
2090   }
2091
2092   // fold (sdiv c1, c2) -> c1/c2
2093   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2094   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2095   if (N0C && N1C && !N1C->isNullValue())
2096     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2097   // fold (sdiv X, 1) -> X
2098   if (N1C && N1C->getAPIntValue() == 1LL)
2099     return N0;
2100   // fold (sdiv X, -1) -> 0-X
2101   if (N1C && N1C->isAllOnesValue())
2102     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2103                        DAG.getConstant(0, VT), N0);
2104   // If we know the sign bits of both operands are zero, strength reduce to a
2105   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2106   if (!VT.isVector()) {
2107     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2108       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2109                          N0, N1);
2110   }
2111
2112   // fold (sdiv X, pow2) -> simple ops after legalize
2113   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2114                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2115     // If dividing by powers of two is cheap, then don't perform the following
2116     // fold.
2117     if (TLI.isPow2SDivCheap())
2118       return SDValue();
2119
2120     // Target-specific implementation of sdiv x, pow2.
2121     SDValue Res = BuildSDIVPow2(N);
2122     if (Res.getNode())
2123       return Res;
2124
2125     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2126
2127     // Splat the sign bit into the register
2128     SDValue SGN =
2129         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2130                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2131                                     getShiftAmountTy(N0.getValueType())));
2132     AddToWorklist(SGN.getNode());
2133
2134     // Add (N0 < 0) ? abs2 - 1 : 0;
2135     SDValue SRL =
2136         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2137                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2138                                     getShiftAmountTy(SGN.getValueType())));
2139     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2140     AddToWorklist(SRL.getNode());
2141     AddToWorklist(ADD.getNode());    // Divide by pow2
2142     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2143                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2144
2145     // If we're dividing by a positive value, we're done.  Otherwise, we must
2146     // negate the result.
2147     if (N1C->getAPIntValue().isNonNegative())
2148       return SRA;
2149
2150     AddToWorklist(SRA.getNode());
2151     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2152   }
2153
2154   // if integer divide is expensive and we satisfy the requirements, emit an
2155   // alternate sequence.
2156   if (N1C && !TLI.isIntDivCheap()) {
2157     SDValue Op = BuildSDIV(N);
2158     if (Op.getNode()) return Op;
2159   }
2160
2161   // undef / X -> 0
2162   if (N0.getOpcode() == ISD::UNDEF)
2163     return DAG.getConstant(0, VT);
2164   // X / undef -> undef
2165   if (N1.getOpcode() == ISD::UNDEF)
2166     return N1;
2167
2168   return SDValue();
2169 }
2170
2171 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2172   SDValue N0 = N->getOperand(0);
2173   SDValue N1 = N->getOperand(1);
2174   EVT VT = N->getValueType(0);
2175
2176   // fold vector ops
2177   if (VT.isVector()) {
2178     SDValue FoldedVOp = SimplifyVBinOp(N);
2179     if (FoldedVOp.getNode()) return FoldedVOp;
2180   }
2181
2182   // fold (udiv c1, c2) -> c1/c2
2183   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2184   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2185   if (N0C && N1C && !N1C->isNullValue())
2186     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2187   // fold (udiv x, (1 << c)) -> x >>u c
2188   if (N1C && N1C->getAPIntValue().isPowerOf2())
2189     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2190                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2191                                        getShiftAmountTy(N0.getValueType())));
2192   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2193   if (N1.getOpcode() == ISD::SHL) {
2194     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2195       if (SHC->getAPIntValue().isPowerOf2()) {
2196         EVT ADDVT = N1.getOperand(1).getValueType();
2197         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2198                                   N1.getOperand(1),
2199                                   DAG.getConstant(SHC->getAPIntValue()
2200                                                                   .logBase2(),
2201                                                   ADDVT));
2202         AddToWorklist(Add.getNode());
2203         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2204       }
2205     }
2206   }
2207   // fold (udiv x, c) -> alternate
2208   if (N1C && !TLI.isIntDivCheap()) {
2209     SDValue Op = BuildUDIV(N);
2210     if (Op.getNode()) return Op;
2211   }
2212
2213   // undef / X -> 0
2214   if (N0.getOpcode() == ISD::UNDEF)
2215     return DAG.getConstant(0, VT);
2216   // X / undef -> undef
2217   if (N1.getOpcode() == ISD::UNDEF)
2218     return N1;
2219
2220   return SDValue();
2221 }
2222
2223 SDValue DAGCombiner::visitSREM(SDNode *N) {
2224   SDValue N0 = N->getOperand(0);
2225   SDValue N1 = N->getOperand(1);
2226   EVT VT = N->getValueType(0);
2227
2228   // fold (srem c1, c2) -> c1%c2
2229   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2230   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2231   if (N0C && N1C && !N1C->isNullValue())
2232     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2233   // If we know the sign bits of both operands are zero, strength reduce to a
2234   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2235   if (!VT.isVector()) {
2236     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2237       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2238   }
2239
2240   // If X/C can be simplified by the division-by-constant logic, lower
2241   // X%C to the equivalent of X-X/C*C.
2242   if (N1C && !N1C->isNullValue()) {
2243     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2244     AddToWorklist(Div.getNode());
2245     SDValue OptimizedDiv = combine(Div.getNode());
2246     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2247       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2248                                 OptimizedDiv, N1);
2249       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2250       AddToWorklist(Mul.getNode());
2251       return Sub;
2252     }
2253   }
2254
2255   // undef % X -> 0
2256   if (N0.getOpcode() == ISD::UNDEF)
2257     return DAG.getConstant(0, VT);
2258   // X % undef -> undef
2259   if (N1.getOpcode() == ISD::UNDEF)
2260     return N1;
2261
2262   return SDValue();
2263 }
2264
2265 SDValue DAGCombiner::visitUREM(SDNode *N) {
2266   SDValue N0 = N->getOperand(0);
2267   SDValue N1 = N->getOperand(1);
2268   EVT VT = N->getValueType(0);
2269
2270   // fold (urem c1, c2) -> c1%c2
2271   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2272   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2273   if (N0C && N1C && !N1C->isNullValue())
2274     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2275   // fold (urem x, pow2) -> (and x, pow2-1)
2276   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2277     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2278                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2279   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2280   if (N1.getOpcode() == ISD::SHL) {
2281     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2282       if (SHC->getAPIntValue().isPowerOf2()) {
2283         SDValue Add =
2284           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2285                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2286                                  VT));
2287         AddToWorklist(Add.getNode());
2288         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2289       }
2290     }
2291   }
2292
2293   // If X/C can be simplified by the division-by-constant logic, lower
2294   // X%C to the equivalent of X-X/C*C.
2295   if (N1C && !N1C->isNullValue()) {
2296     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2297     AddToWorklist(Div.getNode());
2298     SDValue OptimizedDiv = combine(Div.getNode());
2299     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2300       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2301                                 OptimizedDiv, N1);
2302       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2303       AddToWorklist(Mul.getNode());
2304       return Sub;
2305     }
2306   }
2307
2308   // undef % X -> 0
2309   if (N0.getOpcode() == ISD::UNDEF)
2310     return DAG.getConstant(0, VT);
2311   // X % undef -> undef
2312   if (N1.getOpcode() == ISD::UNDEF)
2313     return N1;
2314
2315   return SDValue();
2316 }
2317
2318 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2319   SDValue N0 = N->getOperand(0);
2320   SDValue N1 = N->getOperand(1);
2321   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2322   EVT VT = N->getValueType(0);
2323   SDLoc DL(N);
2324
2325   // fold (mulhs x, 0) -> 0
2326   if (N1C && N1C->isNullValue())
2327     return N1;
2328   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2329   if (N1C && N1C->getAPIntValue() == 1)
2330     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2331                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2332                                        getShiftAmountTy(N0.getValueType())));
2333   // fold (mulhs x, undef) -> 0
2334   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2335     return DAG.getConstant(0, VT);
2336
2337   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2338   // plus a shift.
2339   if (VT.isSimple() && !VT.isVector()) {
2340     MVT Simple = VT.getSimpleVT();
2341     unsigned SimpleSize = Simple.getSizeInBits();
2342     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2343     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2344       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2345       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2346       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2347       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2348             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2349       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2350     }
2351   }
2352
2353   return SDValue();
2354 }
2355
2356 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2357   SDValue N0 = N->getOperand(0);
2358   SDValue N1 = N->getOperand(1);
2359   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2360   EVT VT = N->getValueType(0);
2361   SDLoc DL(N);
2362
2363   // fold (mulhu x, 0) -> 0
2364   if (N1C && N1C->isNullValue())
2365     return N1;
2366   // fold (mulhu x, 1) -> 0
2367   if (N1C && N1C->getAPIntValue() == 1)
2368     return DAG.getConstant(0, N0.getValueType());
2369   // fold (mulhu x, undef) -> 0
2370   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2371     return DAG.getConstant(0, VT);
2372
2373   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2374   // plus a shift.
2375   if (VT.isSimple() && !VT.isVector()) {
2376     MVT Simple = VT.getSimpleVT();
2377     unsigned SimpleSize = Simple.getSizeInBits();
2378     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2379     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2380       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2381       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2382       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2383       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2384             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2385       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2386     }
2387   }
2388
2389   return SDValue();
2390 }
2391
2392 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2393 /// give the opcodes for the two computations that are being performed. Return
2394 /// true if a simplification was made.
2395 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2396                                                 unsigned HiOp) {
2397   // If the high half is not needed, just compute the low half.
2398   bool HiExists = N->hasAnyUseOfValue(1);
2399   if (!HiExists &&
2400       (!LegalOperations ||
2401        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2402     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2403     return CombineTo(N, Res, Res);
2404   }
2405
2406   // If the low half is not needed, just compute the high half.
2407   bool LoExists = N->hasAnyUseOfValue(0);
2408   if (!LoExists &&
2409       (!LegalOperations ||
2410        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2411     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2412     return CombineTo(N, Res, Res);
2413   }
2414
2415   // If both halves are used, return as it is.
2416   if (LoExists && HiExists)
2417     return SDValue();
2418
2419   // If the two computed results can be simplified separately, separate them.
2420   if (LoExists) {
2421     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2422     AddToWorklist(Lo.getNode());
2423     SDValue LoOpt = combine(Lo.getNode());
2424     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2425         (!LegalOperations ||
2426          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2427       return CombineTo(N, LoOpt, LoOpt);
2428   }
2429
2430   if (HiExists) {
2431     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2432     AddToWorklist(Hi.getNode());
2433     SDValue HiOpt = combine(Hi.getNode());
2434     if (HiOpt.getNode() && HiOpt != Hi &&
2435         (!LegalOperations ||
2436          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2437       return CombineTo(N, HiOpt, HiOpt);
2438   }
2439
2440   return SDValue();
2441 }
2442
2443 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2444   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2445   if (Res.getNode()) return Res;
2446
2447   EVT VT = N->getValueType(0);
2448   SDLoc DL(N);
2449
2450   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2451   // plus a shift.
2452   if (VT.isSimple() && !VT.isVector()) {
2453     MVT Simple = VT.getSimpleVT();
2454     unsigned SimpleSize = Simple.getSizeInBits();
2455     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2456     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2457       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2458       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2459       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2460       // Compute the high part as N1.
2461       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2462             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2463       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2464       // Compute the low part as N0.
2465       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2466       return CombineTo(N, Lo, Hi);
2467     }
2468   }
2469
2470   return SDValue();
2471 }
2472
2473 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2474   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2475   if (Res.getNode()) return Res;
2476
2477   EVT VT = N->getValueType(0);
2478   SDLoc DL(N);
2479
2480   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2481   // plus a shift.
2482   if (VT.isSimple() && !VT.isVector()) {
2483     MVT Simple = VT.getSimpleVT();
2484     unsigned SimpleSize = Simple.getSizeInBits();
2485     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2486     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2487       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2488       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2489       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2490       // Compute the high part as N1.
2491       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2492             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2493       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2494       // Compute the low part as N0.
2495       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2496       return CombineTo(N, Lo, Hi);
2497     }
2498   }
2499
2500   return SDValue();
2501 }
2502
2503 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2504   // (smulo x, 2) -> (saddo x, x)
2505   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2506     if (C2->getAPIntValue() == 2)
2507       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2508                          N->getOperand(0), N->getOperand(0));
2509
2510   return SDValue();
2511 }
2512
2513 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2514   // (umulo x, 2) -> (uaddo x, x)
2515   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2516     if (C2->getAPIntValue() == 2)
2517       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2518                          N->getOperand(0), N->getOperand(0));
2519
2520   return SDValue();
2521 }
2522
2523 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2524   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2525   if (Res.getNode()) return Res;
2526
2527   return SDValue();
2528 }
2529
2530 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2531   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2532   if (Res.getNode()) return Res;
2533
2534   return SDValue();
2535 }
2536
2537 /// If this is a binary operator with two operands of the same opcode, try to
2538 /// simplify it.
2539 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2540   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2541   EVT VT = N0.getValueType();
2542   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2543
2544   // Bail early if none of these transforms apply.
2545   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2546
2547   // For each of OP in AND/OR/XOR:
2548   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2549   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2550   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2551   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2552   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2553   //
2554   // do not sink logical op inside of a vector extend, since it may combine
2555   // into a vsetcc.
2556   EVT Op0VT = N0.getOperand(0).getValueType();
2557   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2558        N0.getOpcode() == ISD::SIGN_EXTEND ||
2559        N0.getOpcode() == ISD::BSWAP ||
2560        // Avoid infinite looping with PromoteIntBinOp.
2561        (N0.getOpcode() == ISD::ANY_EXTEND &&
2562         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2563        (N0.getOpcode() == ISD::TRUNCATE &&
2564         (!TLI.isZExtFree(VT, Op0VT) ||
2565          !TLI.isTruncateFree(Op0VT, VT)) &&
2566         TLI.isTypeLegal(Op0VT))) &&
2567       !VT.isVector() &&
2568       Op0VT == N1.getOperand(0).getValueType() &&
2569       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2570     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2571                                  N0.getOperand(0).getValueType(),
2572                                  N0.getOperand(0), N1.getOperand(0));
2573     AddToWorklist(ORNode.getNode());
2574     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2575   }
2576
2577   // For each of OP in SHL/SRL/SRA/AND...
2578   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2579   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2580   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2581   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2582        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2583       N0.getOperand(1) == N1.getOperand(1)) {
2584     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2585                                  N0.getOperand(0).getValueType(),
2586                                  N0.getOperand(0), N1.getOperand(0));
2587     AddToWorklist(ORNode.getNode());
2588     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2589                        ORNode, N0.getOperand(1));
2590   }
2591
2592   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2593   // Only perform this optimization after type legalization and before
2594   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2595   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2596   // we don't want to undo this promotion.
2597   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2598   // on scalars.
2599   if ((N0.getOpcode() == ISD::BITCAST ||
2600        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2601       Level == AfterLegalizeTypes) {
2602     SDValue In0 = N0.getOperand(0);
2603     SDValue In1 = N1.getOperand(0);
2604     EVT In0Ty = In0.getValueType();
2605     EVT In1Ty = In1.getValueType();
2606     SDLoc DL(N);
2607     // If both incoming values are integers, and the original types are the
2608     // same.
2609     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2610       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2611       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2612       AddToWorklist(Op.getNode());
2613       return BC;
2614     }
2615   }
2616
2617   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2618   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2619   // If both shuffles use the same mask, and both shuffle within a single
2620   // vector, then it is worthwhile to move the swizzle after the operation.
2621   // The type-legalizer generates this pattern when loading illegal
2622   // vector types from memory. In many cases this allows additional shuffle
2623   // optimizations.
2624   // There are other cases where moving the shuffle after the xor/and/or
2625   // is profitable even if shuffles don't perform a swizzle.
2626   // If both shuffles use the same mask, and both shuffles have the same first
2627   // or second operand, then it might still be profitable to move the shuffle
2628   // after the xor/and/or operation.
2629   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2630     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2631     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2632
2633     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2634            "Inputs to shuffles are not the same type");
2635
2636     // Check that both shuffles use the same mask. The masks are known to be of
2637     // the same length because the result vector type is the same.
2638     // Check also that shuffles have only one use to avoid introducing extra
2639     // instructions.
2640     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2641         SVN0->getMask().equals(SVN1->getMask())) {
2642       SDValue ShOp = N0->getOperand(1);
2643
2644       // Don't try to fold this node if it requires introducing a
2645       // build vector of all zeros that might be illegal at this stage.
2646       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2647         if (!LegalTypes)
2648           ShOp = DAG.getConstant(0, VT);
2649         else
2650           ShOp = SDValue();
2651       }
2652
2653       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2654       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2655       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2656       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2657         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2658                                       N0->getOperand(0), N1->getOperand(0));
2659         AddToWorklist(NewNode.getNode());
2660         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2661                                     &SVN0->getMask()[0]);
2662       }
2663
2664       // Don't try to fold this node if it requires introducing a
2665       // build vector of all zeros that might be illegal at this stage.
2666       ShOp = N0->getOperand(0);
2667       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2668         if (!LegalTypes)
2669           ShOp = DAG.getConstant(0, VT);
2670         else
2671           ShOp = SDValue();
2672       }
2673
2674       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2675       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2676       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2677       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2678         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2679                                       N0->getOperand(1), N1->getOperand(1));
2680         AddToWorklist(NewNode.getNode());
2681         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2682                                     &SVN0->getMask()[0]);
2683       }
2684     }
2685   }
2686
2687   return SDValue();
2688 }
2689
2690 /// This contains all DAGCombine rules which reduce two values combined by
2691 /// an And operation to a single value. This makes them reusable in the context
2692 /// of visitSELECT(). Rules involving constants are not included as
2693 /// visitSELECT() already handles those cases.
2694 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2695                                   SDNode *LocReference) {
2696   EVT VT = N1.getValueType();
2697
2698   // fold (and x, undef) -> 0
2699   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2700     return DAG.getConstant(0, VT);
2701   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2702   SDValue LL, LR, RL, RR, CC0, CC1;
2703   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2704     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2705     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2706
2707     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2708         LL.getValueType().isInteger()) {
2709       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2710       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2711         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2712                                      LR.getValueType(), LL, RL);
2713         AddToWorklist(ORNode.getNode());
2714         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2715       }
2716       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2717       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2718         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2719                                       LR.getValueType(), LL, RL);
2720         AddToWorklist(ANDNode.getNode());
2721         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2722       }
2723       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2724       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2725         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2726                                      LR.getValueType(), LL, RL);
2727         AddToWorklist(ORNode.getNode());
2728         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2729       }
2730     }
2731     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2732     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2733         Op0 == Op1 && LL.getValueType().isInteger() &&
2734       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2735                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2736                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2737                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2738       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2739                                     LL, DAG.getConstant(1, LL.getValueType()));
2740       AddToWorklist(ADDNode.getNode());
2741       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2742                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2743     }
2744     // canonicalize equivalent to ll == rl
2745     if (LL == RR && LR == RL) {
2746       Op1 = ISD::getSetCCSwappedOperands(Op1);
2747       std::swap(RL, RR);
2748     }
2749     if (LL == RL && LR == RR) {
2750       bool isInteger = LL.getValueType().isInteger();
2751       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2752       if (Result != ISD::SETCC_INVALID &&
2753           (!LegalOperations ||
2754            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2755             TLI.isOperationLegal(ISD::SETCC,
2756                             getSetCCResultType(N0.getSimpleValueType())))))
2757         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2758                             LL, LR, Result);
2759     }
2760   }
2761
2762   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2763       VT.getSizeInBits() <= 64) {
2764     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2765       APInt ADDC = ADDI->getAPIntValue();
2766       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2767         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2768         // immediate for an add, but it is legal if its top c2 bits are set,
2769         // transform the ADD so the immediate doesn't need to be materialized
2770         // in a register.
2771         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2772           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2773                                              SRLI->getZExtValue());
2774           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2775             ADDC |= Mask;
2776             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2777               SDValue NewAdd =
2778                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2779                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2780               CombineTo(N0.getNode(), NewAdd);
2781               // Return N so it doesn't get rechecked!
2782               return SDValue(LocReference, 0);
2783             }
2784           }
2785         }
2786       }
2787     }
2788   }
2789
2790   return SDValue();
2791 }
2792
2793 SDValue DAGCombiner::visitAND(SDNode *N) {
2794   SDValue N0 = N->getOperand(0);
2795   SDValue N1 = N->getOperand(1);
2796   EVT VT = N1.getValueType();
2797
2798   // fold vector ops
2799   if (VT.isVector()) {
2800     SDValue FoldedVOp = SimplifyVBinOp(N);
2801     if (FoldedVOp.getNode()) return FoldedVOp;
2802
2803     // fold (and x, 0) -> 0, vector edition
2804     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2805       // do not return N0, because undef node may exist in N0
2806       return DAG.getConstant(
2807           APInt::getNullValue(
2808               N0.getValueType().getScalarType().getSizeInBits()),
2809           N0.getValueType());
2810     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2811       // do not return N1, because undef node may exist in N1
2812       return DAG.getConstant(
2813           APInt::getNullValue(
2814               N1.getValueType().getScalarType().getSizeInBits()),
2815           N1.getValueType());
2816
2817     // fold (and x, -1) -> x, vector edition
2818     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2819       return N1;
2820     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2821       return N0;
2822   }
2823
2824   // fold (and c1, c2) -> c1&c2
2825   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2826   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2827   if (N0C && N1C)
2828     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2829   // canonicalize constant to RHS
2830   if (N0C && !N1C)
2831     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2832   // fold (and x, -1) -> x
2833   if (N1C && N1C->isAllOnesValue())
2834     return N0;
2835   // if (and x, c) is known to be zero, return 0
2836   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2837   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2838                                    APInt::getAllOnesValue(BitWidth)))
2839     return DAG.getConstant(0, VT);
2840   // reassociate and
2841   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2842   if (RAND.getNode())
2843     return RAND;
2844   // fold (and (or x, C), D) -> D if (C & D) == D
2845   if (N1C && N0.getOpcode() == ISD::OR)
2846     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2847       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2848         return N1;
2849   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2850   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2851     SDValue N0Op0 = N0.getOperand(0);
2852     APInt Mask = ~N1C->getAPIntValue();
2853     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2854     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2855       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2856                                  N0.getValueType(), N0Op0);
2857
2858       // Replace uses of the AND with uses of the Zero extend node.
2859       CombineTo(N, Zext);
2860
2861       // We actually want to replace all uses of the any_extend with the
2862       // zero_extend, to avoid duplicating things.  This will later cause this
2863       // AND to be folded.
2864       CombineTo(N0.getNode(), Zext);
2865       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2866     }
2867   }
2868   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2869   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2870   // already be zero by virtue of the width of the base type of the load.
2871   //
2872   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2873   // more cases.
2874   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2875        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2876       N0.getOpcode() == ISD::LOAD) {
2877     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2878                                          N0 : N0.getOperand(0) );
2879
2880     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2881     // This can be a pure constant or a vector splat, in which case we treat the
2882     // vector as a scalar and use the splat value.
2883     APInt Constant = APInt::getNullValue(1);
2884     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2885       Constant = C->getAPIntValue();
2886     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2887       APInt SplatValue, SplatUndef;
2888       unsigned SplatBitSize;
2889       bool HasAnyUndefs;
2890       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2891                                              SplatBitSize, HasAnyUndefs);
2892       if (IsSplat) {
2893         // Undef bits can contribute to a possible optimisation if set, so
2894         // set them.
2895         SplatValue |= SplatUndef;
2896
2897         // The splat value may be something like "0x00FFFFFF", which means 0 for
2898         // the first vector value and FF for the rest, repeating. We need a mask
2899         // that will apply equally to all members of the vector, so AND all the
2900         // lanes of the constant together.
2901         EVT VT = Vector->getValueType(0);
2902         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2903
2904         // If the splat value has been compressed to a bitlength lower
2905         // than the size of the vector lane, we need to re-expand it to
2906         // the lane size.
2907         if (BitWidth > SplatBitSize)
2908           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2909                SplatBitSize < BitWidth;
2910                SplatBitSize = SplatBitSize * 2)
2911             SplatValue |= SplatValue.shl(SplatBitSize);
2912
2913         Constant = APInt::getAllOnesValue(BitWidth);
2914         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2915           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2916       }
2917     }
2918
2919     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2920     // actually legal and isn't going to get expanded, else this is a false
2921     // optimisation.
2922     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2923                                                     Load->getValueType(0),
2924                                                     Load->getMemoryVT());
2925
2926     // Resize the constant to the same size as the original memory access before
2927     // extension. If it is still the AllOnesValue then this AND is completely
2928     // unneeded.
2929     Constant =
2930       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2931
2932     bool B;
2933     switch (Load->getExtensionType()) {
2934     default: B = false; break;
2935     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2936     case ISD::ZEXTLOAD:
2937     case ISD::NON_EXTLOAD: B = true; break;
2938     }
2939
2940     if (B && Constant.isAllOnesValue()) {
2941       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2942       // preserve semantics once we get rid of the AND.
2943       SDValue NewLoad(Load, 0);
2944       if (Load->getExtensionType() == ISD::EXTLOAD) {
2945         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2946                               Load->getValueType(0), SDLoc(Load),
2947                               Load->getChain(), Load->getBasePtr(),
2948                               Load->getOffset(), Load->getMemoryVT(),
2949                               Load->getMemOperand());
2950         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2951         if (Load->getNumValues() == 3) {
2952           // PRE/POST_INC loads have 3 values.
2953           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2954                            NewLoad.getValue(2) };
2955           CombineTo(Load, To, 3, true);
2956         } else {
2957           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2958         }
2959       }
2960
2961       // Fold the AND away, taking care not to fold to the old load node if we
2962       // replaced it.
2963       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2964
2965       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2966     }
2967   }
2968
2969   // fold (and (load x), 255) -> (zextload x, i8)
2970   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2971   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2972   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2973               (N0.getOpcode() == ISD::ANY_EXTEND &&
2974                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2975     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2976     LoadSDNode *LN0 = HasAnyExt
2977       ? cast<LoadSDNode>(N0.getOperand(0))
2978       : cast<LoadSDNode>(N0);
2979     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2980         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2981       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2982       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2983         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2984         EVT LoadedVT = LN0->getMemoryVT();
2985         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2986
2987         if (ExtVT == LoadedVT &&
2988             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2989                                                     ExtVT))) {
2990
2991           SDValue NewLoad =
2992             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2993                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2994                            LN0->getMemOperand());
2995           AddToWorklist(N);
2996           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2997           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2998         }
2999
3000         // Do not change the width of a volatile load.
3001         // Do not generate loads of non-round integer types since these can
3002         // be expensive (and would be wrong if the type is not byte sized).
3003         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3004             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3005                                                     ExtVT))) {
3006           EVT PtrType = LN0->getOperand(1).getValueType();
3007
3008           unsigned Alignment = LN0->getAlignment();
3009           SDValue NewPtr = LN0->getBasePtr();
3010
3011           // For big endian targets, we need to add an offset to the pointer
3012           // to load the correct bytes.  For little endian systems, we merely
3013           // need to read fewer bytes from the same pointer.
3014           if (TLI.isBigEndian()) {
3015             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3016             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3017             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3018             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3019                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3020             Alignment = MinAlign(Alignment, PtrOff);
3021           }
3022
3023           AddToWorklist(NewPtr.getNode());
3024
3025           SDValue Load =
3026             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3027                            LN0->getChain(), NewPtr,
3028                            LN0->getPointerInfo(),
3029                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3030                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3031           AddToWorklist(N);
3032           CombineTo(LN0, Load, Load.getValue(1));
3033           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3034         }
3035       }
3036     }
3037   }
3038
3039   if (SDValue Combined = visitANDLike(N0, N1, N))
3040     return Combined;
3041
3042   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3043   if (N0.getOpcode() == N1.getOpcode()) {
3044     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3045     if (Tmp.getNode()) return Tmp;
3046   }
3047
3048   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3049   // fold (and (sra)) -> (and (srl)) when possible.
3050   if (!VT.isVector() &&
3051       SimplifyDemandedBits(SDValue(N, 0)))
3052     return SDValue(N, 0);
3053
3054   // fold (zext_inreg (extload x)) -> (zextload x)
3055   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3056     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3057     EVT MemVT = LN0->getMemoryVT();
3058     // If we zero all the possible extended bits, then we can turn this into
3059     // a zextload if we are running before legalize or the operation is legal.
3060     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3061     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3062                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3063         ((!LegalOperations && !LN0->isVolatile()) ||
3064          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3065       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3066                                        LN0->getChain(), LN0->getBasePtr(),
3067                                        MemVT, LN0->getMemOperand());
3068       AddToWorklist(N);
3069       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3070       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3071     }
3072   }
3073   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3074   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3075       N0.hasOneUse()) {
3076     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3077     EVT MemVT = LN0->getMemoryVT();
3078     // If we zero all the possible extended bits, then we can turn this into
3079     // a zextload if we are running before legalize or the operation is legal.
3080     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3081     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3082                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3083         ((!LegalOperations && !LN0->isVolatile()) ||
3084          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3085       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3086                                        LN0->getChain(), LN0->getBasePtr(),
3087                                        MemVT, LN0->getMemOperand());
3088       AddToWorklist(N);
3089       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3090       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3091     }
3092   }
3093   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3094   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3095     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3096                                        N0.getOperand(1), false);
3097     if (BSwap.getNode())
3098       return BSwap;
3099   }
3100
3101   return SDValue();
3102 }
3103
3104 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3105 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3106                                         bool DemandHighBits) {
3107   if (!LegalOperations)
3108     return SDValue();
3109
3110   EVT VT = N->getValueType(0);
3111   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3112     return SDValue();
3113   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3114     return SDValue();
3115
3116   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3117   bool LookPassAnd0 = false;
3118   bool LookPassAnd1 = false;
3119   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3120       std::swap(N0, N1);
3121   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3122       std::swap(N0, N1);
3123   if (N0.getOpcode() == ISD::AND) {
3124     if (!N0.getNode()->hasOneUse())
3125       return SDValue();
3126     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3127     if (!N01C || N01C->getZExtValue() != 0xFF00)
3128       return SDValue();
3129     N0 = N0.getOperand(0);
3130     LookPassAnd0 = true;
3131   }
3132
3133   if (N1.getOpcode() == ISD::AND) {
3134     if (!N1.getNode()->hasOneUse())
3135       return SDValue();
3136     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3137     if (!N11C || N11C->getZExtValue() != 0xFF)
3138       return SDValue();
3139     N1 = N1.getOperand(0);
3140     LookPassAnd1 = true;
3141   }
3142
3143   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3144     std::swap(N0, N1);
3145   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3146     return SDValue();
3147   if (!N0.getNode()->hasOneUse() ||
3148       !N1.getNode()->hasOneUse())
3149     return SDValue();
3150
3151   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3152   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3153   if (!N01C || !N11C)
3154     return SDValue();
3155   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3156     return SDValue();
3157
3158   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3159   SDValue N00 = N0->getOperand(0);
3160   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3161     if (!N00.getNode()->hasOneUse())
3162       return SDValue();
3163     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3164     if (!N001C || N001C->getZExtValue() != 0xFF)
3165       return SDValue();
3166     N00 = N00.getOperand(0);
3167     LookPassAnd0 = true;
3168   }
3169
3170   SDValue N10 = N1->getOperand(0);
3171   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3172     if (!N10.getNode()->hasOneUse())
3173       return SDValue();
3174     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3175     if (!N101C || N101C->getZExtValue() != 0xFF00)
3176       return SDValue();
3177     N10 = N10.getOperand(0);
3178     LookPassAnd1 = true;
3179   }
3180
3181   if (N00 != N10)
3182     return SDValue();
3183
3184   // Make sure everything beyond the low halfword gets set to zero since the SRL
3185   // 16 will clear the top bits.
3186   unsigned OpSizeInBits = VT.getSizeInBits();
3187   if (DemandHighBits && OpSizeInBits > 16) {
3188     // If the left-shift isn't masked out then the only way this is a bswap is
3189     // if all bits beyond the low 8 are 0. In that case the entire pattern
3190     // reduces to a left shift anyway: leave it for other parts of the combiner.
3191     if (!LookPassAnd0)
3192       return SDValue();
3193
3194     // However, if the right shift isn't masked out then it might be because
3195     // it's not needed. See if we can spot that too.
3196     if (!LookPassAnd1 &&
3197         !DAG.MaskedValueIsZero(
3198             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3199       return SDValue();
3200   }
3201
3202   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3203   if (OpSizeInBits > 16)
3204     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3205                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3206   return Res;
3207 }
3208
3209 /// Return true if the specified node is an element that makes up a 32-bit
3210 /// packed halfword byteswap.
3211 /// ((x & 0x000000ff) << 8) |
3212 /// ((x & 0x0000ff00) >> 8) |
3213 /// ((x & 0x00ff0000) << 8) |
3214 /// ((x & 0xff000000) >> 8)
3215 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3216   if (!N.getNode()->hasOneUse())
3217     return false;
3218
3219   unsigned Opc = N.getOpcode();
3220   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3221     return false;
3222
3223   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3224   if (!N1C)
3225     return false;
3226
3227   unsigned Num;
3228   switch (N1C->getZExtValue()) {
3229   default:
3230     return false;
3231   case 0xFF:       Num = 0; break;
3232   case 0xFF00:     Num = 1; break;
3233   case 0xFF0000:   Num = 2; break;
3234   case 0xFF000000: Num = 3; break;
3235   }
3236
3237   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3238   SDValue N0 = N.getOperand(0);
3239   if (Opc == ISD::AND) {
3240     if (Num == 0 || Num == 2) {
3241       // (x >> 8) & 0xff
3242       // (x >> 8) & 0xff0000
3243       if (N0.getOpcode() != ISD::SRL)
3244         return false;
3245       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3246       if (!C || C->getZExtValue() != 8)
3247         return false;
3248     } else {
3249       // (x << 8) & 0xff00
3250       // (x << 8) & 0xff000000
3251       if (N0.getOpcode() != ISD::SHL)
3252         return false;
3253       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3254       if (!C || C->getZExtValue() != 8)
3255         return false;
3256     }
3257   } else if (Opc == ISD::SHL) {
3258     // (x & 0xff) << 8
3259     // (x & 0xff0000) << 8
3260     if (Num != 0 && Num != 2)
3261       return false;
3262     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3263     if (!C || C->getZExtValue() != 8)
3264       return false;
3265   } else { // Opc == ISD::SRL
3266     // (x & 0xff00) >> 8
3267     // (x & 0xff000000) >> 8
3268     if (Num != 1 && Num != 3)
3269       return false;
3270     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3271     if (!C || C->getZExtValue() != 8)
3272       return false;
3273   }
3274
3275   if (Parts[Num])
3276     return false;
3277
3278   Parts[Num] = N0.getOperand(0).getNode();
3279   return true;
3280 }
3281
3282 /// Match a 32-bit packed halfword bswap. That is
3283 /// ((x & 0x000000ff) << 8) |
3284 /// ((x & 0x0000ff00) >> 8) |
3285 /// ((x & 0x00ff0000) << 8) |
3286 /// ((x & 0xff000000) >> 8)
3287 /// => (rotl (bswap x), 16)
3288 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3289   if (!LegalOperations)
3290     return SDValue();
3291
3292   EVT VT = N->getValueType(0);
3293   if (VT != MVT::i32)
3294     return SDValue();
3295   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3296     return SDValue();
3297
3298   // Look for either
3299   // (or (or (and), (and)), (or (and), (and)))
3300   // (or (or (or (and), (and)), (and)), (and))
3301   if (N0.getOpcode() != ISD::OR)
3302     return SDValue();
3303   SDValue N00 = N0.getOperand(0);
3304   SDValue N01 = N0.getOperand(1);
3305   SDNode *Parts[4] = {};
3306
3307   if (N1.getOpcode() == ISD::OR &&
3308       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3309     // (or (or (and), (and)), (or (and), (and)))
3310     SDValue N000 = N00.getOperand(0);
3311     if (!isBSwapHWordElement(N000, Parts))
3312       return SDValue();
3313
3314     SDValue N001 = N00.getOperand(1);
3315     if (!isBSwapHWordElement(N001, Parts))
3316       return SDValue();
3317     SDValue N010 = N01.getOperand(0);
3318     if (!isBSwapHWordElement(N010, Parts))
3319       return SDValue();
3320     SDValue N011 = N01.getOperand(1);
3321     if (!isBSwapHWordElement(N011, Parts))
3322       return SDValue();
3323   } else {
3324     // (or (or (or (and), (and)), (and)), (and))
3325     if (!isBSwapHWordElement(N1, Parts))
3326       return SDValue();
3327     if (!isBSwapHWordElement(N01, Parts))
3328       return SDValue();
3329     if (N00.getOpcode() != ISD::OR)
3330       return SDValue();
3331     SDValue N000 = N00.getOperand(0);
3332     if (!isBSwapHWordElement(N000, Parts))
3333       return SDValue();
3334     SDValue N001 = N00.getOperand(1);
3335     if (!isBSwapHWordElement(N001, Parts))
3336       return SDValue();
3337   }
3338
3339   // Make sure the parts are all coming from the same node.
3340   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3341     return SDValue();
3342
3343   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3344                               SDValue(Parts[0],0));
3345
3346   // Result of the bswap should be rotated by 16. If it's not legal, then
3347   // do  (x << 16) | (x >> 16).
3348   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3349   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3350     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3351   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3352     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3353   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3354                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3355                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3356 }
3357
3358 /// This contains all DAGCombine rules which reduce two values combined by
3359 /// an Or operation to a single value \see visitANDLike().
3360 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3361   EVT VT = N1.getValueType();
3362   // fold (or x, undef) -> -1
3363   if (!LegalOperations &&
3364       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3365     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3366     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3367   }
3368   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3369   SDValue LL, LR, RL, RR, CC0, CC1;
3370   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3371     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3372     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3373
3374     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3375         LL.getValueType().isInteger()) {
3376       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3377       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3378       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3379           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3380         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3381                                      LR.getValueType(), LL, RL);
3382         AddToWorklist(ORNode.getNode());
3383         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3384       }
3385       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3386       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3387       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3388           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3389         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3390                                       LR.getValueType(), LL, RL);
3391         AddToWorklist(ANDNode.getNode());
3392         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3393       }
3394     }
3395     // canonicalize equivalent to ll == rl
3396     if (LL == RR && LR == RL) {
3397       Op1 = ISD::getSetCCSwappedOperands(Op1);
3398       std::swap(RL, RR);
3399     }
3400     if (LL == RL && LR == RR) {
3401       bool isInteger = LL.getValueType().isInteger();
3402       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3403       if (Result != ISD::SETCC_INVALID &&
3404           (!LegalOperations ||
3405            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3406             TLI.isOperationLegal(ISD::SETCC,
3407               getSetCCResultType(N0.getValueType())))))
3408         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3409                             LL, LR, Result);
3410     }
3411   }
3412
3413   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3414   if (N0.getOpcode() == ISD::AND &&
3415       N1.getOpcode() == ISD::AND &&
3416       N0.getOperand(1).getOpcode() == ISD::Constant &&
3417       N1.getOperand(1).getOpcode() == ISD::Constant &&
3418       // Don't increase # computations.
3419       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3420     // We can only do this xform if we know that bits from X that are set in C2
3421     // but not in C1 are already zero.  Likewise for Y.
3422     const APInt &LHSMask =
3423       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3424     const APInt &RHSMask =
3425       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3426
3427     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3428         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3429       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3430                               N0.getOperand(0), N1.getOperand(0));
3431       return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3432                          DAG.getConstant(LHSMask | RHSMask, VT));
3433     }
3434   }
3435
3436   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3437   if (N0.getOpcode() == ISD::AND &&
3438       N1.getOpcode() == ISD::AND &&
3439       N0.getOperand(0) == N1.getOperand(0) &&
3440       // Don't increase # computations.
3441       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3442     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3443                             N0.getOperand(1), N1.getOperand(1));
3444     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3445   }
3446
3447   return SDValue();
3448 }
3449
3450 SDValue DAGCombiner::visitOR(SDNode *N) {
3451   SDValue N0 = N->getOperand(0);
3452   SDValue N1 = N->getOperand(1);
3453   EVT VT = N1.getValueType();
3454
3455   // fold vector ops
3456   if (VT.isVector()) {
3457     SDValue FoldedVOp = SimplifyVBinOp(N);
3458     if (FoldedVOp.getNode()) return FoldedVOp;
3459
3460     // fold (or x, 0) -> x, vector edition
3461     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3462       return N1;
3463     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3464       return N0;
3465
3466     // fold (or x, -1) -> -1, vector edition
3467     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3468       // do not return N0, because undef node may exist in N0
3469       return DAG.getConstant(
3470           APInt::getAllOnesValue(
3471               N0.getValueType().getScalarType().getSizeInBits()),
3472           N0.getValueType());
3473     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3474       // do not return N1, because undef node may exist in N1
3475       return DAG.getConstant(
3476           APInt::getAllOnesValue(
3477               N1.getValueType().getScalarType().getSizeInBits()),
3478           N1.getValueType());
3479
3480     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3481     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3482     // Do this only if the resulting shuffle is legal.
3483     if (isa<ShuffleVectorSDNode>(N0) &&
3484         isa<ShuffleVectorSDNode>(N1) &&
3485         // Avoid folding a node with illegal type.
3486         TLI.isTypeLegal(VT) &&
3487         N0->getOperand(1) == N1->getOperand(1) &&
3488         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3489       bool CanFold = true;
3490       unsigned NumElts = VT.getVectorNumElements();
3491       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3492       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3493       // We construct two shuffle masks:
3494       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3495       // and N1 as the second operand.
3496       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3497       // and N0 as the second operand.
3498       // We do this because OR is commutable and therefore there might be
3499       // two ways to fold this node into a shuffle.
3500       SmallVector<int,4> Mask1;
3501       SmallVector<int,4> Mask2;
3502
3503       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3504         int M0 = SV0->getMaskElt(i);
3505         int M1 = SV1->getMaskElt(i);
3506
3507         // Both shuffle indexes are undef. Propagate Undef.
3508         if (M0 < 0 && M1 < 0) {
3509           Mask1.push_back(M0);
3510           Mask2.push_back(M0);
3511           continue;
3512         }
3513
3514         if (M0 < 0 || M1 < 0 ||
3515             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3516             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3517           CanFold = false;
3518           break;
3519         }
3520
3521         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3522         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3523       }
3524
3525       if (CanFold) {
3526         // Fold this sequence only if the resulting shuffle is 'legal'.
3527         if (TLI.isShuffleMaskLegal(Mask1, VT))
3528           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3529                                       N1->getOperand(0), &Mask1[0]);
3530         if (TLI.isShuffleMaskLegal(Mask2, VT))
3531           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3532                                       N0->getOperand(0), &Mask2[0]);
3533       }
3534     }
3535   }
3536
3537   // fold (or c1, c2) -> c1|c2
3538   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3539   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3540   if (N0C && N1C)
3541     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3542   // canonicalize constant to RHS
3543   if (N0C && !N1C)
3544     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3545   // fold (or x, 0) -> x
3546   if (N1C && N1C->isNullValue())
3547     return N0;
3548   // fold (or x, -1) -> -1
3549   if (N1C && N1C->isAllOnesValue())
3550     return N1;
3551   // fold (or x, c) -> c iff (x & ~c) == 0
3552   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3553     return N1;
3554
3555   if (SDValue Combined = visitORLike(N0, N1, N))
3556     return Combined;
3557
3558   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3559   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3560   if (BSwap.getNode())
3561     return BSwap;
3562   BSwap = MatchBSwapHWordLow(N, N0, N1);
3563   if (BSwap.getNode())
3564     return BSwap;
3565
3566   // reassociate or
3567   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3568   if (ROR.getNode())
3569     return ROR;
3570   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3571   // iff (c1 & c2) == 0.
3572   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3573              isa<ConstantSDNode>(N0.getOperand(1))) {
3574     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3575     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3576       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3577         return DAG.getNode(
3578             ISD::AND, SDLoc(N), VT,
3579             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3580       return SDValue();
3581     }
3582   }
3583   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3584   if (N0.getOpcode() == N1.getOpcode()) {
3585     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3586     if (Tmp.getNode()) return Tmp;
3587   }
3588
3589   // See if this is some rotate idiom.
3590   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3591     return SDValue(Rot, 0);
3592
3593   // Simplify the operands using demanded-bits information.
3594   if (!VT.isVector() &&
3595       SimplifyDemandedBits(SDValue(N, 0)))
3596     return SDValue(N, 0);
3597
3598   return SDValue();
3599 }
3600
3601 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3602 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3603   if (Op.getOpcode() == ISD::AND) {
3604     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3605       Mask = Op.getOperand(1);
3606       Op = Op.getOperand(0);
3607     } else {
3608       return false;
3609     }
3610   }
3611
3612   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3613     Shift = Op;
3614     return true;
3615   }
3616
3617   return false;
3618 }
3619
3620 // Return true if we can prove that, whenever Neg and Pos are both in the
3621 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3622 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3623 //
3624 //     (or (shift1 X, Neg), (shift2 X, Pos))
3625 //
3626 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3627 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3628 // to consider shift amounts with defined behavior.
3629 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3630   // If OpSize is a power of 2 then:
3631   //
3632   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3633   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3634   //
3635   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3636   // for the stronger condition:
3637   //
3638   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3639   //
3640   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3641   // we can just replace Neg with Neg' for the rest of the function.
3642   //
3643   // In other cases we check for the even stronger condition:
3644   //
3645   //     Neg == OpSize - Pos                                    [B]
3646   //
3647   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3648   // behavior if Pos == 0 (and consequently Neg == OpSize).
3649   //
3650   // We could actually use [A] whenever OpSize is a power of 2, but the
3651   // only extra cases that it would match are those uninteresting ones
3652   // where Neg and Pos are never in range at the same time.  E.g. for
3653   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3654   // as well as (sub 32, Pos), but:
3655   //
3656   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3657   //
3658   // always invokes undefined behavior for 32-bit X.
3659   //
3660   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3661   unsigned MaskLoBits = 0;
3662   if (Neg.getOpcode() == ISD::AND &&
3663       isPowerOf2_64(OpSize) &&
3664       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3665       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3666     Neg = Neg.getOperand(0);
3667     MaskLoBits = Log2_64(OpSize);
3668   }
3669
3670   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3671   if (Neg.getOpcode() != ISD::SUB)
3672     return 0;
3673   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3674   if (!NegC)
3675     return 0;
3676   SDValue NegOp1 = Neg.getOperand(1);
3677
3678   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3679   // Pos'.  The truncation is redundant for the purpose of the equality.
3680   if (MaskLoBits &&
3681       Pos.getOpcode() == ISD::AND &&
3682       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3683       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3684     Pos = Pos.getOperand(0);
3685
3686   // The condition we need is now:
3687   //
3688   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3689   //
3690   // If NegOp1 == Pos then we need:
3691   //
3692   //              OpSize & Mask == NegC & Mask
3693   //
3694   // (because "x & Mask" is a truncation and distributes through subtraction).
3695   APInt Width;
3696   if (Pos == NegOp1)
3697     Width = NegC->getAPIntValue();
3698   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3699   // Then the condition we want to prove becomes:
3700   //
3701   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3702   //
3703   // which, again because "x & Mask" is a truncation, becomes:
3704   //
3705   //                NegC & Mask == (OpSize - PosC) & Mask
3706   //              OpSize & Mask == (NegC + PosC) & Mask
3707   else if (Pos.getOpcode() == ISD::ADD &&
3708            Pos.getOperand(0) == NegOp1 &&
3709            Pos.getOperand(1).getOpcode() == ISD::Constant)
3710     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3711              NegC->getAPIntValue());
3712   else
3713     return false;
3714
3715   // Now we just need to check that OpSize & Mask == Width & Mask.
3716   if (MaskLoBits)
3717     // Opsize & Mask is 0 since Mask is Opsize - 1.
3718     return Width.getLoBits(MaskLoBits) == 0;
3719   return Width == OpSize;
3720 }
3721
3722 // A subroutine of MatchRotate used once we have found an OR of two opposite
3723 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3724 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3725 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3726 // Neg with outer conversions stripped away.
3727 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3728                                        SDValue Neg, SDValue InnerPos,
3729                                        SDValue InnerNeg, unsigned PosOpcode,
3730                                        unsigned NegOpcode, SDLoc DL) {
3731   // fold (or (shl x, (*ext y)),
3732   //          (srl x, (*ext (sub 32, y)))) ->
3733   //   (rotl x, y) or (rotr x, (sub 32, y))
3734   //
3735   // fold (or (shl x, (*ext (sub 32, y))),
3736   //          (srl x, (*ext y))) ->
3737   //   (rotr x, y) or (rotl x, (sub 32, y))
3738   EVT VT = Shifted.getValueType();
3739   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3740     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3741     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3742                        HasPos ? Pos : Neg).getNode();
3743   }
3744
3745   return nullptr;
3746 }
3747
3748 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3749 // idioms for rotate, and if the target supports rotation instructions, generate
3750 // a rot[lr].
3751 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3752   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3753   EVT VT = LHS.getValueType();
3754   if (!TLI.isTypeLegal(VT)) return nullptr;
3755
3756   // The target must have at least one rotate flavor.
3757   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3758   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3759   if (!HasROTL && !HasROTR) return nullptr;
3760
3761   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3762   SDValue LHSShift;   // The shift.
3763   SDValue LHSMask;    // AND value if any.
3764   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3765     return nullptr; // Not part of a rotate.
3766
3767   SDValue RHSShift;   // The shift.
3768   SDValue RHSMask;    // AND value if any.
3769   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3770     return nullptr; // Not part of a rotate.
3771
3772   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3773     return nullptr;   // Not shifting the same value.
3774
3775   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3776     return nullptr;   // Shifts must disagree.
3777
3778   // Canonicalize shl to left side in a shl/srl pair.
3779   if (RHSShift.getOpcode() == ISD::SHL) {
3780     std::swap(LHS, RHS);
3781     std::swap(LHSShift, RHSShift);
3782     std::swap(LHSMask , RHSMask );
3783   }
3784
3785   unsigned OpSizeInBits = VT.getSizeInBits();
3786   SDValue LHSShiftArg = LHSShift.getOperand(0);
3787   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3788   SDValue RHSShiftArg = RHSShift.getOperand(0);
3789   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3790
3791   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3792   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3793   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3794       RHSShiftAmt.getOpcode() == ISD::Constant) {
3795     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3796     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3797     if ((LShVal + RShVal) != OpSizeInBits)
3798       return nullptr;
3799
3800     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3801                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3802
3803     // If there is an AND of either shifted operand, apply it to the result.
3804     if (LHSMask.getNode() || RHSMask.getNode()) {
3805       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3806
3807       if (LHSMask.getNode()) {
3808         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3809         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3810       }
3811       if (RHSMask.getNode()) {
3812         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3813         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3814       }
3815
3816       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3817     }
3818
3819     return Rot.getNode();
3820   }
3821
3822   // If there is a mask here, and we have a variable shift, we can't be sure
3823   // that we're masking out the right stuff.
3824   if (LHSMask.getNode() || RHSMask.getNode())
3825     return nullptr;
3826
3827   // If the shift amount is sign/zext/any-extended just peel it off.
3828   SDValue LExtOp0 = LHSShiftAmt;
3829   SDValue RExtOp0 = RHSShiftAmt;
3830   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3831        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3832        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3833        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3834       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3835        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3836        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3837        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3838     LExtOp0 = LHSShiftAmt.getOperand(0);
3839     RExtOp0 = RHSShiftAmt.getOperand(0);
3840   }
3841
3842   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3843                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3844   if (TryL)
3845     return TryL;
3846
3847   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3848                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3849   if (TryR)
3850     return TryR;
3851
3852   return nullptr;
3853 }
3854
3855 SDValue DAGCombiner::visitXOR(SDNode *N) {
3856   SDValue N0 = N->getOperand(0);
3857   SDValue N1 = N->getOperand(1);
3858   EVT VT = N0.getValueType();
3859
3860   // fold vector ops
3861   if (VT.isVector()) {
3862     SDValue FoldedVOp = SimplifyVBinOp(N);
3863     if (FoldedVOp.getNode()) return FoldedVOp;
3864
3865     // fold (xor x, 0) -> x, vector edition
3866     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3867       return N1;
3868     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3869       return N0;
3870   }
3871
3872   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3873   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3874     return DAG.getConstant(0, VT);
3875   // fold (xor x, undef) -> undef
3876   if (N0.getOpcode() == ISD::UNDEF)
3877     return N0;
3878   if (N1.getOpcode() == ISD::UNDEF)
3879     return N1;
3880   // fold (xor c1, c2) -> c1^c2
3881   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3882   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3883   if (N0C && N1C)
3884     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3885   // canonicalize constant to RHS
3886   if (N0C && !N1C)
3887     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3888   // fold (xor x, 0) -> x
3889   if (N1C && N1C->isNullValue())
3890     return N0;
3891   // reassociate xor
3892   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3893   if (RXOR.getNode())
3894     return RXOR;
3895
3896   // fold !(x cc y) -> (x !cc y)
3897   SDValue LHS, RHS, CC;
3898   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3899     bool isInt = LHS.getValueType().isInteger();
3900     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3901                                                isInt);
3902
3903     if (!LegalOperations ||
3904         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3905       switch (N0.getOpcode()) {
3906       default:
3907         llvm_unreachable("Unhandled SetCC Equivalent!");
3908       case ISD::SETCC:
3909         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3910       case ISD::SELECT_CC:
3911         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3912                                N0.getOperand(3), NotCC);
3913       }
3914     }
3915   }
3916
3917   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3918   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3919       N0.getNode()->hasOneUse() &&
3920       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3921     SDValue V = N0.getOperand(0);
3922     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3923                     DAG.getConstant(1, V.getValueType()));
3924     AddToWorklist(V.getNode());
3925     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3926   }
3927
3928   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3929   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3930       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3931     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3932     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3933       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3934       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3935       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3936       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3937       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3938     }
3939   }
3940   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3941   if (N1C && N1C->isAllOnesValue() &&
3942       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3943     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3944     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3945       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3946       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3947       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3948       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3949       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3950     }
3951   }
3952   // fold (xor (and x, y), y) -> (and (not x), y)
3953   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3954       N0->getOperand(1) == N1) {
3955     SDValue X = N0->getOperand(0);
3956     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3957     AddToWorklist(NotX.getNode());
3958     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3959   }
3960   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3961   if (N1C && N0.getOpcode() == ISD::XOR) {
3962     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3963     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3964     if (N00C)
3965       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3966                          DAG.getConstant(N1C->getAPIntValue() ^
3967                                          N00C->getAPIntValue(), VT));
3968     if (N01C)
3969       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3970                          DAG.getConstant(N1C->getAPIntValue() ^
3971                                          N01C->getAPIntValue(), VT));
3972   }
3973   // fold (xor x, x) -> 0
3974   if (N0 == N1)
3975     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3976
3977   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3978   if (N0.getOpcode() == N1.getOpcode()) {
3979     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3980     if (Tmp.getNode()) return Tmp;
3981   }
3982
3983   // Simplify the expression using non-local knowledge.
3984   if (!VT.isVector() &&
3985       SimplifyDemandedBits(SDValue(N, 0)))
3986     return SDValue(N, 0);
3987
3988   return SDValue();
3989 }
3990
3991 /// Handle transforms common to the three shifts, when the shift amount is a
3992 /// constant.
3993 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3994   // We can't and shouldn't fold opaque constants.
3995   if (Amt->isOpaque())
3996     return SDValue();
3997
3998   SDNode *LHS = N->getOperand(0).getNode();
3999   if (!LHS->hasOneUse()) return SDValue();
4000
4001   // We want to pull some binops through shifts, so that we have (and (shift))
4002   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4003   // thing happens with address calculations, so it's important to canonicalize
4004   // it.
4005   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4006
4007   switch (LHS->getOpcode()) {
4008   default: return SDValue();
4009   case ISD::OR:
4010   case ISD::XOR:
4011     HighBitSet = false; // We can only transform sra if the high bit is clear.
4012     break;
4013   case ISD::AND:
4014     HighBitSet = true;  // We can only transform sra if the high bit is set.
4015     break;
4016   case ISD::ADD:
4017     if (N->getOpcode() != ISD::SHL)
4018       return SDValue(); // only shl(add) not sr[al](add).
4019     HighBitSet = false; // We can only transform sra if the high bit is clear.
4020     break;
4021   }
4022
4023   // We require the RHS of the binop to be a constant and not opaque as well.
4024   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4025   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4026
4027   // FIXME: disable this unless the input to the binop is a shift by a constant.
4028   // If it is not a shift, it pessimizes some common cases like:
4029   //
4030   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4031   //    int bar(int *X, int i) { return X[i & 255]; }
4032   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4033   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4034        BinOpLHSVal->getOpcode() != ISD::SRA &&
4035        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4036       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4037     return SDValue();
4038
4039   EVT VT = N->getValueType(0);
4040
4041   // If this is a signed shift right, and the high bit is modified by the
4042   // logical operation, do not perform the transformation. The highBitSet
4043   // boolean indicates the value of the high bit of the constant which would
4044   // cause it to be modified for this operation.
4045   if (N->getOpcode() == ISD::SRA) {
4046     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4047     if (BinOpRHSSignSet != HighBitSet)
4048       return SDValue();
4049   }
4050
4051   if (!TLI.isDesirableToCommuteWithShift(LHS))
4052     return SDValue();
4053
4054   // Fold the constants, shifting the binop RHS by the shift amount.
4055   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4056                                N->getValueType(0),
4057                                LHS->getOperand(1), N->getOperand(1));
4058   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4059
4060   // Create the new shift.
4061   SDValue NewShift = DAG.getNode(N->getOpcode(),
4062                                  SDLoc(LHS->getOperand(0)),
4063                                  VT, LHS->getOperand(0), N->getOperand(1));
4064
4065   // Create the new binop.
4066   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4067 }
4068
4069 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4070   assert(N->getOpcode() == ISD::TRUNCATE);
4071   assert(N->getOperand(0).getOpcode() == ISD::AND);
4072
4073   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4074   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4075     SDValue N01 = N->getOperand(0).getOperand(1);
4076
4077     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4078       EVT TruncVT = N->getValueType(0);
4079       SDValue N00 = N->getOperand(0).getOperand(0);
4080       APInt TruncC = N01C->getAPIntValue();
4081       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4082
4083       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4084                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4085                          DAG.getConstant(TruncC, TruncVT));
4086     }
4087   }
4088
4089   return SDValue();
4090 }
4091
4092 SDValue DAGCombiner::visitRotate(SDNode *N) {
4093   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4094   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4095       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4096     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4097     if (NewOp1.getNode())
4098       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4099                          N->getOperand(0), NewOp1);
4100   }
4101   return SDValue();
4102 }
4103
4104 SDValue DAGCombiner::visitSHL(SDNode *N) {
4105   SDValue N0 = N->getOperand(0);
4106   SDValue N1 = N->getOperand(1);
4107   EVT VT = N0.getValueType();
4108   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4109
4110   // fold vector ops
4111   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4112   if (VT.isVector()) {
4113     SDValue FoldedVOp = SimplifyVBinOp(N);
4114     if (FoldedVOp.getNode()) return FoldedVOp;
4115
4116     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4117     // If setcc produces all-one true value then:
4118     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4119     if (N1CV && N1CV->isConstant()) {
4120       if (N0.getOpcode() == ISD::AND) {
4121         SDValue N00 = N0->getOperand(0);
4122         SDValue N01 = N0->getOperand(1);
4123         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4124
4125         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4126             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4127                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4128           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4129             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4130         }
4131       } else {
4132         N1C = isConstOrConstSplat(N1);
4133       }
4134     }
4135   }
4136
4137   // fold (shl c1, c2) -> c1<<c2
4138   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4139   if (N0C && N1C)
4140     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4141   // fold (shl 0, x) -> 0
4142   if (N0C && N0C->isNullValue())
4143     return N0;
4144   // fold (shl x, c >= size(x)) -> undef
4145   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4146     return DAG.getUNDEF(VT);
4147   // fold (shl x, 0) -> x
4148   if (N1C && N1C->isNullValue())
4149     return N0;
4150   // fold (shl undef, x) -> 0
4151   if (N0.getOpcode() == ISD::UNDEF)
4152     return DAG.getConstant(0, VT);
4153   // if (shl x, c) is known to be zero, return 0
4154   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4155                             APInt::getAllOnesValue(OpSizeInBits)))
4156     return DAG.getConstant(0, VT);
4157   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4158   if (N1.getOpcode() == ISD::TRUNCATE &&
4159       N1.getOperand(0).getOpcode() == ISD::AND) {
4160     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4161     if (NewOp1.getNode())
4162       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4163   }
4164
4165   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4166     return SDValue(N, 0);
4167
4168   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4169   if (N1C && N0.getOpcode() == ISD::SHL) {
4170     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4171       uint64_t c1 = N0C1->getZExtValue();
4172       uint64_t c2 = N1C->getZExtValue();
4173       if (c1 + c2 >= OpSizeInBits)
4174         return DAG.getConstant(0, VT);
4175       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4176                          DAG.getConstant(c1 + c2, N1.getValueType()));
4177     }
4178   }
4179
4180   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4181   // For this to be valid, the second form must not preserve any of the bits
4182   // that are shifted out by the inner shift in the first form.  This means
4183   // the outer shift size must be >= the number of bits added by the ext.
4184   // As a corollary, we don't care what kind of ext it is.
4185   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4186               N0.getOpcode() == ISD::ANY_EXTEND ||
4187               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4188       N0.getOperand(0).getOpcode() == ISD::SHL) {
4189     SDValue N0Op0 = N0.getOperand(0);
4190     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4191       uint64_t c1 = N0Op0C1->getZExtValue();
4192       uint64_t c2 = N1C->getZExtValue();
4193       EVT InnerShiftVT = N0Op0.getValueType();
4194       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4195       if (c2 >= OpSizeInBits - InnerShiftSize) {
4196         if (c1 + c2 >= OpSizeInBits)
4197           return DAG.getConstant(0, VT);
4198         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4199                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4200                                        N0Op0->getOperand(0)),
4201                            DAG.getConstant(c1 + c2, N1.getValueType()));
4202       }
4203     }
4204   }
4205
4206   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4207   // Only fold this if the inner zext has no other uses to avoid increasing
4208   // the total number of instructions.
4209   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4210       N0.getOperand(0).getOpcode() == ISD::SRL) {
4211     SDValue N0Op0 = N0.getOperand(0);
4212     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4213       uint64_t c1 = N0Op0C1->getZExtValue();
4214       if (c1 < VT.getScalarSizeInBits()) {
4215         uint64_t c2 = N1C->getZExtValue();
4216         if (c1 == c2) {
4217           SDValue NewOp0 = N0.getOperand(0);
4218           EVT CountVT = NewOp0.getOperand(1).getValueType();
4219           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4220                                        NewOp0, DAG.getConstant(c2, CountVT));
4221           AddToWorklist(NewSHL.getNode());
4222           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4223         }
4224       }
4225     }
4226   }
4227
4228   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4229   //                               (and (srl x, (sub c1, c2), MASK)
4230   // Only fold this if the inner shift has no other uses -- if it does, folding
4231   // this will increase the total number of instructions.
4232   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4233     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4234       uint64_t c1 = N0C1->getZExtValue();
4235       if (c1 < OpSizeInBits) {
4236         uint64_t c2 = N1C->getZExtValue();
4237         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4238         SDValue Shift;
4239         if (c2 > c1) {
4240           Mask = Mask.shl(c2 - c1);
4241           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4242                               DAG.getConstant(c2 - c1, N1.getValueType()));
4243         } else {
4244           Mask = Mask.lshr(c1 - c2);
4245           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4246                               DAG.getConstant(c1 - c2, N1.getValueType()));
4247         }
4248         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4249                            DAG.getConstant(Mask, VT));
4250       }
4251     }
4252   }
4253   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4254   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4255     unsigned BitSize = VT.getScalarSizeInBits();
4256     SDValue HiBitsMask =
4257       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4258                                             BitSize - N1C->getZExtValue()), VT);
4259     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4260                        HiBitsMask);
4261   }
4262
4263   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4264   // Variant of version done on multiply, except mul by a power of 2 is turned
4265   // into a shift.
4266   APInt Val;
4267   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4268       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4269        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4270     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4271     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4272     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4273   }
4274
4275   if (N1C) {
4276     SDValue NewSHL = visitShiftByConstant(N, N1C);
4277     if (NewSHL.getNode())
4278       return NewSHL;
4279   }
4280
4281   return SDValue();
4282 }
4283
4284 SDValue DAGCombiner::visitSRA(SDNode *N) {
4285   SDValue N0 = N->getOperand(0);
4286   SDValue N1 = N->getOperand(1);
4287   EVT VT = N0.getValueType();
4288   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4289
4290   // fold vector ops
4291   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4292   if (VT.isVector()) {
4293     SDValue FoldedVOp = SimplifyVBinOp(N);
4294     if (FoldedVOp.getNode()) return FoldedVOp;
4295
4296     N1C = isConstOrConstSplat(N1);
4297   }
4298
4299   // fold (sra c1, c2) -> (sra c1, c2)
4300   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4301   if (N0C && N1C)
4302     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4303   // fold (sra 0, x) -> 0
4304   if (N0C && N0C->isNullValue())
4305     return N0;
4306   // fold (sra -1, x) -> -1
4307   if (N0C && N0C->isAllOnesValue())
4308     return N0;
4309   // fold (sra x, (setge c, size(x))) -> undef
4310   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4311     return DAG.getUNDEF(VT);
4312   // fold (sra x, 0) -> x
4313   if (N1C && N1C->isNullValue())
4314     return N0;
4315   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4316   // sext_inreg.
4317   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4318     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4319     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4320     if (VT.isVector())
4321       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4322                                ExtVT, VT.getVectorNumElements());
4323     if ((!LegalOperations ||
4324          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4325       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4326                          N0.getOperand(0), DAG.getValueType(ExtVT));
4327   }
4328
4329   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4330   if (N1C && N0.getOpcode() == ISD::SRA) {
4331     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4332       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4333       if (Sum >= OpSizeInBits)
4334         Sum = OpSizeInBits - 1;
4335       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4336                          DAG.getConstant(Sum, N1.getValueType()));
4337     }
4338   }
4339
4340   // fold (sra (shl X, m), (sub result_size, n))
4341   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4342   // result_size - n != m.
4343   // If truncate is free for the target sext(shl) is likely to result in better
4344   // code.
4345   if (N0.getOpcode() == ISD::SHL && N1C) {
4346     // Get the two constanst of the shifts, CN0 = m, CN = n.
4347     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4348     if (N01C) {
4349       LLVMContext &Ctx = *DAG.getContext();
4350       // Determine what the truncate's result bitsize and type would be.
4351       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4352
4353       if (VT.isVector())
4354         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4355
4356       // Determine the residual right-shift amount.
4357       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4358
4359       // If the shift is not a no-op (in which case this should be just a sign
4360       // extend already), the truncated to type is legal, sign_extend is legal
4361       // on that type, and the truncate to that type is both legal and free,
4362       // perform the transform.
4363       if ((ShiftAmt > 0) &&
4364           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4365           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4366           TLI.isTruncateFree(VT, TruncVT)) {
4367
4368           SDValue Amt = DAG.getConstant(ShiftAmt,
4369               getShiftAmountTy(N0.getOperand(0).getValueType()));
4370           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4371                                       N0.getOperand(0), Amt);
4372           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4373                                       Shift);
4374           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4375                              N->getValueType(0), Trunc);
4376       }
4377     }
4378   }
4379
4380   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4381   if (N1.getOpcode() == ISD::TRUNCATE &&
4382       N1.getOperand(0).getOpcode() == ISD::AND) {
4383     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4384     if (NewOp1.getNode())
4385       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4386   }
4387
4388   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4389   //      if c1 is equal to the number of bits the trunc removes
4390   if (N0.getOpcode() == ISD::TRUNCATE &&
4391       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4392        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4393       N0.getOperand(0).hasOneUse() &&
4394       N0.getOperand(0).getOperand(1).hasOneUse() &&
4395       N1C) {
4396     SDValue N0Op0 = N0.getOperand(0);
4397     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4398       unsigned LargeShiftVal = LargeShift->getZExtValue();
4399       EVT LargeVT = N0Op0.getValueType();
4400
4401       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4402         SDValue Amt =
4403           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4404                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4405         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4406                                   N0Op0.getOperand(0), Amt);
4407         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4408       }
4409     }
4410   }
4411
4412   // Simplify, based on bits shifted out of the LHS.
4413   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4414     return SDValue(N, 0);
4415
4416
4417   // If the sign bit is known to be zero, switch this to a SRL.
4418   if (DAG.SignBitIsZero(N0))
4419     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4420
4421   if (N1C) {
4422     SDValue NewSRA = visitShiftByConstant(N, N1C);
4423     if (NewSRA.getNode())
4424       return NewSRA;
4425   }
4426
4427   return SDValue();
4428 }
4429
4430 SDValue DAGCombiner::visitSRL(SDNode *N) {
4431   SDValue N0 = N->getOperand(0);
4432   SDValue N1 = N->getOperand(1);
4433   EVT VT = N0.getValueType();
4434   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4435
4436   // fold vector ops
4437   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4438   if (VT.isVector()) {
4439     SDValue FoldedVOp = SimplifyVBinOp(N);
4440     if (FoldedVOp.getNode()) return FoldedVOp;
4441
4442     N1C = isConstOrConstSplat(N1);
4443   }
4444
4445   // fold (srl c1, c2) -> c1 >>u c2
4446   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4447   if (N0C && N1C)
4448     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4449   // fold (srl 0, x) -> 0
4450   if (N0C && N0C->isNullValue())
4451     return N0;
4452   // fold (srl x, c >= size(x)) -> undef
4453   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4454     return DAG.getUNDEF(VT);
4455   // fold (srl x, 0) -> x
4456   if (N1C && N1C->isNullValue())
4457     return N0;
4458   // if (srl x, c) is known to be zero, return 0
4459   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4460                                    APInt::getAllOnesValue(OpSizeInBits)))
4461     return DAG.getConstant(0, VT);
4462
4463   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4464   if (N1C && N0.getOpcode() == ISD::SRL) {
4465     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4466       uint64_t c1 = N01C->getZExtValue();
4467       uint64_t c2 = N1C->getZExtValue();
4468       if (c1 + c2 >= OpSizeInBits)
4469         return DAG.getConstant(0, VT);
4470       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4471                          DAG.getConstant(c1 + c2, N1.getValueType()));
4472     }
4473   }
4474
4475   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4476   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4477       N0.getOperand(0).getOpcode() == ISD::SRL &&
4478       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4479     uint64_t c1 =
4480       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4481     uint64_t c2 = N1C->getZExtValue();
4482     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4483     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4484     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4485     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4486     if (c1 + OpSizeInBits == InnerShiftSize) {
4487       if (c1 + c2 >= InnerShiftSize)
4488         return DAG.getConstant(0, VT);
4489       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4490                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4491                                      N0.getOperand(0)->getOperand(0),
4492                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4493     }
4494   }
4495
4496   // fold (srl (shl x, c), c) -> (and x, cst2)
4497   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4498     unsigned BitSize = N0.getScalarValueSizeInBits();
4499     if (BitSize <= 64) {
4500       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4501       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4502                          DAG.getConstant(~0ULL >> ShAmt, VT));
4503     }
4504   }
4505
4506   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4507   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4508     // Shifting in all undef bits?
4509     EVT SmallVT = N0.getOperand(0).getValueType();
4510     unsigned BitSize = SmallVT.getScalarSizeInBits();
4511     if (N1C->getZExtValue() >= BitSize)
4512       return DAG.getUNDEF(VT);
4513
4514     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4515       uint64_t ShiftAmt = N1C->getZExtValue();
4516       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4517                                        N0.getOperand(0),
4518                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4519       AddToWorklist(SmallShift.getNode());
4520       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4521       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4522                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4523                          DAG.getConstant(Mask, VT));
4524     }
4525   }
4526
4527   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4528   // bit, which is unmodified by sra.
4529   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4530     if (N0.getOpcode() == ISD::SRA)
4531       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4532   }
4533
4534   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4535   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4536       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4537     APInt KnownZero, KnownOne;
4538     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4539
4540     // If any of the input bits are KnownOne, then the input couldn't be all
4541     // zeros, thus the result of the srl will always be zero.
4542     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4543
4544     // If all of the bits input the to ctlz node are known to be zero, then
4545     // the result of the ctlz is "32" and the result of the shift is one.
4546     APInt UnknownBits = ~KnownZero;
4547     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4548
4549     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4550     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4551       // Okay, we know that only that the single bit specified by UnknownBits
4552       // could be set on input to the CTLZ node. If this bit is set, the SRL
4553       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4554       // to an SRL/XOR pair, which is likely to simplify more.
4555       unsigned ShAmt = UnknownBits.countTrailingZeros();
4556       SDValue Op = N0.getOperand(0);
4557
4558       if (ShAmt) {
4559         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4560                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4561         AddToWorklist(Op.getNode());
4562       }
4563
4564       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4565                          Op, DAG.getConstant(1, VT));
4566     }
4567   }
4568
4569   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4570   if (N1.getOpcode() == ISD::TRUNCATE &&
4571       N1.getOperand(0).getOpcode() == ISD::AND) {
4572     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4573     if (NewOp1.getNode())
4574       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4575   }
4576
4577   // fold operands of srl based on knowledge that the low bits are not
4578   // demanded.
4579   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4580     return SDValue(N, 0);
4581
4582   if (N1C) {
4583     SDValue NewSRL = visitShiftByConstant(N, N1C);
4584     if (NewSRL.getNode())
4585       return NewSRL;
4586   }
4587
4588   // Attempt to convert a srl of a load into a narrower zero-extending load.
4589   SDValue NarrowLoad = ReduceLoadWidth(N);
4590   if (NarrowLoad.getNode())
4591     return NarrowLoad;
4592
4593   // Here is a common situation. We want to optimize:
4594   //
4595   //   %a = ...
4596   //   %b = and i32 %a, 2
4597   //   %c = srl i32 %b, 1
4598   //   brcond i32 %c ...
4599   //
4600   // into
4601   //
4602   //   %a = ...
4603   //   %b = and %a, 2
4604   //   %c = setcc eq %b, 0
4605   //   brcond %c ...
4606   //
4607   // However when after the source operand of SRL is optimized into AND, the SRL
4608   // itself may not be optimized further. Look for it and add the BRCOND into
4609   // the worklist.
4610   if (N->hasOneUse()) {
4611     SDNode *Use = *N->use_begin();
4612     if (Use->getOpcode() == ISD::BRCOND)
4613       AddToWorklist(Use);
4614     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4615       // Also look pass the truncate.
4616       Use = *Use->use_begin();
4617       if (Use->getOpcode() == ISD::BRCOND)
4618         AddToWorklist(Use);
4619     }
4620   }
4621
4622   return SDValue();
4623 }
4624
4625 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4626   SDValue N0 = N->getOperand(0);
4627   EVT VT = N->getValueType(0);
4628
4629   // fold (ctlz c1) -> c2
4630   if (isa<ConstantSDNode>(N0))
4631     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4632   return SDValue();
4633 }
4634
4635 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4636   SDValue N0 = N->getOperand(0);
4637   EVT VT = N->getValueType(0);
4638
4639   // fold (ctlz_zero_undef c1) -> c2
4640   if (isa<ConstantSDNode>(N0))
4641     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4642   return SDValue();
4643 }
4644
4645 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4646   SDValue N0 = N->getOperand(0);
4647   EVT VT = N->getValueType(0);
4648
4649   // fold (cttz c1) -> c2
4650   if (isa<ConstantSDNode>(N0))
4651     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4652   return SDValue();
4653 }
4654
4655 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4656   SDValue N0 = N->getOperand(0);
4657   EVT VT = N->getValueType(0);
4658
4659   // fold (cttz_zero_undef c1) -> c2
4660   if (isa<ConstantSDNode>(N0))
4661     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4662   return SDValue();
4663 }
4664
4665 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4666   SDValue N0 = N->getOperand(0);
4667   EVT VT = N->getValueType(0);
4668
4669   // fold (ctpop c1) -> c2
4670   if (isa<ConstantSDNode>(N0))
4671     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4672   return SDValue();
4673 }
4674
4675
4676 /// \brief Generate Min/Max node
4677 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4678                                    SDValue True, SDValue False,
4679                                    ISD::CondCode CC, const TargetLowering &TLI,
4680                                    SelectionDAG &DAG) {
4681   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4682     return SDValue();
4683
4684   switch (CC) {
4685   case ISD::SETOLT:
4686   case ISD::SETOLE:
4687   case ISD::SETLT:
4688   case ISD::SETLE:
4689   case ISD::SETULT:
4690   case ISD::SETULE: {
4691     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4692     if (TLI.isOperationLegal(Opcode, VT))
4693       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4694     return SDValue();
4695   }
4696   case ISD::SETOGT:
4697   case ISD::SETOGE:
4698   case ISD::SETGT:
4699   case ISD::SETGE:
4700   case ISD::SETUGT:
4701   case ISD::SETUGE: {
4702     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4703     if (TLI.isOperationLegal(Opcode, VT))
4704       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4705     return SDValue();
4706   }
4707   default:
4708     return SDValue();
4709   }
4710 }
4711
4712 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4713   SDValue N0 = N->getOperand(0);
4714   SDValue N1 = N->getOperand(1);
4715   SDValue N2 = N->getOperand(2);
4716   EVT VT = N->getValueType(0);
4717   EVT VT0 = N0.getValueType();
4718
4719   // fold (select C, X, X) -> X
4720   if (N1 == N2)
4721     return N1;
4722   // fold (select true, X, Y) -> X
4723   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4724   if (N0C && !N0C->isNullValue())
4725     return N1;
4726   // fold (select false, X, Y) -> Y
4727   if (N0C && N0C->isNullValue())
4728     return N2;
4729   // fold (select C, 1, X) -> (or C, X)
4730   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4731   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4732     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4733   // fold (select C, 0, 1) -> (xor C, 1)
4734   // We can't do this reliably if integer based booleans have different contents
4735   // to floating point based booleans. This is because we can't tell whether we
4736   // have an integer-based boolean or a floating-point-based boolean unless we
4737   // can find the SETCC that produced it and inspect its operands. This is
4738   // fairly easy if C is the SETCC node, but it can potentially be
4739   // undiscoverable (or not reasonably discoverable). For example, it could be
4740   // in another basic block or it could require searching a complicated
4741   // expression.
4742   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4743   if (VT.isInteger() &&
4744       (VT0 == MVT::i1 || (VT0.isInteger() &&
4745                           TLI.getBooleanContents(false, false) ==
4746                               TLI.getBooleanContents(false, true) &&
4747                           TLI.getBooleanContents(false, false) ==
4748                               TargetLowering::ZeroOrOneBooleanContent)) &&
4749       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4750     SDValue XORNode;
4751     if (VT == VT0)
4752       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4753                          N0, DAG.getConstant(1, VT0));
4754     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4755                           N0, DAG.getConstant(1, VT0));
4756     AddToWorklist(XORNode.getNode());
4757     if (VT.bitsGT(VT0))
4758       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4759     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4760   }
4761   // fold (select C, 0, X) -> (and (not C), X)
4762   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4763     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4764     AddToWorklist(NOTNode.getNode());
4765     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4766   }
4767   // fold (select C, X, 1) -> (or (not C), X)
4768   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4769     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4770     AddToWorklist(NOTNode.getNode());
4771     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4772   }
4773   // fold (select C, X, 0) -> (and C, X)
4774   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4775     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4776   // fold (select X, X, Y) -> (or X, Y)
4777   // fold (select X, 1, Y) -> (or X, Y)
4778   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4779     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4780   // fold (select X, Y, X) -> (and X, Y)
4781   // fold (select X, Y, 0) -> (and X, Y)
4782   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4783     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4784
4785   // If we can fold this based on the true/false value, do so.
4786   if (SimplifySelectOps(N, N1, N2))
4787     return SDValue(N, 0);  // Don't revisit N.
4788
4789   // fold selects based on a setcc into other things, such as min/max/abs
4790   if (N0.getOpcode() == ISD::SETCC) {
4791     // select x, y (fcmp lt x, y) -> fminnum x, y
4792     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4793     //
4794     // This is OK if we don't care about what happens if either operand is a
4795     // NaN.
4796     //
4797
4798     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4799     // no signed zeros as well as no nans.
4800     const TargetOptions &Options = DAG.getTarget().Options;
4801     if (Options.UnsafeFPMath &&
4802         VT.isFloatingPoint() && N0.hasOneUse() &&
4803         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4804       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4805
4806       SDValue FMinMax =
4807           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4808                               N1, N2, CC, TLI, DAG);
4809       if (FMinMax)
4810         return FMinMax;
4811     }
4812
4813     if ((!LegalOperations &&
4814          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4815         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4816       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4817                          N0.getOperand(0), N0.getOperand(1),
4818                          N1, N2, N0.getOperand(2));
4819     return SimplifySelect(SDLoc(N), N0, N1, N2);
4820   }
4821
4822   return SDValue();
4823 }
4824
4825 static
4826 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4827   SDLoc DL(N);
4828   EVT LoVT, HiVT;
4829   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4830
4831   // Split the inputs.
4832   SDValue Lo, Hi, LL, LH, RL, RH;
4833   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4834   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4835
4836   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4837   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4838
4839   return std::make_pair(Lo, Hi);
4840 }
4841
4842 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4843 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4844 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4845   SDLoc dl(N);
4846   SDValue Cond = N->getOperand(0);
4847   SDValue LHS = N->getOperand(1);
4848   SDValue RHS = N->getOperand(2);
4849   EVT VT = N->getValueType(0);
4850   int NumElems = VT.getVectorNumElements();
4851   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4852          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4853          Cond.getOpcode() == ISD::BUILD_VECTOR);
4854
4855   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4856   // binary ones here.
4857   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4858     return SDValue();
4859
4860   // We're sure we have an even number of elements due to the
4861   // concat_vectors we have as arguments to vselect.
4862   // Skip BV elements until we find one that's not an UNDEF
4863   // After we find an UNDEF element, keep looping until we get to half the
4864   // length of the BV and see if all the non-undef nodes are the same.
4865   ConstantSDNode *BottomHalf = nullptr;
4866   for (int i = 0; i < NumElems / 2; ++i) {
4867     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4868       continue;
4869
4870     if (BottomHalf == nullptr)
4871       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4872     else if (Cond->getOperand(i).getNode() != BottomHalf)
4873       return SDValue();
4874   }
4875
4876   // Do the same for the second half of the BuildVector
4877   ConstantSDNode *TopHalf = nullptr;
4878   for (int i = NumElems / 2; i < NumElems; ++i) {
4879     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4880       continue;
4881
4882     if (TopHalf == nullptr)
4883       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4884     else if (Cond->getOperand(i).getNode() != TopHalf)
4885       return SDValue();
4886   }
4887
4888   assert(TopHalf && BottomHalf &&
4889          "One half of the selector was all UNDEFs and the other was all the "
4890          "same value. This should have been addressed before this function.");
4891   return DAG.getNode(
4892       ISD::CONCAT_VECTORS, dl, VT,
4893       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4894       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4895 }
4896
4897 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4898
4899   if (Level >= AfterLegalizeTypes)
4900     return SDValue();
4901
4902   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4903   SDValue Mask = MST->getMask();
4904   SDValue Data  = MST->getValue();
4905   SDLoc DL(N);
4906
4907   // If the MSTORE data type requires splitting and the mask is provided by a
4908   // SETCC, then split both nodes and its operands before legalization. This
4909   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4910   // and enables future optimizations (e.g. min/max pattern matching on X86).
4911   if (Mask.getOpcode() == ISD::SETCC) {
4912
4913     // Check if any splitting is required.
4914     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4915         TargetLowering::TypeSplitVector)
4916       return SDValue();
4917
4918     SDValue MaskLo, MaskHi, Lo, Hi;
4919     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4920
4921     EVT LoVT, HiVT;
4922     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4923
4924     SDValue Chain = MST->getChain();
4925     SDValue Ptr   = MST->getBasePtr();
4926
4927     EVT MemoryVT = MST->getMemoryVT();
4928     unsigned Alignment = MST->getOriginalAlignment();
4929
4930     // if Alignment is equal to the vector size,
4931     // take the half of it for the second part
4932     unsigned SecondHalfAlignment =
4933       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4934          Alignment/2 : Alignment;
4935
4936     EVT LoMemVT, HiMemVT;
4937     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4938
4939     SDValue DataLo, DataHi;
4940     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4941
4942     MachineMemOperand *MMO = DAG.getMachineFunction().
4943       getMachineMemOperand(MST->getPointerInfo(),
4944                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4945                            Alignment, MST->getAAInfo(), MST->getRanges());
4946
4947     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
4948                             MST->isTruncatingStore());
4949
4950     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4951     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4952                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4953
4954     MMO = DAG.getMachineFunction().
4955       getMachineMemOperand(MST->getPointerInfo(),
4956                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4957                            SecondHalfAlignment, MST->getAAInfo(),
4958                            MST->getRanges());
4959
4960     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
4961                             MST->isTruncatingStore());
4962
4963     AddToWorklist(Lo.getNode());
4964     AddToWorklist(Hi.getNode());
4965
4966     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4967   }
4968   return SDValue();
4969 }
4970
4971 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4972
4973   if (Level >= AfterLegalizeTypes)
4974     return SDValue();
4975
4976   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4977   SDValue Mask = MLD->getMask();
4978   SDLoc DL(N);
4979
4980   // If the MLOAD result requires splitting and the mask is provided by a
4981   // SETCC, then split both nodes and its operands before legalization. This
4982   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4983   // and enables future optimizations (e.g. min/max pattern matching on X86).
4984
4985   if (Mask.getOpcode() == ISD::SETCC) {
4986     EVT VT = N->getValueType(0);
4987
4988     // Check if any splitting is required.
4989     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4990         TargetLowering::TypeSplitVector)
4991       return SDValue();
4992
4993     SDValue MaskLo, MaskHi, Lo, Hi;
4994     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4995
4996     SDValue Src0 = MLD->getSrc0();
4997     SDValue Src0Lo, Src0Hi;
4998     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4999
5000     EVT LoVT, HiVT;
5001     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5002
5003     SDValue Chain = MLD->getChain();
5004     SDValue Ptr   = MLD->getBasePtr();
5005     EVT MemoryVT = MLD->getMemoryVT();
5006     unsigned Alignment = MLD->getOriginalAlignment();
5007
5008     // if Alignment is equal to the vector size,
5009     // take the half of it for the second part
5010     unsigned SecondHalfAlignment =
5011       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5012          Alignment/2 : Alignment;
5013
5014     EVT LoMemVT, HiMemVT;
5015     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5016
5017     MachineMemOperand *MMO = DAG.getMachineFunction().
5018     getMachineMemOperand(MLD->getPointerInfo(),
5019                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5020                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5021
5022     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5023                            ISD::NON_EXTLOAD);
5024
5025     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5026     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5027                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5028
5029     MMO = DAG.getMachineFunction().
5030     getMachineMemOperand(MLD->getPointerInfo(),
5031                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5032                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5033
5034     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5035                            ISD::NON_EXTLOAD);
5036
5037     AddToWorklist(Lo.getNode());
5038     AddToWorklist(Hi.getNode());
5039
5040     // Build a factor node to remember that this load is independent of the
5041     // other one.
5042     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5043                         Hi.getValue(1));
5044
5045     // Legalized the chain result - switch anything that used the old chain to
5046     // use the new one.
5047     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5048
5049     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5050
5051     SDValue RetOps[] = { LoadRes, Chain };
5052     return DAG.getMergeValues(RetOps, DL);
5053   }
5054   return SDValue();
5055 }
5056
5057 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5058   SDValue N0 = N->getOperand(0);
5059   SDValue N1 = N->getOperand(1);
5060   SDValue N2 = N->getOperand(2);
5061   SDLoc DL(N);
5062
5063   // Canonicalize integer abs.
5064   // vselect (setg[te] X,  0),  X, -X ->
5065   // vselect (setgt    X, -1),  X, -X ->
5066   // vselect (setl[te] X,  0), -X,  X ->
5067   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5068   if (N0.getOpcode() == ISD::SETCC) {
5069     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5070     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5071     bool isAbs = false;
5072     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5073
5074     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5075          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5076         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5077       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5078     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5079              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5080       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5081
5082     if (isAbs) {
5083       EVT VT = LHS.getValueType();
5084       SDValue Shift = DAG.getNode(
5085           ISD::SRA, DL, VT, LHS,
5086           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5087       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5088       AddToWorklist(Shift.getNode());
5089       AddToWorklist(Add.getNode());
5090       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5091     }
5092   }
5093
5094   // If the VSELECT result requires splitting and the mask is provided by a
5095   // SETCC, then split both nodes and its operands before legalization. This
5096   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5097   // and enables future optimizations (e.g. min/max pattern matching on X86).
5098   if (N0.getOpcode() == ISD::SETCC) {
5099     EVT VT = N->getValueType(0);
5100
5101     // Check if any splitting is required.
5102     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5103         TargetLowering::TypeSplitVector)
5104       return SDValue();
5105
5106     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5107     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5108     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5109     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5110
5111     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5112     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5113
5114     // Add the new VSELECT nodes to the work list in case they need to be split
5115     // again.
5116     AddToWorklist(Lo.getNode());
5117     AddToWorklist(Hi.getNode());
5118
5119     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5120   }
5121
5122   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5123   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5124     return N1;
5125   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5126   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5127     return N2;
5128
5129   // The ConvertSelectToConcatVector function is assuming both the above
5130   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5131   // and addressed.
5132   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5133       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5134       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5135     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5136     if (CV.getNode())
5137       return CV;
5138   }
5139
5140   return SDValue();
5141 }
5142
5143 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5144   SDValue N0 = N->getOperand(0);
5145   SDValue N1 = N->getOperand(1);
5146   SDValue N2 = N->getOperand(2);
5147   SDValue N3 = N->getOperand(3);
5148   SDValue N4 = N->getOperand(4);
5149   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5150
5151   // fold select_cc lhs, rhs, x, x, cc -> x
5152   if (N2 == N3)
5153     return N2;
5154
5155   // Determine if the condition we're dealing with is constant
5156   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5157                               N0, N1, CC, SDLoc(N), false);
5158   if (SCC.getNode()) {
5159     AddToWorklist(SCC.getNode());
5160
5161     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5162       if (!SCCC->isNullValue())
5163         return N2;    // cond always true -> true val
5164       else
5165         return N3;    // cond always false -> false val
5166     } else if (SCC->getOpcode() == ISD::UNDEF) {
5167       // When the condition is UNDEF, just return the first operand. This is
5168       // coherent the DAG creation, no setcc node is created in this case
5169       return N2;
5170     } else if (SCC.getOpcode() == ISD::SETCC) {
5171       // Fold to a simpler select_cc
5172       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5173                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5174                          SCC.getOperand(2));
5175     }
5176   }
5177
5178   // If we can fold this based on the true/false value, do so.
5179   if (SimplifySelectOps(N, N2, N3))
5180     return SDValue(N, 0);  // Don't revisit N.
5181
5182   // fold select_cc into other things, such as min/max/abs
5183   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5184 }
5185
5186 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5187   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5188                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5189                        SDLoc(N));
5190 }
5191
5192 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5193 // dag node into a ConstantSDNode or a build_vector of constants.
5194 // This function is called by the DAGCombiner when visiting sext/zext/aext
5195 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5196 // Vector extends are not folded if operations are legal; this is to
5197 // avoid introducing illegal build_vector dag nodes.
5198 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5199                                          SelectionDAG &DAG, bool LegalTypes,
5200                                          bool LegalOperations) {
5201   unsigned Opcode = N->getOpcode();
5202   SDValue N0 = N->getOperand(0);
5203   EVT VT = N->getValueType(0);
5204
5205   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5206          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5207
5208   // fold (sext c1) -> c1
5209   // fold (zext c1) -> c1
5210   // fold (aext c1) -> c1
5211   if (isa<ConstantSDNode>(N0))
5212     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5213
5214   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5215   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5216   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5217   EVT SVT = VT.getScalarType();
5218   if (!(VT.isVector() &&
5219       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5220       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5221     return nullptr;
5222
5223   // We can fold this node into a build_vector.
5224   unsigned VTBits = SVT.getSizeInBits();
5225   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5226   unsigned ShAmt = VTBits - EVTBits;
5227   SmallVector<SDValue, 8> Elts;
5228   unsigned NumElts = N0->getNumOperands();
5229   SDLoc DL(N);
5230
5231   for (unsigned i=0; i != NumElts; ++i) {
5232     SDValue Op = N0->getOperand(i);
5233     if (Op->getOpcode() == ISD::UNDEF) {
5234       Elts.push_back(DAG.getUNDEF(SVT));
5235       continue;
5236     }
5237
5238     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5239     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5240     if (Opcode == ISD::SIGN_EXTEND)
5241       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5242                                      SVT));
5243     else
5244       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5245                                      SVT));
5246   }
5247
5248   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5249 }
5250
5251 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5252 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5253 // transformation. Returns true if extension are possible and the above
5254 // mentioned transformation is profitable.
5255 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5256                                     unsigned ExtOpc,
5257                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5258                                     const TargetLowering &TLI) {
5259   bool HasCopyToRegUses = false;
5260   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5261   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5262                             UE = N0.getNode()->use_end();
5263        UI != UE; ++UI) {
5264     SDNode *User = *UI;
5265     if (User == N)
5266       continue;
5267     if (UI.getUse().getResNo() != N0.getResNo())
5268       continue;
5269     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5270     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5271       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5272       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5273         // Sign bits will be lost after a zext.
5274         return false;
5275       bool Add = false;
5276       for (unsigned i = 0; i != 2; ++i) {
5277         SDValue UseOp = User->getOperand(i);
5278         if (UseOp == N0)
5279           continue;
5280         if (!isa<ConstantSDNode>(UseOp))
5281           return false;
5282         Add = true;
5283       }
5284       if (Add)
5285         ExtendNodes.push_back(User);
5286       continue;
5287     }
5288     // If truncates aren't free and there are users we can't
5289     // extend, it isn't worthwhile.
5290     if (!isTruncFree)
5291       return false;
5292     // Remember if this value is live-out.
5293     if (User->getOpcode() == ISD::CopyToReg)
5294       HasCopyToRegUses = true;
5295   }
5296
5297   if (HasCopyToRegUses) {
5298     bool BothLiveOut = false;
5299     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5300          UI != UE; ++UI) {
5301       SDUse &Use = UI.getUse();
5302       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5303         BothLiveOut = true;
5304         break;
5305       }
5306     }
5307     if (BothLiveOut)
5308       // Both unextended and extended values are live out. There had better be
5309       // a good reason for the transformation.
5310       return ExtendNodes.size();
5311   }
5312   return true;
5313 }
5314
5315 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5316                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5317                                   ISD::NodeType ExtType) {
5318   // Extend SetCC uses if necessary.
5319   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5320     SDNode *SetCC = SetCCs[i];
5321     SmallVector<SDValue, 4> Ops;
5322
5323     for (unsigned j = 0; j != 2; ++j) {
5324       SDValue SOp = SetCC->getOperand(j);
5325       if (SOp == Trunc)
5326         Ops.push_back(ExtLoad);
5327       else
5328         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5329     }
5330
5331     Ops.push_back(SetCC->getOperand(2));
5332     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5333   }
5334 }
5335
5336 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5337 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5338   SDValue N0 = N->getOperand(0);
5339   EVT DstVT = N->getValueType(0);
5340   EVT SrcVT = N0.getValueType();
5341
5342   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5343           N->getOpcode() == ISD::ZERO_EXTEND) &&
5344          "Unexpected node type (not an extend)!");
5345
5346   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5347   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5348   //   (v8i32 (sext (v8i16 (load x))))
5349   // into:
5350   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5351   //                          (v4i32 (sextload (x + 16)))))
5352   // Where uses of the original load, i.e.:
5353   //   (v8i16 (load x))
5354   // are replaced with:
5355   //   (v8i16 (truncate
5356   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5357   //                            (v4i32 (sextload (x + 16)))))))
5358   //
5359   // This combine is only applicable to illegal, but splittable, vectors.
5360   // All legal types, and illegal non-vector types, are handled elsewhere.
5361   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5362   //
5363   if (N0->getOpcode() != ISD::LOAD)
5364     return SDValue();
5365
5366   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5367
5368   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5369       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5370       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5371     return SDValue();
5372
5373   SmallVector<SDNode *, 4> SetCCs;
5374   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5375     return SDValue();
5376
5377   ISD::LoadExtType ExtType =
5378       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5379
5380   // Try to split the vector types to get down to legal types.
5381   EVT SplitSrcVT = SrcVT;
5382   EVT SplitDstVT = DstVT;
5383   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5384          SplitSrcVT.getVectorNumElements() > 1) {
5385     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5386     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5387   }
5388
5389   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5390     return SDValue();
5391
5392   SDLoc DL(N);
5393   const unsigned NumSplits =
5394       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5395   const unsigned Stride = SplitSrcVT.getStoreSize();
5396   SmallVector<SDValue, 4> Loads;
5397   SmallVector<SDValue, 4> Chains;
5398
5399   SDValue BasePtr = LN0->getBasePtr();
5400   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5401     const unsigned Offset = Idx * Stride;
5402     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5403
5404     SDValue SplitLoad = DAG.getExtLoad(
5405         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5406         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5407         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5408         Align, LN0->getAAInfo());
5409
5410     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5411                           DAG.getConstant(Stride, BasePtr.getValueType()));
5412
5413     Loads.push_back(SplitLoad.getValue(0));
5414     Chains.push_back(SplitLoad.getValue(1));
5415   }
5416
5417   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5418   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5419
5420   CombineTo(N, NewValue);
5421
5422   // Replace uses of the original load (before extension)
5423   // with a truncate of the concatenated sextloaded vectors.
5424   SDValue Trunc =
5425       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5426   CombineTo(N0.getNode(), Trunc, NewChain);
5427   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5428                   (ISD::NodeType)N->getOpcode());
5429   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5430 }
5431
5432 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5433   SDValue N0 = N->getOperand(0);
5434   EVT VT = N->getValueType(0);
5435
5436   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5437                                               LegalOperations))
5438     return SDValue(Res, 0);
5439
5440   // fold (sext (sext x)) -> (sext x)
5441   // fold (sext (aext x)) -> (sext x)
5442   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5443     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5444                        N0.getOperand(0));
5445
5446   if (N0.getOpcode() == ISD::TRUNCATE) {
5447     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5448     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5449     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5450     if (NarrowLoad.getNode()) {
5451       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5452       if (NarrowLoad.getNode() != N0.getNode()) {
5453         CombineTo(N0.getNode(), NarrowLoad);
5454         // CombineTo deleted the truncate, if needed, but not what's under it.
5455         AddToWorklist(oye);
5456       }
5457       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5458     }
5459
5460     // See if the value being truncated is already sign extended.  If so, just
5461     // eliminate the trunc/sext pair.
5462     SDValue Op = N0.getOperand(0);
5463     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5464     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5465     unsigned DestBits = VT.getScalarType().getSizeInBits();
5466     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5467
5468     if (OpBits == DestBits) {
5469       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5470       // bits, it is already ready.
5471       if (NumSignBits > DestBits-MidBits)
5472         return Op;
5473     } else if (OpBits < DestBits) {
5474       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5475       // bits, just sext from i32.
5476       if (NumSignBits > OpBits-MidBits)
5477         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5478     } else {
5479       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5480       // bits, just truncate to i32.
5481       if (NumSignBits > OpBits-MidBits)
5482         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5483     }
5484
5485     // fold (sext (truncate x)) -> (sextinreg x).
5486     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5487                                                  N0.getValueType())) {
5488       if (OpBits < DestBits)
5489         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5490       else if (OpBits > DestBits)
5491         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5492       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5493                          DAG.getValueType(N0.getValueType()));
5494     }
5495   }
5496
5497   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5498   // Only generate vector extloads when 1) they're legal, and 2) they are
5499   // deemed desirable by the target.
5500   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5501       ((!LegalOperations && !VT.isVector() &&
5502         !cast<LoadSDNode>(N0)->isVolatile()) ||
5503        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5504     bool DoXform = true;
5505     SmallVector<SDNode*, 4> SetCCs;
5506     if (!N0.hasOneUse())
5507       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5508     if (VT.isVector())
5509       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5510     if (DoXform) {
5511       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5512       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5513                                        LN0->getChain(),
5514                                        LN0->getBasePtr(), N0.getValueType(),
5515                                        LN0->getMemOperand());
5516       CombineTo(N, ExtLoad);
5517       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5518                                   N0.getValueType(), ExtLoad);
5519       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5520       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5521                       ISD::SIGN_EXTEND);
5522       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5523     }
5524   }
5525
5526   // fold (sext (load x)) to multiple smaller sextloads.
5527   // Only on illegal but splittable vectors.
5528   if (SDValue ExtLoad = CombineExtLoad(N))
5529     return ExtLoad;
5530
5531   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5532   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5533   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5534       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5535     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5536     EVT MemVT = LN0->getMemoryVT();
5537     if ((!LegalOperations && !LN0->isVolatile()) ||
5538         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5539       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5540                                        LN0->getChain(),
5541                                        LN0->getBasePtr(), MemVT,
5542                                        LN0->getMemOperand());
5543       CombineTo(N, ExtLoad);
5544       CombineTo(N0.getNode(),
5545                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5546                             N0.getValueType(), ExtLoad),
5547                 ExtLoad.getValue(1));
5548       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5549     }
5550   }
5551
5552   // fold (sext (and/or/xor (load x), cst)) ->
5553   //      (and/or/xor (sextload x), (sext cst))
5554   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5555        N0.getOpcode() == ISD::XOR) &&
5556       isa<LoadSDNode>(N0.getOperand(0)) &&
5557       N0.getOperand(1).getOpcode() == ISD::Constant &&
5558       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5559       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5560     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5561     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5562       bool DoXform = true;
5563       SmallVector<SDNode*, 4> SetCCs;
5564       if (!N0.hasOneUse())
5565         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5566                                           SetCCs, TLI);
5567       if (DoXform) {
5568         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5569                                          LN0->getChain(), LN0->getBasePtr(),
5570                                          LN0->getMemoryVT(),
5571                                          LN0->getMemOperand());
5572         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5573         Mask = Mask.sext(VT.getSizeInBits());
5574         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5575                                   ExtLoad, DAG.getConstant(Mask, VT));
5576         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5577                                     SDLoc(N0.getOperand(0)),
5578                                     N0.getOperand(0).getValueType(), ExtLoad);
5579         CombineTo(N, And);
5580         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5581         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5582                         ISD::SIGN_EXTEND);
5583         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5584       }
5585     }
5586   }
5587
5588   if (N0.getOpcode() == ISD::SETCC) {
5589     EVT N0VT = N0.getOperand(0).getValueType();
5590     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5591     // Only do this before legalize for now.
5592     if (VT.isVector() && !LegalOperations &&
5593         TLI.getBooleanContents(N0VT) ==
5594             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5595       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5596       // of the same size as the compared operands. Only optimize sext(setcc())
5597       // if this is the case.
5598       EVT SVT = getSetCCResultType(N0VT);
5599
5600       // We know that the # elements of the results is the same as the
5601       // # elements of the compare (and the # elements of the compare result
5602       // for that matter).  Check to see that they are the same size.  If so,
5603       // we know that the element size of the sext'd result matches the
5604       // element size of the compare operands.
5605       if (VT.getSizeInBits() == SVT.getSizeInBits())
5606         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5607                              N0.getOperand(1),
5608                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5609
5610       // If the desired elements are smaller or larger than the source
5611       // elements we can use a matching integer vector type and then
5612       // truncate/sign extend
5613       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5614       if (SVT == MatchingVectorType) {
5615         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5616                                N0.getOperand(0), N0.getOperand(1),
5617                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5618         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5619       }
5620     }
5621
5622     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5623     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5624     SDValue NegOne =
5625       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5626     SDValue SCC =
5627       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5628                        NegOne, DAG.getConstant(0, VT),
5629                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5630     if (SCC.getNode()) return SCC;
5631
5632     if (!VT.isVector()) {
5633       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5634       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5635         SDLoc DL(N);
5636         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5637         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5638                                      N0.getOperand(0), N0.getOperand(1), CC);
5639         return DAG.getSelect(DL, VT, SetCC,
5640                              NegOne, DAG.getConstant(0, VT));
5641       }
5642     }
5643   }
5644
5645   // fold (sext x) -> (zext x) if the sign bit is known zero.
5646   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5647       DAG.SignBitIsZero(N0))
5648     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5649
5650   return SDValue();
5651 }
5652
5653 // isTruncateOf - If N is a truncate of some other value, return true, record
5654 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5655 // This function computes KnownZero to avoid a duplicated call to
5656 // computeKnownBits in the caller.
5657 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5658                          APInt &KnownZero) {
5659   APInt KnownOne;
5660   if (N->getOpcode() == ISD::TRUNCATE) {
5661     Op = N->getOperand(0);
5662     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5663     return true;
5664   }
5665
5666   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5667       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5668     return false;
5669
5670   SDValue Op0 = N->getOperand(0);
5671   SDValue Op1 = N->getOperand(1);
5672   assert(Op0.getValueType() == Op1.getValueType());
5673
5674   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5675   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5676   if (COp0 && COp0->isNullValue())
5677     Op = Op1;
5678   else if (COp1 && COp1->isNullValue())
5679     Op = Op0;
5680   else
5681     return false;
5682
5683   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5684
5685   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5686     return false;
5687
5688   return true;
5689 }
5690
5691 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5692   SDValue N0 = N->getOperand(0);
5693   EVT VT = N->getValueType(0);
5694
5695   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5696                                               LegalOperations))
5697     return SDValue(Res, 0);
5698
5699   // fold (zext (zext x)) -> (zext x)
5700   // fold (zext (aext x)) -> (zext x)
5701   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5702     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5703                        N0.getOperand(0));
5704
5705   // fold (zext (truncate x)) -> (zext x) or
5706   //      (zext (truncate x)) -> (truncate x)
5707   // This is valid when the truncated bits of x are already zero.
5708   // FIXME: We should extend this to work for vectors too.
5709   SDValue Op;
5710   APInt KnownZero;
5711   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5712     APInt TruncatedBits =
5713       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5714       APInt(Op.getValueSizeInBits(), 0) :
5715       APInt::getBitsSet(Op.getValueSizeInBits(),
5716                         N0.getValueSizeInBits(),
5717                         std::min(Op.getValueSizeInBits(),
5718                                  VT.getSizeInBits()));
5719     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5720       if (VT.bitsGT(Op.getValueType()))
5721         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5722       if (VT.bitsLT(Op.getValueType()))
5723         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5724
5725       return Op;
5726     }
5727   }
5728
5729   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5730   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5731   if (N0.getOpcode() == ISD::TRUNCATE) {
5732     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5733     if (NarrowLoad.getNode()) {
5734       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5735       if (NarrowLoad.getNode() != N0.getNode()) {
5736         CombineTo(N0.getNode(), NarrowLoad);
5737         // CombineTo deleted the truncate, if needed, but not what's under it.
5738         AddToWorklist(oye);
5739       }
5740       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5741     }
5742   }
5743
5744   // fold (zext (truncate x)) -> (and x, mask)
5745   if (N0.getOpcode() == ISD::TRUNCATE &&
5746       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5747
5748     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5749     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5750     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5751     if (NarrowLoad.getNode()) {
5752       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5753       if (NarrowLoad.getNode() != N0.getNode()) {
5754         CombineTo(N0.getNode(), NarrowLoad);
5755         // CombineTo deleted the truncate, if needed, but not what's under it.
5756         AddToWorklist(oye);
5757       }
5758       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5759     }
5760
5761     SDValue Op = N0.getOperand(0);
5762     if (Op.getValueType().bitsLT(VT)) {
5763       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5764       AddToWorklist(Op.getNode());
5765     } else if (Op.getValueType().bitsGT(VT)) {
5766       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5767       AddToWorklist(Op.getNode());
5768     }
5769     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5770                                   N0.getValueType().getScalarType());
5771   }
5772
5773   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5774   // if either of the casts is not free.
5775   if (N0.getOpcode() == ISD::AND &&
5776       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5777       N0.getOperand(1).getOpcode() == ISD::Constant &&
5778       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5779                            N0.getValueType()) ||
5780        !TLI.isZExtFree(N0.getValueType(), VT))) {
5781     SDValue X = N0.getOperand(0).getOperand(0);
5782     if (X.getValueType().bitsLT(VT)) {
5783       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5784     } else if (X.getValueType().bitsGT(VT)) {
5785       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5786     }
5787     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5788     Mask = Mask.zext(VT.getSizeInBits());
5789     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5790                        X, DAG.getConstant(Mask, VT));
5791   }
5792
5793   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5794   // Only generate vector extloads when 1) they're legal, and 2) they are
5795   // deemed desirable by the target.
5796   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5797       ((!LegalOperations && !VT.isVector() &&
5798         !cast<LoadSDNode>(N0)->isVolatile()) ||
5799        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5800     bool DoXform = true;
5801     SmallVector<SDNode*, 4> SetCCs;
5802     if (!N0.hasOneUse())
5803       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5804     if (VT.isVector())
5805       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5806     if (DoXform) {
5807       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5808       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5809                                        LN0->getChain(),
5810                                        LN0->getBasePtr(), N0.getValueType(),
5811                                        LN0->getMemOperand());
5812       CombineTo(N, ExtLoad);
5813       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5814                                   N0.getValueType(), ExtLoad);
5815       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5816
5817       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5818                       ISD::ZERO_EXTEND);
5819       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5820     }
5821   }
5822
5823   // fold (zext (load x)) to multiple smaller zextloads.
5824   // Only on illegal but splittable vectors.
5825   if (SDValue ExtLoad = CombineExtLoad(N))
5826     return ExtLoad;
5827
5828   // fold (zext (and/or/xor (load x), cst)) ->
5829   //      (and/or/xor (zextload x), (zext cst))
5830   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5831        N0.getOpcode() == ISD::XOR) &&
5832       isa<LoadSDNode>(N0.getOperand(0)) &&
5833       N0.getOperand(1).getOpcode() == ISD::Constant &&
5834       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5835       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5836     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5837     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5838       bool DoXform = true;
5839       SmallVector<SDNode*, 4> SetCCs;
5840       if (!N0.hasOneUse())
5841         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5842                                           SetCCs, TLI);
5843       if (DoXform) {
5844         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5845                                          LN0->getChain(), LN0->getBasePtr(),
5846                                          LN0->getMemoryVT(),
5847                                          LN0->getMemOperand());
5848         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5849         Mask = Mask.zext(VT.getSizeInBits());
5850         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5851                                   ExtLoad, DAG.getConstant(Mask, VT));
5852         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5853                                     SDLoc(N0.getOperand(0)),
5854                                     N0.getOperand(0).getValueType(), ExtLoad);
5855         CombineTo(N, And);
5856         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5857         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5858                         ISD::ZERO_EXTEND);
5859         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5860       }
5861     }
5862   }
5863
5864   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5865   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5866   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5867       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5868     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5869     EVT MemVT = LN0->getMemoryVT();
5870     if ((!LegalOperations && !LN0->isVolatile()) ||
5871         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5872       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5873                                        LN0->getChain(),
5874                                        LN0->getBasePtr(), MemVT,
5875                                        LN0->getMemOperand());
5876       CombineTo(N, ExtLoad);
5877       CombineTo(N0.getNode(),
5878                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5879                             ExtLoad),
5880                 ExtLoad.getValue(1));
5881       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5882     }
5883   }
5884
5885   if (N0.getOpcode() == ISD::SETCC) {
5886     if (!LegalOperations && VT.isVector() &&
5887         N0.getValueType().getVectorElementType() == MVT::i1) {
5888       EVT N0VT = N0.getOperand(0).getValueType();
5889       if (getSetCCResultType(N0VT) == N0.getValueType())
5890         return SDValue();
5891
5892       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5893       // Only do this before legalize for now.
5894       EVT EltVT = VT.getVectorElementType();
5895       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5896                                     DAG.getConstant(1, EltVT));
5897       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5898         // We know that the # elements of the results is the same as the
5899         // # elements of the compare (and the # elements of the compare result
5900         // for that matter).  Check to see that they are the same size.  If so,
5901         // we know that the element size of the sext'd result matches the
5902         // element size of the compare operands.
5903         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5904                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5905                                          N0.getOperand(1),
5906                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5907                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5908                                        OneOps));
5909
5910       // If the desired elements are smaller or larger than the source
5911       // elements we can use a matching integer vector type and then
5912       // truncate/sign extend
5913       EVT MatchingElementType =
5914         EVT::getIntegerVT(*DAG.getContext(),
5915                           N0VT.getScalarType().getSizeInBits());
5916       EVT MatchingVectorType =
5917         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5918                          N0VT.getVectorNumElements());
5919       SDValue VsetCC =
5920         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5921                       N0.getOperand(1),
5922                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5923       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5924                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5925                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5926     }
5927
5928     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5929     SDValue SCC =
5930       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5931                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5932                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5933     if (SCC.getNode()) return SCC;
5934   }
5935
5936   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5937   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5938       isa<ConstantSDNode>(N0.getOperand(1)) &&
5939       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5940       N0.hasOneUse()) {
5941     SDValue ShAmt = N0.getOperand(1);
5942     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5943     if (N0.getOpcode() == ISD::SHL) {
5944       SDValue InnerZExt = N0.getOperand(0);
5945       // If the original shl may be shifting out bits, do not perform this
5946       // transformation.
5947       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5948         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5949       if (ShAmtVal > KnownZeroBits)
5950         return SDValue();
5951     }
5952
5953     SDLoc DL(N);
5954
5955     // Ensure that the shift amount is wide enough for the shifted value.
5956     if (VT.getSizeInBits() >= 256)
5957       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5958
5959     return DAG.getNode(N0.getOpcode(), DL, VT,
5960                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5961                        ShAmt);
5962   }
5963
5964   return SDValue();
5965 }
5966
5967 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5968   SDValue N0 = N->getOperand(0);
5969   EVT VT = N->getValueType(0);
5970
5971   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5972                                               LegalOperations))
5973     return SDValue(Res, 0);
5974
5975   // fold (aext (aext x)) -> (aext x)
5976   // fold (aext (zext x)) -> (zext x)
5977   // fold (aext (sext x)) -> (sext x)
5978   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5979       N0.getOpcode() == ISD::ZERO_EXTEND ||
5980       N0.getOpcode() == ISD::SIGN_EXTEND)
5981     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5982
5983   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5984   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5985   if (N0.getOpcode() == ISD::TRUNCATE) {
5986     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5987     if (NarrowLoad.getNode()) {
5988       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5989       if (NarrowLoad.getNode() != N0.getNode()) {
5990         CombineTo(N0.getNode(), NarrowLoad);
5991         // CombineTo deleted the truncate, if needed, but not what's under it.
5992         AddToWorklist(oye);
5993       }
5994       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5995     }
5996   }
5997
5998   // fold (aext (truncate x))
5999   if (N0.getOpcode() == ISD::TRUNCATE) {
6000     SDValue TruncOp = N0.getOperand(0);
6001     if (TruncOp.getValueType() == VT)
6002       return TruncOp; // x iff x size == zext size.
6003     if (TruncOp.getValueType().bitsGT(VT))
6004       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6005     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6006   }
6007
6008   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6009   // if the trunc is not free.
6010   if (N0.getOpcode() == ISD::AND &&
6011       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6012       N0.getOperand(1).getOpcode() == ISD::Constant &&
6013       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6014                           N0.getValueType())) {
6015     SDValue X = N0.getOperand(0).getOperand(0);
6016     if (X.getValueType().bitsLT(VT)) {
6017       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6018     } else if (X.getValueType().bitsGT(VT)) {
6019       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6020     }
6021     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6022     Mask = Mask.zext(VT.getSizeInBits());
6023     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6024                        X, DAG.getConstant(Mask, VT));
6025   }
6026
6027   // fold (aext (load x)) -> (aext (truncate (extload x)))
6028   // None of the supported targets knows how to perform load and any_ext
6029   // on vectors in one instruction.  We only perform this transformation on
6030   // scalars.
6031   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6032       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6033       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6034     bool DoXform = true;
6035     SmallVector<SDNode*, 4> SetCCs;
6036     if (!N0.hasOneUse())
6037       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6038     if (DoXform) {
6039       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6040       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6041                                        LN0->getChain(),
6042                                        LN0->getBasePtr(), N0.getValueType(),
6043                                        LN0->getMemOperand());
6044       CombineTo(N, ExtLoad);
6045       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6046                                   N0.getValueType(), ExtLoad);
6047       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6048       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6049                       ISD::ANY_EXTEND);
6050       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6051     }
6052   }
6053
6054   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6055   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6056   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6057   if (N0.getOpcode() == ISD::LOAD &&
6058       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6059       N0.hasOneUse()) {
6060     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6061     ISD::LoadExtType ExtType = LN0->getExtensionType();
6062     EVT MemVT = LN0->getMemoryVT();
6063     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6064       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6065                                        VT, LN0->getChain(), LN0->getBasePtr(),
6066                                        MemVT, LN0->getMemOperand());
6067       CombineTo(N, ExtLoad);
6068       CombineTo(N0.getNode(),
6069                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6070                             N0.getValueType(), ExtLoad),
6071                 ExtLoad.getValue(1));
6072       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6073     }
6074   }
6075
6076   if (N0.getOpcode() == ISD::SETCC) {
6077     // For vectors:
6078     // aext(setcc) -> vsetcc
6079     // aext(setcc) -> truncate(vsetcc)
6080     // aext(setcc) -> aext(vsetcc)
6081     // Only do this before legalize for now.
6082     if (VT.isVector() && !LegalOperations) {
6083       EVT N0VT = N0.getOperand(0).getValueType();
6084         // We know that the # elements of the results is the same as the
6085         // # elements of the compare (and the # elements of the compare result
6086         // for that matter).  Check to see that they are the same size.  If so,
6087         // we know that the element size of the sext'd result matches the
6088         // element size of the compare operands.
6089       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6090         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6091                              N0.getOperand(1),
6092                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6093       // If the desired elements are smaller or larger than the source
6094       // elements we can use a matching integer vector type and then
6095       // truncate/any extend
6096       else {
6097         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6098         SDValue VsetCC =
6099           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6100                         N0.getOperand(1),
6101                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6102         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6103       }
6104     }
6105
6106     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6107     SDValue SCC =
6108       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6109                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6110                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6111     if (SCC.getNode())
6112       return SCC;
6113   }
6114
6115   return SDValue();
6116 }
6117
6118 /// See if the specified operand can be simplified with the knowledge that only
6119 /// the bits specified by Mask are used.  If so, return the simpler operand,
6120 /// otherwise return a null SDValue.
6121 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6122   switch (V.getOpcode()) {
6123   default: break;
6124   case ISD::Constant: {
6125     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6126     assert(CV && "Const value should be ConstSDNode.");
6127     const APInt &CVal = CV->getAPIntValue();
6128     APInt NewVal = CVal & Mask;
6129     if (NewVal != CVal)
6130       return DAG.getConstant(NewVal, V.getValueType());
6131     break;
6132   }
6133   case ISD::OR:
6134   case ISD::XOR:
6135     // If the LHS or RHS don't contribute bits to the or, drop them.
6136     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6137       return V.getOperand(1);
6138     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6139       return V.getOperand(0);
6140     break;
6141   case ISD::SRL:
6142     // Only look at single-use SRLs.
6143     if (!V.getNode()->hasOneUse())
6144       break;
6145     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6146       // See if we can recursively simplify the LHS.
6147       unsigned Amt = RHSC->getZExtValue();
6148
6149       // Watch out for shift count overflow though.
6150       if (Amt >= Mask.getBitWidth()) break;
6151       APInt NewMask = Mask << Amt;
6152       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6153       if (SimplifyLHS.getNode())
6154         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6155                            SimplifyLHS, V.getOperand(1));
6156     }
6157   }
6158   return SDValue();
6159 }
6160
6161 /// If the result of a wider load is shifted to right of N  bits and then
6162 /// truncated to a narrower type and where N is a multiple of number of bits of
6163 /// the narrower type, transform it to a narrower load from address + N / num of
6164 /// bits of new type. If the result is to be extended, also fold the extension
6165 /// to form a extending load.
6166 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6167   unsigned Opc = N->getOpcode();
6168
6169   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6170   SDValue N0 = N->getOperand(0);
6171   EVT VT = N->getValueType(0);
6172   EVT ExtVT = VT;
6173
6174   // This transformation isn't valid for vector loads.
6175   if (VT.isVector())
6176     return SDValue();
6177
6178   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6179   // extended to VT.
6180   if (Opc == ISD::SIGN_EXTEND_INREG) {
6181     ExtType = ISD::SEXTLOAD;
6182     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6183   } else if (Opc == ISD::SRL) {
6184     // Another special-case: SRL is basically zero-extending a narrower value.
6185     ExtType = ISD::ZEXTLOAD;
6186     N0 = SDValue(N, 0);
6187     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6188     if (!N01) return SDValue();
6189     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6190                               VT.getSizeInBits() - N01->getZExtValue());
6191   }
6192   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6193     return SDValue();
6194
6195   unsigned EVTBits = ExtVT.getSizeInBits();
6196
6197   // Do not generate loads of non-round integer types since these can
6198   // be expensive (and would be wrong if the type is not byte sized).
6199   if (!ExtVT.isRound())
6200     return SDValue();
6201
6202   unsigned ShAmt = 0;
6203   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6204     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6205       ShAmt = N01->getZExtValue();
6206       // Is the shift amount a multiple of size of VT?
6207       if ((ShAmt & (EVTBits-1)) == 0) {
6208         N0 = N0.getOperand(0);
6209         // Is the load width a multiple of size of VT?
6210         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6211           return SDValue();
6212       }
6213
6214       // At this point, we must have a load or else we can't do the transform.
6215       if (!isa<LoadSDNode>(N0)) return SDValue();
6216
6217       // Because a SRL must be assumed to *need* to zero-extend the high bits
6218       // (as opposed to anyext the high bits), we can't combine the zextload
6219       // lowering of SRL and an sextload.
6220       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6221         return SDValue();
6222
6223       // If the shift amount is larger than the input type then we're not
6224       // accessing any of the loaded bytes.  If the load was a zextload/extload
6225       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6226       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6227         return SDValue();
6228     }
6229   }
6230
6231   // If the load is shifted left (and the result isn't shifted back right),
6232   // we can fold the truncate through the shift.
6233   unsigned ShLeftAmt = 0;
6234   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6235       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6236     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6237       ShLeftAmt = N01->getZExtValue();
6238       N0 = N0.getOperand(0);
6239     }
6240   }
6241
6242   // If we haven't found a load, we can't narrow it.  Don't transform one with
6243   // multiple uses, this would require adding a new load.
6244   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6245     return SDValue();
6246
6247   // Don't change the width of a volatile load.
6248   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6249   if (LN0->isVolatile())
6250     return SDValue();
6251
6252   // Verify that we are actually reducing a load width here.
6253   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6254     return SDValue();
6255
6256   // For the transform to be legal, the load must produce only two values
6257   // (the value loaded and the chain).  Don't transform a pre-increment
6258   // load, for example, which produces an extra value.  Otherwise the
6259   // transformation is not equivalent, and the downstream logic to replace
6260   // uses gets things wrong.
6261   if (LN0->getNumValues() > 2)
6262     return SDValue();
6263
6264   // If the load that we're shrinking is an extload and we're not just
6265   // discarding the extension we can't simply shrink the load. Bail.
6266   // TODO: It would be possible to merge the extensions in some cases.
6267   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6268       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6269     return SDValue();
6270
6271   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6272     return SDValue();
6273
6274   EVT PtrType = N0.getOperand(1).getValueType();
6275
6276   if (PtrType == MVT::Untyped || PtrType.isExtended())
6277     // It's not possible to generate a constant of extended or untyped type.
6278     return SDValue();
6279
6280   // For big endian targets, we need to adjust the offset to the pointer to
6281   // load the correct bytes.
6282   if (TLI.isBigEndian()) {
6283     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6284     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6285     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6286   }
6287
6288   uint64_t PtrOff = ShAmt / 8;
6289   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6290   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6291                                PtrType, LN0->getBasePtr(),
6292                                DAG.getConstant(PtrOff, PtrType));
6293   AddToWorklist(NewPtr.getNode());
6294
6295   SDValue Load;
6296   if (ExtType == ISD::NON_EXTLOAD)
6297     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6298                         LN0->getPointerInfo().getWithOffset(PtrOff),
6299                         LN0->isVolatile(), LN0->isNonTemporal(),
6300                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6301   else
6302     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6303                           LN0->getPointerInfo().getWithOffset(PtrOff),
6304                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6305                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6306
6307   // Replace the old load's chain with the new load's chain.
6308   WorklistRemover DeadNodes(*this);
6309   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6310
6311   // Shift the result left, if we've swallowed a left shift.
6312   SDValue Result = Load;
6313   if (ShLeftAmt != 0) {
6314     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6315     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6316       ShImmTy = VT;
6317     // If the shift amount is as large as the result size (but, presumably,
6318     // no larger than the source) then the useful bits of the result are
6319     // zero; we can't simply return the shortened shift, because the result
6320     // of that operation is undefined.
6321     if (ShLeftAmt >= VT.getSizeInBits())
6322       Result = DAG.getConstant(0, VT);
6323     else
6324       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6325                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6326   }
6327
6328   // Return the new loaded value.
6329   return Result;
6330 }
6331
6332 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6333   SDValue N0 = N->getOperand(0);
6334   SDValue N1 = N->getOperand(1);
6335   EVT VT = N->getValueType(0);
6336   EVT EVT = cast<VTSDNode>(N1)->getVT();
6337   unsigned VTBits = VT.getScalarType().getSizeInBits();
6338   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6339
6340   // fold (sext_in_reg c1) -> c1
6341   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6342     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6343
6344   // If the input is already sign extended, just drop the extension.
6345   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6346     return N0;
6347
6348   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6349   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6350       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6351     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6352                        N0.getOperand(0), N1);
6353
6354   // fold (sext_in_reg (sext x)) -> (sext x)
6355   // fold (sext_in_reg (aext x)) -> (sext x)
6356   // if x is small enough.
6357   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6358     SDValue N00 = N0.getOperand(0);
6359     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6360         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6361       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6362   }
6363
6364   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6365   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6366     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6367
6368   // fold operands of sext_in_reg based on knowledge that the top bits are not
6369   // demanded.
6370   if (SimplifyDemandedBits(SDValue(N, 0)))
6371     return SDValue(N, 0);
6372
6373   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6374   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6375   SDValue NarrowLoad = ReduceLoadWidth(N);
6376   if (NarrowLoad.getNode())
6377     return NarrowLoad;
6378
6379   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6380   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6381   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6382   if (N0.getOpcode() == ISD::SRL) {
6383     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6384       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6385         // We can turn this into an SRA iff the input to the SRL is already sign
6386         // extended enough.
6387         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6388         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6389           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6390                              N0.getOperand(0), N0.getOperand(1));
6391       }
6392   }
6393
6394   // fold (sext_inreg (extload x)) -> (sextload x)
6395   if (ISD::isEXTLoad(N0.getNode()) &&
6396       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6397       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6398       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6399        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6400     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6401     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6402                                      LN0->getChain(),
6403                                      LN0->getBasePtr(), EVT,
6404                                      LN0->getMemOperand());
6405     CombineTo(N, ExtLoad);
6406     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6407     AddToWorklist(ExtLoad.getNode());
6408     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6409   }
6410   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6411   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6412       N0.hasOneUse() &&
6413       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6414       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6415        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6416     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6417     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6418                                      LN0->getChain(),
6419                                      LN0->getBasePtr(), EVT,
6420                                      LN0->getMemOperand());
6421     CombineTo(N, ExtLoad);
6422     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6423     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6424   }
6425
6426   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6427   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6428     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6429                                        N0.getOperand(1), false);
6430     if (BSwap.getNode())
6431       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6432                          BSwap, N1);
6433   }
6434
6435   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6436   // into a build_vector.
6437   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6438     SmallVector<SDValue, 8> Elts;
6439     unsigned NumElts = N0->getNumOperands();
6440     unsigned ShAmt = VTBits - EVTBits;
6441
6442     for (unsigned i = 0; i != NumElts; ++i) {
6443       SDValue Op = N0->getOperand(i);
6444       if (Op->getOpcode() == ISD::UNDEF) {
6445         Elts.push_back(Op);
6446         continue;
6447       }
6448
6449       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6450       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6451       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6452                                      Op.getValueType()));
6453     }
6454
6455     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6456   }
6457
6458   return SDValue();
6459 }
6460
6461 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6462   SDValue N0 = N->getOperand(0);
6463   EVT VT = N->getValueType(0);
6464   bool isLE = TLI.isLittleEndian();
6465
6466   // noop truncate
6467   if (N0.getValueType() == N->getValueType(0))
6468     return N0;
6469   // fold (truncate c1) -> c1
6470   if (isa<ConstantSDNode>(N0))
6471     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6472   // fold (truncate (truncate x)) -> (truncate x)
6473   if (N0.getOpcode() == ISD::TRUNCATE)
6474     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6475   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6476   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6477       N0.getOpcode() == ISD::SIGN_EXTEND ||
6478       N0.getOpcode() == ISD::ANY_EXTEND) {
6479     if (N0.getOperand(0).getValueType().bitsLT(VT))
6480       // if the source is smaller than the dest, we still need an extend
6481       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6482                          N0.getOperand(0));
6483     if (N0.getOperand(0).getValueType().bitsGT(VT))
6484       // if the source is larger than the dest, than we just need the truncate
6485       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6486     // if the source and dest are the same type, we can drop both the extend
6487     // and the truncate.
6488     return N0.getOperand(0);
6489   }
6490
6491   // Fold extract-and-trunc into a narrow extract. For example:
6492   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6493   //   i32 y = TRUNCATE(i64 x)
6494   //        -- becomes --
6495   //   v16i8 b = BITCAST (v2i64 val)
6496   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6497   //
6498   // Note: We only run this optimization after type legalization (which often
6499   // creates this pattern) and before operation legalization after which
6500   // we need to be more careful about the vector instructions that we generate.
6501   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6502       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6503
6504     EVT VecTy = N0.getOperand(0).getValueType();
6505     EVT ExTy = N0.getValueType();
6506     EVT TrTy = N->getValueType(0);
6507
6508     unsigned NumElem = VecTy.getVectorNumElements();
6509     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6510
6511     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6512     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6513
6514     SDValue EltNo = N0->getOperand(1);
6515     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6516       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6517       EVT IndexTy = TLI.getVectorIdxTy();
6518       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6519
6520       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6521                               NVT, N0.getOperand(0));
6522
6523       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6524                          SDLoc(N), TrTy, V,
6525                          DAG.getConstant(Index, IndexTy));
6526     }
6527   }
6528
6529   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6530   if (N0.getOpcode() == ISD::SELECT) {
6531     EVT SrcVT = N0.getValueType();
6532     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6533         TLI.isTruncateFree(SrcVT, VT)) {
6534       SDLoc SL(N0);
6535       SDValue Cond = N0.getOperand(0);
6536       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6537       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6538       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6539     }
6540   }
6541
6542   // Fold a series of buildvector, bitcast, and truncate if possible.
6543   // For example fold
6544   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6545   //   (2xi32 (buildvector x, y)).
6546   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6547       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6548       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6549       N0.getOperand(0).hasOneUse()) {
6550
6551     SDValue BuildVect = N0.getOperand(0);
6552     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6553     EVT TruncVecEltTy = VT.getVectorElementType();
6554
6555     // Check that the element types match.
6556     if (BuildVectEltTy == TruncVecEltTy) {
6557       // Now we only need to compute the offset of the truncated elements.
6558       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6559       unsigned TruncVecNumElts = VT.getVectorNumElements();
6560       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6561
6562       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6563              "Invalid number of elements");
6564
6565       SmallVector<SDValue, 8> Opnds;
6566       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6567         Opnds.push_back(BuildVect.getOperand(i));
6568
6569       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6570     }
6571   }
6572
6573   // See if we can simplify the input to this truncate through knowledge that
6574   // only the low bits are being used.
6575   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6576   // Currently we only perform this optimization on scalars because vectors
6577   // may have different active low bits.
6578   if (!VT.isVector()) {
6579     SDValue Shorter =
6580       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6581                                                VT.getSizeInBits()));
6582     if (Shorter.getNode())
6583       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6584   }
6585   // fold (truncate (load x)) -> (smaller load x)
6586   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6587   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6588     SDValue Reduced = ReduceLoadWidth(N);
6589     if (Reduced.getNode())
6590       return Reduced;
6591     // Handle the case where the load remains an extending load even
6592     // after truncation.
6593     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6594       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6595       if (!LN0->isVolatile() &&
6596           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6597         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6598                                          VT, LN0->getChain(), LN0->getBasePtr(),
6599                                          LN0->getMemoryVT(),
6600                                          LN0->getMemOperand());
6601         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6602         return NewLoad;
6603       }
6604     }
6605   }
6606   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6607   // where ... are all 'undef'.
6608   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6609     SmallVector<EVT, 8> VTs;
6610     SDValue V;
6611     unsigned Idx = 0;
6612     unsigned NumDefs = 0;
6613
6614     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6615       SDValue X = N0.getOperand(i);
6616       if (X.getOpcode() != ISD::UNDEF) {
6617         V = X;
6618         Idx = i;
6619         NumDefs++;
6620       }
6621       // Stop if more than one members are non-undef.
6622       if (NumDefs > 1)
6623         break;
6624       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6625                                      VT.getVectorElementType(),
6626                                      X.getValueType().getVectorNumElements()));
6627     }
6628
6629     if (NumDefs == 0)
6630       return DAG.getUNDEF(VT);
6631
6632     if (NumDefs == 1) {
6633       assert(V.getNode() && "The single defined operand is empty!");
6634       SmallVector<SDValue, 8> Opnds;
6635       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6636         if (i != Idx) {
6637           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6638           continue;
6639         }
6640         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6641         AddToWorklist(NV.getNode());
6642         Opnds.push_back(NV);
6643       }
6644       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6645     }
6646   }
6647
6648   // Simplify the operands using demanded-bits information.
6649   if (!VT.isVector() &&
6650       SimplifyDemandedBits(SDValue(N, 0)))
6651     return SDValue(N, 0);
6652
6653   return SDValue();
6654 }
6655
6656 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6657   SDValue Elt = N->getOperand(i);
6658   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6659     return Elt.getNode();
6660   return Elt.getOperand(Elt.getResNo()).getNode();
6661 }
6662
6663 /// build_pair (load, load) -> load
6664 /// if load locations are consecutive.
6665 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6666   assert(N->getOpcode() == ISD::BUILD_PAIR);
6667
6668   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6669   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6670   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6671       LD1->getAddressSpace() != LD2->getAddressSpace())
6672     return SDValue();
6673   EVT LD1VT = LD1->getValueType(0);
6674
6675   if (ISD::isNON_EXTLoad(LD2) &&
6676       LD2->hasOneUse() &&
6677       // If both are volatile this would reduce the number of volatile loads.
6678       // If one is volatile it might be ok, but play conservative and bail out.
6679       !LD1->isVolatile() &&
6680       !LD2->isVolatile() &&
6681       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6682     unsigned Align = LD1->getAlignment();
6683     unsigned NewAlign = TLI.getDataLayout()->
6684       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6685
6686     if (NewAlign <= Align &&
6687         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6688       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6689                          LD1->getBasePtr(), LD1->getPointerInfo(),
6690                          false, false, false, Align);
6691   }
6692
6693   return SDValue();
6694 }
6695
6696 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6697   SDValue N0 = N->getOperand(0);
6698   EVT VT = N->getValueType(0);
6699
6700   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6701   // Only do this before legalize, since afterward the target may be depending
6702   // on the bitconvert.
6703   // First check to see if this is all constant.
6704   if (!LegalTypes &&
6705       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6706       VT.isVector()) {
6707     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6708
6709     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6710     assert(!DestEltVT.isVector() &&
6711            "Element type of vector ValueType must not be vector!");
6712     if (isSimple)
6713       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6714   }
6715
6716   // If the input is a constant, let getNode fold it.
6717   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6718     // If we can't allow illegal operations, we need to check that this is just
6719     // a fp -> int or int -> conversion and that the resulting operation will
6720     // be legal.
6721     if (!LegalOperations ||
6722         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6723          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6724         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6725          TLI.isOperationLegal(ISD::Constant, VT)))
6726       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6727   }
6728
6729   // (conv (conv x, t1), t2) -> (conv x, t2)
6730   if (N0.getOpcode() == ISD::BITCAST)
6731     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6732                        N0.getOperand(0));
6733
6734   // fold (conv (load x)) -> (load (conv*)x)
6735   // If the resultant load doesn't need a higher alignment than the original!
6736   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6737       // Do not change the width of a volatile load.
6738       !cast<LoadSDNode>(N0)->isVolatile() &&
6739       // Do not remove the cast if the types differ in endian layout.
6740       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6741       TLI.hasBigEndianPartOrdering(VT) &&
6742       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6743       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6744     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6745     unsigned Align = TLI.getDataLayout()->
6746       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6747     unsigned OrigAlign = LN0->getAlignment();
6748
6749     if (Align <= OrigAlign) {
6750       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6751                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6752                                  LN0->isVolatile(), LN0->isNonTemporal(),
6753                                  LN0->isInvariant(), OrigAlign,
6754                                  LN0->getAAInfo());
6755       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6756       return Load;
6757     }
6758   }
6759
6760   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6761   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6762   // This often reduces constant pool loads.
6763   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6764        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6765       N0.getNode()->hasOneUse() && VT.isInteger() &&
6766       !VT.isVector() && !N0.getValueType().isVector()) {
6767     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6768                                   N0.getOperand(0));
6769     AddToWorklist(NewConv.getNode());
6770
6771     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6772     if (N0.getOpcode() == ISD::FNEG)
6773       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6774                          NewConv, DAG.getConstant(SignBit, VT));
6775     assert(N0.getOpcode() == ISD::FABS);
6776     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6777                        NewConv, DAG.getConstant(~SignBit, VT));
6778   }
6779
6780   // fold (bitconvert (fcopysign cst, x)) ->
6781   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6782   // Note that we don't handle (copysign x, cst) because this can always be
6783   // folded to an fneg or fabs.
6784   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6785       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6786       VT.isInteger() && !VT.isVector()) {
6787     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6788     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6789     if (isTypeLegal(IntXVT)) {
6790       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6791                               IntXVT, N0.getOperand(1));
6792       AddToWorklist(X.getNode());
6793
6794       // If X has a different width than the result/lhs, sext it or truncate it.
6795       unsigned VTWidth = VT.getSizeInBits();
6796       if (OrigXWidth < VTWidth) {
6797         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6798         AddToWorklist(X.getNode());
6799       } else if (OrigXWidth > VTWidth) {
6800         // To get the sign bit in the right place, we have to shift it right
6801         // before truncating.
6802         X = DAG.getNode(ISD::SRL, SDLoc(X),
6803                         X.getValueType(), X,
6804                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6805         AddToWorklist(X.getNode());
6806         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6807         AddToWorklist(X.getNode());
6808       }
6809
6810       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6811       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6812                       X, DAG.getConstant(SignBit, VT));
6813       AddToWorklist(X.getNode());
6814
6815       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6816                                 VT, N0.getOperand(0));
6817       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6818                         Cst, DAG.getConstant(~SignBit, VT));
6819       AddToWorklist(Cst.getNode());
6820
6821       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6822     }
6823   }
6824
6825   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6826   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6827     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6828     if (CombineLD.getNode())
6829       return CombineLD;
6830   }
6831
6832   return SDValue();
6833 }
6834
6835 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6836   EVT VT = N->getValueType(0);
6837   return CombineConsecutiveLoads(N, VT);
6838 }
6839
6840 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6841 /// operands. DstEltVT indicates the destination element value type.
6842 SDValue DAGCombiner::
6843 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6844   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6845
6846   // If this is already the right type, we're done.
6847   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6848
6849   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6850   unsigned DstBitSize = DstEltVT.getSizeInBits();
6851
6852   // If this is a conversion of N elements of one type to N elements of another
6853   // type, convert each element.  This handles FP<->INT cases.
6854   if (SrcBitSize == DstBitSize) {
6855     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6856                               BV->getValueType(0).getVectorNumElements());
6857
6858     // Due to the FP element handling below calling this routine recursively,
6859     // we can end up with a scalar-to-vector node here.
6860     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6861       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6862                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6863                                      DstEltVT, BV->getOperand(0)));
6864
6865     SmallVector<SDValue, 8> Ops;
6866     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6867       SDValue Op = BV->getOperand(i);
6868       // If the vector element type is not legal, the BUILD_VECTOR operands
6869       // are promoted and implicitly truncated.  Make that explicit here.
6870       if (Op.getValueType() != SrcEltVT)
6871         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6872       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6873                                 DstEltVT, Op));
6874       AddToWorklist(Ops.back().getNode());
6875     }
6876     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6877   }
6878
6879   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6880   // handle annoying details of growing/shrinking FP values, we convert them to
6881   // int first.
6882   if (SrcEltVT.isFloatingPoint()) {
6883     // Convert the input float vector to a int vector where the elements are the
6884     // same sizes.
6885     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6886     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6887     SrcEltVT = IntVT;
6888   }
6889
6890   // Now we know the input is an integer vector.  If the output is a FP type,
6891   // convert to integer first, then to FP of the right size.
6892   if (DstEltVT.isFloatingPoint()) {
6893     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6894     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6895
6896     // Next, convert to FP elements of the same size.
6897     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6898   }
6899
6900   // Okay, we know the src/dst types are both integers of differing types.
6901   // Handling growing first.
6902   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6903   if (SrcBitSize < DstBitSize) {
6904     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6905
6906     SmallVector<SDValue, 8> Ops;
6907     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6908          i += NumInputsPerOutput) {
6909       bool isLE = TLI.isLittleEndian();
6910       APInt NewBits = APInt(DstBitSize, 0);
6911       bool EltIsUndef = true;
6912       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6913         // Shift the previously computed bits over.
6914         NewBits <<= SrcBitSize;
6915         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6916         if (Op.getOpcode() == ISD::UNDEF) continue;
6917         EltIsUndef = false;
6918
6919         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6920                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6921       }
6922
6923       if (EltIsUndef)
6924         Ops.push_back(DAG.getUNDEF(DstEltVT));
6925       else
6926         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6927     }
6928
6929     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6930     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6931   }
6932
6933   // Finally, this must be the case where we are shrinking elements: each input
6934   // turns into multiple outputs.
6935   bool isS2V = ISD::isScalarToVector(BV);
6936   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6937   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6938                             NumOutputsPerInput*BV->getNumOperands());
6939   SmallVector<SDValue, 8> Ops;
6940
6941   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6942     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6943       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
6944       continue;
6945     }
6946
6947     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6948                   getAPIntValue().zextOrTrunc(SrcBitSize);
6949
6950     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6951       APInt ThisVal = OpVal.trunc(DstBitSize);
6952       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6953       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6954         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6955         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6956                            Ops[0]);
6957       OpVal = OpVal.lshr(DstBitSize);
6958     }
6959
6960     // For big endian targets, swap the order of the pieces of each element.
6961     if (TLI.isBigEndian())
6962       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6963   }
6964
6965   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6966 }
6967
6968 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
6969 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
6970                                        bool Aggressive,
6971                                        SDNode *N,
6972                                        const TargetLowering &TLI,
6973                                        SelectionDAG &DAG) {
6974   SDValue N0 = N->getOperand(0);
6975   SDValue N1 = N->getOperand(1);
6976   EVT VT = N->getValueType(0);
6977
6978   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6979   if (N0.getOpcode() == ISD::FMUL &&
6980       (Aggressive || N0->hasOneUse())) {
6981     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
6982                        N0.getOperand(0), N0.getOperand(1), N1);
6983   }
6984
6985   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6986   // Note: Commutes FADD operands.
6987   if (N1.getOpcode() == ISD::FMUL &&
6988       (Aggressive || N1->hasOneUse())) {
6989     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
6990                        N1.getOperand(0), N1.getOperand(1), N0);
6991   }
6992
6993   // More folding opportunities when target permits.
6994   if (Aggressive) {
6995     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
6996     if (N0.getOpcode() == ISD::FMA &&
6997         N0.getOperand(2).getOpcode() == ISD::FMUL) {
6998       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
6999                          N0.getOperand(0), N0.getOperand(1),
7000                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7001                                      N0.getOperand(2).getOperand(0),
7002                                      N0.getOperand(2).getOperand(1),
7003                                      N1));
7004     }
7005
7006     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7007     if (N1->getOpcode() == ISD::FMA &&
7008         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7009       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7010                          N1.getOperand(0), N1.getOperand(1),
7011                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7012                                      N1.getOperand(2).getOperand(0),
7013                                      N1.getOperand(2).getOperand(1),
7014                                      N0));
7015     }
7016   }
7017
7018   return SDValue();
7019 }
7020
7021 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7022                                        bool Aggressive,
7023                                        SDNode *N,
7024                                        const TargetLowering &TLI,
7025                                        SelectionDAG &DAG) {
7026   SDValue N0 = N->getOperand(0);
7027   SDValue N1 = N->getOperand(1);
7028   EVT VT = N->getValueType(0);
7029
7030   SDLoc SL(N);
7031
7032   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7033   if (N0.getOpcode() == ISD::FMUL &&
7034       (Aggressive || N0->hasOneUse())) {
7035     return DAG.getNode(FusedOpcode, SL, VT,
7036                        N0.getOperand(0), N0.getOperand(1),
7037                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7038   }
7039
7040   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7041   // Note: Commutes FSUB operands.
7042   if (N1.getOpcode() == ISD::FMUL &&
7043       (Aggressive || N1->hasOneUse()))
7044     return DAG.getNode(FusedOpcode, SL, VT,
7045                        DAG.getNode(ISD::FNEG, SL, VT,
7046                                    N1.getOperand(0)),
7047                        N1.getOperand(1), N0);
7048
7049   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7050   if (N0.getOpcode() == ISD::FNEG &&
7051       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7052       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7053     SDValue N00 = N0.getOperand(0).getOperand(0);
7054     SDValue N01 = N0.getOperand(0).getOperand(1);
7055     return DAG.getNode(FusedOpcode, SL, VT,
7056                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7057                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7058   }
7059
7060   // More folding opportunities when target permits.
7061   if (Aggressive) {
7062     // fold (fsub (fma x, y, (fmul u, v)), z)
7063     //   -> (fma x, y (fma u, v, (fneg z)))
7064     if (N0.getOpcode() == FusedOpcode &&
7065         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7066       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7067                          N0.getOperand(0), N0.getOperand(1),
7068                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7069                                      N0.getOperand(2).getOperand(0),
7070                                      N0.getOperand(2).getOperand(1),
7071                                      DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7072                                                  N1)));
7073     }
7074
7075     // fold (fsub x, (fma y, z, (fmul u, v)))
7076     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7077     if (N1.getOpcode() == FusedOpcode &&
7078         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7079       SDValue N20 = N1.getOperand(2).getOperand(0);
7080       SDValue N21 = N1.getOperand(2).getOperand(1);
7081       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7082                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7083                                      N1.getOperand(0)),
7084                          N1.getOperand(1),
7085                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7086                                      DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7087                                                  N20),
7088                                      N21, N0));
7089     }
7090   }
7091
7092   return SDValue();
7093 }
7094
7095 SDValue DAGCombiner::visitFADD(SDNode *N) {
7096   SDValue N0 = N->getOperand(0);
7097   SDValue N1 = N->getOperand(1);
7098   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7099   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7100   EVT VT = N->getValueType(0);
7101   const TargetOptions &Options = DAG.getTarget().Options;
7102
7103   // fold vector ops
7104   if (VT.isVector()) {
7105     SDValue FoldedVOp = SimplifyVBinOp(N);
7106     if (FoldedVOp.getNode()) return FoldedVOp;
7107   }
7108
7109   // fold (fadd c1, c2) -> c1 + c2
7110   if (N0CFP && N1CFP)
7111     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7112
7113   // canonicalize constant to RHS
7114   if (N0CFP && !N1CFP)
7115     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7116
7117   // fold (fadd A, (fneg B)) -> (fsub A, B)
7118   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7119       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7120     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7121                        GetNegatedExpression(N1, DAG, LegalOperations));
7122
7123   // fold (fadd (fneg A), B) -> (fsub B, A)
7124   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7125       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7126     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7127                        GetNegatedExpression(N0, DAG, LegalOperations));
7128
7129   // If 'unsafe math' is enabled, fold lots of things.
7130   if (Options.UnsafeFPMath) {
7131     // No FP constant should be created after legalization as Instruction
7132     // Selection pass has a hard time dealing with FP constants.
7133     bool AllowNewConst = (Level < AfterLegalizeDAG);
7134
7135     // fold (fadd A, 0) -> A
7136     if (N1CFP && N1CFP->getValueAPF().isZero())
7137       return N0;
7138
7139     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7140     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7141         isa<ConstantFPSDNode>(N0.getOperand(1)))
7142       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7143                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7144                                      N0.getOperand(1), N1));
7145
7146     // If allowed, fold (fadd (fneg x), x) -> 0.0
7147     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7148       return DAG.getConstantFP(0.0, VT);
7149
7150     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7151     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7152       return DAG.getConstantFP(0.0, VT);
7153
7154     // We can fold chains of FADD's of the same value into multiplications.
7155     // This transform is not safe in general because we are reducing the number
7156     // of rounding steps.
7157     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7158       if (N0.getOpcode() == ISD::FMUL) {
7159         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7160         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7161
7162         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7163         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7164           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7165                                        SDValue(CFP01, 0),
7166                                        DAG.getConstantFP(1.0, VT));
7167           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7168         }
7169
7170         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7171         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7172             N1.getOperand(0) == N1.getOperand(1) &&
7173             N0.getOperand(0) == N1.getOperand(0)) {
7174           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7175                                        SDValue(CFP01, 0),
7176                                        DAG.getConstantFP(2.0, VT));
7177           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7178                              N0.getOperand(0), NewCFP);
7179         }
7180       }
7181
7182       if (N1.getOpcode() == ISD::FMUL) {
7183         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7184         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7185
7186         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7187         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7188           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7189                                        SDValue(CFP11, 0),
7190                                        DAG.getConstantFP(1.0, VT));
7191           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7192         }
7193
7194         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7195         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7196             N0.getOperand(0) == N0.getOperand(1) &&
7197             N1.getOperand(0) == N0.getOperand(0)) {
7198           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7199                                        SDValue(CFP11, 0),
7200                                        DAG.getConstantFP(2.0, VT));
7201           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7202         }
7203       }
7204
7205       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7206         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7207         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7208         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7209             (N0.getOperand(0) == N1))
7210           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7211                              N1, DAG.getConstantFP(3.0, VT));
7212       }
7213
7214       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7215         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7216         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7217         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7218             N1.getOperand(0) == N0)
7219           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7220                              N0, DAG.getConstantFP(3.0, VT));
7221       }
7222
7223       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7224       if (AllowNewConst &&
7225           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7226           N0.getOperand(0) == N0.getOperand(1) &&
7227           N1.getOperand(0) == N1.getOperand(1) &&
7228           N0.getOperand(0) == N1.getOperand(0))
7229         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7230                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7231     }
7232   } // enable-unsafe-fp-math
7233
7234   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7235     // Assume if there is an fmad instruction that it should be aggressively
7236     // used.
7237     if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7238       return Fused;
7239   }
7240
7241   // FADD -> FMA combines:
7242   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7243       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7244       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7245
7246     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7247       // Don't form FMA if we are preferring FMAD.
7248       if (SDValue Fused
7249           = performFaddFmulCombines(ISD::FMA,
7250                                     TLI.enableAggressiveFMAFusion(VT),
7251                                     N, TLI, DAG)) {
7252         return Fused;
7253       }
7254     }
7255
7256     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7257     // to combine into FMA, arrange such nodes accordingly.
7258     if (TLI.isFPExtFree(VT)) {
7259
7260       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7261       if (N0.getOpcode() == ISD::FP_EXTEND) {
7262         SDValue N00 = N0.getOperand(0);
7263         if (N00.getOpcode() == ISD::FMUL)
7264           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7265                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7266                                          N00.getOperand(0)),
7267                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7268                                          N00.getOperand(1)), N1);
7269       }
7270
7271       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7272       // Note: Commutes FADD operands.
7273       if (N1.getOpcode() == ISD::FP_EXTEND) {
7274         SDValue N10 = N1.getOperand(0);
7275         if (N10.getOpcode() == ISD::FMUL)
7276           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7277                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7278                                          N10.getOperand(0)),
7279                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7280                                          N10.getOperand(1)), N0);
7281       }
7282     }
7283   }
7284
7285   return SDValue();
7286 }
7287
7288 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7289   SDValue N0 = N->getOperand(0);
7290   SDValue N1 = N->getOperand(1);
7291   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7292   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7293   EVT VT = N->getValueType(0);
7294   SDLoc dl(N);
7295   const TargetOptions &Options = DAG.getTarget().Options;
7296
7297   // fold vector ops
7298   if (VT.isVector()) {
7299     SDValue FoldedVOp = SimplifyVBinOp(N);
7300     if (FoldedVOp.getNode()) return FoldedVOp;
7301   }
7302
7303   // fold (fsub c1, c2) -> c1-c2
7304   if (N0CFP && N1CFP)
7305     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7306
7307   // fold (fsub A, (fneg B)) -> (fadd A, B)
7308   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7309     return DAG.getNode(ISD::FADD, dl, VT, N0,
7310                        GetNegatedExpression(N1, DAG, LegalOperations));
7311
7312   // If 'unsafe math' is enabled, fold lots of things.
7313   if (Options.UnsafeFPMath) {
7314     // (fsub A, 0) -> A
7315     if (N1CFP && N1CFP->getValueAPF().isZero())
7316       return N0;
7317
7318     // (fsub 0, B) -> -B
7319     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7320       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7321         return GetNegatedExpression(N1, DAG, LegalOperations);
7322       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7323         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7324     }
7325
7326     // (fsub x, x) -> 0.0
7327     if (N0 == N1)
7328       return DAG.getConstantFP(0.0f, VT);
7329
7330     // (fsub x, (fadd x, y)) -> (fneg y)
7331     // (fsub x, (fadd y, x)) -> (fneg y)
7332     if (N1.getOpcode() == ISD::FADD) {
7333       SDValue N10 = N1->getOperand(0);
7334       SDValue N11 = N1->getOperand(1);
7335
7336       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7337         return GetNegatedExpression(N11, DAG, LegalOperations);
7338
7339       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7340         return GetNegatedExpression(N10, DAG, LegalOperations);
7341     }
7342   }
7343
7344   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7345     // Assume if there is an fmad instruction that it should be aggressively
7346     // used.
7347     if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7348       return Fused;
7349   }
7350
7351   // FSUB -> FMA combines:
7352   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7353       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7354       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7355
7356     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7357       // Don't form FMA if we are preferring FMAD.
7358
7359       if (SDValue Fused
7360           = performFsubFmulCombines(ISD::FMA,
7361                                     TLI.enableAggressiveFMAFusion(VT),
7362                                     N, TLI, DAG)) {
7363         return Fused;
7364       }
7365     }
7366
7367     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7368     // to combine into FMA, arrange such nodes accordingly.
7369     if (TLI.isFPExtFree(VT)) {
7370       // fold (fsub (fpext (fmul x, y)), z)
7371       //   -> (fma (fpext x), (fpext y), (fneg z))
7372       if (N0.getOpcode() == ISD::FP_EXTEND) {
7373         SDValue N00 = N0.getOperand(0);
7374         if (N00.getOpcode() == ISD::FMUL)
7375           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7376                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7377                                          N00.getOperand(0)),
7378                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7379                                          N00.getOperand(1)),
7380                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7381       }
7382
7383       // fold (fsub x, (fpext (fmul y, z)))
7384       //   -> (fma (fneg (fpext y)), (fpext z), x)
7385       // Note: Commutes FSUB operands.
7386       if (N1.getOpcode() == ISD::FP_EXTEND) {
7387         SDValue N10 = N1.getOperand(0);
7388         if (N10.getOpcode() == ISD::FMUL)
7389           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7390                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7391                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7392                                                      VT, N10.getOperand(0))),
7393                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7394                                          N10.getOperand(1)),
7395                              N0);
7396       }
7397
7398       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7399       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7400       if (N0.getOpcode() == ISD::FP_EXTEND) {
7401         SDValue N00 = N0.getOperand(0);
7402         if (N00.getOpcode() == ISD::FNEG) {
7403           SDValue N000 = N00.getOperand(0);
7404           if (N000.getOpcode() == ISD::FMUL) {
7405             return DAG.getNode(ISD::FMA, dl, VT,
7406                                DAG.getNode(ISD::FNEG, dl, VT,
7407                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7408                                                        VT, N000.getOperand(0))),
7409                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7410                                            N000.getOperand(1)),
7411                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7412           }
7413         }
7414       }
7415
7416       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7417       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7418       if (N0.getOpcode() == ISD::FNEG) {
7419         SDValue N00 = N0.getOperand(0);
7420         if (N00.getOpcode() == ISD::FP_EXTEND) {
7421           SDValue N000 = N00.getOperand(0);
7422           if (N000.getOpcode() == ISD::FMUL) {
7423             return DAG.getNode(ISD::FMA, dl, VT,
7424                                DAG.getNode(ISD::FNEG, dl, VT,
7425                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7426                                            VT, N000.getOperand(0))),
7427                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7428                                            N000.getOperand(1)),
7429                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7430           }
7431         }
7432       }
7433     }
7434   }
7435
7436   return SDValue();
7437 }
7438
7439 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7440   SDValue N0 = N->getOperand(0);
7441   SDValue N1 = N->getOperand(1);
7442   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7443   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7444   EVT VT = N->getValueType(0);
7445   const TargetOptions &Options = DAG.getTarget().Options;
7446
7447   // fold vector ops
7448   if (VT.isVector()) {
7449     // This just handles C1 * C2 for vectors. Other vector folds are below.
7450     SDValue FoldedVOp = SimplifyVBinOp(N);
7451     if (FoldedVOp.getNode())
7452       return FoldedVOp;
7453     // Canonicalize vector constant to RHS.
7454     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7455         N1.getOpcode() != ISD::BUILD_VECTOR)
7456       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7457         if (BV0->isConstant())
7458           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7459   }
7460
7461   // fold (fmul c1, c2) -> c1*c2
7462   if (N0CFP && N1CFP)
7463     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7464
7465   // canonicalize constant to RHS
7466   if (N0CFP && !N1CFP)
7467     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7468
7469   // fold (fmul A, 1.0) -> A
7470   if (N1CFP && N1CFP->isExactlyValue(1.0))
7471     return N0;
7472
7473   if (Options.UnsafeFPMath) {
7474     // fold (fmul A, 0) -> 0
7475     if (N1CFP && N1CFP->getValueAPF().isZero())
7476       return N1;
7477
7478     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7479     if (N0.getOpcode() == ISD::FMUL) {
7480       // Fold scalars or any vector constants (not just splats).
7481       // This fold is done in general by InstCombine, but extra fmul insts
7482       // may have been generated during lowering.
7483       SDValue N00 = N0.getOperand(0);
7484       SDValue N01 = N0.getOperand(1);
7485       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7486       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7487       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7488       
7489       // Check 1: Make sure that the first operand of the inner multiply is NOT
7490       // a constant. Otherwise, we may induce infinite looping.
7491       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7492         // Check 2: Make sure that the second operand of the inner multiply and
7493         // the second operand of the outer multiply are constants.
7494         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7495             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7496           SDLoc SL(N);
7497           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7498           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7499         }
7500       }
7501     }
7502
7503     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7504     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7505     // during an early run of DAGCombiner can prevent folding with fmuls
7506     // inserted during lowering.
7507     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7508       SDLoc SL(N);
7509       const SDValue Two = DAG.getConstantFP(2.0, VT);
7510       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7511       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7512     }
7513   }
7514
7515   // fold (fmul X, 2.0) -> (fadd X, X)
7516   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7517     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7518
7519   // fold (fmul X, -1.0) -> (fneg X)
7520   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7521     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7522       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7523
7524   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7525   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7526     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7527       // Both can be negated for free, check to see if at least one is cheaper
7528       // negated.
7529       if (LHSNeg == 2 || RHSNeg == 2)
7530         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7531                            GetNegatedExpression(N0, DAG, LegalOperations),
7532                            GetNegatedExpression(N1, DAG, LegalOperations));
7533     }
7534   }
7535
7536   return SDValue();
7537 }
7538
7539 SDValue DAGCombiner::visitFMA(SDNode *N) {
7540   SDValue N0 = N->getOperand(0);
7541   SDValue N1 = N->getOperand(1);
7542   SDValue N2 = N->getOperand(2);
7543   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7544   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7545   EVT VT = N->getValueType(0);
7546   SDLoc dl(N);
7547   const TargetOptions &Options = DAG.getTarget().Options;
7548
7549   // Constant fold FMA.
7550   if (isa<ConstantFPSDNode>(N0) &&
7551       isa<ConstantFPSDNode>(N1) &&
7552       isa<ConstantFPSDNode>(N2)) {
7553     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7554   }
7555
7556   if (Options.UnsafeFPMath) {
7557     if (N0CFP && N0CFP->isZero())
7558       return N2;
7559     if (N1CFP && N1CFP->isZero())
7560       return N2;
7561   }
7562   if (N0CFP && N0CFP->isExactlyValue(1.0))
7563     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7564   if (N1CFP && N1CFP->isExactlyValue(1.0))
7565     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7566
7567   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7568   if (N0CFP && !N1CFP)
7569     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7570
7571   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7572   if (Options.UnsafeFPMath && N1CFP &&
7573       N2.getOpcode() == ISD::FMUL &&
7574       N0 == N2.getOperand(0) &&
7575       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7576     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7577                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7578   }
7579
7580
7581   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7582   if (Options.UnsafeFPMath &&
7583       N0.getOpcode() == ISD::FMUL && N1CFP &&
7584       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7585     return DAG.getNode(ISD::FMA, dl, VT,
7586                        N0.getOperand(0),
7587                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7588                        N2);
7589   }
7590
7591   // (fma x, 1, y) -> (fadd x, y)
7592   // (fma x, -1, y) -> (fadd (fneg x), y)
7593   if (N1CFP) {
7594     if (N1CFP->isExactlyValue(1.0))
7595       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7596
7597     if (N1CFP->isExactlyValue(-1.0) &&
7598         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7599       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7600       AddToWorklist(RHSNeg.getNode());
7601       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7602     }
7603   }
7604
7605   // (fma x, c, x) -> (fmul x, (c+1))
7606   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7607     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7608                        DAG.getNode(ISD::FADD, dl, VT,
7609                                    N1, DAG.getConstantFP(1.0, VT)));
7610
7611   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7612   if (Options.UnsafeFPMath && N1CFP &&
7613       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7614     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7615                        DAG.getNode(ISD::FADD, dl, VT,
7616                                    N1, DAG.getConstantFP(-1.0, VT)));
7617
7618
7619   return SDValue();
7620 }
7621
7622 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7623   SDValue N0 = N->getOperand(0);
7624   SDValue N1 = N->getOperand(1);
7625   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7626   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7627   EVT VT = N->getValueType(0);
7628   SDLoc DL(N);
7629   const TargetOptions &Options = DAG.getTarget().Options;
7630
7631   // fold vector ops
7632   if (VT.isVector()) {
7633     SDValue FoldedVOp = SimplifyVBinOp(N);
7634     if (FoldedVOp.getNode()) return FoldedVOp;
7635   }
7636
7637   // fold (fdiv c1, c2) -> c1/c2
7638   if (N0CFP && N1CFP)
7639     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7640
7641   if (Options.UnsafeFPMath) {
7642     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7643     if (N1CFP) {
7644       // Compute the reciprocal 1.0 / c2.
7645       APFloat N1APF = N1CFP->getValueAPF();
7646       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7647       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7648       // Only do the transform if the reciprocal is a legal fp immediate that
7649       // isn't too nasty (eg NaN, denormal, ...).
7650       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7651           (!LegalOperations ||
7652            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7653            // backend)... we should handle this gracefully after Legalize.
7654            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7655            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7656            TLI.isFPImmLegal(Recip, VT)))
7657         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7658                            DAG.getConstantFP(Recip, VT));
7659     }
7660
7661     // If this FDIV is part of a reciprocal square root, it may be folded
7662     // into a target-specific square root estimate instruction.
7663     if (N1.getOpcode() == ISD::FSQRT) {
7664       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7665         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7666       }
7667     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7668                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7669       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7670         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7671         AddToWorklist(RV.getNode());
7672         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7673       }
7674     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7675                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7676       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7677         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7678         AddToWorklist(RV.getNode());
7679         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7680       }
7681     } else if (N1.getOpcode() == ISD::FMUL) {
7682       // Look through an FMUL. Even though this won't remove the FDIV directly,
7683       // it's still worthwhile to get rid of the FSQRT if possible.
7684       SDValue SqrtOp;
7685       SDValue OtherOp;
7686       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7687         SqrtOp = N1.getOperand(0);
7688         OtherOp = N1.getOperand(1);
7689       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7690         SqrtOp = N1.getOperand(1);
7691         OtherOp = N1.getOperand(0);
7692       }
7693       if (SqrtOp.getNode()) {
7694         // We found a FSQRT, so try to make this fold:
7695         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7696         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7697           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7698           AddToWorklist(RV.getNode());
7699           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7700         }
7701       }
7702     }
7703
7704     // Fold into a reciprocal estimate and multiply instead of a real divide.
7705     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7706       AddToWorklist(RV.getNode());
7707       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7708     }
7709   }
7710
7711   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7712   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7713     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7714       // Both can be negated for free, check to see if at least one is cheaper
7715       // negated.
7716       if (LHSNeg == 2 || RHSNeg == 2)
7717         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7718                            GetNegatedExpression(N0, DAG, LegalOperations),
7719                            GetNegatedExpression(N1, DAG, LegalOperations));
7720     }
7721   }
7722
7723   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7724   // reciprocal.
7725   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7726   // Notice that this is not always beneficial. One reason is different target
7727   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7728   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7729   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7730   if (Options.UnsafeFPMath) {
7731     // Skip if current node is a reciprocal.
7732     if (N0CFP && N0CFP->isExactlyValue(1.0))
7733       return SDValue();
7734
7735     SmallVector<SDNode *, 4> Users;
7736     // Find all FDIV users of the same divisor.
7737     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7738                               UE = N1.getNode()->use_end();
7739          UI != UE; ++UI) {
7740       SDNode *User = UI.getUse().getUser();
7741       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7742         Users.push_back(User);
7743     }
7744
7745     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7746       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7747       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7748
7749       // Dividend / Divisor -> Dividend * Reciprocal
7750       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7751         if ((*I)->getOperand(0) != FPOne) {
7752           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7753                                         (*I)->getOperand(0), Reciprocal);
7754           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7755         }
7756       }
7757       return SDValue();
7758     }
7759   }
7760
7761   return SDValue();
7762 }
7763
7764 SDValue DAGCombiner::visitFREM(SDNode *N) {
7765   SDValue N0 = N->getOperand(0);
7766   SDValue N1 = N->getOperand(1);
7767   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7768   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7769   EVT VT = N->getValueType(0);
7770
7771   // fold (frem c1, c2) -> fmod(c1,c2)
7772   if (N0CFP && N1CFP)
7773     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7774
7775   return SDValue();
7776 }
7777
7778 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7779   if (DAG.getTarget().Options.UnsafeFPMath &&
7780       !TLI.isFsqrtCheap()) {
7781     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7782     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7783       EVT VT = RV.getValueType();
7784       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7785       AddToWorklist(RV.getNode());
7786
7787       // Unfortunately, RV is now NaN if the input was exactly 0.
7788       // Select out this case and force the answer to 0.
7789       SDValue Zero = DAG.getConstantFP(0.0, VT);
7790       SDValue ZeroCmp =
7791         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7792                      N->getOperand(0), Zero, ISD::SETEQ);
7793       AddToWorklist(ZeroCmp.getNode());
7794       AddToWorklist(RV.getNode());
7795
7796       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7797                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7798       return RV;
7799     }
7800   }
7801   return SDValue();
7802 }
7803
7804 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7805   SDValue N0 = N->getOperand(0);
7806   SDValue N1 = N->getOperand(1);
7807   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7808   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7809   EVT VT = N->getValueType(0);
7810
7811   if (N0CFP && N1CFP)  // Constant fold
7812     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7813
7814   if (N1CFP) {
7815     const APFloat& V = N1CFP->getValueAPF();
7816     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7817     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7818     if (!V.isNegative()) {
7819       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7820         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7821     } else {
7822       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7823         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7824                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7825     }
7826   }
7827
7828   // copysign(fabs(x), y) -> copysign(x, y)
7829   // copysign(fneg(x), y) -> copysign(x, y)
7830   // copysign(copysign(x,z), y) -> copysign(x, y)
7831   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7832       N0.getOpcode() == ISD::FCOPYSIGN)
7833     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7834                        N0.getOperand(0), N1);
7835
7836   // copysign(x, abs(y)) -> abs(x)
7837   if (N1.getOpcode() == ISD::FABS)
7838     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7839
7840   // copysign(x, copysign(y,z)) -> copysign(x, z)
7841   if (N1.getOpcode() == ISD::FCOPYSIGN)
7842     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7843                        N0, N1.getOperand(1));
7844
7845   // copysign(x, fp_extend(y)) -> copysign(x, y)
7846   // copysign(x, fp_round(y)) -> copysign(x, y)
7847   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7848     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7849                        N0, N1.getOperand(0));
7850
7851   return SDValue();
7852 }
7853
7854 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7855   SDValue N0 = N->getOperand(0);
7856   EVT VT = N->getValueType(0);
7857   EVT OpVT = N0.getValueType();
7858
7859   // fold (sint_to_fp c1) -> c1fp
7860   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7861   if (N0C &&
7862       // ...but only if the target supports immediate floating-point values
7863       (!LegalOperations ||
7864        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7865     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7866
7867   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7868   // but UINT_TO_FP is legal on this target, try to convert.
7869   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7870       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7871     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7872     if (DAG.SignBitIsZero(N0))
7873       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7874   }
7875
7876   // The next optimizations are desirable only if SELECT_CC can be lowered.
7877   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7878     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7879     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7880         !VT.isVector() &&
7881         (!LegalOperations ||
7882          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7883       SDValue Ops[] =
7884         { N0.getOperand(0), N0.getOperand(1),
7885           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7886           N0.getOperand(2) };
7887       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7888     }
7889
7890     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7891     //      (select_cc x, y, 1.0, 0.0,, cc)
7892     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7893         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7894         (!LegalOperations ||
7895          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7896       SDValue Ops[] =
7897         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7898           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7899           N0.getOperand(0).getOperand(2) };
7900       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7901     }
7902   }
7903
7904   return SDValue();
7905 }
7906
7907 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7908   SDValue N0 = N->getOperand(0);
7909   EVT VT = N->getValueType(0);
7910   EVT OpVT = N0.getValueType();
7911
7912   // fold (uint_to_fp c1) -> c1fp
7913   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7914   if (N0C &&
7915       // ...but only if the target supports immediate floating-point values
7916       (!LegalOperations ||
7917        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7918     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7919
7920   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7921   // but SINT_TO_FP is legal on this target, try to convert.
7922   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7923       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7924     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7925     if (DAG.SignBitIsZero(N0))
7926       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7927   }
7928
7929   // The next optimizations are desirable only if SELECT_CC can be lowered.
7930   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7931     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7932
7933     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7934         (!LegalOperations ||
7935          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7936       SDValue Ops[] =
7937         { N0.getOperand(0), N0.getOperand(1),
7938           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7939           N0.getOperand(2) };
7940       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7941     }
7942   }
7943
7944   return SDValue();
7945 }
7946
7947 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
7948 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
7949   SDValue N0 = N->getOperand(0);
7950   EVT VT = N->getValueType(0);
7951
7952   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
7953     return SDValue();
7954
7955   SDValue Src = N0.getOperand(0);
7956   EVT SrcVT = Src.getValueType();
7957   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
7958   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
7959
7960   // We can safely assume the conversion won't overflow the output range,
7961   // because (for example) (uint8_t)18293.f is undefined behavior.
7962
7963   // Since we can assume the conversion won't overflow, our decision as to
7964   // whether the input will fit in the float should depend on the minimum
7965   // of the input range and output range.
7966
7967   // This means this is also safe for a signed input and unsigned output, since
7968   // a negative input would lead to undefined behavior.
7969   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
7970   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
7971   unsigned ActualSize = std::min(InputSize, OutputSize);
7972   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
7973
7974   // We can only fold away the float conversion if the input range can be
7975   // represented exactly in the float range.
7976   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
7977     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
7978       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
7979                                                        : ISD::ZERO_EXTEND;
7980       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
7981     }
7982     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
7983       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
7984     if (SrcVT == VT)
7985       return Src;
7986     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
7987   }
7988   return SDValue();
7989 }
7990
7991 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7992   SDValue N0 = N->getOperand(0);
7993   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7994   EVT VT = N->getValueType(0);
7995
7996   // fold (fp_to_sint c1fp) -> c1
7997   if (N0CFP)
7998     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7999
8000   return FoldIntToFPToInt(N, DAG);
8001 }
8002
8003 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8004   SDValue N0 = N->getOperand(0);
8005   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8006   EVT VT = N->getValueType(0);
8007
8008   // fold (fp_to_uint c1fp) -> c1
8009   if (N0CFP)
8010     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8011
8012   return FoldIntToFPToInt(N, DAG);
8013 }
8014
8015 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8016   SDValue N0 = N->getOperand(0);
8017   SDValue N1 = N->getOperand(1);
8018   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8019   EVT VT = N->getValueType(0);
8020
8021   // fold (fp_round c1fp) -> c1fp
8022   if (N0CFP)
8023     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8024
8025   // fold (fp_round (fp_extend x)) -> x
8026   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8027     return N0.getOperand(0);
8028
8029   // fold (fp_round (fp_round x)) -> (fp_round x)
8030   if (N0.getOpcode() == ISD::FP_ROUND) {
8031     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8032     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8033     // If the first fp_round isn't a value preserving truncation, it might
8034     // introduce a tie in the second fp_round, that wouldn't occur in the
8035     // single-step fp_round we want to fold to.
8036     // In other words, double rounding isn't the same as rounding.
8037     // Also, this is a value preserving truncation iff both fp_round's are.
8038     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8039       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8040                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8041   }
8042
8043   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8044   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8045     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8046                               N0.getOperand(0), N1);
8047     AddToWorklist(Tmp.getNode());
8048     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8049                        Tmp, N0.getOperand(1));
8050   }
8051
8052   return SDValue();
8053 }
8054
8055 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8056   SDValue N0 = N->getOperand(0);
8057   EVT VT = N->getValueType(0);
8058   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8059   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8060
8061   // fold (fp_round_inreg c1fp) -> c1fp
8062   if (N0CFP && isTypeLegal(EVT)) {
8063     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8064     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8065   }
8066
8067   return SDValue();
8068 }
8069
8070 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8071   SDValue N0 = N->getOperand(0);
8072   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8073   EVT VT = N->getValueType(0);
8074
8075   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8076   if (N->hasOneUse() &&
8077       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8078     return SDValue();
8079
8080   // fold (fp_extend c1fp) -> c1fp
8081   if (N0CFP)
8082     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8083
8084   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8085   // value of X.
8086   if (N0.getOpcode() == ISD::FP_ROUND
8087       && N0.getNode()->getConstantOperandVal(1) == 1) {
8088     SDValue In = N0.getOperand(0);
8089     if (In.getValueType() == VT) return In;
8090     if (VT.bitsLT(In.getValueType()))
8091       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8092                          In, N0.getOperand(1));
8093     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8094   }
8095
8096   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8097   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8098        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8099     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8100     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8101                                      LN0->getChain(),
8102                                      LN0->getBasePtr(), N0.getValueType(),
8103                                      LN0->getMemOperand());
8104     CombineTo(N, ExtLoad);
8105     CombineTo(N0.getNode(),
8106               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8107                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8108               ExtLoad.getValue(1));
8109     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8110   }
8111
8112   return SDValue();
8113 }
8114
8115 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8116   SDValue N0 = N->getOperand(0);
8117   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8118   EVT VT = N->getValueType(0);
8119
8120   // fold (fceil c1) -> fceil(c1)
8121   if (N0CFP)
8122     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8123
8124   return SDValue();
8125 }
8126
8127 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8128   SDValue N0 = N->getOperand(0);
8129   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8130   EVT VT = N->getValueType(0);
8131
8132   // fold (ftrunc c1) -> ftrunc(c1)
8133   if (N0CFP)
8134     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8135
8136   return SDValue();
8137 }
8138
8139 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8140   SDValue N0 = N->getOperand(0);
8141   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8142   EVT VT = N->getValueType(0);
8143
8144   // fold (ffloor c1) -> ffloor(c1)
8145   if (N0CFP)
8146     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8147
8148   return SDValue();
8149 }
8150
8151 // FIXME: FNEG and FABS have a lot in common; refactor.
8152 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8153   SDValue N0 = N->getOperand(0);
8154   EVT VT = N->getValueType(0);
8155
8156   if (VT.isVector()) {
8157     SDValue FoldedVOp = SimplifyVUnaryOp(N);
8158     if (FoldedVOp.getNode()) return FoldedVOp;
8159   }
8160
8161   // Constant fold FNEG.
8162   if (isa<ConstantFPSDNode>(N0))
8163     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8164
8165   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8166                          &DAG.getTarget().Options))
8167     return GetNegatedExpression(N0, DAG, LegalOperations);
8168
8169   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8170   // constant pool values.
8171   if (!TLI.isFNegFree(VT) &&
8172       N0.getOpcode() == ISD::BITCAST &&
8173       N0.getNode()->hasOneUse()) {
8174     SDValue Int = N0.getOperand(0);
8175     EVT IntVT = Int.getValueType();
8176     if (IntVT.isInteger() && !IntVT.isVector()) {
8177       APInt SignMask;
8178       if (N0.getValueType().isVector()) {
8179         // For a vector, get a mask such as 0x80... per scalar element
8180         // and splat it.
8181         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8182         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8183       } else {
8184         // For a scalar, just generate 0x80...
8185         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8186       }
8187       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8188                         DAG.getConstant(SignMask, IntVT));
8189       AddToWorklist(Int.getNode());
8190       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8191     }
8192   }
8193
8194   // (fneg (fmul c, x)) -> (fmul -c, x)
8195   if (N0.getOpcode() == ISD::FMUL) {
8196     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8197     if (CFP1) {
8198       APFloat CVal = CFP1->getValueAPF();
8199       CVal.changeSign();
8200       if (Level >= AfterLegalizeDAG &&
8201           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8202            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8203         return DAG.getNode(
8204             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8205             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8206     }
8207   }
8208
8209   return SDValue();
8210 }
8211
8212 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8213   SDValue N0 = N->getOperand(0);
8214   SDValue N1 = N->getOperand(1);
8215   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8216   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8217
8218   if (N0CFP && N1CFP) {
8219     const APFloat &C0 = N0CFP->getValueAPF();
8220     const APFloat &C1 = N1CFP->getValueAPF();
8221     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8222   }
8223
8224   if (N0CFP) {
8225     EVT VT = N->getValueType(0);
8226     // Canonicalize to constant on RHS.
8227     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8228   }
8229
8230   return SDValue();
8231 }
8232
8233 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8234   SDValue N0 = N->getOperand(0);
8235   SDValue N1 = N->getOperand(1);
8236   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8237   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8238
8239   if (N0CFP && N1CFP) {
8240     const APFloat &C0 = N0CFP->getValueAPF();
8241     const APFloat &C1 = N1CFP->getValueAPF();
8242     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8243   }
8244
8245   if (N0CFP) {
8246     EVT VT = N->getValueType(0);
8247     // Canonicalize to constant on RHS.
8248     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8249   }
8250
8251   return SDValue();
8252 }
8253
8254 SDValue DAGCombiner::visitFABS(SDNode *N) {
8255   SDValue N0 = N->getOperand(0);
8256   EVT VT = N->getValueType(0);
8257
8258   if (VT.isVector()) {
8259     SDValue FoldedVOp = SimplifyVUnaryOp(N);
8260     if (FoldedVOp.getNode()) return FoldedVOp;
8261   }
8262
8263   // fold (fabs c1) -> fabs(c1)
8264   if (isa<ConstantFPSDNode>(N0))
8265     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8266
8267   // fold (fabs (fabs x)) -> (fabs x)
8268   if (N0.getOpcode() == ISD::FABS)
8269     return N->getOperand(0);
8270
8271   // fold (fabs (fneg x)) -> (fabs x)
8272   // fold (fabs (fcopysign x, y)) -> (fabs x)
8273   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8274     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8275
8276   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8277   // constant pool values.
8278   if (!TLI.isFAbsFree(VT) &&
8279       N0.getOpcode() == ISD::BITCAST &&
8280       N0.getNode()->hasOneUse()) {
8281     SDValue Int = N0.getOperand(0);
8282     EVT IntVT = Int.getValueType();
8283     if (IntVT.isInteger() && !IntVT.isVector()) {
8284       APInt SignMask;
8285       if (N0.getValueType().isVector()) {
8286         // For a vector, get a mask such as 0x7f... per scalar element
8287         // and splat it.
8288         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8289         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8290       } else {
8291         // For a scalar, just generate 0x7f...
8292         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8293       }
8294       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8295                         DAG.getConstant(SignMask, IntVT));
8296       AddToWorklist(Int.getNode());
8297       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8298     }
8299   }
8300
8301   return SDValue();
8302 }
8303
8304 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8305   SDValue Chain = N->getOperand(0);
8306   SDValue N1 = N->getOperand(1);
8307   SDValue N2 = N->getOperand(2);
8308
8309   // If N is a constant we could fold this into a fallthrough or unconditional
8310   // branch. However that doesn't happen very often in normal code, because
8311   // Instcombine/SimplifyCFG should have handled the available opportunities.
8312   // If we did this folding here, it would be necessary to update the
8313   // MachineBasicBlock CFG, which is awkward.
8314
8315   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8316   // on the target.
8317   if (N1.getOpcode() == ISD::SETCC &&
8318       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8319                                    N1.getOperand(0).getValueType())) {
8320     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8321                        Chain, N1.getOperand(2),
8322                        N1.getOperand(0), N1.getOperand(1), N2);
8323   }
8324
8325   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8326       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8327        (N1.getOperand(0).hasOneUse() &&
8328         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8329     SDNode *Trunc = nullptr;
8330     if (N1.getOpcode() == ISD::TRUNCATE) {
8331       // Look pass the truncate.
8332       Trunc = N1.getNode();
8333       N1 = N1.getOperand(0);
8334     }
8335
8336     // Match this pattern so that we can generate simpler code:
8337     //
8338     //   %a = ...
8339     //   %b = and i32 %a, 2
8340     //   %c = srl i32 %b, 1
8341     //   brcond i32 %c ...
8342     //
8343     // into
8344     //
8345     //   %a = ...
8346     //   %b = and i32 %a, 2
8347     //   %c = setcc eq %b, 0
8348     //   brcond %c ...
8349     //
8350     // This applies only when the AND constant value has one bit set and the
8351     // SRL constant is equal to the log2 of the AND constant. The back-end is
8352     // smart enough to convert the result into a TEST/JMP sequence.
8353     SDValue Op0 = N1.getOperand(0);
8354     SDValue Op1 = N1.getOperand(1);
8355
8356     if (Op0.getOpcode() == ISD::AND &&
8357         Op1.getOpcode() == ISD::Constant) {
8358       SDValue AndOp1 = Op0.getOperand(1);
8359
8360       if (AndOp1.getOpcode() == ISD::Constant) {
8361         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8362
8363         if (AndConst.isPowerOf2() &&
8364             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8365           SDValue SetCC =
8366             DAG.getSetCC(SDLoc(N),
8367                          getSetCCResultType(Op0.getValueType()),
8368                          Op0, DAG.getConstant(0, Op0.getValueType()),
8369                          ISD::SETNE);
8370
8371           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8372                                           MVT::Other, Chain, SetCC, N2);
8373           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8374           // will convert it back to (X & C1) >> C2.
8375           CombineTo(N, NewBRCond, false);
8376           // Truncate is dead.
8377           if (Trunc)
8378             deleteAndRecombine(Trunc);
8379           // Replace the uses of SRL with SETCC
8380           WorklistRemover DeadNodes(*this);
8381           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8382           deleteAndRecombine(N1.getNode());
8383           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8384         }
8385       }
8386     }
8387
8388     if (Trunc)
8389       // Restore N1 if the above transformation doesn't match.
8390       N1 = N->getOperand(1);
8391   }
8392
8393   // Transform br(xor(x, y)) -> br(x != y)
8394   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8395   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8396     SDNode *TheXor = N1.getNode();
8397     SDValue Op0 = TheXor->getOperand(0);
8398     SDValue Op1 = TheXor->getOperand(1);
8399     if (Op0.getOpcode() == Op1.getOpcode()) {
8400       // Avoid missing important xor optimizations.
8401       SDValue Tmp = visitXOR(TheXor);
8402       if (Tmp.getNode()) {
8403         if (Tmp.getNode() != TheXor) {
8404           DEBUG(dbgs() << "\nReplacing.8 ";
8405                 TheXor->dump(&DAG);
8406                 dbgs() << "\nWith: ";
8407                 Tmp.getNode()->dump(&DAG);
8408                 dbgs() << '\n');
8409           WorklistRemover DeadNodes(*this);
8410           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8411           deleteAndRecombine(TheXor);
8412           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8413                              MVT::Other, Chain, Tmp, N2);
8414         }
8415
8416         // visitXOR has changed XOR's operands or replaced the XOR completely,
8417         // bail out.
8418         return SDValue(N, 0);
8419       }
8420     }
8421
8422     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8423       bool Equal = false;
8424       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8425         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8426             Op0.getOpcode() == ISD::XOR) {
8427           TheXor = Op0.getNode();
8428           Equal = true;
8429         }
8430
8431       EVT SetCCVT = N1.getValueType();
8432       if (LegalTypes)
8433         SetCCVT = getSetCCResultType(SetCCVT);
8434       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8435                                    SetCCVT,
8436                                    Op0, Op1,
8437                                    Equal ? ISD::SETEQ : ISD::SETNE);
8438       // Replace the uses of XOR with SETCC
8439       WorklistRemover DeadNodes(*this);
8440       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8441       deleteAndRecombine(N1.getNode());
8442       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8443                          MVT::Other, Chain, SetCC, N2);
8444     }
8445   }
8446
8447   return SDValue();
8448 }
8449
8450 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8451 //
8452 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8453   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8454   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8455
8456   // If N is a constant we could fold this into a fallthrough or unconditional
8457   // branch. However that doesn't happen very often in normal code, because
8458   // Instcombine/SimplifyCFG should have handled the available opportunities.
8459   // If we did this folding here, it would be necessary to update the
8460   // MachineBasicBlock CFG, which is awkward.
8461
8462   // Use SimplifySetCC to simplify SETCC's.
8463   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8464                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8465                                false);
8466   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8467
8468   // fold to a simpler setcc
8469   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8470     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8471                        N->getOperand(0), Simp.getOperand(2),
8472                        Simp.getOperand(0), Simp.getOperand(1),
8473                        N->getOperand(4));
8474
8475   return SDValue();
8476 }
8477
8478 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8479 /// and that N may be folded in the load / store addressing mode.
8480 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8481                                     SelectionDAG &DAG,
8482                                     const TargetLowering &TLI) {
8483   EVT VT;
8484   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8485     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8486       return false;
8487     VT = Use->getValueType(0);
8488   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8489     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8490       return false;
8491     VT = ST->getValue().getValueType();
8492   } else
8493     return false;
8494
8495   TargetLowering::AddrMode AM;
8496   if (N->getOpcode() == ISD::ADD) {
8497     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8498     if (Offset)
8499       // [reg +/- imm]
8500       AM.BaseOffs = Offset->getSExtValue();
8501     else
8502       // [reg +/- reg]
8503       AM.Scale = 1;
8504   } else if (N->getOpcode() == ISD::SUB) {
8505     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8506     if (Offset)
8507       // [reg +/- imm]
8508       AM.BaseOffs = -Offset->getSExtValue();
8509     else
8510       // [reg +/- reg]
8511       AM.Scale = 1;
8512   } else
8513     return false;
8514
8515   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8516 }
8517
8518 /// Try turning a load/store into a pre-indexed load/store when the base
8519 /// pointer is an add or subtract and it has other uses besides the load/store.
8520 /// After the transformation, the new indexed load/store has effectively folded
8521 /// the add/subtract in and all of its other uses are redirected to the
8522 /// new load/store.
8523 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8524   if (Level < AfterLegalizeDAG)
8525     return false;
8526
8527   bool isLoad = true;
8528   SDValue Ptr;
8529   EVT VT;
8530   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8531     if (LD->isIndexed())
8532       return false;
8533     VT = LD->getMemoryVT();
8534     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8535         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8536       return false;
8537     Ptr = LD->getBasePtr();
8538   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8539     if (ST->isIndexed())
8540       return false;
8541     VT = ST->getMemoryVT();
8542     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8543         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8544       return false;
8545     Ptr = ST->getBasePtr();
8546     isLoad = false;
8547   } else {
8548     return false;
8549   }
8550
8551   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8552   // out.  There is no reason to make this a preinc/predec.
8553   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8554       Ptr.getNode()->hasOneUse())
8555     return false;
8556
8557   // Ask the target to do addressing mode selection.
8558   SDValue BasePtr;
8559   SDValue Offset;
8560   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8561   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8562     return false;
8563
8564   // Backends without true r+i pre-indexed forms may need to pass a
8565   // constant base with a variable offset so that constant coercion
8566   // will work with the patterns in canonical form.
8567   bool Swapped = false;
8568   if (isa<ConstantSDNode>(BasePtr)) {
8569     std::swap(BasePtr, Offset);
8570     Swapped = true;
8571   }
8572
8573   // Don't create a indexed load / store with zero offset.
8574   if (isa<ConstantSDNode>(Offset) &&
8575       cast<ConstantSDNode>(Offset)->isNullValue())
8576     return false;
8577
8578   // Try turning it into a pre-indexed load / store except when:
8579   // 1) The new base ptr is a frame index.
8580   // 2) If N is a store and the new base ptr is either the same as or is a
8581   //    predecessor of the value being stored.
8582   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8583   //    that would create a cycle.
8584   // 4) All uses are load / store ops that use it as old base ptr.
8585
8586   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8587   // (plus the implicit offset) to a register to preinc anyway.
8588   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8589     return false;
8590
8591   // Check #2.
8592   if (!isLoad) {
8593     SDValue Val = cast<StoreSDNode>(N)->getValue();
8594     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8595       return false;
8596   }
8597
8598   // If the offset is a constant, there may be other adds of constants that
8599   // can be folded with this one. We should do this to avoid having to keep
8600   // a copy of the original base pointer.
8601   SmallVector<SDNode *, 16> OtherUses;
8602   if (isa<ConstantSDNode>(Offset))
8603     for (SDNode *Use : BasePtr.getNode()->uses()) {
8604       if (Use == Ptr.getNode())
8605         continue;
8606
8607       if (Use->isPredecessorOf(N))
8608         continue;
8609
8610       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8611         OtherUses.clear();
8612         break;
8613       }
8614
8615       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8616       if (Op1.getNode() == BasePtr.getNode())
8617         std::swap(Op0, Op1);
8618       assert(Op0.getNode() == BasePtr.getNode() &&
8619              "Use of ADD/SUB but not an operand");
8620
8621       if (!isa<ConstantSDNode>(Op1)) {
8622         OtherUses.clear();
8623         break;
8624       }
8625
8626       // FIXME: In some cases, we can be smarter about this.
8627       if (Op1.getValueType() != Offset.getValueType()) {
8628         OtherUses.clear();
8629         break;
8630       }
8631
8632       OtherUses.push_back(Use);
8633     }
8634
8635   if (Swapped)
8636     std::swap(BasePtr, Offset);
8637
8638   // Now check for #3 and #4.
8639   bool RealUse = false;
8640
8641   // Caches for hasPredecessorHelper
8642   SmallPtrSet<const SDNode *, 32> Visited;
8643   SmallVector<const SDNode *, 16> Worklist;
8644
8645   for (SDNode *Use : Ptr.getNode()->uses()) {
8646     if (Use == N)
8647       continue;
8648     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8649       return false;
8650
8651     // If Ptr may be folded in addressing mode of other use, then it's
8652     // not profitable to do this transformation.
8653     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8654       RealUse = true;
8655   }
8656
8657   if (!RealUse)
8658     return false;
8659
8660   SDValue Result;
8661   if (isLoad)
8662     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8663                                 BasePtr, Offset, AM);
8664   else
8665     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8666                                  BasePtr, Offset, AM);
8667   ++PreIndexedNodes;
8668   ++NodesCombined;
8669   DEBUG(dbgs() << "\nReplacing.4 ";
8670         N->dump(&DAG);
8671         dbgs() << "\nWith: ";
8672         Result.getNode()->dump(&DAG);
8673         dbgs() << '\n');
8674   WorklistRemover DeadNodes(*this);
8675   if (isLoad) {
8676     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8677     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8678   } else {
8679     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8680   }
8681
8682   // Finally, since the node is now dead, remove it from the graph.
8683   deleteAndRecombine(N);
8684
8685   if (Swapped)
8686     std::swap(BasePtr, Offset);
8687
8688   // Replace other uses of BasePtr that can be updated to use Ptr
8689   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8690     unsigned OffsetIdx = 1;
8691     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8692       OffsetIdx = 0;
8693     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8694            BasePtr.getNode() && "Expected BasePtr operand");
8695
8696     // We need to replace ptr0 in the following expression:
8697     //   x0 * offset0 + y0 * ptr0 = t0
8698     // knowing that
8699     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8700     //
8701     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8702     // indexed load/store and the expresion that needs to be re-written.
8703     //
8704     // Therefore, we have:
8705     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8706
8707     ConstantSDNode *CN =
8708       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8709     int X0, X1, Y0, Y1;
8710     APInt Offset0 = CN->getAPIntValue();
8711     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8712
8713     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8714     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8715     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8716     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8717
8718     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8719
8720     APInt CNV = Offset0;
8721     if (X0 < 0) CNV = -CNV;
8722     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8723     else CNV = CNV - Offset1;
8724
8725     // We can now generate the new expression.
8726     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8727     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8728
8729     SDValue NewUse = DAG.getNode(Opcode,
8730                                  SDLoc(OtherUses[i]),
8731                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8732     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8733     deleteAndRecombine(OtherUses[i]);
8734   }
8735
8736   // Replace the uses of Ptr with uses of the updated base value.
8737   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8738   deleteAndRecombine(Ptr.getNode());
8739
8740   return true;
8741 }
8742
8743 /// Try to combine a load/store with a add/sub of the base pointer node into a
8744 /// post-indexed load/store. The transformation folded the add/subtract into the
8745 /// new indexed load/store effectively and all of its uses are redirected to the
8746 /// new load/store.
8747 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8748   if (Level < AfterLegalizeDAG)
8749     return false;
8750
8751   bool isLoad = true;
8752   SDValue Ptr;
8753   EVT VT;
8754   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8755     if (LD->isIndexed())
8756       return false;
8757     VT = LD->getMemoryVT();
8758     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8759         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8760       return false;
8761     Ptr = LD->getBasePtr();
8762   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8763     if (ST->isIndexed())
8764       return false;
8765     VT = ST->getMemoryVT();
8766     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8767         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8768       return false;
8769     Ptr = ST->getBasePtr();
8770     isLoad = false;
8771   } else {
8772     return false;
8773   }
8774
8775   if (Ptr.getNode()->hasOneUse())
8776     return false;
8777
8778   for (SDNode *Op : Ptr.getNode()->uses()) {
8779     if (Op == N ||
8780         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8781       continue;
8782
8783     SDValue BasePtr;
8784     SDValue Offset;
8785     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8786     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8787       // Don't create a indexed load / store with zero offset.
8788       if (isa<ConstantSDNode>(Offset) &&
8789           cast<ConstantSDNode>(Offset)->isNullValue())
8790         continue;
8791
8792       // Try turning it into a post-indexed load / store except when
8793       // 1) All uses are load / store ops that use it as base ptr (and
8794       //    it may be folded as addressing mmode).
8795       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8796       //    nor a successor of N. Otherwise, if Op is folded that would
8797       //    create a cycle.
8798
8799       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8800         continue;
8801
8802       // Check for #1.
8803       bool TryNext = false;
8804       for (SDNode *Use : BasePtr.getNode()->uses()) {
8805         if (Use == Ptr.getNode())
8806           continue;
8807
8808         // If all the uses are load / store addresses, then don't do the
8809         // transformation.
8810         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8811           bool RealUse = false;
8812           for (SDNode *UseUse : Use->uses()) {
8813             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8814               RealUse = true;
8815           }
8816
8817           if (!RealUse) {
8818             TryNext = true;
8819             break;
8820           }
8821         }
8822       }
8823
8824       if (TryNext)
8825         continue;
8826
8827       // Check for #2
8828       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8829         SDValue Result = isLoad
8830           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8831                                BasePtr, Offset, AM)
8832           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8833                                 BasePtr, Offset, AM);
8834         ++PostIndexedNodes;
8835         ++NodesCombined;
8836         DEBUG(dbgs() << "\nReplacing.5 ";
8837               N->dump(&DAG);
8838               dbgs() << "\nWith: ";
8839               Result.getNode()->dump(&DAG);
8840               dbgs() << '\n');
8841         WorklistRemover DeadNodes(*this);
8842         if (isLoad) {
8843           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8844           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8845         } else {
8846           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8847         }
8848
8849         // Finally, since the node is now dead, remove it from the graph.
8850         deleteAndRecombine(N);
8851
8852         // Replace the uses of Use with uses of the updated base value.
8853         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8854                                       Result.getValue(isLoad ? 1 : 0));
8855         deleteAndRecombine(Op);
8856         return true;
8857       }
8858     }
8859   }
8860
8861   return false;
8862 }
8863
8864 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8865 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8866   ISD::MemIndexedMode AM = LD->getAddressingMode();
8867   assert(AM != ISD::UNINDEXED);
8868   SDValue BP = LD->getOperand(1);
8869   SDValue Inc = LD->getOperand(2);
8870
8871   // Some backends use TargetConstants for load offsets, but don't expect
8872   // TargetConstants in general ADD nodes. We can convert these constants into
8873   // regular Constants (if the constant is not opaque).
8874   assert((Inc.getOpcode() != ISD::TargetConstant ||
8875           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8876          "Cannot split out indexing using opaque target constants");
8877   if (Inc.getOpcode() == ISD::TargetConstant) {
8878     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8879     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8880                           ConstInc->getValueType(0));
8881   }
8882
8883   unsigned Opc =
8884       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8885   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8886 }
8887
8888 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8889   LoadSDNode *LD  = cast<LoadSDNode>(N);
8890   SDValue Chain = LD->getChain();
8891   SDValue Ptr   = LD->getBasePtr();
8892
8893   // If load is not volatile and there are no uses of the loaded value (and
8894   // the updated indexed value in case of indexed loads), change uses of the
8895   // chain value into uses of the chain input (i.e. delete the dead load).
8896   if (!LD->isVolatile()) {
8897     if (N->getValueType(1) == MVT::Other) {
8898       // Unindexed loads.
8899       if (!N->hasAnyUseOfValue(0)) {
8900         // It's not safe to use the two value CombineTo variant here. e.g.
8901         // v1, chain2 = load chain1, loc
8902         // v2, chain3 = load chain2, loc
8903         // v3         = add v2, c
8904         // Now we replace use of chain2 with chain1.  This makes the second load
8905         // isomorphic to the one we are deleting, and thus makes this load live.
8906         DEBUG(dbgs() << "\nReplacing.6 ";
8907               N->dump(&DAG);
8908               dbgs() << "\nWith chain: ";
8909               Chain.getNode()->dump(&DAG);
8910               dbgs() << "\n");
8911         WorklistRemover DeadNodes(*this);
8912         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8913
8914         if (N->use_empty())
8915           deleteAndRecombine(N);
8916
8917         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8918       }
8919     } else {
8920       // Indexed loads.
8921       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8922
8923       // If this load has an opaque TargetConstant offset, then we cannot split
8924       // the indexing into an add/sub directly (that TargetConstant may not be
8925       // valid for a different type of node, and we cannot convert an opaque
8926       // target constant into a regular constant).
8927       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8928                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8929
8930       if (!N->hasAnyUseOfValue(0) &&
8931           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8932         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8933         SDValue Index;
8934         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8935           Index = SplitIndexingFromLoad(LD);
8936           // Try to fold the base pointer arithmetic into subsequent loads and
8937           // stores.
8938           AddUsersToWorklist(N);
8939         } else
8940           Index = DAG.getUNDEF(N->getValueType(1));
8941         DEBUG(dbgs() << "\nReplacing.7 ";
8942               N->dump(&DAG);
8943               dbgs() << "\nWith: ";
8944               Undef.getNode()->dump(&DAG);
8945               dbgs() << " and 2 other values\n");
8946         WorklistRemover DeadNodes(*this);
8947         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8948         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8949         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8950         deleteAndRecombine(N);
8951         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8952       }
8953     }
8954   }
8955
8956   // If this load is directly stored, replace the load value with the stored
8957   // value.
8958   // TODO: Handle store large -> read small portion.
8959   // TODO: Handle TRUNCSTORE/LOADEXT
8960   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8961     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8962       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8963       if (PrevST->getBasePtr() == Ptr &&
8964           PrevST->getValue().getValueType() == N->getValueType(0))
8965       return CombineTo(N, Chain.getOperand(1), Chain);
8966     }
8967   }
8968
8969   // Try to infer better alignment information than the load already has.
8970   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8971     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8972       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8973         SDValue NewLoad =
8974                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8975                               LD->getValueType(0),
8976                               Chain, Ptr, LD->getPointerInfo(),
8977                               LD->getMemoryVT(),
8978                               LD->isVolatile(), LD->isNonTemporal(),
8979                               LD->isInvariant(), Align, LD->getAAInfo());
8980         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8981       }
8982     }
8983   }
8984
8985   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8986                                                   : DAG.getSubtarget().useAA();
8987 #ifndef NDEBUG
8988   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8989       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8990     UseAA = false;
8991 #endif
8992   if (UseAA && LD->isUnindexed()) {
8993     // Walk up chain skipping non-aliasing memory nodes.
8994     SDValue BetterChain = FindBetterChain(N, Chain);
8995
8996     // If there is a better chain.
8997     if (Chain != BetterChain) {
8998       SDValue ReplLoad;
8999
9000       // Replace the chain to void dependency.
9001       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9002         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9003                                BetterChain, Ptr, LD->getMemOperand());
9004       } else {
9005         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9006                                   LD->getValueType(0),
9007                                   BetterChain, Ptr, LD->getMemoryVT(),
9008                                   LD->getMemOperand());
9009       }
9010
9011       // Create token factor to keep old chain connected.
9012       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9013                                   MVT::Other, Chain, ReplLoad.getValue(1));
9014
9015       // Make sure the new and old chains are cleaned up.
9016       AddToWorklist(Token.getNode());
9017
9018       // Replace uses with load result and token factor. Don't add users
9019       // to work list.
9020       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9021     }
9022   }
9023
9024   // Try transforming N to an indexed load.
9025   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9026     return SDValue(N, 0);
9027
9028   // Try to slice up N to more direct loads if the slices are mapped to
9029   // different register banks or pairing can take place.
9030   if (SliceUpLoad(N))
9031     return SDValue(N, 0);
9032
9033   return SDValue();
9034 }
9035
9036 namespace {
9037 /// \brief Helper structure used to slice a load in smaller loads.
9038 /// Basically a slice is obtained from the following sequence:
9039 /// Origin = load Ty1, Base
9040 /// Shift = srl Ty1 Origin, CstTy Amount
9041 /// Inst = trunc Shift to Ty2
9042 ///
9043 /// Then, it will be rewriten into:
9044 /// Slice = load SliceTy, Base + SliceOffset
9045 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9046 ///
9047 /// SliceTy is deduced from the number of bits that are actually used to
9048 /// build Inst.
9049 struct LoadedSlice {
9050   /// \brief Helper structure used to compute the cost of a slice.
9051   struct Cost {
9052     /// Are we optimizing for code size.
9053     bool ForCodeSize;
9054     /// Various cost.
9055     unsigned Loads;
9056     unsigned Truncates;
9057     unsigned CrossRegisterBanksCopies;
9058     unsigned ZExts;
9059     unsigned Shift;
9060
9061     Cost(bool ForCodeSize = false)
9062         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9063           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9064
9065     /// \brief Get the cost of one isolated slice.
9066     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9067         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9068           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9069       EVT TruncType = LS.Inst->getValueType(0);
9070       EVT LoadedType = LS.getLoadedType();
9071       if (TruncType != LoadedType &&
9072           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9073         ZExts = 1;
9074     }
9075
9076     /// \brief Account for slicing gain in the current cost.
9077     /// Slicing provide a few gains like removing a shift or a
9078     /// truncate. This method allows to grow the cost of the original
9079     /// load with the gain from this slice.
9080     void addSliceGain(const LoadedSlice &LS) {
9081       // Each slice saves a truncate.
9082       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9083       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9084                               LS.Inst->getOperand(0).getValueType()))
9085         ++Truncates;
9086       // If there is a shift amount, this slice gets rid of it.
9087       if (LS.Shift)
9088         ++Shift;
9089       // If this slice can merge a cross register bank copy, account for it.
9090       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9091         ++CrossRegisterBanksCopies;
9092     }
9093
9094     Cost &operator+=(const Cost &RHS) {
9095       Loads += RHS.Loads;
9096       Truncates += RHS.Truncates;
9097       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9098       ZExts += RHS.ZExts;
9099       Shift += RHS.Shift;
9100       return *this;
9101     }
9102
9103     bool operator==(const Cost &RHS) const {
9104       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9105              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9106              ZExts == RHS.ZExts && Shift == RHS.Shift;
9107     }
9108
9109     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9110
9111     bool operator<(const Cost &RHS) const {
9112       // Assume cross register banks copies are as expensive as loads.
9113       // FIXME: Do we want some more target hooks?
9114       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9115       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9116       // Unless we are optimizing for code size, consider the
9117       // expensive operation first.
9118       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9119         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9120       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9121              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9122     }
9123
9124     bool operator>(const Cost &RHS) const { return RHS < *this; }
9125
9126     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9127
9128     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9129   };
9130   // The last instruction that represent the slice. This should be a
9131   // truncate instruction.
9132   SDNode *Inst;
9133   // The original load instruction.
9134   LoadSDNode *Origin;
9135   // The right shift amount in bits from the original load.
9136   unsigned Shift;
9137   // The DAG from which Origin came from.
9138   // This is used to get some contextual information about legal types, etc.
9139   SelectionDAG *DAG;
9140
9141   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9142               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9143       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9144
9145   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9146   /// \return Result is \p BitWidth and has used bits set to 1 and
9147   ///         not used bits set to 0.
9148   APInt getUsedBits() const {
9149     // Reproduce the trunc(lshr) sequence:
9150     // - Start from the truncated value.
9151     // - Zero extend to the desired bit width.
9152     // - Shift left.
9153     assert(Origin && "No original load to compare against.");
9154     unsigned BitWidth = Origin->getValueSizeInBits(0);
9155     assert(Inst && "This slice is not bound to an instruction");
9156     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9157            "Extracted slice is bigger than the whole type!");
9158     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9159     UsedBits.setAllBits();
9160     UsedBits = UsedBits.zext(BitWidth);
9161     UsedBits <<= Shift;
9162     return UsedBits;
9163   }
9164
9165   /// \brief Get the size of the slice to be loaded in bytes.
9166   unsigned getLoadedSize() const {
9167     unsigned SliceSize = getUsedBits().countPopulation();
9168     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9169     return SliceSize / 8;
9170   }
9171
9172   /// \brief Get the type that will be loaded for this slice.
9173   /// Note: This may not be the final type for the slice.
9174   EVT getLoadedType() const {
9175     assert(DAG && "Missing context");
9176     LLVMContext &Ctxt = *DAG->getContext();
9177     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9178   }
9179
9180   /// \brief Get the alignment of the load used for this slice.
9181   unsigned getAlignment() const {
9182     unsigned Alignment = Origin->getAlignment();
9183     unsigned Offset = getOffsetFromBase();
9184     if (Offset != 0)
9185       Alignment = MinAlign(Alignment, Alignment + Offset);
9186     return Alignment;
9187   }
9188
9189   /// \brief Check if this slice can be rewritten with legal operations.
9190   bool isLegal() const {
9191     // An invalid slice is not legal.
9192     if (!Origin || !Inst || !DAG)
9193       return false;
9194
9195     // Offsets are for indexed load only, we do not handle that.
9196     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9197       return false;
9198
9199     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9200
9201     // Check that the type is legal.
9202     EVT SliceType = getLoadedType();
9203     if (!TLI.isTypeLegal(SliceType))
9204       return false;
9205
9206     // Check that the load is legal for this type.
9207     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9208       return false;
9209
9210     // Check that the offset can be computed.
9211     // 1. Check its type.
9212     EVT PtrType = Origin->getBasePtr().getValueType();
9213     if (PtrType == MVT::Untyped || PtrType.isExtended())
9214       return false;
9215
9216     // 2. Check that it fits in the immediate.
9217     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9218       return false;
9219
9220     // 3. Check that the computation is legal.
9221     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9222       return false;
9223
9224     // Check that the zext is legal if it needs one.
9225     EVT TruncateType = Inst->getValueType(0);
9226     if (TruncateType != SliceType &&
9227         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9228       return false;
9229
9230     return true;
9231   }
9232
9233   /// \brief Get the offset in bytes of this slice in the original chunk of
9234   /// bits.
9235   /// \pre DAG != nullptr.
9236   uint64_t getOffsetFromBase() const {
9237     assert(DAG && "Missing context.");
9238     bool IsBigEndian =
9239         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9240     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9241     uint64_t Offset = Shift / 8;
9242     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9243     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9244            "The size of the original loaded type is not a multiple of a"
9245            " byte.");
9246     // If Offset is bigger than TySizeInBytes, it means we are loading all
9247     // zeros. This should have been optimized before in the process.
9248     assert(TySizeInBytes > Offset &&
9249            "Invalid shift amount for given loaded size");
9250     if (IsBigEndian)
9251       Offset = TySizeInBytes - Offset - getLoadedSize();
9252     return Offset;
9253   }
9254
9255   /// \brief Generate the sequence of instructions to load the slice
9256   /// represented by this object and redirect the uses of this slice to
9257   /// this new sequence of instructions.
9258   /// \pre this->Inst && this->Origin are valid Instructions and this
9259   /// object passed the legal check: LoadedSlice::isLegal returned true.
9260   /// \return The last instruction of the sequence used to load the slice.
9261   SDValue loadSlice() const {
9262     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9263     const SDValue &OldBaseAddr = Origin->getBasePtr();
9264     SDValue BaseAddr = OldBaseAddr;
9265     // Get the offset in that chunk of bytes w.r.t. the endianess.
9266     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9267     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9268     if (Offset) {
9269       // BaseAddr = BaseAddr + Offset.
9270       EVT ArithType = BaseAddr.getValueType();
9271       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9272                               DAG->getConstant(Offset, ArithType));
9273     }
9274
9275     // Create the type of the loaded slice according to its size.
9276     EVT SliceType = getLoadedType();
9277
9278     // Create the load for the slice.
9279     SDValue LastInst = DAG->getLoad(
9280         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9281         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9282         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9283     // If the final type is not the same as the loaded type, this means that
9284     // we have to pad with zero. Create a zero extend for that.
9285     EVT FinalType = Inst->getValueType(0);
9286     if (SliceType != FinalType)
9287       LastInst =
9288           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9289     return LastInst;
9290   }
9291
9292   /// \brief Check if this slice can be merged with an expensive cross register
9293   /// bank copy. E.g.,
9294   /// i = load i32
9295   /// f = bitcast i32 i to float
9296   bool canMergeExpensiveCrossRegisterBankCopy() const {
9297     if (!Inst || !Inst->hasOneUse())
9298       return false;
9299     SDNode *Use = *Inst->use_begin();
9300     if (Use->getOpcode() != ISD::BITCAST)
9301       return false;
9302     assert(DAG && "Missing context");
9303     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9304     EVT ResVT = Use->getValueType(0);
9305     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9306     const TargetRegisterClass *ArgRC =
9307         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9308     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9309       return false;
9310
9311     // At this point, we know that we perform a cross-register-bank copy.
9312     // Check if it is expensive.
9313     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9314     // Assume bitcasts are cheap, unless both register classes do not
9315     // explicitly share a common sub class.
9316     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9317       return false;
9318
9319     // Check if it will be merged with the load.
9320     // 1. Check the alignment constraint.
9321     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9322         ResVT.getTypeForEVT(*DAG->getContext()));
9323
9324     if (RequiredAlignment > getAlignment())
9325       return false;
9326
9327     // 2. Check that the load is a legal operation for that type.
9328     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9329       return false;
9330
9331     // 3. Check that we do not have a zext in the way.
9332     if (Inst->getValueType(0) != getLoadedType())
9333       return false;
9334
9335     return true;
9336   }
9337 };
9338 }
9339
9340 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9341 /// \p UsedBits looks like 0..0 1..1 0..0.
9342 static bool areUsedBitsDense(const APInt &UsedBits) {
9343   // If all the bits are one, this is dense!
9344   if (UsedBits.isAllOnesValue())
9345     return true;
9346
9347   // Get rid of the unused bits on the right.
9348   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9349   // Get rid of the unused bits on the left.
9350   if (NarrowedUsedBits.countLeadingZeros())
9351     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9352   // Check that the chunk of bits is completely used.
9353   return NarrowedUsedBits.isAllOnesValue();
9354 }
9355
9356 /// \brief Check whether or not \p First and \p Second are next to each other
9357 /// in memory. This means that there is no hole between the bits loaded
9358 /// by \p First and the bits loaded by \p Second.
9359 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9360                                      const LoadedSlice &Second) {
9361   assert(First.Origin == Second.Origin && First.Origin &&
9362          "Unable to match different memory origins.");
9363   APInt UsedBits = First.getUsedBits();
9364   assert((UsedBits & Second.getUsedBits()) == 0 &&
9365          "Slices are not supposed to overlap.");
9366   UsedBits |= Second.getUsedBits();
9367   return areUsedBitsDense(UsedBits);
9368 }
9369
9370 /// \brief Adjust the \p GlobalLSCost according to the target
9371 /// paring capabilities and the layout of the slices.
9372 /// \pre \p GlobalLSCost should account for at least as many loads as
9373 /// there is in the slices in \p LoadedSlices.
9374 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9375                                  LoadedSlice::Cost &GlobalLSCost) {
9376   unsigned NumberOfSlices = LoadedSlices.size();
9377   // If there is less than 2 elements, no pairing is possible.
9378   if (NumberOfSlices < 2)
9379     return;
9380
9381   // Sort the slices so that elements that are likely to be next to each
9382   // other in memory are next to each other in the list.
9383   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9384             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9385     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9386     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9387   });
9388   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9389   // First (resp. Second) is the first (resp. Second) potentially candidate
9390   // to be placed in a paired load.
9391   const LoadedSlice *First = nullptr;
9392   const LoadedSlice *Second = nullptr;
9393   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9394                 // Set the beginning of the pair.
9395                                                            First = Second) {
9396
9397     Second = &LoadedSlices[CurrSlice];
9398
9399     // If First is NULL, it means we start a new pair.
9400     // Get to the next slice.
9401     if (!First)
9402       continue;
9403
9404     EVT LoadedType = First->getLoadedType();
9405
9406     // If the types of the slices are different, we cannot pair them.
9407     if (LoadedType != Second->getLoadedType())
9408       continue;
9409
9410     // Check if the target supplies paired loads for this type.
9411     unsigned RequiredAlignment = 0;
9412     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9413       // move to the next pair, this type is hopeless.
9414       Second = nullptr;
9415       continue;
9416     }
9417     // Check if we meet the alignment requirement.
9418     if (RequiredAlignment > First->getAlignment())
9419       continue;
9420
9421     // Check that both loads are next to each other in memory.
9422     if (!areSlicesNextToEachOther(*First, *Second))
9423       continue;
9424
9425     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9426     --GlobalLSCost.Loads;
9427     // Move to the next pair.
9428     Second = nullptr;
9429   }
9430 }
9431
9432 /// \brief Check the profitability of all involved LoadedSlice.
9433 /// Currently, it is considered profitable if there is exactly two
9434 /// involved slices (1) which are (2) next to each other in memory, and
9435 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9436 ///
9437 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9438 /// the elements themselves.
9439 ///
9440 /// FIXME: When the cost model will be mature enough, we can relax
9441 /// constraints (1) and (2).
9442 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9443                                 const APInt &UsedBits, bool ForCodeSize) {
9444   unsigned NumberOfSlices = LoadedSlices.size();
9445   if (StressLoadSlicing)
9446     return NumberOfSlices > 1;
9447
9448   // Check (1).
9449   if (NumberOfSlices != 2)
9450     return false;
9451
9452   // Check (2).
9453   if (!areUsedBitsDense(UsedBits))
9454     return false;
9455
9456   // Check (3).
9457   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9458   // The original code has one big load.
9459   OrigCost.Loads = 1;
9460   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9461     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9462     // Accumulate the cost of all the slices.
9463     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9464     GlobalSlicingCost += SliceCost;
9465
9466     // Account as cost in the original configuration the gain obtained
9467     // with the current slices.
9468     OrigCost.addSliceGain(LS);
9469   }
9470
9471   // If the target supports paired load, adjust the cost accordingly.
9472   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9473   return OrigCost > GlobalSlicingCost;
9474 }
9475
9476 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9477 /// operations, split it in the various pieces being extracted.
9478 ///
9479 /// This sort of thing is introduced by SROA.
9480 /// This slicing takes care not to insert overlapping loads.
9481 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9482 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9483   if (Level < AfterLegalizeDAG)
9484     return false;
9485
9486   LoadSDNode *LD = cast<LoadSDNode>(N);
9487   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9488       !LD->getValueType(0).isInteger())
9489     return false;
9490
9491   // Keep track of already used bits to detect overlapping values.
9492   // In that case, we will just abort the transformation.
9493   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9494
9495   SmallVector<LoadedSlice, 4> LoadedSlices;
9496
9497   // Check if this load is used as several smaller chunks of bits.
9498   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9499   // of computation for each trunc.
9500   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9501        UI != UIEnd; ++UI) {
9502     // Skip the uses of the chain.
9503     if (UI.getUse().getResNo() != 0)
9504       continue;
9505
9506     SDNode *User = *UI;
9507     unsigned Shift = 0;
9508
9509     // Check if this is a trunc(lshr).
9510     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9511         isa<ConstantSDNode>(User->getOperand(1))) {
9512       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9513       User = *User->use_begin();
9514     }
9515
9516     // At this point, User is a Truncate, iff we encountered, trunc or
9517     // trunc(lshr).
9518     if (User->getOpcode() != ISD::TRUNCATE)
9519       return false;
9520
9521     // The width of the type must be a power of 2 and greater than 8-bits.
9522     // Otherwise the load cannot be represented in LLVM IR.
9523     // Moreover, if we shifted with a non-8-bits multiple, the slice
9524     // will be across several bytes. We do not support that.
9525     unsigned Width = User->getValueSizeInBits(0);
9526     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9527       return 0;
9528
9529     // Build the slice for this chain of computations.
9530     LoadedSlice LS(User, LD, Shift, &DAG);
9531     APInt CurrentUsedBits = LS.getUsedBits();
9532
9533     // Check if this slice overlaps with another.
9534     if ((CurrentUsedBits & UsedBits) != 0)
9535       return false;
9536     // Update the bits used globally.
9537     UsedBits |= CurrentUsedBits;
9538
9539     // Check if the new slice would be legal.
9540     if (!LS.isLegal())
9541       return false;
9542
9543     // Record the slice.
9544     LoadedSlices.push_back(LS);
9545   }
9546
9547   // Abort slicing if it does not seem to be profitable.
9548   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9549     return false;
9550
9551   ++SlicedLoads;
9552
9553   // Rewrite each chain to use an independent load.
9554   // By construction, each chain can be represented by a unique load.
9555
9556   // Prepare the argument for the new token factor for all the slices.
9557   SmallVector<SDValue, 8> ArgChains;
9558   for (SmallVectorImpl<LoadedSlice>::const_iterator
9559            LSIt = LoadedSlices.begin(),
9560            LSItEnd = LoadedSlices.end();
9561        LSIt != LSItEnd; ++LSIt) {
9562     SDValue SliceInst = LSIt->loadSlice();
9563     CombineTo(LSIt->Inst, SliceInst, true);
9564     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9565       SliceInst = SliceInst.getOperand(0);
9566     assert(SliceInst->getOpcode() == ISD::LOAD &&
9567            "It takes more than a zext to get to the loaded slice!!");
9568     ArgChains.push_back(SliceInst.getValue(1));
9569   }
9570
9571   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9572                               ArgChains);
9573   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9574   return true;
9575 }
9576
9577 /// Check to see if V is (and load (ptr), imm), where the load is having
9578 /// specific bytes cleared out.  If so, return the byte size being masked out
9579 /// and the shift amount.
9580 static std::pair<unsigned, unsigned>
9581 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9582   std::pair<unsigned, unsigned> Result(0, 0);
9583
9584   // Check for the structure we're looking for.
9585   if (V->getOpcode() != ISD::AND ||
9586       !isa<ConstantSDNode>(V->getOperand(1)) ||
9587       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9588     return Result;
9589
9590   // Check the chain and pointer.
9591   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9592   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9593
9594   // The store should be chained directly to the load or be an operand of a
9595   // tokenfactor.
9596   if (LD == Chain.getNode())
9597     ; // ok.
9598   else if (Chain->getOpcode() != ISD::TokenFactor)
9599     return Result; // Fail.
9600   else {
9601     bool isOk = false;
9602     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9603       if (Chain->getOperand(i).getNode() == LD) {
9604         isOk = true;
9605         break;
9606       }
9607     if (!isOk) return Result;
9608   }
9609
9610   // This only handles simple types.
9611   if (V.getValueType() != MVT::i16 &&
9612       V.getValueType() != MVT::i32 &&
9613       V.getValueType() != MVT::i64)
9614     return Result;
9615
9616   // Check the constant mask.  Invert it so that the bits being masked out are
9617   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9618   // follow the sign bit for uniformity.
9619   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9620   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9621   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9622   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9623   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9624   if (NotMaskLZ == 64) return Result;  // All zero mask.
9625
9626   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9627   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9628     return Result;
9629
9630   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9631   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9632     NotMaskLZ -= 64-V.getValueSizeInBits();
9633
9634   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9635   switch (MaskedBytes) {
9636   case 1:
9637   case 2:
9638   case 4: break;
9639   default: return Result; // All one mask, or 5-byte mask.
9640   }
9641
9642   // Verify that the first bit starts at a multiple of mask so that the access
9643   // is aligned the same as the access width.
9644   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9645
9646   Result.first = MaskedBytes;
9647   Result.second = NotMaskTZ/8;
9648   return Result;
9649 }
9650
9651
9652 /// Check to see if IVal is something that provides a value as specified by
9653 /// MaskInfo. If so, replace the specified store with a narrower store of
9654 /// truncated IVal.
9655 static SDNode *
9656 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9657                                 SDValue IVal, StoreSDNode *St,
9658                                 DAGCombiner *DC) {
9659   unsigned NumBytes = MaskInfo.first;
9660   unsigned ByteShift = MaskInfo.second;
9661   SelectionDAG &DAG = DC->getDAG();
9662
9663   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9664   // that uses this.  If not, this is not a replacement.
9665   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9666                                   ByteShift*8, (ByteShift+NumBytes)*8);
9667   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9668
9669   // Check that it is legal on the target to do this.  It is legal if the new
9670   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9671   // legalization.
9672   MVT VT = MVT::getIntegerVT(NumBytes*8);
9673   if (!DC->isTypeLegal(VT))
9674     return nullptr;
9675
9676   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9677   // shifted by ByteShift and truncated down to NumBytes.
9678   if (ByteShift)
9679     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9680                        DAG.getConstant(ByteShift*8,
9681                                     DC->getShiftAmountTy(IVal.getValueType())));
9682
9683   // Figure out the offset for the store and the alignment of the access.
9684   unsigned StOffset;
9685   unsigned NewAlign = St->getAlignment();
9686
9687   if (DAG.getTargetLoweringInfo().isLittleEndian())
9688     StOffset = ByteShift;
9689   else
9690     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9691
9692   SDValue Ptr = St->getBasePtr();
9693   if (StOffset) {
9694     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9695                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9696     NewAlign = MinAlign(NewAlign, StOffset);
9697   }
9698
9699   // Truncate down to the new size.
9700   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9701
9702   ++OpsNarrowed;
9703   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9704                       St->getPointerInfo().getWithOffset(StOffset),
9705                       false, false, NewAlign).getNode();
9706 }
9707
9708
9709 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9710 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9711 /// narrowing the load and store if it would end up being a win for performance
9712 /// or code size.
9713 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9714   StoreSDNode *ST  = cast<StoreSDNode>(N);
9715   if (ST->isVolatile())
9716     return SDValue();
9717
9718   SDValue Chain = ST->getChain();
9719   SDValue Value = ST->getValue();
9720   SDValue Ptr   = ST->getBasePtr();
9721   EVT VT = Value.getValueType();
9722
9723   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9724     return SDValue();
9725
9726   unsigned Opc = Value.getOpcode();
9727
9728   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9729   // is a byte mask indicating a consecutive number of bytes, check to see if
9730   // Y is known to provide just those bytes.  If so, we try to replace the
9731   // load + replace + store sequence with a single (narrower) store, which makes
9732   // the load dead.
9733   if (Opc == ISD::OR) {
9734     std::pair<unsigned, unsigned> MaskedLoad;
9735     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9736     if (MaskedLoad.first)
9737       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9738                                                   Value.getOperand(1), ST,this))
9739         return SDValue(NewST, 0);
9740
9741     // Or is commutative, so try swapping X and Y.
9742     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9743     if (MaskedLoad.first)
9744       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9745                                                   Value.getOperand(0), ST,this))
9746         return SDValue(NewST, 0);
9747   }
9748
9749   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9750       Value.getOperand(1).getOpcode() != ISD::Constant)
9751     return SDValue();
9752
9753   SDValue N0 = Value.getOperand(0);
9754   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9755       Chain == SDValue(N0.getNode(), 1)) {
9756     LoadSDNode *LD = cast<LoadSDNode>(N0);
9757     if (LD->getBasePtr() != Ptr ||
9758         LD->getPointerInfo().getAddrSpace() !=
9759         ST->getPointerInfo().getAddrSpace())
9760       return SDValue();
9761
9762     // Find the type to narrow it the load / op / store to.
9763     SDValue N1 = Value.getOperand(1);
9764     unsigned BitWidth = N1.getValueSizeInBits();
9765     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9766     if (Opc == ISD::AND)
9767       Imm ^= APInt::getAllOnesValue(BitWidth);
9768     if (Imm == 0 || Imm.isAllOnesValue())
9769       return SDValue();
9770     unsigned ShAmt = Imm.countTrailingZeros();
9771     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9772     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9773     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9774     // The narrowing should be profitable, the load/store operation should be
9775     // legal (or custom) and the store size should be equal to the NewVT width.
9776     while (NewBW < BitWidth &&
9777            (NewVT.getStoreSizeInBits() != NewBW ||
9778             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9779             !TLI.isNarrowingProfitable(VT, NewVT))) {
9780       NewBW = NextPowerOf2(NewBW);
9781       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9782     }
9783     if (NewBW >= BitWidth)
9784       return SDValue();
9785
9786     // If the lsb changed does not start at the type bitwidth boundary,
9787     // start at the previous one.
9788     if (ShAmt % NewBW)
9789       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9790     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9791                                    std::min(BitWidth, ShAmt + NewBW));
9792     if ((Imm & Mask) == Imm) {
9793       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9794       if (Opc == ISD::AND)
9795         NewImm ^= APInt::getAllOnesValue(NewBW);
9796       uint64_t PtrOff = ShAmt / 8;
9797       // For big endian targets, we need to adjust the offset to the pointer to
9798       // load the correct bytes.
9799       if (TLI.isBigEndian())
9800         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9801
9802       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9803       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9804       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9805         return SDValue();
9806
9807       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9808                                    Ptr.getValueType(), Ptr,
9809                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9810       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9811                                   LD->getChain(), NewPtr,
9812                                   LD->getPointerInfo().getWithOffset(PtrOff),
9813                                   LD->isVolatile(), LD->isNonTemporal(),
9814                                   LD->isInvariant(), NewAlign,
9815                                   LD->getAAInfo());
9816       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9817                                    DAG.getConstant(NewImm, NewVT));
9818       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9819                                    NewVal, NewPtr,
9820                                    ST->getPointerInfo().getWithOffset(PtrOff),
9821                                    false, false, NewAlign);
9822
9823       AddToWorklist(NewPtr.getNode());
9824       AddToWorklist(NewLD.getNode());
9825       AddToWorklist(NewVal.getNode());
9826       WorklistRemover DeadNodes(*this);
9827       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9828       ++OpsNarrowed;
9829       return NewST;
9830     }
9831   }
9832
9833   return SDValue();
9834 }
9835
9836 /// For a given floating point load / store pair, if the load value isn't used
9837 /// by any other operations, then consider transforming the pair to integer
9838 /// load / store operations if the target deems the transformation profitable.
9839 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9840   StoreSDNode *ST  = cast<StoreSDNode>(N);
9841   SDValue Chain = ST->getChain();
9842   SDValue Value = ST->getValue();
9843   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9844       Value.hasOneUse() &&
9845       Chain == SDValue(Value.getNode(), 1)) {
9846     LoadSDNode *LD = cast<LoadSDNode>(Value);
9847     EVT VT = LD->getMemoryVT();
9848     if (!VT.isFloatingPoint() ||
9849         VT != ST->getMemoryVT() ||
9850         LD->isNonTemporal() ||
9851         ST->isNonTemporal() ||
9852         LD->getPointerInfo().getAddrSpace() != 0 ||
9853         ST->getPointerInfo().getAddrSpace() != 0)
9854       return SDValue();
9855
9856     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9857     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9858         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9859         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9860         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9861       return SDValue();
9862
9863     unsigned LDAlign = LD->getAlignment();
9864     unsigned STAlign = ST->getAlignment();
9865     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9866     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9867     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9868       return SDValue();
9869
9870     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9871                                 LD->getChain(), LD->getBasePtr(),
9872                                 LD->getPointerInfo(),
9873                                 false, false, false, LDAlign);
9874
9875     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9876                                  NewLD, ST->getBasePtr(),
9877                                  ST->getPointerInfo(),
9878                                  false, false, STAlign);
9879
9880     AddToWorklist(NewLD.getNode());
9881     AddToWorklist(NewST.getNode());
9882     WorklistRemover DeadNodes(*this);
9883     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9884     ++LdStFP2Int;
9885     return NewST;
9886   }
9887
9888   return SDValue();
9889 }
9890
9891 /// Helper struct to parse and store a memory address as base + index + offset.
9892 /// We ignore sign extensions when it is safe to do so.
9893 /// The following two expressions are not equivalent. To differentiate we need
9894 /// to store whether there was a sign extension involved in the index
9895 /// computation.
9896 ///  (load (i64 add (i64 copyfromreg %c)
9897 ///                 (i64 signextend (add (i8 load %index)
9898 ///                                      (i8 1))))
9899 /// vs
9900 ///
9901 /// (load (i64 add (i64 copyfromreg %c)
9902 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9903 ///                                         (i32 1)))))
9904 struct BaseIndexOffset {
9905   SDValue Base;
9906   SDValue Index;
9907   int64_t Offset;
9908   bool IsIndexSignExt;
9909
9910   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9911
9912   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9913                   bool IsIndexSignExt) :
9914     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9915
9916   bool equalBaseIndex(const BaseIndexOffset &Other) {
9917     return Other.Base == Base && Other.Index == Index &&
9918       Other.IsIndexSignExt == IsIndexSignExt;
9919   }
9920
9921   /// Parses tree in Ptr for base, index, offset addresses.
9922   static BaseIndexOffset match(SDValue Ptr) {
9923     bool IsIndexSignExt = false;
9924
9925     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9926     // instruction, then it could be just the BASE or everything else we don't
9927     // know how to handle. Just use Ptr as BASE and give up.
9928     if (Ptr->getOpcode() != ISD::ADD)
9929       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9930
9931     // We know that we have at least an ADD instruction. Try to pattern match
9932     // the simple case of BASE + OFFSET.
9933     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9934       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9935       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9936                               IsIndexSignExt);
9937     }
9938
9939     // Inside a loop the current BASE pointer is calculated using an ADD and a
9940     // MUL instruction. In this case Ptr is the actual BASE pointer.
9941     // (i64 add (i64 %array_ptr)
9942     //          (i64 mul (i64 %induction_var)
9943     //                   (i64 %element_size)))
9944     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9945       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9946
9947     // Look at Base + Index + Offset cases.
9948     SDValue Base = Ptr->getOperand(0);
9949     SDValue IndexOffset = Ptr->getOperand(1);
9950
9951     // Skip signextends.
9952     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9953       IndexOffset = IndexOffset->getOperand(0);
9954       IsIndexSignExt = true;
9955     }
9956
9957     // Either the case of Base + Index (no offset) or something else.
9958     if (IndexOffset->getOpcode() != ISD::ADD)
9959       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9960
9961     // Now we have the case of Base + Index + offset.
9962     SDValue Index = IndexOffset->getOperand(0);
9963     SDValue Offset = IndexOffset->getOperand(1);
9964
9965     if (!isa<ConstantSDNode>(Offset))
9966       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9967
9968     // Ignore signextends.
9969     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9970       Index = Index->getOperand(0);
9971       IsIndexSignExt = true;
9972     } else IsIndexSignExt = false;
9973
9974     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9975     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9976   }
9977 };
9978
9979 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
9980                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
9981                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
9982   // Make sure we have something to merge.
9983   if (NumElem < 2)
9984     return false;
9985
9986   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
9987   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9988   unsigned EarliestNodeUsed = 0;
9989
9990   for (unsigned i=0; i < NumElem; ++i) {
9991     // Find a chain for the new wide-store operand. Notice that some
9992     // of the store nodes that we found may not be selected for inclusion
9993     // in the wide store. The chain we use needs to be the chain of the
9994     // earliest store node which is *used* and replaced by the wide store.
9995     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9996       EarliestNodeUsed = i;
9997   }
9998
9999   // The earliest Node in the DAG.
10000   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10001   SDLoc DL(StoreNodes[0].MemNode);
10002
10003   SDValue StoredVal;
10004   if (UseVector) {
10005     // Find a legal type for the vector store.
10006     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10007     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10008     if (IsConstantSrc) {
10009       // A vector store with a constant source implies that the constant is
10010       // zero; we only handle merging stores of constant zeros because the zero
10011       // can be materialized without a load.
10012       // It may be beneficial to loosen this restriction to allow non-zero
10013       // store merging.
10014       StoredVal = DAG.getConstant(0, Ty);
10015     } else {
10016       SmallVector<SDValue, 8> Ops;
10017       for (unsigned i = 0; i < NumElem ; ++i) {
10018         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10019         SDValue Val = St->getValue();
10020         // All of the operands of a BUILD_VECTOR must have the same type.
10021         if (Val.getValueType() != MemVT)
10022           return false;
10023         Ops.push_back(Val);
10024       }
10025
10026       // Build the extracted vector elements back into a vector.
10027       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10028     }
10029   } else {
10030     // We should always use a vector store when merging extracted vector
10031     // elements, so this path implies a store of constants.
10032     assert(IsConstantSrc && "Merged vector elements should use vector store");
10033
10034     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10035     APInt StoreInt(StoreBW, 0);
10036
10037     // Construct a single integer constant which is made of the smaller
10038     // constant inputs.
10039     bool IsLE = TLI.isLittleEndian();
10040     for (unsigned i = 0; i < NumElem ; ++i) {
10041       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10042       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10043       SDValue Val = St->getValue();
10044       StoreInt <<= ElementSizeBytes*8;
10045       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10046         StoreInt |= C->getAPIntValue().zext(StoreBW);
10047       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10048         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10049       } else {
10050         llvm_unreachable("Invalid constant element type");
10051       }
10052     }
10053
10054     // Create the new Load and Store operations.
10055     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10056     StoredVal = DAG.getConstant(StoreInt, StoreTy);
10057   }
10058
10059   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10060                                   FirstInChain->getBasePtr(),
10061                                   FirstInChain->getPointerInfo(),
10062                                   false, false,
10063                                   FirstInChain->getAlignment());
10064
10065   // Replace the first store with the new store
10066   CombineTo(EarliestOp, NewStore);
10067   // Erase all other stores.
10068   for (unsigned i = 0; i < NumElem ; ++i) {
10069     if (StoreNodes[i].MemNode == EarliestOp)
10070       continue;
10071     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10072     // ReplaceAllUsesWith will replace all uses that existed when it was
10073     // called, but graph optimizations may cause new ones to appear. For
10074     // example, the case in pr14333 looks like
10075     //
10076     //  St's chain -> St -> another store -> X
10077     //
10078     // And the only difference from St to the other store is the chain.
10079     // When we change it's chain to be St's chain they become identical,
10080     // get CSEed and the net result is that X is now a use of St.
10081     // Since we know that St is redundant, just iterate.
10082     while (!St->use_empty())
10083       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10084     deleteAndRecombine(St);
10085   }
10086
10087   return true;
10088 }
10089
10090 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10091   if (OptLevel == CodeGenOpt::None)
10092     return false;
10093
10094   EVT MemVT = St->getMemoryVT();
10095   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10096   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10097       Attribute::NoImplicitFloat);
10098
10099   // Don't merge vectors into wider inputs.
10100   if (MemVT.isVector() || !MemVT.isSimple())
10101     return false;
10102
10103   // Perform an early exit check. Do not bother looking at stored values that
10104   // are not constants, loads, or extracted vector elements.
10105   SDValue StoredVal = St->getValue();
10106   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10107   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10108                        isa<ConstantFPSDNode>(StoredVal);
10109   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10110
10111   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10112     return false;
10113
10114   // Only look at ends of store sequences.
10115   SDValue Chain = SDValue(St, 0);
10116   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10117     return false;
10118
10119   // This holds the base pointer, index, and the offset in bytes from the base
10120   // pointer.
10121   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10122
10123   // We must have a base and an offset.
10124   if (!BasePtr.Base.getNode())
10125     return false;
10126
10127   // Do not handle stores to undef base pointers.
10128   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10129     return false;
10130
10131   // Save the LoadSDNodes that we find in the chain.
10132   // We need to make sure that these nodes do not interfere with
10133   // any of the store nodes.
10134   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10135
10136   // Save the StoreSDNodes that we find in the chain.
10137   SmallVector<MemOpLink, 8> StoreNodes;
10138
10139   // Walk up the chain and look for nodes with offsets from the same
10140   // base pointer. Stop when reaching an instruction with a different kind
10141   // or instruction which has a different base pointer.
10142   unsigned Seq = 0;
10143   StoreSDNode *Index = St;
10144   while (Index) {
10145     // If the chain has more than one use, then we can't reorder the mem ops.
10146     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10147       break;
10148
10149     // Find the base pointer and offset for this memory node.
10150     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10151
10152     // Check that the base pointer is the same as the original one.
10153     if (!Ptr.equalBaseIndex(BasePtr))
10154       break;
10155
10156     // Check that the alignment is the same.
10157     if (Index->getAlignment() != St->getAlignment())
10158       break;
10159
10160     // The memory operands must not be volatile.
10161     if (Index->isVolatile() || Index->isIndexed())
10162       break;
10163
10164     // No truncation.
10165     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10166       if (St->isTruncatingStore())
10167         break;
10168
10169     // The stored memory type must be the same.
10170     if (Index->getMemoryVT() != MemVT)
10171       break;
10172
10173     // We do not allow unaligned stores because we want to prevent overriding
10174     // stores.
10175     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10176       break;
10177
10178     // We found a potential memory operand to merge.
10179     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10180
10181     // Find the next memory operand in the chain. If the next operand in the
10182     // chain is a store then move up and continue the scan with the next
10183     // memory operand. If the next operand is a load save it and use alias
10184     // information to check if it interferes with anything.
10185     SDNode *NextInChain = Index->getChain().getNode();
10186     while (1) {
10187       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10188         // We found a store node. Use it for the next iteration.
10189         Index = STn;
10190         break;
10191       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10192         if (Ldn->isVolatile()) {
10193           Index = nullptr;
10194           break;
10195         }
10196
10197         // Save the load node for later. Continue the scan.
10198         AliasLoadNodes.push_back(Ldn);
10199         NextInChain = Ldn->getChain().getNode();
10200         continue;
10201       } else {
10202         Index = nullptr;
10203         break;
10204       }
10205     }
10206   }
10207
10208   // Check if there is anything to merge.
10209   if (StoreNodes.size() < 2)
10210     return false;
10211
10212   // Sort the memory operands according to their distance from the base pointer.
10213   std::sort(StoreNodes.begin(), StoreNodes.end(),
10214             [](MemOpLink LHS, MemOpLink RHS) {
10215     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10216            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10217             LHS.SequenceNum > RHS.SequenceNum);
10218   });
10219
10220   // Scan the memory operations on the chain and find the first non-consecutive
10221   // store memory address.
10222   unsigned LastConsecutiveStore = 0;
10223   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10224   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10225
10226     // Check that the addresses are consecutive starting from the second
10227     // element in the list of stores.
10228     if (i > 0) {
10229       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10230       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10231         break;
10232     }
10233
10234     bool Alias = false;
10235     // Check if this store interferes with any of the loads that we found.
10236     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10237       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10238         Alias = true;
10239         break;
10240       }
10241     // We found a load that alias with this store. Stop the sequence.
10242     if (Alias)
10243       break;
10244
10245     // Mark this node as useful.
10246     LastConsecutiveStore = i;
10247   }
10248
10249   // The node with the lowest store address.
10250   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10251
10252   // Store the constants into memory as one consecutive store.
10253   if (IsConstantSrc) {
10254     unsigned LastLegalType = 0;
10255     unsigned LastLegalVectorType = 0;
10256     bool NonZero = false;
10257     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10258       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10259       SDValue StoredVal = St->getValue();
10260
10261       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10262         NonZero |= !C->isNullValue();
10263       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10264         NonZero |= !C->getConstantFPValue()->isNullValue();
10265       } else {
10266         // Non-constant.
10267         break;
10268       }
10269
10270       // Find a legal type for the constant store.
10271       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10272       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10273       if (TLI.isTypeLegal(StoreTy))
10274         LastLegalType = i+1;
10275       // Or check whether a truncstore is legal.
10276       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10277                TargetLowering::TypePromoteInteger) {
10278         EVT LegalizedStoredValueTy =
10279           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10280         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10281           LastLegalType = i+1;
10282       }
10283
10284       // Find a legal type for the vector store.
10285       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10286       if (TLI.isTypeLegal(Ty))
10287         LastLegalVectorType = i + 1;
10288     }
10289
10290     // We only use vectors if the constant is known to be zero and the
10291     // function is not marked with the noimplicitfloat attribute.
10292     if (NonZero || NoVectors)
10293       LastLegalVectorType = 0;
10294
10295     // Check if we found a legal integer type to store.
10296     if (LastLegalType == 0 && LastLegalVectorType == 0)
10297       return false;
10298
10299     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10300     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10301
10302     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10303                                            true, UseVector);
10304   }
10305
10306   // When extracting multiple vector elements, try to store them
10307   // in one vector store rather than a sequence of scalar stores.
10308   if (IsExtractVecEltSrc) {
10309     unsigned NumElem = 0;
10310     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10311       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10312       SDValue StoredVal = St->getValue();
10313       // This restriction could be loosened.
10314       // Bail out if any stored values are not elements extracted from a vector.
10315       // It should be possible to handle mixed sources, but load sources need
10316       // more careful handling (see the block of code below that handles
10317       // consecutive loads).
10318       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10319         return false;
10320
10321       // Find a legal type for the vector store.
10322       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10323       if (TLI.isTypeLegal(Ty))
10324         NumElem = i + 1;
10325     }
10326
10327     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10328                                            false, true);
10329   }
10330
10331   // Below we handle the case of multiple consecutive stores that
10332   // come from multiple consecutive loads. We merge them into a single
10333   // wide load and a single wide store.
10334
10335   // Look for load nodes which are used by the stored values.
10336   SmallVector<MemOpLink, 8> LoadNodes;
10337
10338   // Find acceptable loads. Loads need to have the same chain (token factor),
10339   // must not be zext, volatile, indexed, and they must be consecutive.
10340   BaseIndexOffset LdBasePtr;
10341   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10342     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10343     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10344     if (!Ld) break;
10345
10346     // Loads must only have one use.
10347     if (!Ld->hasNUsesOfValue(1, 0))
10348       break;
10349
10350     // Check that the alignment is the same as the stores.
10351     if (Ld->getAlignment() != St->getAlignment())
10352       break;
10353
10354     // The memory operands must not be volatile.
10355     if (Ld->isVolatile() || Ld->isIndexed())
10356       break;
10357
10358     // We do not accept ext loads.
10359     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10360       break;
10361
10362     // The stored memory type must be the same.
10363     if (Ld->getMemoryVT() != MemVT)
10364       break;
10365
10366     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10367     // If this is not the first ptr that we check.
10368     if (LdBasePtr.Base.getNode()) {
10369       // The base ptr must be the same.
10370       if (!LdPtr.equalBaseIndex(LdBasePtr))
10371         break;
10372     } else {
10373       // Check that all other base pointers are the same as this one.
10374       LdBasePtr = LdPtr;
10375     }
10376
10377     // We found a potential memory operand to merge.
10378     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10379   }
10380
10381   if (LoadNodes.size() < 2)
10382     return false;
10383
10384   // If we have load/store pair instructions and we only have two values,
10385   // don't bother.
10386   unsigned RequiredAlignment;
10387   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10388       St->getAlignment() >= RequiredAlignment)
10389     return false;
10390
10391   // Scan the memory operations on the chain and find the first non-consecutive
10392   // load memory address. These variables hold the index in the store node
10393   // array.
10394   unsigned LastConsecutiveLoad = 0;
10395   // This variable refers to the size and not index in the array.
10396   unsigned LastLegalVectorType = 0;
10397   unsigned LastLegalIntegerType = 0;
10398   StartAddress = LoadNodes[0].OffsetFromBase;
10399   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10400   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10401     // All loads much share the same chain.
10402     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10403       break;
10404
10405     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10406     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10407       break;
10408     LastConsecutiveLoad = i;
10409
10410     // Find a legal type for the vector store.
10411     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10412     if (TLI.isTypeLegal(StoreTy))
10413       LastLegalVectorType = i + 1;
10414
10415     // Find a legal type for the integer store.
10416     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10417     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10418     if (TLI.isTypeLegal(StoreTy))
10419       LastLegalIntegerType = i + 1;
10420     // Or check whether a truncstore and extload is legal.
10421     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10422              TargetLowering::TypePromoteInteger) {
10423       EVT LegalizedStoredValueTy =
10424         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10425       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10426           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10427           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10428           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10429         LastLegalIntegerType = i+1;
10430     }
10431   }
10432
10433   // Only use vector types if the vector type is larger than the integer type.
10434   // If they are the same, use integers.
10435   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10436   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10437
10438   // We add +1 here because the LastXXX variables refer to location while
10439   // the NumElem refers to array/index size.
10440   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10441   NumElem = std::min(LastLegalType, NumElem);
10442
10443   if (NumElem < 2)
10444     return false;
10445
10446   // The earliest Node in the DAG.
10447   unsigned EarliestNodeUsed = 0;
10448   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10449   for (unsigned i=1; i<NumElem; ++i) {
10450     // Find a chain for the new wide-store operand. Notice that some
10451     // of the store nodes that we found may not be selected for inclusion
10452     // in the wide store. The chain we use needs to be the chain of the
10453     // earliest store node which is *used* and replaced by the wide store.
10454     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10455       EarliestNodeUsed = i;
10456   }
10457
10458   // Find if it is better to use vectors or integers to load and store
10459   // to memory.
10460   EVT JointMemOpVT;
10461   if (UseVectorTy) {
10462     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10463   } else {
10464     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10465     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10466   }
10467
10468   SDLoc LoadDL(LoadNodes[0].MemNode);
10469   SDLoc StoreDL(StoreNodes[0].MemNode);
10470
10471   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10472   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10473                                 FirstLoad->getChain(),
10474                                 FirstLoad->getBasePtr(),
10475                                 FirstLoad->getPointerInfo(),
10476                                 false, false, false,
10477                                 FirstLoad->getAlignment());
10478
10479   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10480                                   FirstInChain->getBasePtr(),
10481                                   FirstInChain->getPointerInfo(), false, false,
10482                                   FirstInChain->getAlignment());
10483
10484   // Replace one of the loads with the new load.
10485   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10486   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10487                                 SDValue(NewLoad.getNode(), 1));
10488
10489   // Remove the rest of the load chains.
10490   for (unsigned i = 1; i < NumElem ; ++i) {
10491     // Replace all chain users of the old load nodes with the chain of the new
10492     // load node.
10493     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10494     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10495   }
10496
10497   // Replace the first store with the new store.
10498   CombineTo(EarliestOp, NewStore);
10499   // Erase all other stores.
10500   for (unsigned i = 0; i < NumElem ; ++i) {
10501     // Remove all Store nodes.
10502     if (StoreNodes[i].MemNode == EarliestOp)
10503       continue;
10504     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10505     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10506     deleteAndRecombine(St);
10507   }
10508
10509   return true;
10510 }
10511
10512 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10513   StoreSDNode *ST  = cast<StoreSDNode>(N);
10514   SDValue Chain = ST->getChain();
10515   SDValue Value = ST->getValue();
10516   SDValue Ptr   = ST->getBasePtr();
10517
10518   // If this is a store of a bit convert, store the input value if the
10519   // resultant store does not need a higher alignment than the original.
10520   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10521       ST->isUnindexed()) {
10522     unsigned OrigAlign = ST->getAlignment();
10523     EVT SVT = Value.getOperand(0).getValueType();
10524     unsigned Align = TLI.getDataLayout()->
10525       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10526     if (Align <= OrigAlign &&
10527         ((!LegalOperations && !ST->isVolatile()) ||
10528          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10529       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10530                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10531                           ST->isNonTemporal(), OrigAlign,
10532                           ST->getAAInfo());
10533   }
10534
10535   // Turn 'store undef, Ptr' -> nothing.
10536   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10537     return Chain;
10538
10539   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10540   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10541     // NOTE: If the original store is volatile, this transform must not increase
10542     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10543     // processor operation but an i64 (which is not legal) requires two.  So the
10544     // transform should not be done in this case.
10545     if (Value.getOpcode() != ISD::TargetConstantFP) {
10546       SDValue Tmp;
10547       switch (CFP->getSimpleValueType(0).SimpleTy) {
10548       default: llvm_unreachable("Unknown FP type");
10549       case MVT::f16:    // We don't do this for these yet.
10550       case MVT::f80:
10551       case MVT::f128:
10552       case MVT::ppcf128:
10553         break;
10554       case MVT::f32:
10555         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10556             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10557           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10558                               bitcastToAPInt().getZExtValue(), MVT::i32);
10559           return DAG.getStore(Chain, SDLoc(N), Tmp,
10560                               Ptr, ST->getMemOperand());
10561         }
10562         break;
10563       case MVT::f64:
10564         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10565              !ST->isVolatile()) ||
10566             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10567           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10568                                 getZExtValue(), MVT::i64);
10569           return DAG.getStore(Chain, SDLoc(N), Tmp,
10570                               Ptr, ST->getMemOperand());
10571         }
10572
10573         if (!ST->isVolatile() &&
10574             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10575           // Many FP stores are not made apparent until after legalize, e.g. for
10576           // argument passing.  Since this is so common, custom legalize the
10577           // 64-bit integer store into two 32-bit stores.
10578           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10579           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10580           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10581           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10582
10583           unsigned Alignment = ST->getAlignment();
10584           bool isVolatile = ST->isVolatile();
10585           bool isNonTemporal = ST->isNonTemporal();
10586           AAMDNodes AAInfo = ST->getAAInfo();
10587
10588           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10589                                      Ptr, ST->getPointerInfo(),
10590                                      isVolatile, isNonTemporal,
10591                                      ST->getAlignment(), AAInfo);
10592           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10593                             DAG.getConstant(4, Ptr.getValueType()));
10594           Alignment = MinAlign(Alignment, 4U);
10595           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10596                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10597                                      isVolatile, isNonTemporal,
10598                                      Alignment, AAInfo);
10599           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10600                              St0, St1);
10601         }
10602
10603         break;
10604       }
10605     }
10606   }
10607
10608   // Try to infer better alignment information than the store already has.
10609   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10610     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10611       if (Align > ST->getAlignment())
10612         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10613                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10614                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10615                                  ST->getAAInfo());
10616     }
10617   }
10618
10619   // Try transforming a pair floating point load / store ops to integer
10620   // load / store ops.
10621   SDValue NewST = TransformFPLoadStorePair(N);
10622   if (NewST.getNode())
10623     return NewST;
10624
10625   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10626                                                   : DAG.getSubtarget().useAA();
10627 #ifndef NDEBUG
10628   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10629       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10630     UseAA = false;
10631 #endif
10632   if (UseAA && ST->isUnindexed()) {
10633     // Walk up chain skipping non-aliasing memory nodes.
10634     SDValue BetterChain = FindBetterChain(N, Chain);
10635
10636     // If there is a better chain.
10637     if (Chain != BetterChain) {
10638       SDValue ReplStore;
10639
10640       // Replace the chain to avoid dependency.
10641       if (ST->isTruncatingStore()) {
10642         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10643                                       ST->getMemoryVT(), ST->getMemOperand());
10644       } else {
10645         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10646                                  ST->getMemOperand());
10647       }
10648
10649       // Create token to keep both nodes around.
10650       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10651                                   MVT::Other, Chain, ReplStore);
10652
10653       // Make sure the new and old chains are cleaned up.
10654       AddToWorklist(Token.getNode());
10655
10656       // Don't add users to work list.
10657       return CombineTo(N, Token, false);
10658     }
10659   }
10660
10661   // Try transforming N to an indexed store.
10662   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10663     return SDValue(N, 0);
10664
10665   // FIXME: is there such a thing as a truncating indexed store?
10666   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10667       Value.getValueType().isInteger()) {
10668     // See if we can simplify the input to this truncstore with knowledge that
10669     // only the low bits are being used.  For example:
10670     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10671     SDValue Shorter =
10672       GetDemandedBits(Value,
10673                       APInt::getLowBitsSet(
10674                         Value.getValueType().getScalarType().getSizeInBits(),
10675                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10676     AddToWorklist(Value.getNode());
10677     if (Shorter.getNode())
10678       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10679                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10680
10681     // Otherwise, see if we can simplify the operation with
10682     // SimplifyDemandedBits, which only works if the value has a single use.
10683     if (SimplifyDemandedBits(Value,
10684                         APInt::getLowBitsSet(
10685                           Value.getValueType().getScalarType().getSizeInBits(),
10686                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10687       return SDValue(N, 0);
10688   }
10689
10690   // If this is a load followed by a store to the same location, then the store
10691   // is dead/noop.
10692   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10693     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10694         ST->isUnindexed() && !ST->isVolatile() &&
10695         // There can't be any side effects between the load and store, such as
10696         // a call or store.
10697         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10698       // The store is dead, remove it.
10699       return Chain;
10700     }
10701   }
10702
10703   // If this is a store followed by a store with the same value to the same
10704   // location, then the store is dead/noop.
10705   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10706     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10707         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10708         ST1->isUnindexed() && !ST1->isVolatile()) {
10709       // The store is dead, remove it.
10710       return Chain;
10711     }
10712   }
10713
10714   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10715   // truncating store.  We can do this even if this is already a truncstore.
10716   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10717       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10718       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10719                             ST->getMemoryVT())) {
10720     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10721                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10722   }
10723
10724   // Only perform this optimization before the types are legal, because we
10725   // don't want to perform this optimization on every DAGCombine invocation.
10726   if (!LegalTypes) {
10727     bool EverChanged = false;
10728
10729     do {
10730       // There can be multiple store sequences on the same chain.
10731       // Keep trying to merge store sequences until we are unable to do so
10732       // or until we merge the last store on the chain.
10733       bool Changed = MergeConsecutiveStores(ST);
10734       EverChanged |= Changed;
10735       if (!Changed) break;
10736     } while (ST->getOpcode() != ISD::DELETED_NODE);
10737
10738     if (EverChanged)
10739       return SDValue(N, 0);
10740   }
10741
10742   return ReduceLoadOpStoreWidth(N);
10743 }
10744
10745 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10746   SDValue InVec = N->getOperand(0);
10747   SDValue InVal = N->getOperand(1);
10748   SDValue EltNo = N->getOperand(2);
10749   SDLoc dl(N);
10750
10751   // If the inserted element is an UNDEF, just use the input vector.
10752   if (InVal.getOpcode() == ISD::UNDEF)
10753     return InVec;
10754
10755   EVT VT = InVec.getValueType();
10756
10757   // If we can't generate a legal BUILD_VECTOR, exit
10758   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10759     return SDValue();
10760
10761   // Check that we know which element is being inserted
10762   if (!isa<ConstantSDNode>(EltNo))
10763     return SDValue();
10764   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10765
10766   // Canonicalize insert_vector_elt dag nodes.
10767   // Example:
10768   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10769   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10770   //
10771   // Do this only if the child insert_vector node has one use; also
10772   // do this only if indices are both constants and Idx1 < Idx0.
10773   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10774       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10775     unsigned OtherElt =
10776       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10777     if (Elt < OtherElt) {
10778       // Swap nodes.
10779       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10780                                   InVec.getOperand(0), InVal, EltNo);
10781       AddToWorklist(NewOp.getNode());
10782       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10783                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10784     }
10785   }
10786
10787   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10788   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10789   // vector elements.
10790   SmallVector<SDValue, 8> Ops;
10791   // Do not combine these two vectors if the output vector will not replace
10792   // the input vector.
10793   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10794     Ops.append(InVec.getNode()->op_begin(),
10795                InVec.getNode()->op_end());
10796   } else if (InVec.getOpcode() == ISD::UNDEF) {
10797     unsigned NElts = VT.getVectorNumElements();
10798     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10799   } else {
10800     return SDValue();
10801   }
10802
10803   // Insert the element
10804   if (Elt < Ops.size()) {
10805     // All the operands of BUILD_VECTOR must have the same type;
10806     // we enforce that here.
10807     EVT OpVT = Ops[0].getValueType();
10808     if (InVal.getValueType() != OpVT)
10809       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10810                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10811                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10812     Ops[Elt] = InVal;
10813   }
10814
10815   // Return the new vector
10816   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10817 }
10818
10819 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10820     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10821   EVT ResultVT = EVE->getValueType(0);
10822   EVT VecEltVT = InVecVT.getVectorElementType();
10823   unsigned Align = OriginalLoad->getAlignment();
10824   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10825       VecEltVT.getTypeForEVT(*DAG.getContext()));
10826
10827   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10828     return SDValue();
10829
10830   Align = NewAlign;
10831
10832   SDValue NewPtr = OriginalLoad->getBasePtr();
10833   SDValue Offset;
10834   EVT PtrType = NewPtr.getValueType();
10835   MachinePointerInfo MPI;
10836   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10837     int Elt = ConstEltNo->getZExtValue();
10838     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10839     if (TLI.isBigEndian())
10840       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10841     Offset = DAG.getConstant(PtrOff, PtrType);
10842     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10843   } else {
10844     Offset = DAG.getNode(
10845         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10846         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10847     if (TLI.isBigEndian())
10848       Offset = DAG.getNode(
10849           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10850           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10851     MPI = OriginalLoad->getPointerInfo();
10852   }
10853   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10854
10855   // The replacement we need to do here is a little tricky: we need to
10856   // replace an extractelement of a load with a load.
10857   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10858   // Note that this replacement assumes that the extractvalue is the only
10859   // use of the load; that's okay because we don't want to perform this
10860   // transformation in other cases anyway.
10861   SDValue Load;
10862   SDValue Chain;
10863   if (ResultVT.bitsGT(VecEltVT)) {
10864     // If the result type of vextract is wider than the load, then issue an
10865     // extending load instead.
10866     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10867                                                   VecEltVT)
10868                                    ? ISD::ZEXTLOAD
10869                                    : ISD::EXTLOAD;
10870     Load = DAG.getExtLoad(
10871         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10872         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10873         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10874     Chain = Load.getValue(1);
10875   } else {
10876     Load = DAG.getLoad(
10877         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10878         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10879         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10880     Chain = Load.getValue(1);
10881     if (ResultVT.bitsLT(VecEltVT))
10882       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10883     else
10884       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10885   }
10886   WorklistRemover DeadNodes(*this);
10887   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10888   SDValue To[] = { Load, Chain };
10889   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10890   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10891   // worklist explicitly as well.
10892   AddToWorklist(Load.getNode());
10893   AddUsersToWorklist(Load.getNode()); // Add users too
10894   // Make sure to revisit this node to clean it up; it will usually be dead.
10895   AddToWorklist(EVE);
10896   ++OpsNarrowed;
10897   return SDValue(EVE, 0);
10898 }
10899
10900 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10901   // (vextract (scalar_to_vector val, 0) -> val
10902   SDValue InVec = N->getOperand(0);
10903   EVT VT = InVec.getValueType();
10904   EVT NVT = N->getValueType(0);
10905
10906   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10907     // Check if the result type doesn't match the inserted element type. A
10908     // SCALAR_TO_VECTOR may truncate the inserted element and the
10909     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10910     SDValue InOp = InVec.getOperand(0);
10911     if (InOp.getValueType() != NVT) {
10912       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10913       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10914     }
10915     return InOp;
10916   }
10917
10918   SDValue EltNo = N->getOperand(1);
10919   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10920
10921   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10922   // We only perform this optimization before the op legalization phase because
10923   // we may introduce new vector instructions which are not backed by TD
10924   // patterns. For example on AVX, extracting elements from a wide vector
10925   // without using extract_subvector. However, if we can find an underlying
10926   // scalar value, then we can always use that.
10927   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10928       && ConstEltNo) {
10929     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10930     int NumElem = VT.getVectorNumElements();
10931     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10932     // Find the new index to extract from.
10933     int OrigElt = SVOp->getMaskElt(Elt);
10934
10935     // Extracting an undef index is undef.
10936     if (OrigElt == -1)
10937       return DAG.getUNDEF(NVT);
10938
10939     // Select the right vector half to extract from.
10940     SDValue SVInVec;
10941     if (OrigElt < NumElem) {
10942       SVInVec = InVec->getOperand(0);
10943     } else {
10944       SVInVec = InVec->getOperand(1);
10945       OrigElt -= NumElem;
10946     }
10947
10948     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10949       SDValue InOp = SVInVec.getOperand(OrigElt);
10950       if (InOp.getValueType() != NVT) {
10951         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10952         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10953       }
10954
10955       return InOp;
10956     }
10957
10958     // FIXME: We should handle recursing on other vector shuffles and
10959     // scalar_to_vector here as well.
10960
10961     if (!LegalOperations) {
10962       EVT IndexTy = TLI.getVectorIdxTy();
10963       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10964                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10965     }
10966   }
10967
10968   bool BCNumEltsChanged = false;
10969   EVT ExtVT = VT.getVectorElementType();
10970   EVT LVT = ExtVT;
10971
10972   // If the result of load has to be truncated, then it's not necessarily
10973   // profitable.
10974   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10975     return SDValue();
10976
10977   if (InVec.getOpcode() == ISD::BITCAST) {
10978     // Don't duplicate a load with other uses.
10979     if (!InVec.hasOneUse())
10980       return SDValue();
10981
10982     EVT BCVT = InVec.getOperand(0).getValueType();
10983     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10984       return SDValue();
10985     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10986       BCNumEltsChanged = true;
10987     InVec = InVec.getOperand(0);
10988     ExtVT = BCVT.getVectorElementType();
10989   }
10990
10991   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10992   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10993       ISD::isNormalLoad(InVec.getNode()) &&
10994       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10995     SDValue Index = N->getOperand(1);
10996     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10997       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10998                                                            OrigLoad);
10999   }
11000
11001   // Perform only after legalization to ensure build_vector / vector_shuffle
11002   // optimizations have already been done.
11003   if (!LegalOperations) return SDValue();
11004
11005   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11006   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11007   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11008
11009   if (ConstEltNo) {
11010     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11011
11012     LoadSDNode *LN0 = nullptr;
11013     const ShuffleVectorSDNode *SVN = nullptr;
11014     if (ISD::isNormalLoad(InVec.getNode())) {
11015       LN0 = cast<LoadSDNode>(InVec);
11016     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11017                InVec.getOperand(0).getValueType() == ExtVT &&
11018                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11019       // Don't duplicate a load with other uses.
11020       if (!InVec.hasOneUse())
11021         return SDValue();
11022
11023       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11024     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11025       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11026       // =>
11027       // (load $addr+1*size)
11028
11029       // Don't duplicate a load with other uses.
11030       if (!InVec.hasOneUse())
11031         return SDValue();
11032
11033       // If the bit convert changed the number of elements, it is unsafe
11034       // to examine the mask.
11035       if (BCNumEltsChanged)
11036         return SDValue();
11037
11038       // Select the input vector, guarding against out of range extract vector.
11039       unsigned NumElems = VT.getVectorNumElements();
11040       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11041       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11042
11043       if (InVec.getOpcode() == ISD::BITCAST) {
11044         // Don't duplicate a load with other uses.
11045         if (!InVec.hasOneUse())
11046           return SDValue();
11047
11048         InVec = InVec.getOperand(0);
11049       }
11050       if (ISD::isNormalLoad(InVec.getNode())) {
11051         LN0 = cast<LoadSDNode>(InVec);
11052         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11053         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11054       }
11055     }
11056
11057     // Make sure we found a non-volatile load and the extractelement is
11058     // the only use.
11059     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11060       return SDValue();
11061
11062     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11063     if (Elt == -1)
11064       return DAG.getUNDEF(LVT);
11065
11066     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11067   }
11068
11069   return SDValue();
11070 }
11071
11072 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11073 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11074   // We perform this optimization post type-legalization because
11075   // the type-legalizer often scalarizes integer-promoted vectors.
11076   // Performing this optimization before may create bit-casts which
11077   // will be type-legalized to complex code sequences.
11078   // We perform this optimization only before the operation legalizer because we
11079   // may introduce illegal operations.
11080   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11081     return SDValue();
11082
11083   unsigned NumInScalars = N->getNumOperands();
11084   SDLoc dl(N);
11085   EVT VT = N->getValueType(0);
11086
11087   // Check to see if this is a BUILD_VECTOR of a bunch of values
11088   // which come from any_extend or zero_extend nodes. If so, we can create
11089   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11090   // optimizations. We do not handle sign-extend because we can't fill the sign
11091   // using shuffles.
11092   EVT SourceType = MVT::Other;
11093   bool AllAnyExt = true;
11094
11095   for (unsigned i = 0; i != NumInScalars; ++i) {
11096     SDValue In = N->getOperand(i);
11097     // Ignore undef inputs.
11098     if (In.getOpcode() == ISD::UNDEF) continue;
11099
11100     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11101     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11102
11103     // Abort if the element is not an extension.
11104     if (!ZeroExt && !AnyExt) {
11105       SourceType = MVT::Other;
11106       break;
11107     }
11108
11109     // The input is a ZeroExt or AnyExt. Check the original type.
11110     EVT InTy = In.getOperand(0).getValueType();
11111
11112     // Check that all of the widened source types are the same.
11113     if (SourceType == MVT::Other)
11114       // First time.
11115       SourceType = InTy;
11116     else if (InTy != SourceType) {
11117       // Multiple income types. Abort.
11118       SourceType = MVT::Other;
11119       break;
11120     }
11121
11122     // Check if all of the extends are ANY_EXTENDs.
11123     AllAnyExt &= AnyExt;
11124   }
11125
11126   // In order to have valid types, all of the inputs must be extended from the
11127   // same source type and all of the inputs must be any or zero extend.
11128   // Scalar sizes must be a power of two.
11129   EVT OutScalarTy = VT.getScalarType();
11130   bool ValidTypes = SourceType != MVT::Other &&
11131                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11132                  isPowerOf2_32(SourceType.getSizeInBits());
11133
11134   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11135   // turn into a single shuffle instruction.
11136   if (!ValidTypes)
11137     return SDValue();
11138
11139   bool isLE = TLI.isLittleEndian();
11140   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11141   assert(ElemRatio > 1 && "Invalid element size ratio");
11142   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11143                                DAG.getConstant(0, SourceType);
11144
11145   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11146   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11147
11148   // Populate the new build_vector
11149   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11150     SDValue Cast = N->getOperand(i);
11151     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11152             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11153             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11154     SDValue In;
11155     if (Cast.getOpcode() == ISD::UNDEF)
11156       In = DAG.getUNDEF(SourceType);
11157     else
11158       In = Cast->getOperand(0);
11159     unsigned Index = isLE ? (i * ElemRatio) :
11160                             (i * ElemRatio + (ElemRatio - 1));
11161
11162     assert(Index < Ops.size() && "Invalid index");
11163     Ops[Index] = In;
11164   }
11165
11166   // The type of the new BUILD_VECTOR node.
11167   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11168   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11169          "Invalid vector size");
11170   // Check if the new vector type is legal.
11171   if (!isTypeLegal(VecVT)) return SDValue();
11172
11173   // Make the new BUILD_VECTOR.
11174   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11175
11176   // The new BUILD_VECTOR node has the potential to be further optimized.
11177   AddToWorklist(BV.getNode());
11178   // Bitcast to the desired type.
11179   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11180 }
11181
11182 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11183   EVT VT = N->getValueType(0);
11184
11185   unsigned NumInScalars = N->getNumOperands();
11186   SDLoc dl(N);
11187
11188   EVT SrcVT = MVT::Other;
11189   unsigned Opcode = ISD::DELETED_NODE;
11190   unsigned NumDefs = 0;
11191
11192   for (unsigned i = 0; i != NumInScalars; ++i) {
11193     SDValue In = N->getOperand(i);
11194     unsigned Opc = In.getOpcode();
11195
11196     if (Opc == ISD::UNDEF)
11197       continue;
11198
11199     // If all scalar values are floats and converted from integers.
11200     if (Opcode == ISD::DELETED_NODE &&
11201         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11202       Opcode = Opc;
11203     }
11204
11205     if (Opc != Opcode)
11206       return SDValue();
11207
11208     EVT InVT = In.getOperand(0).getValueType();
11209
11210     // If all scalar values are typed differently, bail out. It's chosen to
11211     // simplify BUILD_VECTOR of integer types.
11212     if (SrcVT == MVT::Other)
11213       SrcVT = InVT;
11214     if (SrcVT != InVT)
11215       return SDValue();
11216     NumDefs++;
11217   }
11218
11219   // If the vector has just one element defined, it's not worth to fold it into
11220   // a vectorized one.
11221   if (NumDefs < 2)
11222     return SDValue();
11223
11224   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11225          && "Should only handle conversion from integer to float.");
11226   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11227
11228   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11229
11230   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11231     return SDValue();
11232
11233   // Just because the floating-point vector type is legal does not necessarily
11234   // mean that the corresponding integer vector type is.
11235   if (!isTypeLegal(NVT))
11236     return SDValue();
11237
11238   SmallVector<SDValue, 8> Opnds;
11239   for (unsigned i = 0; i != NumInScalars; ++i) {
11240     SDValue In = N->getOperand(i);
11241
11242     if (In.getOpcode() == ISD::UNDEF)
11243       Opnds.push_back(DAG.getUNDEF(SrcVT));
11244     else
11245       Opnds.push_back(In.getOperand(0));
11246   }
11247   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11248   AddToWorklist(BV.getNode());
11249
11250   return DAG.getNode(Opcode, dl, VT, BV);
11251 }
11252
11253 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11254   unsigned NumInScalars = N->getNumOperands();
11255   SDLoc dl(N);
11256   EVT VT = N->getValueType(0);
11257
11258   // A vector built entirely of undefs is undef.
11259   if (ISD::allOperandsUndef(N))
11260     return DAG.getUNDEF(VT);
11261
11262   SDValue V = reduceBuildVecExtToExtBuildVec(N);
11263   if (V.getNode())
11264     return V;
11265
11266   V = reduceBuildVecConvertToConvertBuildVec(N);
11267   if (V.getNode())
11268     return V;
11269
11270   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11271   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11272   // at most two distinct vectors, turn this into a shuffle node.
11273
11274   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11275   if (!isTypeLegal(VT))
11276     return SDValue();
11277
11278   // May only combine to shuffle after legalize if shuffle is legal.
11279   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11280     return SDValue();
11281
11282   SDValue VecIn1, VecIn2;
11283   bool UsesZeroVector = false;
11284   for (unsigned i = 0; i != NumInScalars; ++i) {
11285     SDValue Op = N->getOperand(i);
11286     // Ignore undef inputs.
11287     if (Op.getOpcode() == ISD::UNDEF) continue;
11288
11289     // See if we can combine this build_vector into a blend with a zero vector.
11290     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11291         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11292         (Op.getOpcode() == ISD::ConstantFP &&
11293         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11294       UsesZeroVector = true;
11295       continue;
11296     }
11297
11298     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11299     // constant index, bail out.
11300     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11301         !isa<ConstantSDNode>(Op.getOperand(1))) {
11302       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11303       break;
11304     }
11305
11306     // We allow up to two distinct input vectors.
11307     SDValue ExtractedFromVec = Op.getOperand(0);
11308     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11309       continue;
11310
11311     if (!VecIn1.getNode()) {
11312       VecIn1 = ExtractedFromVec;
11313     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11314       VecIn2 = ExtractedFromVec;
11315     } else {
11316       // Too many inputs.
11317       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11318       break;
11319     }
11320   }
11321
11322   // If everything is good, we can make a shuffle operation.
11323   if (VecIn1.getNode()) {
11324     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11325     SmallVector<int, 8> Mask;
11326     for (unsigned i = 0; i != NumInScalars; ++i) {
11327       unsigned Opcode = N->getOperand(i).getOpcode();
11328       if (Opcode == ISD::UNDEF) {
11329         Mask.push_back(-1);
11330         continue;
11331       }
11332
11333       // Operands can also be zero.
11334       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11335         assert(UsesZeroVector &&
11336                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11337                "Unexpected node found!");
11338         Mask.push_back(NumInScalars+i);
11339         continue;
11340       }
11341
11342       // If extracting from the first vector, just use the index directly.
11343       SDValue Extract = N->getOperand(i);
11344       SDValue ExtVal = Extract.getOperand(1);
11345       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11346       if (Extract.getOperand(0) == VecIn1) {
11347         Mask.push_back(ExtIndex);
11348         continue;
11349       }
11350
11351       // Otherwise, use InIdx + InputVecSize
11352       Mask.push_back(InNumElements + ExtIndex);
11353     }
11354
11355     // Avoid introducing illegal shuffles with zero.
11356     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11357       return SDValue();
11358
11359     // We can't generate a shuffle node with mismatched input and output types.
11360     // Attempt to transform a single input vector to the correct type.
11361     if ((VT != VecIn1.getValueType())) {
11362       // If the input vector type has a different base type to the output
11363       // vector type, bail out.
11364       EVT VTElemType = VT.getVectorElementType();
11365       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11366           (VecIn2.getNode() &&
11367            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11368         return SDValue();
11369
11370       // If the input vector is too small, widen it.
11371       // We only support widening of vectors which are half the size of the
11372       // output registers. For example XMM->YMM widening on X86 with AVX.
11373       EVT VecInT = VecIn1.getValueType();
11374       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11375         // If we only have one small input, widen it by adding undef values.
11376         if (!VecIn2.getNode())
11377           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11378                                DAG.getUNDEF(VecIn1.getValueType()));
11379         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11380           // If we have two small inputs of the same type, try to concat them.
11381           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11382           VecIn2 = SDValue(nullptr, 0);
11383         } else
11384           return SDValue();
11385       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11386         // If the input vector is too large, try to split it.
11387         // We don't support having two input vectors that are too large.
11388         // If the zero vector was used, we can not split the vector,
11389         // since we'd need 3 inputs.
11390         if (UsesZeroVector || VecIn2.getNode())
11391           return SDValue();
11392
11393         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11394           return SDValue();
11395
11396         // Try to replace VecIn1 with two extract_subvectors
11397         // No need to update the masks, they should still be correct.
11398         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11399           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11400         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11401           DAG.getConstant(0, TLI.getVectorIdxTy()));
11402       } else
11403         return SDValue();
11404     }
11405
11406     if (UsesZeroVector)
11407       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11408                                 DAG.getConstantFP(0.0, VT);
11409     else
11410       // If VecIn2 is unused then change it to undef.
11411       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11412
11413     // Check that we were able to transform all incoming values to the same
11414     // type.
11415     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11416         VecIn1.getValueType() != VT)
11417           return SDValue();
11418
11419     // Return the new VECTOR_SHUFFLE node.
11420     SDValue Ops[2];
11421     Ops[0] = VecIn1;
11422     Ops[1] = VecIn2;
11423     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11424   }
11425
11426   return SDValue();
11427 }
11428
11429 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11430   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11431   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11432   // inputs come from at most two distinct vectors, turn this into a shuffle
11433   // node.
11434
11435   // If we only have one input vector, we don't need to do any concatenation.
11436   if (N->getNumOperands() == 1)
11437     return N->getOperand(0);
11438
11439   // Check if all of the operands are undefs.
11440   EVT VT = N->getValueType(0);
11441   if (ISD::allOperandsUndef(N))
11442     return DAG.getUNDEF(VT);
11443
11444   // Optimize concat_vectors where one of the vectors is undef.
11445   if (N->getNumOperands() == 2 &&
11446       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11447     SDValue In = N->getOperand(0);
11448     assert(In.getValueType().isVector() && "Must concat vectors");
11449
11450     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11451     if (In->getOpcode() == ISD::BITCAST &&
11452         !In->getOperand(0)->getValueType(0).isVector()) {
11453       SDValue Scalar = In->getOperand(0);
11454       EVT SclTy = Scalar->getValueType(0);
11455
11456       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11457         return SDValue();
11458
11459       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11460                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11461       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11462         return SDValue();
11463
11464       SDLoc dl = SDLoc(N);
11465       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11466       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11467     }
11468   }
11469
11470   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11471   // We have already tested above for an UNDEF only concatenation.
11472   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11473   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11474   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11475     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11476   };
11477   bool AllBuildVectorsOrUndefs =
11478       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11479   if (AllBuildVectorsOrUndefs) {
11480     SmallVector<SDValue, 8> Opnds;
11481     EVT SVT = VT.getScalarType();
11482
11483     EVT MinVT = SVT;
11484     if (!SVT.isFloatingPoint()) {
11485       // If BUILD_VECTOR are from built from integer, they may have different
11486       // operand types. Get the smallest type and truncate all operands to it.
11487       bool FoundMinVT = false;
11488       for (const SDValue &Op : N->ops())
11489         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11490           EVT OpSVT = Op.getOperand(0)->getValueType(0);
11491           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11492           FoundMinVT = true;
11493         }
11494       assert(FoundMinVT && "Concat vector type mismatch");
11495     }
11496
11497     for (const SDValue &Op : N->ops()) {
11498       EVT OpVT = Op.getValueType();
11499       unsigned NumElts = OpVT.getVectorNumElements();
11500
11501       if (ISD::UNDEF == Op.getOpcode())
11502         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11503
11504       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11505         if (SVT.isFloatingPoint()) {
11506           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11507           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11508         } else {
11509           for (unsigned i = 0; i != NumElts; ++i)
11510             Opnds.push_back(
11511                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11512         }
11513       }
11514     }
11515
11516     assert(VT.getVectorNumElements() == Opnds.size() &&
11517            "Concat vector type mismatch");
11518     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11519   }
11520
11521   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11522   // nodes often generate nop CONCAT_VECTOR nodes.
11523   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11524   // place the incoming vectors at the exact same location.
11525   SDValue SingleSource = SDValue();
11526   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11527
11528   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11529     SDValue Op = N->getOperand(i);
11530
11531     if (Op.getOpcode() == ISD::UNDEF)
11532       continue;
11533
11534     // Check if this is the identity extract:
11535     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11536       return SDValue();
11537
11538     // Find the single incoming vector for the extract_subvector.
11539     if (SingleSource.getNode()) {
11540       if (Op.getOperand(0) != SingleSource)
11541         return SDValue();
11542     } else {
11543       SingleSource = Op.getOperand(0);
11544
11545       // Check the source type is the same as the type of the result.
11546       // If not, this concat may extend the vector, so we can not
11547       // optimize it away.
11548       if (SingleSource.getValueType() != N->getValueType(0))
11549         return SDValue();
11550     }
11551
11552     unsigned IdentityIndex = i * PartNumElem;
11553     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11554     // The extract index must be constant.
11555     if (!CS)
11556       return SDValue();
11557
11558     // Check that we are reading from the identity index.
11559     if (CS->getZExtValue() != IdentityIndex)
11560       return SDValue();
11561   }
11562
11563   if (SingleSource.getNode())
11564     return SingleSource;
11565
11566   return SDValue();
11567 }
11568
11569 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11570   EVT NVT = N->getValueType(0);
11571   SDValue V = N->getOperand(0);
11572
11573   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11574     // Combine:
11575     //    (extract_subvec (concat V1, V2, ...), i)
11576     // Into:
11577     //    Vi if possible
11578     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11579     // type.
11580     if (V->getOperand(0).getValueType() != NVT)
11581       return SDValue();
11582     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11583     unsigned NumElems = NVT.getVectorNumElements();
11584     assert((Idx % NumElems) == 0 &&
11585            "IDX in concat is not a multiple of the result vector length.");
11586     return V->getOperand(Idx / NumElems);
11587   }
11588
11589   // Skip bitcasting
11590   if (V->getOpcode() == ISD::BITCAST)
11591     V = V.getOperand(0);
11592
11593   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11594     SDLoc dl(N);
11595     // Handle only simple case where vector being inserted and vector
11596     // being extracted are of same type, and are half size of larger vectors.
11597     EVT BigVT = V->getOperand(0).getValueType();
11598     EVT SmallVT = V->getOperand(1).getValueType();
11599     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11600       return SDValue();
11601
11602     // Only handle cases where both indexes are constants with the same type.
11603     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11604     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11605
11606     if (InsIdx && ExtIdx &&
11607         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11608         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11609       // Combine:
11610       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11611       // Into:
11612       //    indices are equal or bit offsets are equal => V1
11613       //    otherwise => (extract_subvec V1, ExtIdx)
11614       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11615           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11616         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11617       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11618                          DAG.getNode(ISD::BITCAST, dl,
11619                                      N->getOperand(0).getValueType(),
11620                                      V->getOperand(0)), N->getOperand(1));
11621     }
11622   }
11623
11624   return SDValue();
11625 }
11626
11627 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11628                                                  SDValue V, SelectionDAG &DAG) {
11629   SDLoc DL(V);
11630   EVT VT = V.getValueType();
11631
11632   switch (V.getOpcode()) {
11633   default:
11634     return V;
11635
11636   case ISD::CONCAT_VECTORS: {
11637     EVT OpVT = V->getOperand(0).getValueType();
11638     int OpSize = OpVT.getVectorNumElements();
11639     SmallBitVector OpUsedElements(OpSize, false);
11640     bool FoundSimplification = false;
11641     SmallVector<SDValue, 4> NewOps;
11642     NewOps.reserve(V->getNumOperands());
11643     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11644       SDValue Op = V->getOperand(i);
11645       bool OpUsed = false;
11646       for (int j = 0; j < OpSize; ++j)
11647         if (UsedElements[i * OpSize + j]) {
11648           OpUsedElements[j] = true;
11649           OpUsed = true;
11650         }
11651       NewOps.push_back(
11652           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11653                  : DAG.getUNDEF(OpVT));
11654       FoundSimplification |= Op == NewOps.back();
11655       OpUsedElements.reset();
11656     }
11657     if (FoundSimplification)
11658       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11659     return V;
11660   }
11661
11662   case ISD::INSERT_SUBVECTOR: {
11663     SDValue BaseV = V->getOperand(0);
11664     SDValue SubV = V->getOperand(1);
11665     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11666     if (!IdxN)
11667       return V;
11668
11669     int SubSize = SubV.getValueType().getVectorNumElements();
11670     int Idx = IdxN->getZExtValue();
11671     bool SubVectorUsed = false;
11672     SmallBitVector SubUsedElements(SubSize, false);
11673     for (int i = 0; i < SubSize; ++i)
11674       if (UsedElements[i + Idx]) {
11675         SubVectorUsed = true;
11676         SubUsedElements[i] = true;
11677         UsedElements[i + Idx] = false;
11678       }
11679
11680     // Now recurse on both the base and sub vectors.
11681     SDValue SimplifiedSubV =
11682         SubVectorUsed
11683             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11684             : DAG.getUNDEF(SubV.getValueType());
11685     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11686     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11687       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11688                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11689     return V;
11690   }
11691   }
11692 }
11693
11694 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11695                                        SDValue N1, SelectionDAG &DAG) {
11696   EVT VT = SVN->getValueType(0);
11697   int NumElts = VT.getVectorNumElements();
11698   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11699   for (int M : SVN->getMask())
11700     if (M >= 0 && M < NumElts)
11701       N0UsedElements[M] = true;
11702     else if (M >= NumElts)
11703       N1UsedElements[M - NumElts] = true;
11704
11705   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11706   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11707   if (S0 == N0 && S1 == N1)
11708     return SDValue();
11709
11710   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11711 }
11712
11713 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11714 // or turn a shuffle of a single concat into simpler shuffle then concat.
11715 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11716   EVT VT = N->getValueType(0);
11717   unsigned NumElts = VT.getVectorNumElements();
11718
11719   SDValue N0 = N->getOperand(0);
11720   SDValue N1 = N->getOperand(1);
11721   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11722
11723   SmallVector<SDValue, 4> Ops;
11724   EVT ConcatVT = N0.getOperand(0).getValueType();
11725   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11726   unsigned NumConcats = NumElts / NumElemsPerConcat;
11727
11728   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11729   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11730   // half vector elements.
11731   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11732       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11733                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11734     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11735                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11736     N1 = DAG.getUNDEF(ConcatVT);
11737     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11738   }
11739
11740   // Look at every vector that's inserted. We're looking for exact
11741   // subvector-sized copies from a concatenated vector
11742   for (unsigned I = 0; I != NumConcats; ++I) {
11743     // Make sure we're dealing with a copy.
11744     unsigned Begin = I * NumElemsPerConcat;
11745     bool AllUndef = true, NoUndef = true;
11746     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11747       if (SVN->getMaskElt(J) >= 0)
11748         AllUndef = false;
11749       else
11750         NoUndef = false;
11751     }
11752
11753     if (NoUndef) {
11754       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11755         return SDValue();
11756
11757       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11758         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11759           return SDValue();
11760
11761       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11762       if (FirstElt < N0.getNumOperands())
11763         Ops.push_back(N0.getOperand(FirstElt));
11764       else
11765         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11766
11767     } else if (AllUndef) {
11768       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11769     } else { // Mixed with general masks and undefs, can't do optimization.
11770       return SDValue();
11771     }
11772   }
11773
11774   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11775 }
11776
11777 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11778   EVT VT = N->getValueType(0);
11779   unsigned NumElts = VT.getVectorNumElements();
11780
11781   SDValue N0 = N->getOperand(0);
11782   SDValue N1 = N->getOperand(1);
11783
11784   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11785
11786   // Canonicalize shuffle undef, undef -> undef
11787   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11788     return DAG.getUNDEF(VT);
11789
11790   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11791
11792   // Canonicalize shuffle v, v -> v, undef
11793   if (N0 == N1) {
11794     SmallVector<int, 8> NewMask;
11795     for (unsigned i = 0; i != NumElts; ++i) {
11796       int Idx = SVN->getMaskElt(i);
11797       if (Idx >= (int)NumElts) Idx -= NumElts;
11798       NewMask.push_back(Idx);
11799     }
11800     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11801                                 &NewMask[0]);
11802   }
11803
11804   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11805   if (N0.getOpcode() == ISD::UNDEF) {
11806     SmallVector<int, 8> NewMask;
11807     for (unsigned i = 0; i != NumElts; ++i) {
11808       int Idx = SVN->getMaskElt(i);
11809       if (Idx >= 0) {
11810         if (Idx >= (int)NumElts)
11811           Idx -= NumElts;
11812         else
11813           Idx = -1; // remove reference to lhs
11814       }
11815       NewMask.push_back(Idx);
11816     }
11817     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11818                                 &NewMask[0]);
11819   }
11820
11821   // Remove references to rhs if it is undef
11822   if (N1.getOpcode() == ISD::UNDEF) {
11823     bool Changed = false;
11824     SmallVector<int, 8> NewMask;
11825     for (unsigned i = 0; i != NumElts; ++i) {
11826       int Idx = SVN->getMaskElt(i);
11827       if (Idx >= (int)NumElts) {
11828         Idx = -1;
11829         Changed = true;
11830       }
11831       NewMask.push_back(Idx);
11832     }
11833     if (Changed)
11834       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11835   }
11836
11837   // If it is a splat, check if the argument vector is another splat or a
11838   // build_vector.
11839   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11840     SDNode *V = N0.getNode();
11841
11842     // If this is a bit convert that changes the element type of the vector but
11843     // not the number of vector elements, look through it.  Be careful not to
11844     // look though conversions that change things like v4f32 to v2f64.
11845     if (V->getOpcode() == ISD::BITCAST) {
11846       SDValue ConvInput = V->getOperand(0);
11847       if (ConvInput.getValueType().isVector() &&
11848           ConvInput.getValueType().getVectorNumElements() == NumElts)
11849         V = ConvInput.getNode();
11850     }
11851
11852     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11853       assert(V->getNumOperands() == NumElts &&
11854              "BUILD_VECTOR has wrong number of operands");
11855       SDValue Base;
11856       bool AllSame = true;
11857       for (unsigned i = 0; i != NumElts; ++i) {
11858         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11859           Base = V->getOperand(i);
11860           break;
11861         }
11862       }
11863       // Splat of <u, u, u, u>, return <u, u, u, u>
11864       if (!Base.getNode())
11865         return N0;
11866       for (unsigned i = 0; i != NumElts; ++i) {
11867         if (V->getOperand(i) != Base) {
11868           AllSame = false;
11869           break;
11870         }
11871       }
11872       // Splat of <x, x, x, x>, return <x, x, x, x>
11873       if (AllSame)
11874         return N0;
11875
11876       // Canonicalize any other splat as a build_vector.
11877       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11878       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11879       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11880                                   V->getValueType(0), Ops);
11881
11882       // We may have jumped through bitcasts, so the type of the
11883       // BUILD_VECTOR may not match the type of the shuffle.
11884       if (V->getValueType(0) != VT)
11885           NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11886       return NewBV;
11887     }
11888   }
11889
11890   // There are various patterns used to build up a vector from smaller vectors,
11891   // subvectors, or elements. Scan chains of these and replace unused insertions
11892   // or components with undef.
11893   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11894     return S;
11895
11896   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11897       Level < AfterLegalizeVectorOps &&
11898       (N1.getOpcode() == ISD::UNDEF ||
11899       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11900        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11901     SDValue V = partitionShuffleOfConcats(N, DAG);
11902
11903     if (V.getNode())
11904       return V;
11905   }
11906
11907   // If this shuffle only has a single input that is a bitcasted shuffle,
11908   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
11909   // back to their original types.
11910   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
11911       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
11912       TLI.isTypeLegal(VT)) {
11913
11914     // Peek through the bitcast only if there is one user.
11915     SDValue BC0 = N0;
11916     while (BC0.getOpcode() == ISD::BITCAST) {
11917       if (!BC0.hasOneUse())
11918         break;
11919       BC0 = BC0.getOperand(0);
11920     }
11921
11922     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
11923       if (Scale == 1)
11924         return SmallVector<int, 8>(Mask.begin(), Mask.end());
11925
11926       SmallVector<int, 8> NewMask;
11927       for (int M : Mask)
11928         for (int s = 0; s != Scale; ++s)
11929           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
11930       return NewMask;
11931     };
11932
11933     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
11934       EVT SVT = VT.getScalarType();
11935       EVT InnerVT = BC0->getValueType(0);
11936       EVT InnerSVT = InnerVT.getScalarType();
11937
11938       // Determine which shuffle works with the smaller scalar type.
11939       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
11940       EVT ScaleSVT = ScaleVT.getScalarType();
11941
11942       if (TLI.isTypeLegal(ScaleVT) &&
11943           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
11944           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
11945
11946         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
11947         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
11948
11949         // Scale the shuffle masks to the smaller scalar type.
11950         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
11951         SmallVector<int, 8> InnerMask =
11952             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
11953         SmallVector<int, 8> OuterMask =
11954             ScaleShuffleMask(SVN->getMask(), OuterScale);
11955
11956         // Merge the shuffle masks.
11957         SmallVector<int, 8> NewMask;
11958         for (int M : OuterMask)
11959           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
11960
11961         // Test for shuffle mask legality over both commutations.
11962         SDValue SV0 = BC0->getOperand(0);
11963         SDValue SV1 = BC0->getOperand(1);
11964         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
11965         if (!LegalMask) {
11966           for (int i = 0, e = (int)NewMask.size(); i != e; ++i) {
11967             int idx = NewMask[i];
11968             if (idx < 0)
11969               continue;
11970             else if (idx < e)
11971               NewMask[i] = idx + e;
11972             else
11973               NewMask[i] = idx - e;
11974           }
11975           std::swap(SV0, SV1);
11976           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
11977         }
11978
11979         if (LegalMask) {
11980           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
11981           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
11982           return DAG.getNode(
11983               ISD::BITCAST, SDLoc(N), VT,
11984               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
11985         }
11986       }
11987     }
11988   }
11989
11990   // Canonicalize shuffles according to rules:
11991   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11992   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11993   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11994   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11995       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11996       TLI.isTypeLegal(VT)) {
11997     // The incoming shuffle must be of the same type as the result of the
11998     // current shuffle.
11999     assert(N1->getOperand(0).getValueType() == VT &&
12000            "Shuffle types don't match");
12001
12002     SDValue SV0 = N1->getOperand(0);
12003     SDValue SV1 = N1->getOperand(1);
12004     bool HasSameOp0 = N0 == SV0;
12005     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12006     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12007       // Commute the operands of this shuffle so that next rule
12008       // will trigger.
12009       return DAG.getCommutedVectorShuffle(*SVN);
12010   }
12011
12012   // Try to fold according to rules:
12013   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12014   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12015   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12016   // Don't try to fold shuffles with illegal type.
12017   // Only fold if this shuffle is the only user of the other shuffle.
12018   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12019       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12020     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12021
12022     // The incoming shuffle must be of the same type as the result of the
12023     // current shuffle.
12024     assert(OtherSV->getOperand(0).getValueType() == VT &&
12025            "Shuffle types don't match");
12026
12027     SDValue SV0, SV1;
12028     SmallVector<int, 4> Mask;
12029     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12030     // operand, and SV1 as the second operand.
12031     for (unsigned i = 0; i != NumElts; ++i) {
12032       int Idx = SVN->getMaskElt(i);
12033       if (Idx < 0) {
12034         // Propagate Undef.
12035         Mask.push_back(Idx);
12036         continue;
12037       }
12038
12039       SDValue CurrentVec;
12040       if (Idx < (int)NumElts) {
12041         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12042         // shuffle mask to identify which vector is actually referenced.
12043         Idx = OtherSV->getMaskElt(Idx);
12044         if (Idx < 0) {
12045           // Propagate Undef.
12046           Mask.push_back(Idx);
12047           continue;
12048         }
12049
12050         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12051                                            : OtherSV->getOperand(1);
12052       } else {
12053         // This shuffle index references an element within N1.
12054         CurrentVec = N1;
12055       }
12056
12057       // Simple case where 'CurrentVec' is UNDEF.
12058       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12059         Mask.push_back(-1);
12060         continue;
12061       }
12062
12063       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12064       // will be the first or second operand of the combined shuffle.
12065       Idx = Idx % NumElts;
12066       if (!SV0.getNode() || SV0 == CurrentVec) {
12067         // Ok. CurrentVec is the left hand side.
12068         // Update the mask accordingly.
12069         SV0 = CurrentVec;
12070         Mask.push_back(Idx);
12071         continue;
12072       }
12073
12074       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12075       if (SV1.getNode() && SV1 != CurrentVec)
12076         return SDValue();
12077
12078       // Ok. CurrentVec is the right hand side.
12079       // Update the mask accordingly.
12080       SV1 = CurrentVec;
12081       Mask.push_back(Idx + NumElts);
12082     }
12083
12084     // Check if all indices in Mask are Undef. In case, propagate Undef.
12085     bool isUndefMask = true;
12086     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12087       isUndefMask &= Mask[i] < 0;
12088
12089     if (isUndefMask)
12090       return DAG.getUNDEF(VT);
12091
12092     if (!SV0.getNode())
12093       SV0 = DAG.getUNDEF(VT);
12094     if (!SV1.getNode())
12095       SV1 = DAG.getUNDEF(VT);
12096
12097     // Avoid introducing shuffles with illegal mask.
12098     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12099       // Compute the commuted shuffle mask and test again.
12100       for (unsigned i = 0; i != NumElts; ++i) {
12101         int idx = Mask[i];
12102         if (idx < 0)
12103           continue;
12104         else if (idx < (int)NumElts)
12105           Mask[i] = idx + NumElts;
12106         else
12107           Mask[i] = idx - NumElts;
12108       }
12109
12110       if (!TLI.isShuffleMaskLegal(Mask, VT))
12111         return SDValue();
12112
12113       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12114       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12115       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12116       std::swap(SV0, SV1);
12117     }
12118
12119     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12120     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12121     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12122     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12123   }
12124
12125   return SDValue();
12126 }
12127
12128 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12129   SDValue N0 = N->getOperand(0);
12130   SDValue N2 = N->getOperand(2);
12131
12132   // If the input vector is a concatenation, and the insert replaces
12133   // one of the halves, we can optimize into a single concat_vectors.
12134   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12135       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12136     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12137     EVT VT = N->getValueType(0);
12138
12139     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12140     // (concat_vectors Z, Y)
12141     if (InsIdx == 0)
12142       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12143                          N->getOperand(1), N0.getOperand(1));
12144
12145     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12146     // (concat_vectors X, Z)
12147     if (InsIdx == VT.getVectorNumElements()/2)
12148       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12149                          N0.getOperand(0), N->getOperand(1));
12150   }
12151
12152   return SDValue();
12153 }
12154
12155 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12156 /// with the destination vector and a zero vector.
12157 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12158 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12159 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12160   EVT VT = N->getValueType(0);
12161   SDLoc dl(N);
12162   SDValue LHS = N->getOperand(0);
12163   SDValue RHS = N->getOperand(1);
12164   if (N->getOpcode() == ISD::AND) {
12165     if (RHS.getOpcode() == ISD::BITCAST)
12166       RHS = RHS.getOperand(0);
12167     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12168       SmallVector<int, 8> Indices;
12169       unsigned NumElts = RHS.getNumOperands();
12170       for (unsigned i = 0; i != NumElts; ++i) {
12171         SDValue Elt = RHS.getOperand(i);
12172         if (!isa<ConstantSDNode>(Elt))
12173           return SDValue();
12174
12175         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12176           Indices.push_back(i);
12177         else if (cast<ConstantSDNode>(Elt)->isNullValue())
12178           Indices.push_back(NumElts+i);
12179         else
12180           return SDValue();
12181       }
12182
12183       // Let's see if the target supports this vector_shuffle and make sure
12184       // we're not running after operation legalization where it may have
12185       // custom lowered the vector shuffles.
12186       EVT RVT = RHS.getValueType();
12187       if (LegalOperations || !TLI.isVectorClearMaskLegal(Indices, RVT))
12188         return SDValue();
12189
12190       // Return the new VECTOR_SHUFFLE node.
12191       EVT EltVT = RVT.getVectorElementType();
12192       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12193                                      DAG.getConstant(0, EltVT));
12194       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12195       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12196       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12197       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12198     }
12199   }
12200
12201   return SDValue();
12202 }
12203
12204 /// Visit a binary vector operation, like ADD.
12205 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12206   assert(N->getValueType(0).isVector() &&
12207          "SimplifyVBinOp only works on vectors!");
12208
12209   SDValue LHS = N->getOperand(0);
12210   SDValue RHS = N->getOperand(1);
12211   SDValue Shuffle = XformToShuffleWithZero(N);
12212   if (Shuffle.getNode()) return Shuffle;
12213
12214   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12215   // this operation.
12216   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12217       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12218     // Check if both vectors are constants. If not bail out.
12219     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12220           cast<BuildVectorSDNode>(RHS)->isConstant()))
12221       return SDValue();
12222
12223     SmallVector<SDValue, 8> Ops;
12224     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12225       SDValue LHSOp = LHS.getOperand(i);
12226       SDValue RHSOp = RHS.getOperand(i);
12227
12228       // Can't fold divide by zero.
12229       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12230           N->getOpcode() == ISD::FDIV) {
12231         if ((RHSOp.getOpcode() == ISD::Constant &&
12232              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12233             (RHSOp.getOpcode() == ISD::ConstantFP &&
12234              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12235           break;
12236       }
12237
12238       EVT VT = LHSOp.getValueType();
12239       EVT RVT = RHSOp.getValueType();
12240       if (RVT != VT) {
12241         // Integer BUILD_VECTOR operands may have types larger than the element
12242         // size (e.g., when the element type is not legal).  Prior to type
12243         // legalization, the types may not match between the two BUILD_VECTORS.
12244         // Truncate one of the operands to make them match.
12245         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12246           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12247         } else {
12248           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12249           VT = RVT;
12250         }
12251       }
12252       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12253                                    LHSOp, RHSOp);
12254       if (FoldOp.getOpcode() != ISD::UNDEF &&
12255           FoldOp.getOpcode() != ISD::Constant &&
12256           FoldOp.getOpcode() != ISD::ConstantFP)
12257         break;
12258       Ops.push_back(FoldOp);
12259       AddToWorklist(FoldOp.getNode());
12260     }
12261
12262     if (Ops.size() == LHS.getNumOperands())
12263       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12264   }
12265
12266   // Type legalization might introduce new shuffles in the DAG.
12267   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12268   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12269   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12270       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12271       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12272       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12273     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12274     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12275
12276     if (SVN0->getMask().equals(SVN1->getMask())) {
12277       EVT VT = N->getValueType(0);
12278       SDValue UndefVector = LHS.getOperand(1);
12279       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12280                                      LHS.getOperand(0), RHS.getOperand(0));
12281       AddUsersToWorklist(N);
12282       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12283                                   &SVN0->getMask()[0]);
12284     }
12285   }
12286
12287   return SDValue();
12288 }
12289
12290 /// Visit a binary vector operation, like FABS/FNEG.
12291 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
12292   assert(N->getValueType(0).isVector() &&
12293          "SimplifyVUnaryOp only works on vectors!");
12294
12295   SDValue N0 = N->getOperand(0);
12296
12297   if (N0.getOpcode() != ISD::BUILD_VECTOR)
12298     return SDValue();
12299
12300   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12301   SmallVector<SDValue, 8> Ops;
12302   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12303     SDValue Op = N0.getOperand(i);
12304     if (Op.getOpcode() != ISD::UNDEF &&
12305         Op.getOpcode() != ISD::ConstantFP)
12306       break;
12307     EVT EltVT = Op.getValueType();
12308     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
12309     if (FoldOp.getOpcode() != ISD::UNDEF &&
12310         FoldOp.getOpcode() != ISD::ConstantFP)
12311       break;
12312     Ops.push_back(FoldOp);
12313     AddToWorklist(FoldOp.getNode());
12314   }
12315
12316   if (Ops.size() != N0.getNumOperands())
12317     return SDValue();
12318
12319   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
12320 }
12321
12322 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12323                                     SDValue N1, SDValue N2){
12324   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12325
12326   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12327                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12328
12329   // If we got a simplified select_cc node back from SimplifySelectCC, then
12330   // break it down into a new SETCC node, and a new SELECT node, and then return
12331   // the SELECT node, since we were called with a SELECT node.
12332   if (SCC.getNode()) {
12333     // Check to see if we got a select_cc back (to turn into setcc/select).
12334     // Otherwise, just return whatever node we got back, like fabs.
12335     if (SCC.getOpcode() == ISD::SELECT_CC) {
12336       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12337                                   N0.getValueType(),
12338                                   SCC.getOperand(0), SCC.getOperand(1),
12339                                   SCC.getOperand(4));
12340       AddToWorklist(SETCC.getNode());
12341       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12342                            SCC.getOperand(2), SCC.getOperand(3));
12343     }
12344
12345     return SCC;
12346   }
12347   return SDValue();
12348 }
12349
12350 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12351 /// being selected between, see if we can simplify the select.  Callers of this
12352 /// should assume that TheSelect is deleted if this returns true.  As such, they
12353 /// should return the appropriate thing (e.g. the node) back to the top-level of
12354 /// the DAG combiner loop to avoid it being looked at.
12355 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12356                                     SDValue RHS) {
12357
12358   // Cannot simplify select with vector condition
12359   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12360
12361   // If this is a select from two identical things, try to pull the operation
12362   // through the select.
12363   if (LHS.getOpcode() != RHS.getOpcode() ||
12364       !LHS.hasOneUse() || !RHS.hasOneUse())
12365     return false;
12366
12367   // If this is a load and the token chain is identical, replace the select
12368   // of two loads with a load through a select of the address to load from.
12369   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12370   // constants have been dropped into the constant pool.
12371   if (LHS.getOpcode() == ISD::LOAD) {
12372     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12373     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12374
12375     // Token chains must be identical.
12376     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12377         // Do not let this transformation reduce the number of volatile loads.
12378         LLD->isVolatile() || RLD->isVolatile() ||
12379         // If this is an EXTLOAD, the VT's must match.
12380         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12381         // If this is an EXTLOAD, the kind of extension must match.
12382         (LLD->getExtensionType() != RLD->getExtensionType() &&
12383          // The only exception is if one of the extensions is anyext.
12384          LLD->getExtensionType() != ISD::EXTLOAD &&
12385          RLD->getExtensionType() != ISD::EXTLOAD) ||
12386         // FIXME: this discards src value information.  This is
12387         // over-conservative. It would be beneficial to be able to remember
12388         // both potential memory locations.  Since we are discarding
12389         // src value info, don't do the transformation if the memory
12390         // locations are not in the default address space.
12391         LLD->getPointerInfo().getAddrSpace() != 0 ||
12392         RLD->getPointerInfo().getAddrSpace() != 0 ||
12393         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12394                                       LLD->getBasePtr().getValueType()))
12395       return false;
12396
12397     // Check that the select condition doesn't reach either load.  If so,
12398     // folding this will induce a cycle into the DAG.  If not, this is safe to
12399     // xform, so create a select of the addresses.
12400     SDValue Addr;
12401     if (TheSelect->getOpcode() == ISD::SELECT) {
12402       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12403       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12404           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12405         return false;
12406       // The loads must not depend on one another.
12407       if (LLD->isPredecessorOf(RLD) ||
12408           RLD->isPredecessorOf(LLD))
12409         return false;
12410       Addr = DAG.getSelect(SDLoc(TheSelect),
12411                            LLD->getBasePtr().getValueType(),
12412                            TheSelect->getOperand(0), LLD->getBasePtr(),
12413                            RLD->getBasePtr());
12414     } else {  // Otherwise SELECT_CC
12415       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12416       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12417
12418       if ((LLD->hasAnyUseOfValue(1) &&
12419            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12420           (RLD->hasAnyUseOfValue(1) &&
12421            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12422         return false;
12423
12424       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12425                          LLD->getBasePtr().getValueType(),
12426                          TheSelect->getOperand(0),
12427                          TheSelect->getOperand(1),
12428                          LLD->getBasePtr(), RLD->getBasePtr(),
12429                          TheSelect->getOperand(4));
12430     }
12431
12432     SDValue Load;
12433     // It is safe to replace the two loads if they have different alignments,
12434     // but the new load must be the minimum (most restrictive) alignment of the
12435     // inputs.
12436     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12437     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12438     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12439       Load = DAG.getLoad(TheSelect->getValueType(0),
12440                          SDLoc(TheSelect),
12441                          // FIXME: Discards pointer and AA info.
12442                          LLD->getChain(), Addr, MachinePointerInfo(),
12443                          LLD->isVolatile(), LLD->isNonTemporal(),
12444                          isInvariant, Alignment);
12445     } else {
12446       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12447                             RLD->getExtensionType() : LLD->getExtensionType(),
12448                             SDLoc(TheSelect),
12449                             TheSelect->getValueType(0),
12450                             // FIXME: Discards pointer and AA info.
12451                             LLD->getChain(), Addr, MachinePointerInfo(),
12452                             LLD->getMemoryVT(), LLD->isVolatile(),
12453                             LLD->isNonTemporal(), isInvariant, Alignment);
12454     }
12455
12456     // Users of the select now use the result of the load.
12457     CombineTo(TheSelect, Load);
12458
12459     // Users of the old loads now use the new load's chain.  We know the
12460     // old-load value is dead now.
12461     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12462     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12463     return true;
12464   }
12465
12466   return false;
12467 }
12468
12469 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12470 /// where 'cond' is the comparison specified by CC.
12471 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12472                                       SDValue N2, SDValue N3,
12473                                       ISD::CondCode CC, bool NotExtCompare) {
12474   // (x ? y : y) -> y.
12475   if (N2 == N3) return N2;
12476
12477   EVT VT = N2.getValueType();
12478   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12479   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12480   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12481
12482   // Determine if the condition we're dealing with is constant
12483   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12484                               N0, N1, CC, DL, false);
12485   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12486   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12487
12488   // fold select_cc true, x, y -> x
12489   if (SCCC && !SCCC->isNullValue())
12490     return N2;
12491   // fold select_cc false, x, y -> y
12492   if (SCCC && SCCC->isNullValue())
12493     return N3;
12494
12495   // Check to see if we can simplify the select into an fabs node
12496   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12497     // Allow either -0.0 or 0.0
12498     if (CFP->getValueAPF().isZero()) {
12499       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12500       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12501           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12502           N2 == N3.getOperand(0))
12503         return DAG.getNode(ISD::FABS, DL, VT, N0);
12504
12505       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12506       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12507           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12508           N2.getOperand(0) == N3)
12509         return DAG.getNode(ISD::FABS, DL, VT, N3);
12510     }
12511   }
12512
12513   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12514   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12515   // in it.  This is a win when the constant is not otherwise available because
12516   // it replaces two constant pool loads with one.  We only do this if the FP
12517   // type is known to be legal, because if it isn't, then we are before legalize
12518   // types an we want the other legalization to happen first (e.g. to avoid
12519   // messing with soft float) and if the ConstantFP is not legal, because if
12520   // it is legal, we may not need to store the FP constant in a constant pool.
12521   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12522     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12523       if (TLI.isTypeLegal(N2.getValueType()) &&
12524           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12525                TargetLowering::Legal &&
12526            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12527            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12528           // If both constants have multiple uses, then we won't need to do an
12529           // extra load, they are likely around in registers for other users.
12530           (TV->hasOneUse() || FV->hasOneUse())) {
12531         Constant *Elts[] = {
12532           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12533           const_cast<ConstantFP*>(TV->getConstantFPValue())
12534         };
12535         Type *FPTy = Elts[0]->getType();
12536         const DataLayout &TD = *TLI.getDataLayout();
12537
12538         // Create a ConstantArray of the two constants.
12539         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12540         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12541                                             TD.getPrefTypeAlignment(FPTy));
12542         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12543
12544         // Get the offsets to the 0 and 1 element of the array so that we can
12545         // select between them.
12546         SDValue Zero = DAG.getIntPtrConstant(0);
12547         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12548         SDValue One = DAG.getIntPtrConstant(EltSize);
12549
12550         SDValue Cond = DAG.getSetCC(DL,
12551                                     getSetCCResultType(N0.getValueType()),
12552                                     N0, N1, CC);
12553         AddToWorklist(Cond.getNode());
12554         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12555                                           Cond, One, Zero);
12556         AddToWorklist(CstOffset.getNode());
12557         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12558                             CstOffset);
12559         AddToWorklist(CPIdx.getNode());
12560         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12561                            MachinePointerInfo::getConstantPool(), false,
12562                            false, false, Alignment);
12563
12564       }
12565     }
12566
12567   // Check to see if we can perform the "gzip trick", transforming
12568   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12569   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12570       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12571        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12572     EVT XType = N0.getValueType();
12573     EVT AType = N2.getValueType();
12574     if (XType.bitsGE(AType)) {
12575       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12576       // single-bit constant.
12577       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12578         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12579         ShCtV = XType.getSizeInBits()-ShCtV-1;
12580         SDValue ShCt = DAG.getConstant(ShCtV,
12581                                        getShiftAmountTy(N0.getValueType()));
12582         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12583                                     XType, N0, ShCt);
12584         AddToWorklist(Shift.getNode());
12585
12586         if (XType.bitsGT(AType)) {
12587           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12588           AddToWorklist(Shift.getNode());
12589         }
12590
12591         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12592       }
12593
12594       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12595                                   XType, N0,
12596                                   DAG.getConstant(XType.getSizeInBits()-1,
12597                                          getShiftAmountTy(N0.getValueType())));
12598       AddToWorklist(Shift.getNode());
12599
12600       if (XType.bitsGT(AType)) {
12601         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12602         AddToWorklist(Shift.getNode());
12603       }
12604
12605       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12606     }
12607   }
12608
12609   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12610   // where y is has a single bit set.
12611   // A plaintext description would be, we can turn the SELECT_CC into an AND
12612   // when the condition can be materialized as an all-ones register.  Any
12613   // single bit-test can be materialized as an all-ones register with
12614   // shift-left and shift-right-arith.
12615   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12616       N0->getValueType(0) == VT &&
12617       N1C && N1C->isNullValue() &&
12618       N2C && N2C->isNullValue()) {
12619     SDValue AndLHS = N0->getOperand(0);
12620     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12621     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12622       // Shift the tested bit over the sign bit.
12623       APInt AndMask = ConstAndRHS->getAPIntValue();
12624       SDValue ShlAmt =
12625         DAG.getConstant(AndMask.countLeadingZeros(),
12626                         getShiftAmountTy(AndLHS.getValueType()));
12627       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12628
12629       // Now arithmetic right shift it all the way over, so the result is either
12630       // all-ones, or zero.
12631       SDValue ShrAmt =
12632         DAG.getConstant(AndMask.getBitWidth()-1,
12633                         getShiftAmountTy(Shl.getValueType()));
12634       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12635
12636       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12637     }
12638   }
12639
12640   // fold select C, 16, 0 -> shl C, 4
12641   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12642       TLI.getBooleanContents(N0.getValueType()) ==
12643           TargetLowering::ZeroOrOneBooleanContent) {
12644
12645     // If the caller doesn't want us to simplify this into a zext of a compare,
12646     // don't do it.
12647     if (NotExtCompare && N2C->getAPIntValue() == 1)
12648       return SDValue();
12649
12650     // Get a SetCC of the condition
12651     // NOTE: Don't create a SETCC if it's not legal on this target.
12652     if (!LegalOperations ||
12653         TLI.isOperationLegal(ISD::SETCC,
12654           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12655       SDValue Temp, SCC;
12656       // cast from setcc result type to select result type
12657       if (LegalTypes) {
12658         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12659                             N0, N1, CC);
12660         if (N2.getValueType().bitsLT(SCC.getValueType()))
12661           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12662                                         N2.getValueType());
12663         else
12664           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12665                              N2.getValueType(), SCC);
12666       } else {
12667         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12668         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12669                            N2.getValueType(), SCC);
12670       }
12671
12672       AddToWorklist(SCC.getNode());
12673       AddToWorklist(Temp.getNode());
12674
12675       if (N2C->getAPIntValue() == 1)
12676         return Temp;
12677
12678       // shl setcc result by log2 n2c
12679       return DAG.getNode(
12680           ISD::SHL, DL, N2.getValueType(), Temp,
12681           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12682                           getShiftAmountTy(Temp.getValueType())));
12683     }
12684   }
12685
12686   // Check to see if this is the equivalent of setcc
12687   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12688   // otherwise, go ahead with the folds.
12689   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12690     EVT XType = N0.getValueType();
12691     if (!LegalOperations ||
12692         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12693       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12694       if (Res.getValueType() != VT)
12695         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12696       return Res;
12697     }
12698
12699     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12700     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12701         (!LegalOperations ||
12702          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12703       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12704       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12705                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12706                                        getShiftAmountTy(Ctlz.getValueType())));
12707     }
12708     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12709     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12710       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12711                                   XType, DAG.getConstant(0, XType), N0);
12712       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12713       return DAG.getNode(ISD::SRL, DL, XType,
12714                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12715                          DAG.getConstant(XType.getSizeInBits()-1,
12716                                          getShiftAmountTy(XType)));
12717     }
12718     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12719     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12720       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12721                                  DAG.getConstant(XType.getSizeInBits()-1,
12722                                          getShiftAmountTy(N0.getValueType())));
12723       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12724     }
12725   }
12726
12727   // Check to see if this is an integer abs.
12728   // select_cc setg[te] X,  0,  X, -X ->
12729   // select_cc setgt    X, -1,  X, -X ->
12730   // select_cc setl[te] X,  0, -X,  X ->
12731   // select_cc setlt    X,  1, -X,  X ->
12732   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12733   if (N1C) {
12734     ConstantSDNode *SubC = nullptr;
12735     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12736          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12737         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12738       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12739     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12740               (N1C->isOne() && CC == ISD::SETLT)) &&
12741              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12742       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12743
12744     EVT XType = N0.getValueType();
12745     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12746       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12747                                   N0,
12748                                   DAG.getConstant(XType.getSizeInBits()-1,
12749                                          getShiftAmountTy(N0.getValueType())));
12750       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12751                                 XType, N0, Shift);
12752       AddToWorklist(Shift.getNode());
12753       AddToWorklist(Add.getNode());
12754       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12755     }
12756   }
12757
12758   return SDValue();
12759 }
12760
12761 /// This is a stub for TargetLowering::SimplifySetCC.
12762 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12763                                    SDValue N1, ISD::CondCode Cond,
12764                                    SDLoc DL, bool foldBooleans) {
12765   TargetLowering::DAGCombinerInfo
12766     DagCombineInfo(DAG, Level, false, this);
12767   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12768 }
12769
12770 /// Given an ISD::SDIV node expressing a divide by constant, return
12771 /// a DAG expression to select that will generate the same value by multiplying
12772 /// by a magic number.
12773 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12774 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12775   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12776   if (!C)
12777     return SDValue();
12778
12779   // Avoid division by zero.
12780   if (!C->getAPIntValue())
12781     return SDValue();
12782
12783   std::vector<SDNode*> Built;
12784   SDValue S =
12785       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12786
12787   for (SDNode *N : Built)
12788     AddToWorklist(N);
12789   return S;
12790 }
12791
12792 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12793 /// DAG expression that will generate the same value by right shifting.
12794 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12795   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12796   if (!C)
12797     return SDValue();
12798
12799   // Avoid division by zero.
12800   if (!C->getAPIntValue())
12801     return SDValue();
12802
12803   std::vector<SDNode *> Built;
12804   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12805
12806   for (SDNode *N : Built)
12807     AddToWorklist(N);
12808   return S;
12809 }
12810
12811 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12812 /// expression that will generate the same value by multiplying by a magic
12813 /// number.
12814 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12815 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12816   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12817   if (!C)
12818     return SDValue();
12819
12820   // Avoid division by zero.
12821   if (!C->getAPIntValue())
12822     return SDValue();
12823
12824   std::vector<SDNode*> Built;
12825   SDValue S =
12826       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12827
12828   for (SDNode *N : Built)
12829     AddToWorklist(N);
12830   return S;
12831 }
12832
12833 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12834   if (Level >= AfterLegalizeDAG)
12835     return SDValue();
12836
12837   // Expose the DAG combiner to the target combiner implementations.
12838   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12839
12840   unsigned Iterations = 0;
12841   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12842     if (Iterations) {
12843       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12844       // For the reciprocal, we need to find the zero of the function:
12845       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12846       //     =>
12847       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12848       //     does not require additional intermediate precision]
12849       EVT VT = Op.getValueType();
12850       SDLoc DL(Op);
12851       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12852
12853       AddToWorklist(Est.getNode());
12854
12855       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12856       for (unsigned i = 0; i < Iterations; ++i) {
12857         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12858         AddToWorklist(NewEst.getNode());
12859
12860         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12861         AddToWorklist(NewEst.getNode());
12862
12863         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12864         AddToWorklist(NewEst.getNode());
12865
12866         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12867         AddToWorklist(Est.getNode());
12868       }
12869     }
12870     return Est;
12871   }
12872
12873   return SDValue();
12874 }
12875
12876 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12877 /// For the reciprocal sqrt, we need to find the zero of the function:
12878 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12879 ///     =>
12880 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12881 /// As a result, we precompute A/2 prior to the iteration loop.
12882 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12883                                           unsigned Iterations) {
12884   EVT VT = Arg.getValueType();
12885   SDLoc DL(Arg);
12886   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12887
12888   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12889   // this entire sequence requires only one FP constant.
12890   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12891   AddToWorklist(HalfArg.getNode());
12892
12893   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12894   AddToWorklist(HalfArg.getNode());
12895
12896   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12897   for (unsigned i = 0; i < Iterations; ++i) {
12898     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12899     AddToWorklist(NewEst.getNode());
12900
12901     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12902     AddToWorklist(NewEst.getNode());
12903
12904     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12905     AddToWorklist(NewEst.getNode());
12906
12907     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12908     AddToWorklist(Est.getNode());
12909   }
12910   return Est;
12911 }
12912
12913 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12914 /// For the reciprocal sqrt, we need to find the zero of the function:
12915 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12916 ///     =>
12917 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12918 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12919                                           unsigned Iterations) {
12920   EVT VT = Arg.getValueType();
12921   SDLoc DL(Arg);
12922   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12923   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12924
12925   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12926   for (unsigned i = 0; i < Iterations; ++i) {
12927     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12928     AddToWorklist(HalfEst.getNode());
12929
12930     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12931     AddToWorklist(Est.getNode());
12932
12933     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12934     AddToWorklist(Est.getNode());
12935
12936     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12937     AddToWorklist(Est.getNode());
12938
12939     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12940     AddToWorklist(Est.getNode());
12941   }
12942   return Est;
12943 }
12944
12945 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12946   if (Level >= AfterLegalizeDAG)
12947     return SDValue();
12948
12949   // Expose the DAG combiner to the target combiner implementations.
12950   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12951   unsigned Iterations = 0;
12952   bool UseOneConstNR = false;
12953   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12954     AddToWorklist(Est.getNode());
12955     if (Iterations) {
12956       Est = UseOneConstNR ?
12957         BuildRsqrtNROneConst(Op, Est, Iterations) :
12958         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12959     }
12960     return Est;
12961   }
12962
12963   return SDValue();
12964 }
12965
12966 /// Return true if base is a frame index, which is known not to alias with
12967 /// anything but itself.  Provides base object and offset as results.
12968 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12969                            const GlobalValue *&GV, const void *&CV) {
12970   // Assume it is a primitive operation.
12971   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12972
12973   // If it's an adding a simple constant then integrate the offset.
12974   if (Base.getOpcode() == ISD::ADD) {
12975     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12976       Base = Base.getOperand(0);
12977       Offset += C->getZExtValue();
12978     }
12979   }
12980
12981   // Return the underlying GlobalValue, and update the Offset.  Return false
12982   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12983   // by multiple nodes with different offsets.
12984   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12985     GV = G->getGlobal();
12986     Offset += G->getOffset();
12987     return false;
12988   }
12989
12990   // Return the underlying Constant value, and update the Offset.  Return false
12991   // for ConstantSDNodes since the same constant pool entry may be represented
12992   // by multiple nodes with different offsets.
12993   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12994     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12995                                          : (const void *)C->getConstVal();
12996     Offset += C->getOffset();
12997     return false;
12998   }
12999   // If it's any of the following then it can't alias with anything but itself.
13000   return isa<FrameIndexSDNode>(Base);
13001 }
13002
13003 /// Return true if there is any possibility that the two addresses overlap.
13004 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13005   // If they are the same then they must be aliases.
13006   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13007
13008   // If they are both volatile then they cannot be reordered.
13009   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13010
13011   // Gather base node and offset information.
13012   SDValue Base1, Base2;
13013   int64_t Offset1, Offset2;
13014   const GlobalValue *GV1, *GV2;
13015   const void *CV1, *CV2;
13016   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13017                                       Base1, Offset1, GV1, CV1);
13018   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13019                                       Base2, Offset2, GV2, CV2);
13020
13021   // If they have a same base address then check to see if they overlap.
13022   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13023     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13024              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13025
13026   // It is possible for different frame indices to alias each other, mostly
13027   // when tail call optimization reuses return address slots for arguments.
13028   // To catch this case, look up the actual index of frame indices to compute
13029   // the real alias relationship.
13030   if (isFrameIndex1 && isFrameIndex2) {
13031     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13032     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13033     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13034     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13035              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13036   }
13037
13038   // Otherwise, if we know what the bases are, and they aren't identical, then
13039   // we know they cannot alias.
13040   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13041     return false;
13042
13043   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13044   // compared to the size and offset of the access, we may be able to prove they
13045   // do not alias.  This check is conservative for now to catch cases created by
13046   // splitting vector types.
13047   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13048       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13049       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13050        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13051       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13052     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13053     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13054
13055     // There is no overlap between these relatively aligned accesses of similar
13056     // size, return no alias.
13057     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13058         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13059       return false;
13060   }
13061
13062   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13063                    ? CombinerGlobalAA
13064                    : DAG.getSubtarget().useAA();
13065 #ifndef NDEBUG
13066   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13067       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13068     UseAA = false;
13069 #endif
13070   if (UseAA &&
13071       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13072     // Use alias analysis information.
13073     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13074                                  Op1->getSrcValueOffset());
13075     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13076         Op0->getSrcValueOffset() - MinOffset;
13077     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13078         Op1->getSrcValueOffset() - MinOffset;
13079     AliasAnalysis::AliasResult AAResult =
13080         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13081                                          Overlap1,
13082                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13083                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13084                                          Overlap2,
13085                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13086     if (AAResult == AliasAnalysis::NoAlias)
13087       return false;
13088   }
13089
13090   // Otherwise we have to assume they alias.
13091   return true;
13092 }
13093
13094 /// Walk up chain skipping non-aliasing memory nodes,
13095 /// looking for aliasing nodes and adding them to the Aliases vector.
13096 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13097                                    SmallVectorImpl<SDValue> &Aliases) {
13098   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13099   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13100
13101   // Get alias information for node.
13102   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13103
13104   // Starting off.
13105   Chains.push_back(OriginalChain);
13106   unsigned Depth = 0;
13107
13108   // Look at each chain and determine if it is an alias.  If so, add it to the
13109   // aliases list.  If not, then continue up the chain looking for the next
13110   // candidate.
13111   while (!Chains.empty()) {
13112     SDValue Chain = Chains.back();
13113     Chains.pop_back();
13114
13115     // For TokenFactor nodes, look at each operand and only continue up the
13116     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13117     // find more and revert to original chain since the xform is unlikely to be
13118     // profitable.
13119     //
13120     // FIXME: The depth check could be made to return the last non-aliasing
13121     // chain we found before we hit a tokenfactor rather than the original
13122     // chain.
13123     if (Depth > 6 || Aliases.size() == 2) {
13124       Aliases.clear();
13125       Aliases.push_back(OriginalChain);
13126       return;
13127     }
13128
13129     // Don't bother if we've been before.
13130     if (!Visited.insert(Chain.getNode()).second)
13131       continue;
13132
13133     switch (Chain.getOpcode()) {
13134     case ISD::EntryToken:
13135       // Entry token is ideal chain operand, but handled in FindBetterChain.
13136       break;
13137
13138     case ISD::LOAD:
13139     case ISD::STORE: {
13140       // Get alias information for Chain.
13141       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13142           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13143
13144       // If chain is alias then stop here.
13145       if (!(IsLoad && IsOpLoad) &&
13146           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13147         Aliases.push_back(Chain);
13148       } else {
13149         // Look further up the chain.
13150         Chains.push_back(Chain.getOperand(0));
13151         ++Depth;
13152       }
13153       break;
13154     }
13155
13156     case ISD::TokenFactor:
13157       // We have to check each of the operands of the token factor for "small"
13158       // token factors, so we queue them up.  Adding the operands to the queue
13159       // (stack) in reverse order maintains the original order and increases the
13160       // likelihood that getNode will find a matching token factor (CSE.)
13161       if (Chain.getNumOperands() > 16) {
13162         Aliases.push_back(Chain);
13163         break;
13164       }
13165       for (unsigned n = Chain.getNumOperands(); n;)
13166         Chains.push_back(Chain.getOperand(--n));
13167       ++Depth;
13168       break;
13169
13170     default:
13171       // For all other instructions we will just have to take what we can get.
13172       Aliases.push_back(Chain);
13173       break;
13174     }
13175   }
13176
13177   // We need to be careful here to also search for aliases through the
13178   // value operand of a store, etc. Consider the following situation:
13179   //   Token1 = ...
13180   //   L1 = load Token1, %52
13181   //   S1 = store Token1, L1, %51
13182   //   L2 = load Token1, %52+8
13183   //   S2 = store Token1, L2, %51+8
13184   //   Token2 = Token(S1, S2)
13185   //   L3 = load Token2, %53
13186   //   S3 = store Token2, L3, %52
13187   //   L4 = load Token2, %53+8
13188   //   S4 = store Token2, L4, %52+8
13189   // If we search for aliases of S3 (which loads address %52), and we look
13190   // only through the chain, then we'll miss the trivial dependence on L1
13191   // (which also loads from %52). We then might change all loads and
13192   // stores to use Token1 as their chain operand, which could result in
13193   // copying %53 into %52 before copying %52 into %51 (which should
13194   // happen first).
13195   //
13196   // The problem is, however, that searching for such data dependencies
13197   // can become expensive, and the cost is not directly related to the
13198   // chain depth. Instead, we'll rule out such configurations here by
13199   // insisting that we've visited all chain users (except for users
13200   // of the original chain, which is not necessary). When doing this,
13201   // we need to look through nodes we don't care about (otherwise, things
13202   // like register copies will interfere with trivial cases).
13203
13204   SmallVector<const SDNode *, 16> Worklist;
13205   for (const SDNode *N : Visited)
13206     if (N != OriginalChain.getNode())
13207       Worklist.push_back(N);
13208
13209   while (!Worklist.empty()) {
13210     const SDNode *M = Worklist.pop_back_val();
13211
13212     // We have already visited M, and want to make sure we've visited any uses
13213     // of M that we care about. For uses that we've not visisted, and don't
13214     // care about, queue them to the worklist.
13215
13216     for (SDNode::use_iterator UI = M->use_begin(),
13217          UIE = M->use_end(); UI != UIE; ++UI)
13218       if (UI.getUse().getValueType() == MVT::Other &&
13219           Visited.insert(*UI).second) {
13220         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13221           // We've not visited this use, and we care about it (it could have an
13222           // ordering dependency with the original node).
13223           Aliases.clear();
13224           Aliases.push_back(OriginalChain);
13225           return;
13226         }
13227
13228         // We've not visited this use, but we don't care about it. Mark it as
13229         // visited and enqueue it to the worklist.
13230         Worklist.push_back(*UI);
13231       }
13232   }
13233 }
13234
13235 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13236 /// (aliasing node.)
13237 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13238   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13239
13240   // Accumulate all the aliases to this node.
13241   GatherAllAliases(N, OldChain, Aliases);
13242
13243   // If no operands then chain to entry token.
13244   if (Aliases.size() == 0)
13245     return DAG.getEntryNode();
13246
13247   // If a single operand then chain to it.  We don't need to revisit it.
13248   if (Aliases.size() == 1)
13249     return Aliases[0];
13250
13251   // Construct a custom tailored token factor.
13252   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13253 }
13254
13255 /// This is the entry point for the file.
13256 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13257                            CodeGenOpt::Level OptLevel) {
13258   /// This is the main entry point to this class.
13259   DAGCombiner(*this, AA, OptLevel).Run(Level);
13260 }