Always assert in DAGCombine and not only when -debug is enabled
[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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.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 visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFSQRT(SDNode *N);
280     SDValue visitFCOPYSIGN(SDNode *N);
281     SDValue visitSINT_TO_FP(SDNode *N);
282     SDValue visitUINT_TO_FP(SDNode *N);
283     SDValue visitFP_TO_SINT(SDNode *N);
284     SDValue visitFP_TO_UINT(SDNode *N);
285     SDValue visitFP_ROUND(SDNode *N);
286     SDValue visitFP_ROUND_INREG(SDNode *N);
287     SDValue visitFP_EXTEND(SDNode *N);
288     SDValue visitFNEG(SDNode *N);
289     SDValue visitFABS(SDNode *N);
290     SDValue visitFCEIL(SDNode *N);
291     SDValue visitFTRUNC(SDNode *N);
292     SDValue visitFFLOOR(SDNode *N);
293     SDValue visitFMINNUM(SDNode *N);
294     SDValue visitFMAXNUM(SDNode *N);
295     SDValue visitBRCOND(SDNode *N);
296     SDValue visitBR_CC(SDNode *N);
297     SDValue visitLOAD(SDNode *N);
298     SDValue visitSTORE(SDNode *N);
299     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301     SDValue visitBUILD_VECTOR(SDNode *N);
302     SDValue visitCONCAT_VECTORS(SDNode *N);
303     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304     SDValue visitVECTOR_SHUFFLE(SDNode *N);
305     SDValue visitINSERT_SUBVECTOR(SDNode *N);
306     SDValue visitMLOAD(SDNode *N);
307     SDValue visitMSTORE(SDNode *N);
308
309     SDValue XformToShuffleWithZero(SDNode *N);
310     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
311
312     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
313
314     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318                              SDValue N3, ISD::CondCode CC,
319                              bool NotExtCompare = false);
320     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321                           SDLoc DL, bool foldBooleans = true);
322
323     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
324                            SDValue &CC) const;
325     bool isOneUseSetCC(SDValue N) const;
326
327     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
328                                          unsigned HiOp);
329     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
331     SDValue BuildSDIV(SDNode *N);
332     SDValue BuildSDIVPow2(SDNode *N);
333     SDValue BuildUDIV(SDNode *N);
334     SDValue BuildReciprocalEstimate(SDValue Op);
335     SDValue BuildRsqrtEstimate(SDValue Op);
336     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
338     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339                                bool DemandHighBits = true);
340     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
341     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342                               SDValue InnerPos, SDValue InnerNeg,
343                               unsigned PosOpcode, unsigned NegOpcode,
344                               SDLoc DL);
345     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
346     SDValue ReduceLoadWidth(SDNode *N);
347     SDValue ReduceLoadOpStoreWidth(SDNode *N);
348     SDValue TransformFPLoadStorePair(SDNode *N);
349     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
350     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
351
352     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
353
354     /// Walk up chain skipping non-aliasing memory nodes,
355     /// looking for aliasing nodes and adding them to the Aliases vector.
356     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
357                           SmallVectorImpl<SDValue> &Aliases);
358
359     /// Return true if there is any possibility that the two addresses overlap.
360     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
361
362     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363     /// chain (aliasing node.)
364     SDValue FindBetterChain(SDNode *N, SDValue Chain);
365
366     /// Merge consecutive store operations into a wide store.
367     /// This optimization uses wide integers or vectors when possible.
368     /// \return True if some memory operations were changed.
369     bool MergeConsecutiveStores(StoreSDNode *N);
370
371     /// \brief Try to transform a truncation where C is a constant:
372     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
373     ///
374     /// \p N needs to be a truncation and its first operand an AND. Other
375     /// requirements are checked by the function (e.g. that trunc is
376     /// single-use) and if missed an empty SDValue is returned.
377     SDValue distributeTruncateThroughAnd(SDNode *N);
378
379   public:
380     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
381         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383       AttributeSet FnAttrs =
384           DAG.getMachineFunction().getFunction()->getAttributes();
385       ForCodeSize =
386           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387                                Attribute::OptimizeForSize) ||
388           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
389     }
390
391     /// Runs the dag combiner on all nodes in the work list
392     void Run(CombineLevel AtLevel);
393
394     SelectionDAG &getDAG() const { return DAG; }
395
396     /// Returns a type large enough to hold any valid shift amount - before type
397     /// legalization these can be huge.
398     EVT getShiftAmountTy(EVT LHSTy) {
399       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400       if (LHSTy.isVector())
401         return LHSTy;
402       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403                         : TLI.getPointerTy();
404     }
405
406     /// This method returns true if we are running before type legalization or
407     /// if the specified VT is legal.
408     bool isTypeLegal(const EVT &VT) {
409       if (!LegalTypes) return true;
410       return TLI.isTypeLegal(VT);
411     }
412
413     /// Convenience wrapper around TargetLowering::getSetCCResultType
414     EVT getSetCCResultType(EVT VT) const {
415       return TLI.getSetCCResultType(*DAG.getContext(), VT);
416     }
417   };
418 }
419
420
421 namespace {
422 /// This class is a DAGUpdateListener that removes any deleted
423 /// nodes from the worklist.
424 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
425   DAGCombiner &DC;
426 public:
427   explicit WorklistRemover(DAGCombiner &dc)
428     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
429
430   void NodeDeleted(SDNode *N, SDNode *E) override {
431     DC.removeFromWorklist(N);
432   }
433 };
434 }
435
436 //===----------------------------------------------------------------------===//
437 //  TargetLowering::DAGCombinerInfo implementation
438 //===----------------------------------------------------------------------===//
439
440 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
441   ((DAGCombiner*)DC)->AddToWorklist(N);
442 }
443
444 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
445   ((DAGCombiner*)DC)->removeFromWorklist(N);
446 }
447
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
451 }
452
453 SDValue TargetLowering::DAGCombinerInfo::
454 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
456 }
457
458
459 SDValue TargetLowering::DAGCombinerInfo::
460 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
462 }
463
464 void TargetLowering::DAGCombinerInfo::
465 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
467 }
468
469 //===----------------------------------------------------------------------===//
470 // Helper Functions
471 //===----------------------------------------------------------------------===//
472
473 void DAGCombiner::deleteAndRecombine(SDNode *N) {
474   removeFromWorklist(N);
475
476   // If the operands of this node are only used by the node, they will now be
477   // dead. Make sure to re-visit them and recursively delete dead nodes.
478   for (const SDValue &Op : N->ops())
479     // For an operand generating multiple values, one of the values may
480     // become dead allowing further simplification (e.g. split index
481     // arithmetic from an indexed load).
482     if (Op->hasOneUse() || Op->getNumValues() > 1)
483       AddToWorklist(Op.getNode());
484
485   DAG.DeleteNode(N);
486 }
487
488 /// Return 1 if we can compute the negated form of the specified expression for
489 /// the same cost as the expression itself, or 2 if we can compute the negated
490 /// form more cheaply than the expression itself.
491 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
492                                const TargetLowering &TLI,
493                                const TargetOptions *Options,
494                                unsigned Depth = 0) {
495   // fneg is removable even if it has multiple uses.
496   if (Op.getOpcode() == ISD::FNEG) return 2;
497
498   // Don't allow anything with multiple uses.
499   if (!Op.hasOneUse()) return 0;
500
501   // Don't recurse exponentially.
502   if (Depth > 6) return 0;
503
504   switch (Op.getOpcode()) {
505   default: return false;
506   case ISD::ConstantFP:
507     // Don't invert constant FP values after legalize.  The negated constant
508     // isn't necessarily legal.
509     return LegalOperations ? 0 : 1;
510   case ISD::FADD:
511     // FIXME: determine better conditions for this xform.
512     if (!Options->UnsafeFPMath) return 0;
513
514     // After operation legalization, it might not be legal to create new FSUBs.
515     if (LegalOperations &&
516         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
517       return 0;
518
519     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
520     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521                                     Options, Depth + 1))
522       return V;
523     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
525                               Depth + 1);
526   case ISD::FSUB:
527     // We can't turn -(A-B) into B-A when we honor signed zeros.
528     if (!Options->UnsafeFPMath) return 0;
529
530     // fold (fneg (fsub A, B)) -> (fsub B, A)
531     return 1;
532
533   case ISD::FMUL:
534   case ISD::FDIV:
535     if (Options->HonorSignDependentRoundingFPMath()) return 0;
536
537     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
538     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
539                                     Options, Depth + 1))
540       return V;
541
542     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
543                               Depth + 1);
544
545   case ISD::FP_EXTEND:
546   case ISD::FP_ROUND:
547   case ISD::FSIN:
548     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
549                               Depth + 1);
550   }
551 }
552
553 /// If isNegatibleForFree returns true, return the newly negated expression.
554 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
555                                     bool LegalOperations, unsigned Depth = 0) {
556   const TargetOptions &Options = DAG.getTarget().Options;
557   // fneg is removable even if it has multiple uses.
558   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
559
560   // Don't allow anything with multiple uses.
561   assert(Op.hasOneUse() && "Unknown reuse!");
562
563   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
564   switch (Op.getOpcode()) {
565   default: llvm_unreachable("Unknown code");
566   case ISD::ConstantFP: {
567     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
568     V.changeSign();
569     return DAG.getConstantFP(V, Op.getValueType());
570   }
571   case ISD::FADD:
572     // FIXME: determine better conditions for this xform.
573     assert(Options.UnsafeFPMath);
574
575     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
577                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
578       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579                          GetNegatedExpression(Op.getOperand(0), DAG,
580                                               LegalOperations, Depth+1),
581                          Op.getOperand(1));
582     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
584                        GetNegatedExpression(Op.getOperand(1), DAG,
585                                             LegalOperations, Depth+1),
586                        Op.getOperand(0));
587   case ISD::FSUB:
588     // We can't turn -(A-B) into B-A when we honor signed zeros.
589     assert(Options.UnsafeFPMath);
590
591     // fold (fneg (fsub 0, B)) -> B
592     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
593       if (N0CFP->getValueAPF().isZero())
594         return Op.getOperand(1);
595
596     // fold (fneg (fsub A, B)) -> (fsub B, A)
597     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
598                        Op.getOperand(1), Op.getOperand(0));
599
600   case ISD::FMUL:
601   case ISD::FDIV:
602     assert(!Options.HonorSignDependentRoundingFPMath());
603
604     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
605     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
607       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
608                          GetNegatedExpression(Op.getOperand(0), DAG,
609                                               LegalOperations, Depth+1),
610                          Op.getOperand(1));
611
612     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
613     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
614                        Op.getOperand(0),
615                        GetNegatedExpression(Op.getOperand(1), DAG,
616                                             LegalOperations, Depth+1));
617
618   case ISD::FP_EXTEND:
619   case ISD::FSIN:
620     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
621                        GetNegatedExpression(Op.getOperand(0), DAG,
622                                             LegalOperations, Depth+1));
623   case ISD::FP_ROUND:
624       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
625                          GetNegatedExpression(Op.getOperand(0), DAG,
626                                               LegalOperations, Depth+1),
627                          Op.getOperand(1));
628   }
629 }
630
631 // Return true if this node is a setcc, or is a select_cc
632 // that selects between the target values used for true and false, making it
633 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634 // the appropriate nodes based on the type of node we are checking. This
635 // simplifies life a bit for the callers.
636 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
637                                     SDValue &CC) const {
638   if (N.getOpcode() == ISD::SETCC) {
639     LHS = N.getOperand(0);
640     RHS = N.getOperand(1);
641     CC  = N.getOperand(2);
642     return true;
643   }
644
645   if (N.getOpcode() != ISD::SELECT_CC ||
646       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
648     return false;
649
650   if (TLI.getBooleanContents(N.getValueType()) ==
651       TargetLowering::UndefinedBooleanContent)
652     return false;
653
654   LHS = N.getOperand(0);
655   RHS = N.getOperand(1);
656   CC  = N.getOperand(4);
657   return true;
658 }
659
660 /// Return true if this is a SetCC-equivalent operation with only one use.
661 /// If this is true, it allows the users to invert the operation for free when
662 /// it is profitable to do so.
663 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
664   SDValue N0, N1, N2;
665   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
666     return true;
667   return false;
668 }
669
670 /// Returns true if N is a BUILD_VECTOR node whose
671 /// elements are all the same constant or undefined.
672 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
674   if (!C)
675     return false;
676
677   APInt SplatUndef;
678   unsigned SplatBitSize;
679   bool HasAnyUndefs;
680   EVT EltVT = N->getValueType(0).getVectorElementType();
681   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
682                              HasAnyUndefs) &&
683           EltVT.getSizeInBits() >= SplatBitSize);
684 }
685
686 // \brief Returns the SDNode if it is a constant BuildVector or constant.
687 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688   if (isa<ConstantSDNode>(N))
689     return N.getNode();
690   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
691   if (BV && BV->isConstant())
692     return BV;
693   return nullptr;
694 }
695
696 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
697 // int.
698 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
700     return CN;
701
702   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
703     BitVector UndefElements;
704     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
705
706     // BuildVectors can truncate their operands. Ignore that case here.
707     // FIXME: We blindly ignore splats which include undef which is overly
708     // pessimistic.
709     if (CN && UndefElements.none() &&
710         CN->getValueType(0) == N.getValueType().getScalarType())
711       return CN;
712   }
713
714   return nullptr;
715 }
716
717 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
718 // float.
719 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
721     return CN;
722
723   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724     BitVector UndefElements;
725     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
726
727     if (CN && UndefElements.none())
728       return CN;
729   }
730
731   return nullptr;
732 }
733
734 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
735                                     SDValue N0, SDValue N1) {
736   EVT VT = N0.getValueType();
737   if (N0.getOpcode() == Opc) {
738     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
741         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
742         if (!OpNode.getNode())
743           return SDValue();
744         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
745       }
746       if (N0.hasOneUse()) {
747         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
748         // use
749         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
750         if (!OpNode.getNode())
751           return SDValue();
752         AddToWorklist(OpNode.getNode());
753         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
754       }
755     }
756   }
757
758   if (N1.getOpcode() == Opc) {
759     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
760       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
761         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
762         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
763         if (!OpNode.getNode())
764           return SDValue();
765         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
766       }
767       if (N1.hasOneUse()) {
768         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
769         // use
770         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
771         if (!OpNode.getNode())
772           return SDValue();
773         AddToWorklist(OpNode.getNode());
774         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
775       }
776     }
777   }
778
779   return SDValue();
780 }
781
782 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
783                                bool AddTo) {
784   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
785   ++NodesCombined;
786   DEBUG(dbgs() << "\nReplacing.1 ";
787         N->dump(&DAG);
788         dbgs() << "\nWith: ";
789         To[0].getNode()->dump(&DAG);
790         dbgs() << " and " << NumTo-1 << " other values\n");
791   for (unsigned i = 0, e = NumTo; i != e; ++i)
792     assert((!To[i].getNode() ||
793             N->getValueType(i) == To[i].getValueType()) &&
794            "Cannot combine value to value of different type!");
795
796   WorklistRemover DeadNodes(*this);
797   DAG.ReplaceAllUsesWith(N, To);
798   if (AddTo) {
799     // Push the new nodes and any users onto the worklist
800     for (unsigned i = 0, e = NumTo; i != e; ++i) {
801       if (To[i].getNode()) {
802         AddToWorklist(To[i].getNode());
803         AddUsersToWorklist(To[i].getNode());
804       }
805     }
806   }
807
808   // Finally, if the node is now dead, remove it from the graph.  The node
809   // may not be dead if the replacement process recursively simplified to
810   // something else needing this node.
811   if (N->use_empty())
812     deleteAndRecombine(N);
813   return SDValue(N, 0);
814 }
815
816 void DAGCombiner::
817 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
818   // Replace all uses.  If any nodes become isomorphic to other nodes and
819   // are deleted, make sure to remove them from our worklist.
820   WorklistRemover DeadNodes(*this);
821   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
822
823   // Push the new node and any (possibly new) users onto the worklist.
824   AddToWorklist(TLO.New.getNode());
825   AddUsersToWorklist(TLO.New.getNode());
826
827   // Finally, if the node is now dead, remove it from the graph.  The node
828   // may not be dead if the replacement process recursively simplified to
829   // something else needing this node.
830   if (TLO.Old.getNode()->use_empty())
831     deleteAndRecombine(TLO.Old.getNode());
832 }
833
834 /// Check the specified integer node value to see if it can be simplified or if
835 /// things it uses can be simplified by bit propagation. If so, return true.
836 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
837   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
838   APInt KnownZero, KnownOne;
839   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
840     return false;
841
842   // Revisit the node.
843   AddToWorklist(Op.getNode());
844
845   // Replace the old value with the new one.
846   ++NodesCombined;
847   DEBUG(dbgs() << "\nReplacing.2 ";
848         TLO.Old.getNode()->dump(&DAG);
849         dbgs() << "\nWith: ";
850         TLO.New.getNode()->dump(&DAG);
851         dbgs() << '\n');
852
853   CommitTargetLoweringOpt(TLO);
854   return true;
855 }
856
857 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
858   SDLoc dl(Load);
859   EVT VT = Load->getValueType(0);
860   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
861
862   DEBUG(dbgs() << "\nReplacing.9 ";
863         Load->dump(&DAG);
864         dbgs() << "\nWith: ";
865         Trunc.getNode()->dump(&DAG);
866         dbgs() << '\n');
867   WorklistRemover DeadNodes(*this);
868   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
869   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
870   deleteAndRecombine(Load);
871   AddToWorklist(Trunc.getNode());
872 }
873
874 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
875   Replace = false;
876   SDLoc dl(Op);
877   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
878     EVT MemVT = LD->getMemoryVT();
879     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
880       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
881                                                   : ISD::EXTLOAD)
882       : LD->getExtensionType();
883     Replace = true;
884     return DAG.getExtLoad(ExtType, dl, PVT,
885                           LD->getChain(), LD->getBasePtr(),
886                           MemVT, LD->getMemOperand());
887   }
888
889   unsigned Opc = Op.getOpcode();
890   switch (Opc) {
891   default: break;
892   case ISD::AssertSext:
893     return DAG.getNode(ISD::AssertSext, dl, PVT,
894                        SExtPromoteOperand(Op.getOperand(0), PVT),
895                        Op.getOperand(1));
896   case ISD::AssertZext:
897     return DAG.getNode(ISD::AssertZext, dl, PVT,
898                        ZExtPromoteOperand(Op.getOperand(0), PVT),
899                        Op.getOperand(1));
900   case ISD::Constant: {
901     unsigned ExtOpc =
902       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
903     return DAG.getNode(ExtOpc, dl, PVT, Op);
904   }
905   }
906
907   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
908     return SDValue();
909   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
910 }
911
912 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
913   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
914     return SDValue();
915   EVT OldVT = Op.getValueType();
916   SDLoc dl(Op);
917   bool Replace = false;
918   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
919   if (!NewOp.getNode())
920     return SDValue();
921   AddToWorklist(NewOp.getNode());
922
923   if (Replace)
924     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
925   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
926                      DAG.getValueType(OldVT));
927 }
928
929 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
930   EVT OldVT = Op.getValueType();
931   SDLoc dl(Op);
932   bool Replace = false;
933   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
934   if (!NewOp.getNode())
935     return SDValue();
936   AddToWorklist(NewOp.getNode());
937
938   if (Replace)
939     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
940   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
941 }
942
943 /// Promote the specified integer binary operation if the target indicates it is
944 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
945 /// i32 since i16 instructions are longer.
946 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
947   if (!LegalOperations)
948     return SDValue();
949
950   EVT VT = Op.getValueType();
951   if (VT.isVector() || !VT.isInteger())
952     return SDValue();
953
954   // If operation type is 'undesirable', e.g. i16 on x86, consider
955   // promoting it.
956   unsigned Opc = Op.getOpcode();
957   if (TLI.isTypeDesirableForOp(Opc, VT))
958     return SDValue();
959
960   EVT PVT = VT;
961   // Consult target whether it is a good idea to promote this operation and
962   // what's the right type to promote it to.
963   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
964     assert(PVT != VT && "Don't know what type to promote to!");
965
966     bool Replace0 = false;
967     SDValue N0 = Op.getOperand(0);
968     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
969     if (!NN0.getNode())
970       return SDValue();
971
972     bool Replace1 = false;
973     SDValue N1 = Op.getOperand(1);
974     SDValue NN1;
975     if (N0 == N1)
976       NN1 = NN0;
977     else {
978       NN1 = PromoteOperand(N1, PVT, Replace1);
979       if (!NN1.getNode())
980         return SDValue();
981     }
982
983     AddToWorklist(NN0.getNode());
984     if (NN1.getNode())
985       AddToWorklist(NN1.getNode());
986
987     if (Replace0)
988       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
989     if (Replace1)
990       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
991
992     DEBUG(dbgs() << "\nPromoting ";
993           Op.getNode()->dump(&DAG));
994     SDLoc dl(Op);
995     return DAG.getNode(ISD::TRUNCATE, dl, VT,
996                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
997   }
998   return SDValue();
999 }
1000
1001 /// Promote the specified integer shift operation if the target indicates it is
1002 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1003 /// i32 since i16 instructions are longer.
1004 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1005   if (!LegalOperations)
1006     return SDValue();
1007
1008   EVT VT = Op.getValueType();
1009   if (VT.isVector() || !VT.isInteger())
1010     return SDValue();
1011
1012   // If operation type is 'undesirable', e.g. i16 on x86, consider
1013   // promoting it.
1014   unsigned Opc = Op.getOpcode();
1015   if (TLI.isTypeDesirableForOp(Opc, VT))
1016     return SDValue();
1017
1018   EVT PVT = VT;
1019   // Consult target whether it is a good idea to promote this operation and
1020   // what's the right type to promote it to.
1021   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1022     assert(PVT != VT && "Don't know what type to promote to!");
1023
1024     bool Replace = false;
1025     SDValue N0 = Op.getOperand(0);
1026     if (Opc == ISD::SRA)
1027       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1028     else if (Opc == ISD::SRL)
1029       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1030     else
1031       N0 = PromoteOperand(N0, PVT, Replace);
1032     if (!N0.getNode())
1033       return SDValue();
1034
1035     AddToWorklist(N0.getNode());
1036     if (Replace)
1037       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1038
1039     DEBUG(dbgs() << "\nPromoting ";
1040           Op.getNode()->dump(&DAG));
1041     SDLoc dl(Op);
1042     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1043                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1044   }
1045   return SDValue();
1046 }
1047
1048 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1049   if (!LegalOperations)
1050     return SDValue();
1051
1052   EVT VT = Op.getValueType();
1053   if (VT.isVector() || !VT.isInteger())
1054     return SDValue();
1055
1056   // If operation type is 'undesirable', e.g. i16 on x86, consider
1057   // promoting it.
1058   unsigned Opc = Op.getOpcode();
1059   if (TLI.isTypeDesirableForOp(Opc, VT))
1060     return SDValue();
1061
1062   EVT PVT = VT;
1063   // Consult target whether it is a good idea to promote this operation and
1064   // what's the right type to promote it to.
1065   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1066     assert(PVT != VT && "Don't know what type to promote to!");
1067     // fold (aext (aext x)) -> (aext x)
1068     // fold (aext (zext x)) -> (zext x)
1069     // fold (aext (sext x)) -> (sext x)
1070     DEBUG(dbgs() << "\nPromoting ";
1071           Op.getNode()->dump(&DAG));
1072     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1073   }
1074   return SDValue();
1075 }
1076
1077 bool DAGCombiner::PromoteLoad(SDValue Op) {
1078   if (!LegalOperations)
1079     return false;
1080
1081   EVT VT = Op.getValueType();
1082   if (VT.isVector() || !VT.isInteger())
1083     return false;
1084
1085   // If operation type is 'undesirable', e.g. i16 on x86, consider
1086   // promoting it.
1087   unsigned Opc = Op.getOpcode();
1088   if (TLI.isTypeDesirableForOp(Opc, VT))
1089     return false;
1090
1091   EVT PVT = VT;
1092   // Consult target whether it is a good idea to promote this operation and
1093   // what's the right type to promote it to.
1094   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1095     assert(PVT != VT && "Don't know what type to promote to!");
1096
1097     SDLoc dl(Op);
1098     SDNode *N = Op.getNode();
1099     LoadSDNode *LD = cast<LoadSDNode>(N);
1100     EVT MemVT = LD->getMemoryVT();
1101     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1102       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1103                                                   : ISD::EXTLOAD)
1104       : LD->getExtensionType();
1105     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1106                                    LD->getChain(), LD->getBasePtr(),
1107                                    MemVT, LD->getMemOperand());
1108     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1109
1110     DEBUG(dbgs() << "\nPromoting ";
1111           N->dump(&DAG);
1112           dbgs() << "\nTo: ";
1113           Result.getNode()->dump(&DAG);
1114           dbgs() << '\n');
1115     WorklistRemover DeadNodes(*this);
1116     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1117     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1118     deleteAndRecombine(N);
1119     AddToWorklist(Result.getNode());
1120     return true;
1121   }
1122   return false;
1123 }
1124
1125 /// \brief Recursively delete a node which has no uses and any operands for
1126 /// which it is the only use.
1127 ///
1128 /// Note that this both deletes the nodes and removes them from the worklist.
1129 /// It also adds any nodes who have had a user deleted to the worklist as they
1130 /// may now have only one use and subject to other combines.
1131 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1132   if (!N->use_empty())
1133     return false;
1134
1135   SmallSetVector<SDNode *, 16> Nodes;
1136   Nodes.insert(N);
1137   do {
1138     N = Nodes.pop_back_val();
1139     if (!N)
1140       continue;
1141
1142     if (N->use_empty()) {
1143       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1144         Nodes.insert(N->getOperand(i).getNode());
1145
1146       removeFromWorklist(N);
1147       DAG.DeleteNode(N);
1148     } else {
1149       AddToWorklist(N);
1150     }
1151   } while (!Nodes.empty());
1152   return true;
1153 }
1154
1155 //===----------------------------------------------------------------------===//
1156 //  Main DAG Combiner implementation
1157 //===----------------------------------------------------------------------===//
1158
1159 void DAGCombiner::Run(CombineLevel AtLevel) {
1160   // set the instance variables, so that the various visit routines may use it.
1161   Level = AtLevel;
1162   LegalOperations = Level >= AfterLegalizeVectorOps;
1163   LegalTypes = Level >= AfterLegalizeTypes;
1164
1165   // Early exit if this basic block is in an optnone function.
1166   AttributeSet FnAttrs =
1167     DAG.getMachineFunction().getFunction()->getAttributes();
1168   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1169                            Attribute::OptimizeNone))
1170     return;
1171
1172   // Add all the dag nodes to the worklist.
1173   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1174        E = DAG.allnodes_end(); I != E; ++I)
1175     AddToWorklist(I);
1176
1177   // Create a dummy node (which is not added to allnodes), that adds a reference
1178   // to the root node, preventing it from being deleted, and tracking any
1179   // changes of the root.
1180   HandleSDNode Dummy(DAG.getRoot());
1181
1182   // while the worklist isn't empty, find a node and
1183   // try and combine it.
1184   while (!WorklistMap.empty()) {
1185     SDNode *N;
1186     // The Worklist holds the SDNodes in order, but it may contain null entries.
1187     do {
1188       N = Worklist.pop_back_val();
1189     } while (!N);
1190
1191     bool GoodWorklistEntry = WorklistMap.erase(N);
1192     (void)GoodWorklistEntry;
1193     assert(GoodWorklistEntry &&
1194            "Found a worklist entry without a corresponding map entry!");
1195
1196     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1197     // N is deleted from the DAG, since they too may now be dead or may have a
1198     // reduced number of uses, allowing other xforms.
1199     if (recursivelyDeleteUnusedNodes(N))
1200       continue;
1201
1202     WorklistRemover DeadNodes(*this);
1203
1204     // If this combine is running after legalizing the DAG, re-legalize any
1205     // nodes pulled off the worklist.
1206     if (Level == AfterLegalizeDAG) {
1207       SmallSetVector<SDNode *, 16> UpdatedNodes;
1208       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1209
1210       for (SDNode *LN : UpdatedNodes) {
1211         AddToWorklist(LN);
1212         AddUsersToWorklist(LN);
1213       }
1214       if (!NIsValid)
1215         continue;
1216     }
1217
1218     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1219
1220     // Add any operands of the new node which have not yet been combined to the
1221     // worklist as well. Because the worklist uniques things already, this
1222     // won't repeatedly process the same operand.
1223     CombinedNodes.insert(N);
1224     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1225       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1226         AddToWorklist(N->getOperand(i).getNode());
1227
1228     SDValue RV = combine(N);
1229
1230     if (!RV.getNode())
1231       continue;
1232
1233     ++NodesCombined;
1234
1235     // If we get back the same node we passed in, rather than a new node or
1236     // zero, we know that the node must have defined multiple values and
1237     // CombineTo was used.  Since CombineTo takes care of the worklist
1238     // mechanics for us, we have no work to do in this case.
1239     if (RV.getNode() == N)
1240       continue;
1241
1242     assert(N->getOpcode() != ISD::DELETED_NODE &&
1243            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1244            "Node was deleted but visit returned new node!");
1245
1246     DEBUG(dbgs() << " ... into: ";
1247           RV.getNode()->dump(&DAG));
1248
1249     // Transfer debug value.
1250     DAG.TransferDbgValues(SDValue(N, 0), RV);
1251     if (N->getNumValues() == RV.getNode()->getNumValues())
1252       DAG.ReplaceAllUsesWith(N, RV.getNode());
1253     else {
1254       assert(N->getValueType(0) == RV.getValueType() &&
1255              N->getNumValues() == 1 && "Type mismatch");
1256       SDValue OpV = RV;
1257       DAG.ReplaceAllUsesWith(N, &OpV);
1258     }
1259
1260     // Push the new node and any users onto the worklist
1261     AddToWorklist(RV.getNode());
1262     AddUsersToWorklist(RV.getNode());
1263
1264     // Finally, if the node is now dead, remove it from the graph.  The node
1265     // may not be dead if the replacement process recursively simplified to
1266     // something else needing this node. This will also take care of adding any
1267     // operands which have lost a user to the worklist.
1268     recursivelyDeleteUnusedNodes(N);
1269   }
1270
1271   // If the root changed (e.g. it was a dead load, update the root).
1272   DAG.setRoot(Dummy.getValue());
1273   DAG.RemoveDeadNodes();
1274 }
1275
1276 SDValue DAGCombiner::visit(SDNode *N) {
1277   switch (N->getOpcode()) {
1278   default: break;
1279   case ISD::TokenFactor:        return visitTokenFactor(N);
1280   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1281   case ISD::ADD:                return visitADD(N);
1282   case ISD::SUB:                return visitSUB(N);
1283   case ISD::ADDC:               return visitADDC(N);
1284   case ISD::SUBC:               return visitSUBC(N);
1285   case ISD::ADDE:               return visitADDE(N);
1286   case ISD::SUBE:               return visitSUBE(N);
1287   case ISD::MUL:                return visitMUL(N);
1288   case ISD::SDIV:               return visitSDIV(N);
1289   case ISD::UDIV:               return visitUDIV(N);
1290   case ISD::SREM:               return visitSREM(N);
1291   case ISD::UREM:               return visitUREM(N);
1292   case ISD::MULHU:              return visitMULHU(N);
1293   case ISD::MULHS:              return visitMULHS(N);
1294   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1295   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1296   case ISD::SMULO:              return visitSMULO(N);
1297   case ISD::UMULO:              return visitUMULO(N);
1298   case ISD::SDIVREM:            return visitSDIVREM(N);
1299   case ISD::UDIVREM:            return visitUDIVREM(N);
1300   case ISD::AND:                return visitAND(N);
1301   case ISD::OR:                 return visitOR(N);
1302   case ISD::XOR:                return visitXOR(N);
1303   case ISD::SHL:                return visitSHL(N);
1304   case ISD::SRA:                return visitSRA(N);
1305   case ISD::SRL:                return visitSRL(N);
1306   case ISD::ROTR:
1307   case ISD::ROTL:               return visitRotate(N);
1308   case ISD::CTLZ:               return visitCTLZ(N);
1309   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1310   case ISD::CTTZ:               return visitCTTZ(N);
1311   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1312   case ISD::CTPOP:              return visitCTPOP(N);
1313   case ISD::SELECT:             return visitSELECT(N);
1314   case ISD::VSELECT:            return visitVSELECT(N);
1315   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1316   case ISD::SETCC:              return visitSETCC(N);
1317   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1318   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1319   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1320   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1321   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1322   case ISD::BITCAST:            return visitBITCAST(N);
1323   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1324   case ISD::FADD:               return visitFADD(N);
1325   case ISD::FSUB:               return visitFSUB(N);
1326   case ISD::FMUL:               return visitFMUL(N);
1327   case ISD::FMA:                return visitFMA(N);
1328   case ISD::FDIV:               return visitFDIV(N);
1329   case ISD::FREM:               return visitFREM(N);
1330   case ISD::FSQRT:              return visitFSQRT(N);
1331   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1332   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1333   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1334   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1335   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1336   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1337   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1338   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1339   case ISD::FNEG:               return visitFNEG(N);
1340   case ISD::FABS:               return visitFABS(N);
1341   case ISD::FFLOOR:             return visitFFLOOR(N);
1342   case ISD::FMINNUM:            return visitFMINNUM(N);
1343   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1344   case ISD::FCEIL:              return visitFCEIL(N);
1345   case ISD::FTRUNC:             return visitFTRUNC(N);
1346   case ISD::BRCOND:             return visitBRCOND(N);
1347   case ISD::BR_CC:              return visitBR_CC(N);
1348   case ISD::LOAD:               return visitLOAD(N);
1349   case ISD::STORE:              return visitSTORE(N);
1350   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1351   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1352   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1353   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1354   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1355   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1356   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1357   case ISD::MLOAD:              return visitMLOAD(N);
1358   case ISD::MSTORE:             return visitMSTORE(N);
1359   }
1360   return SDValue();
1361 }
1362
1363 SDValue DAGCombiner::combine(SDNode *N) {
1364   SDValue RV = visit(N);
1365
1366   // If nothing happened, try a target-specific DAG combine.
1367   if (!RV.getNode()) {
1368     assert(N->getOpcode() != ISD::DELETED_NODE &&
1369            "Node was deleted but visit returned NULL!");
1370
1371     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1372         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1373
1374       // Expose the DAG combiner to the target combiner impls.
1375       TargetLowering::DAGCombinerInfo
1376         DagCombineInfo(DAG, Level, false, this);
1377
1378       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1379     }
1380   }
1381
1382   // If nothing happened still, try promoting the operation.
1383   if (!RV.getNode()) {
1384     switch (N->getOpcode()) {
1385     default: break;
1386     case ISD::ADD:
1387     case ISD::SUB:
1388     case ISD::MUL:
1389     case ISD::AND:
1390     case ISD::OR:
1391     case ISD::XOR:
1392       RV = PromoteIntBinOp(SDValue(N, 0));
1393       break;
1394     case ISD::SHL:
1395     case ISD::SRA:
1396     case ISD::SRL:
1397       RV = PromoteIntShiftOp(SDValue(N, 0));
1398       break;
1399     case ISD::SIGN_EXTEND:
1400     case ISD::ZERO_EXTEND:
1401     case ISD::ANY_EXTEND:
1402       RV = PromoteExtend(SDValue(N, 0));
1403       break;
1404     case ISD::LOAD:
1405       if (PromoteLoad(SDValue(N, 0)))
1406         RV = SDValue(N, 0);
1407       break;
1408     }
1409   }
1410
1411   // If N is a commutative binary node, try commuting it to enable more
1412   // sdisel CSE.
1413   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1414       N->getNumValues() == 1) {
1415     SDValue N0 = N->getOperand(0);
1416     SDValue N1 = N->getOperand(1);
1417
1418     // Constant operands are canonicalized to RHS.
1419     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1420       SDValue Ops[] = {N1, N0};
1421       SDNode *CSENode;
1422       if (const BinaryWithFlagsSDNode *BinNode =
1423               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1424         CSENode = DAG.getNodeIfExists(
1425             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1426             BinNode->hasNoSignedWrap(), BinNode->isExact());
1427       } else {
1428         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1429       }
1430       if (CSENode)
1431         return SDValue(CSENode, 0);
1432     }
1433   }
1434
1435   return RV;
1436 }
1437
1438 /// Given a node, return its input chain if it has one, otherwise return a null
1439 /// sd operand.
1440 static SDValue getInputChainForNode(SDNode *N) {
1441   if (unsigned NumOps = N->getNumOperands()) {
1442     if (N->getOperand(0).getValueType() == MVT::Other)
1443       return N->getOperand(0);
1444     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1445       return N->getOperand(NumOps-1);
1446     for (unsigned i = 1; i < NumOps-1; ++i)
1447       if (N->getOperand(i).getValueType() == MVT::Other)
1448         return N->getOperand(i);
1449   }
1450   return SDValue();
1451 }
1452
1453 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1454   // If N has two operands, where one has an input chain equal to the other,
1455   // the 'other' chain is redundant.
1456   if (N->getNumOperands() == 2) {
1457     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1458       return N->getOperand(0);
1459     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1460       return N->getOperand(1);
1461   }
1462
1463   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1464   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1465   SmallPtrSet<SDNode*, 16> SeenOps;
1466   bool Changed = false;             // If we should replace this token factor.
1467
1468   // Start out with this token factor.
1469   TFs.push_back(N);
1470
1471   // Iterate through token factors.  The TFs grows when new token factors are
1472   // encountered.
1473   for (unsigned i = 0; i < TFs.size(); ++i) {
1474     SDNode *TF = TFs[i];
1475
1476     // Check each of the operands.
1477     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1478       SDValue Op = TF->getOperand(i);
1479
1480       switch (Op.getOpcode()) {
1481       case ISD::EntryToken:
1482         // Entry tokens don't need to be added to the list. They are
1483         // rededundant.
1484         Changed = true;
1485         break;
1486
1487       case ISD::TokenFactor:
1488         if (Op.hasOneUse() &&
1489             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1490           // Queue up for processing.
1491           TFs.push_back(Op.getNode());
1492           // Clean up in case the token factor is removed.
1493           AddToWorklist(Op.getNode());
1494           Changed = true;
1495           break;
1496         }
1497         // Fall thru
1498
1499       default:
1500         // Only add if it isn't already in the list.
1501         if (SeenOps.insert(Op.getNode()).second)
1502           Ops.push_back(Op);
1503         else
1504           Changed = true;
1505         break;
1506       }
1507     }
1508   }
1509
1510   SDValue Result;
1511
1512   // If we've change things around then replace token factor.
1513   if (Changed) {
1514     if (Ops.empty()) {
1515       // The entry token is the only possible outcome.
1516       Result = DAG.getEntryNode();
1517     } else {
1518       // New and improved token factor.
1519       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1520     }
1521
1522     // Don't add users to work list.
1523     return CombineTo(N, Result, false);
1524   }
1525
1526   return Result;
1527 }
1528
1529 /// MERGE_VALUES can always be eliminated.
1530 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1531   WorklistRemover DeadNodes(*this);
1532   // Replacing results may cause a different MERGE_VALUES to suddenly
1533   // be CSE'd with N, and carry its uses with it. Iterate until no
1534   // uses remain, to ensure that the node can be safely deleted.
1535   // First add the users of this node to the work list so that they
1536   // can be tried again once they have new operands.
1537   AddUsersToWorklist(N);
1538   do {
1539     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1540       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1541   } while (!N->use_empty());
1542   deleteAndRecombine(N);
1543   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1544 }
1545
1546 SDValue DAGCombiner::visitADD(SDNode *N) {
1547   SDValue N0 = N->getOperand(0);
1548   SDValue N1 = N->getOperand(1);
1549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1551   EVT VT = N0.getValueType();
1552
1553   // fold vector ops
1554   if (VT.isVector()) {
1555     SDValue FoldedVOp = SimplifyVBinOp(N);
1556     if (FoldedVOp.getNode()) return FoldedVOp;
1557
1558     // fold (add x, 0) -> x, vector edition
1559     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1560       return N0;
1561     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1562       return N1;
1563   }
1564
1565   // fold (add x, undef) -> undef
1566   if (N0.getOpcode() == ISD::UNDEF)
1567     return N0;
1568   if (N1.getOpcode() == ISD::UNDEF)
1569     return N1;
1570   // fold (add c1, c2) -> c1+c2
1571   if (N0C && N1C)
1572     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1573   // canonicalize constant to RHS
1574   if (N0C && !N1C)
1575     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1576   // fold (add x, 0) -> x
1577   if (N1C && N1C->isNullValue())
1578     return N0;
1579   // fold (add Sym, c) -> Sym+c
1580   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1581     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1582         GA->getOpcode() == ISD::GlobalAddress)
1583       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1584                                   GA->getOffset() +
1585                                     (uint64_t)N1C->getSExtValue());
1586   // fold ((c1-A)+c2) -> (c1+c2)-A
1587   if (N1C && N0.getOpcode() == ISD::SUB)
1588     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1589       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1590                          DAG.getConstant(N1C->getAPIntValue()+
1591                                          N0C->getAPIntValue(), VT),
1592                          N0.getOperand(1));
1593   // reassociate add
1594   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1595   if (RADD.getNode())
1596     return RADD;
1597   // fold ((0-A) + B) -> B-A
1598   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1599       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1600     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1601   // fold (A + (0-B)) -> A-B
1602   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1603       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1604     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1605   // fold (A+(B-A)) -> B
1606   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1607     return N1.getOperand(0);
1608   // fold ((B-A)+A) -> B
1609   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1610     return N0.getOperand(0);
1611   // fold (A+(B-(A+C))) to (B-C)
1612   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613       N0 == N1.getOperand(1).getOperand(0))
1614     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615                        N1.getOperand(1).getOperand(1));
1616   // fold (A+(B-(C+A))) to (B-C)
1617   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1618       N0 == N1.getOperand(1).getOperand(1))
1619     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1620                        N1.getOperand(1).getOperand(0));
1621   // fold (A+((B-A)+or-C)) to (B+or-C)
1622   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1623       N1.getOperand(0).getOpcode() == ISD::SUB &&
1624       N0 == N1.getOperand(0).getOperand(1))
1625     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1626                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1627
1628   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1629   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1630     SDValue N00 = N0.getOperand(0);
1631     SDValue N01 = N0.getOperand(1);
1632     SDValue N10 = N1.getOperand(0);
1633     SDValue N11 = N1.getOperand(1);
1634
1635     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1636       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1637                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1638                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1639   }
1640
1641   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1642     return SDValue(N, 0);
1643
1644   // fold (a+b) -> (a|b) iff a and b share no bits.
1645   if (VT.isInteger() && !VT.isVector()) {
1646     APInt LHSZero, LHSOne;
1647     APInt RHSZero, RHSOne;
1648     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1649
1650     if (LHSZero.getBoolValue()) {
1651       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1652
1653       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1654       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1655       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1656         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1657           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1658       }
1659     }
1660   }
1661
1662   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1663   if (N1.getOpcode() == ISD::SHL &&
1664       N1.getOperand(0).getOpcode() == ISD::SUB)
1665     if (ConstantSDNode *C =
1666           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1667       if (C->getAPIntValue() == 0)
1668         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1669                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1670                                        N1.getOperand(0).getOperand(1),
1671                                        N1.getOperand(1)));
1672   if (N0.getOpcode() == ISD::SHL &&
1673       N0.getOperand(0).getOpcode() == ISD::SUB)
1674     if (ConstantSDNode *C =
1675           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1676       if (C->getAPIntValue() == 0)
1677         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1678                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1679                                        N0.getOperand(0).getOperand(1),
1680                                        N0.getOperand(1)));
1681
1682   if (N1.getOpcode() == ISD::AND) {
1683     SDValue AndOp0 = N1.getOperand(0);
1684     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1685     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1686     unsigned DestBits = VT.getScalarType().getSizeInBits();
1687
1688     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1689     // and similar xforms where the inner op is either ~0 or 0.
1690     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1691       SDLoc DL(N);
1692       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1693     }
1694   }
1695
1696   // add (sext i1), X -> sub X, (zext i1)
1697   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1698       N0.getOperand(0).getValueType() == MVT::i1 &&
1699       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1700     SDLoc DL(N);
1701     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1702     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1703   }
1704
1705   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1706   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1707     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1708     if (TN->getVT() == MVT::i1) {
1709       SDLoc DL(N);
1710       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1711                                  DAG.getConstant(1, VT));
1712       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1713     }
1714   }
1715
1716   return SDValue();
1717 }
1718
1719 SDValue DAGCombiner::visitADDC(SDNode *N) {
1720   SDValue N0 = N->getOperand(0);
1721   SDValue N1 = N->getOperand(1);
1722   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724   EVT VT = N0.getValueType();
1725
1726   // If the flag result is dead, turn this into an ADD.
1727   if (!N->hasAnyUseOfValue(1))
1728     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1729                      DAG.getNode(ISD::CARRY_FALSE,
1730                                  SDLoc(N), MVT::Glue));
1731
1732   // canonicalize constant to RHS.
1733   if (N0C && !N1C)
1734     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1735
1736   // fold (addc x, 0) -> x + no carry out
1737   if (N1C && N1C->isNullValue())
1738     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1739                                         SDLoc(N), MVT::Glue));
1740
1741   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1742   APInt LHSZero, LHSOne;
1743   APInt RHSZero, RHSOne;
1744   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745
1746   if (LHSZero.getBoolValue()) {
1747     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748
1749     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1752       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1753                        DAG.getNode(ISD::CARRY_FALSE,
1754                                    SDLoc(N), MVT::Glue));
1755   }
1756
1757   return SDValue();
1758 }
1759
1760 SDValue DAGCombiner::visitADDE(SDNode *N) {
1761   SDValue N0 = N->getOperand(0);
1762   SDValue N1 = N->getOperand(1);
1763   SDValue CarryIn = N->getOperand(2);
1764   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766
1767   // canonicalize constant to RHS
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1770                        N1, N0, CarryIn);
1771
1772   // fold (adde x, y, false) -> (addc x, y)
1773   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1774     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1775
1776   return SDValue();
1777 }
1778
1779 // Since it may not be valid to emit a fold to zero for vector initializers
1780 // check if we can before folding.
1781 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1782                              SelectionDAG &DAG,
1783                              bool LegalOperations, bool LegalTypes) {
1784   if (!VT.isVector())
1785     return DAG.getConstant(0, VT);
1786   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1787     return DAG.getConstant(0, VT);
1788   return SDValue();
1789 }
1790
1791 SDValue DAGCombiner::visitSUB(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1796   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1797     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1798   EVT VT = N0.getValueType();
1799
1800   // fold vector ops
1801   if (VT.isVector()) {
1802     SDValue FoldedVOp = SimplifyVBinOp(N);
1803     if (FoldedVOp.getNode()) return FoldedVOp;
1804
1805     // fold (sub x, 0) -> x, vector edition
1806     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1807       return N0;
1808   }
1809
1810   // fold (sub x, x) -> 0
1811   // FIXME: Refactor this and xor and other similar operations together.
1812   if (N0 == N1)
1813     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1814   // fold (sub c1, c2) -> c1-c2
1815   if (N0C && N1C)
1816     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1817   // fold (sub x, c) -> (add x, -c)
1818   if (N1C)
1819     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1820                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1821   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1822   if (N0C && N0C->isAllOnesValue())
1823     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1824   // fold A-(A-B) -> B
1825   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1826     return N1.getOperand(1);
1827   // fold (A+B)-A -> B
1828   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1829     return N0.getOperand(1);
1830   // fold (A+B)-B -> A
1831   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1832     return N0.getOperand(0);
1833   // fold C2-(A+C1) -> (C2-C1)-A
1834   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1835     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1836                                    VT);
1837     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1838                        N1.getOperand(0));
1839   }
1840   // fold ((A+(B+or-C))-B) -> A+or-C
1841   if (N0.getOpcode() == ISD::ADD &&
1842       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1843        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1844       N0.getOperand(1).getOperand(0) == N1)
1845     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1846                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1847   // fold ((A+(C+B))-B) -> A+C
1848   if (N0.getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOpcode() == ISD::ADD &&
1850       N0.getOperand(1).getOperand(1) == N1)
1851     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1852                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1853   // fold ((A-(B-C))-C) -> A-B
1854   if (N0.getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOpcode() == ISD::SUB &&
1856       N0.getOperand(1).getOperand(1) == N1)
1857     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1858                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1859
1860   // If either operand of a sub is undef, the result is undef
1861   if (N0.getOpcode() == ISD::UNDEF)
1862     return N0;
1863   if (N1.getOpcode() == ISD::UNDEF)
1864     return N1;
1865
1866   // If the relocation model supports it, consider symbol offsets.
1867   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1868     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1869       // fold (sub Sym, c) -> Sym-c
1870       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1871         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1872                                     GA->getOffset() -
1873                                       (uint64_t)N1C->getSExtValue());
1874       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1875       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1876         if (GA->getGlobal() == GB->getGlobal())
1877           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1878                                  VT);
1879     }
1880
1881   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1882   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1883     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1884     if (TN->getVT() == MVT::i1) {
1885       SDLoc DL(N);
1886       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1887                                  DAG.getConstant(1, VT));
1888       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1889     }
1890   }
1891
1892   return SDValue();
1893 }
1894
1895 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1896   SDValue N0 = N->getOperand(0);
1897   SDValue N1 = N->getOperand(1);
1898   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1899   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1900   EVT VT = N0.getValueType();
1901
1902   // If the flag result is dead, turn this into an SUB.
1903   if (!N->hasAnyUseOfValue(1))
1904     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1905                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1906                                  MVT::Glue));
1907
1908   // fold (subc x, x) -> 0 + no borrow
1909   if (N0 == N1)
1910     return CombineTo(N, DAG.getConstant(0, VT),
1911                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1912                                  MVT::Glue));
1913
1914   // fold (subc x, 0) -> x + no borrow
1915   if (N1C && N1C->isNullValue())
1916     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1917                                         MVT::Glue));
1918
1919   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1920   if (N0C && N0C->isAllOnesValue())
1921     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1922                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1923                                  MVT::Glue));
1924
1925   return SDValue();
1926 }
1927
1928 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1929   SDValue N0 = N->getOperand(0);
1930   SDValue N1 = N->getOperand(1);
1931   SDValue CarryIn = N->getOperand(2);
1932
1933   // fold (sube x, y, false) -> (subc x, y)
1934   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1935     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1936
1937   return SDValue();
1938 }
1939
1940 SDValue DAGCombiner::visitMUL(SDNode *N) {
1941   SDValue N0 = N->getOperand(0);
1942   SDValue N1 = N->getOperand(1);
1943   EVT VT = N0.getValueType();
1944
1945   // fold (mul x, undef) -> 0
1946   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1947     return DAG.getConstant(0, VT);
1948
1949   bool N0IsConst = false;
1950   bool N1IsConst = false;
1951   APInt ConstValue0, ConstValue1;
1952   // fold vector ops
1953   if (VT.isVector()) {
1954     SDValue FoldedVOp = SimplifyVBinOp(N);
1955     if (FoldedVOp.getNode()) return FoldedVOp;
1956
1957     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1958     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1959   } else {
1960     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1961     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1962                             : APInt();
1963     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1964     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1965                             : APInt();
1966   }
1967
1968   // fold (mul c1, c2) -> c1*c2
1969   if (N0IsConst && N1IsConst)
1970     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1971
1972   // canonicalize constant to RHS
1973   if (N0IsConst && !N1IsConst)
1974     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1975   // fold (mul x, 0) -> 0
1976   if (N1IsConst && ConstValue1 == 0)
1977     return N1;
1978   // We require a splat of the entire scalar bit width for non-contiguous
1979   // bit patterns.
1980   bool IsFullSplat =
1981     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1982   // fold (mul x, 1) -> x
1983   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1984     return N0;
1985   // fold (mul x, -1) -> 0-x
1986   if (N1IsConst && ConstValue1.isAllOnesValue())
1987     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988                        DAG.getConstant(0, VT), N0);
1989   // fold (mul x, (1 << c)) -> x << c
1990   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1991     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1992                        DAG.getConstant(ConstValue1.logBase2(),
1993                                        getShiftAmountTy(N0.getValueType())));
1994   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1995   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1996     unsigned Log2Val = (-ConstValue1).logBase2();
1997     // FIXME: If the input is something that is easily negated (e.g. a
1998     // single-use add), we should put the negate there.
1999     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2000                        DAG.getConstant(0, VT),
2001                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2002                             DAG.getConstant(Log2Val,
2003                                       getShiftAmountTy(N0.getValueType()))));
2004   }
2005
2006   APInt Val;
2007   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2008   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2009       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2010                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2011     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2012                              N1, N0.getOperand(1));
2013     AddToWorklist(C3.getNode());
2014     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2015                        N0.getOperand(0), C3);
2016   }
2017
2018   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2019   // use.
2020   {
2021     SDValue Sh(nullptr,0), Y(nullptr,0);
2022     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2023     if (N0.getOpcode() == ISD::SHL &&
2024         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2025                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2026         N0.getNode()->hasOneUse()) {
2027       Sh = N0; Y = N1;
2028     } else if (N1.getOpcode() == ISD::SHL &&
2029                isa<ConstantSDNode>(N1.getOperand(1)) &&
2030                N1.getNode()->hasOneUse()) {
2031       Sh = N1; Y = N0;
2032     }
2033
2034     if (Sh.getNode()) {
2035       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2036                                 Sh.getOperand(0), Y);
2037       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2038                          Mul, Sh.getOperand(1));
2039     }
2040   }
2041
2042   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2043   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2044       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2045                      isa<ConstantSDNode>(N0.getOperand(1))))
2046     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2047                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2048                                    N0.getOperand(0), N1),
2049                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2050                                    N0.getOperand(1), N1));
2051
2052   // reassociate mul
2053   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2054   if (RMUL.getNode())
2055     return RMUL;
2056
2057   return SDValue();
2058 }
2059
2060 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2061   SDValue N0 = N->getOperand(0);
2062   SDValue N1 = N->getOperand(1);
2063   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2064   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2065   EVT VT = N->getValueType(0);
2066
2067   // fold vector ops
2068   if (VT.isVector()) {
2069     SDValue FoldedVOp = SimplifyVBinOp(N);
2070     if (FoldedVOp.getNode()) return FoldedVOp;
2071   }
2072
2073   // fold (sdiv c1, c2) -> c1/c2
2074   if (N0C && N1C && !N1C->isNullValue())
2075     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2076   // fold (sdiv X, 1) -> X
2077   if (N1C && N1C->getAPIntValue() == 1LL)
2078     return N0;
2079   // fold (sdiv X, -1) -> 0-X
2080   if (N1C && N1C->isAllOnesValue())
2081     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2082                        DAG.getConstant(0, VT), N0);
2083   // If we know the sign bits of both operands are zero, strength reduce to a
2084   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2085   if (!VT.isVector()) {
2086     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2087       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2088                          N0, N1);
2089   }
2090
2091   // fold (sdiv X, pow2) -> simple ops after legalize
2092   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2093                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2094     // If dividing by powers of two is cheap, then don't perform the following
2095     // fold.
2096     if (TLI.isPow2SDivCheap())
2097       return SDValue();
2098
2099     // Target-specific implementation of sdiv x, pow2.
2100     SDValue Res = BuildSDIVPow2(N);
2101     if (Res.getNode())
2102       return Res;
2103
2104     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2105
2106     // Splat the sign bit into the register
2107     SDValue SGN =
2108         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2109                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2110                                     getShiftAmountTy(N0.getValueType())));
2111     AddToWorklist(SGN.getNode());
2112
2113     // Add (N0 < 0) ? abs2 - 1 : 0;
2114     SDValue SRL =
2115         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2116                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2117                                     getShiftAmountTy(SGN.getValueType())));
2118     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2119     AddToWorklist(SRL.getNode());
2120     AddToWorklist(ADD.getNode());    // Divide by pow2
2121     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2122                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2123
2124     // If we're dividing by a positive value, we're done.  Otherwise, we must
2125     // negate the result.
2126     if (N1C->getAPIntValue().isNonNegative())
2127       return SRA;
2128
2129     AddToWorklist(SRA.getNode());
2130     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2131   }
2132
2133   // if integer divide is expensive and we satisfy the requirements, emit an
2134   // alternate sequence.
2135   if (N1C && !TLI.isIntDivCheap()) {
2136     SDValue Op = BuildSDIV(N);
2137     if (Op.getNode()) return Op;
2138   }
2139
2140   // undef / X -> 0
2141   if (N0.getOpcode() == ISD::UNDEF)
2142     return DAG.getConstant(0, VT);
2143   // X / undef -> undef
2144   if (N1.getOpcode() == ISD::UNDEF)
2145     return N1;
2146
2147   return SDValue();
2148 }
2149
2150 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2151   SDValue N0 = N->getOperand(0);
2152   SDValue N1 = N->getOperand(1);
2153   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2154   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2155   EVT VT = N->getValueType(0);
2156
2157   // fold vector ops
2158   if (VT.isVector()) {
2159     SDValue FoldedVOp = SimplifyVBinOp(N);
2160     if (FoldedVOp.getNode()) return FoldedVOp;
2161   }
2162
2163   // fold (udiv c1, c2) -> c1/c2
2164   if (N0C && N1C && !N1C->isNullValue())
2165     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2166   // fold (udiv x, (1 << c)) -> x >>u c
2167   if (N1C && N1C->getAPIntValue().isPowerOf2())
2168     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2169                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2170                                        getShiftAmountTy(N0.getValueType())));
2171   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2172   if (N1.getOpcode() == ISD::SHL) {
2173     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2174       if (SHC->getAPIntValue().isPowerOf2()) {
2175         EVT ADDVT = N1.getOperand(1).getValueType();
2176         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2177                                   N1.getOperand(1),
2178                                   DAG.getConstant(SHC->getAPIntValue()
2179                                                                   .logBase2(),
2180                                                   ADDVT));
2181         AddToWorklist(Add.getNode());
2182         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2183       }
2184     }
2185   }
2186   // fold (udiv x, c) -> alternate
2187   if (N1C && !TLI.isIntDivCheap()) {
2188     SDValue Op = BuildUDIV(N);
2189     if (Op.getNode()) return Op;
2190   }
2191
2192   // undef / X -> 0
2193   if (N0.getOpcode() == ISD::UNDEF)
2194     return DAG.getConstant(0, VT);
2195   // X / undef -> undef
2196   if (N1.getOpcode() == ISD::UNDEF)
2197     return N1;
2198
2199   return SDValue();
2200 }
2201
2202 SDValue DAGCombiner::visitSREM(SDNode *N) {
2203   SDValue N0 = N->getOperand(0);
2204   SDValue N1 = N->getOperand(1);
2205   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2206   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2207   EVT VT = N->getValueType(0);
2208
2209   // fold (srem c1, c2) -> c1%c2
2210   if (N0C && N1C && !N1C->isNullValue())
2211     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2212   // If we know the sign bits of both operands are zero, strength reduce to a
2213   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2214   if (!VT.isVector()) {
2215     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2216       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2217   }
2218
2219   // If X/C can be simplified by the division-by-constant logic, lower
2220   // X%C to the equivalent of X-X/C*C.
2221   if (N1C && !N1C->isNullValue()) {
2222     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2223     AddToWorklist(Div.getNode());
2224     SDValue OptimizedDiv = combine(Div.getNode());
2225     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2226       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2227                                 OptimizedDiv, N1);
2228       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2229       AddToWorklist(Mul.getNode());
2230       return Sub;
2231     }
2232   }
2233
2234   // undef % X -> 0
2235   if (N0.getOpcode() == ISD::UNDEF)
2236     return DAG.getConstant(0, VT);
2237   // X % undef -> undef
2238   if (N1.getOpcode() == ISD::UNDEF)
2239     return N1;
2240
2241   return SDValue();
2242 }
2243
2244 SDValue DAGCombiner::visitUREM(SDNode *N) {
2245   SDValue N0 = N->getOperand(0);
2246   SDValue N1 = N->getOperand(1);
2247   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2248   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2249   EVT VT = N->getValueType(0);
2250
2251   // fold (urem c1, c2) -> c1%c2
2252   if (N0C && N1C && !N1C->isNullValue())
2253     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2254   // fold (urem x, pow2) -> (and x, pow2-1)
2255   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2256     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2257                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2258   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2259   if (N1.getOpcode() == ISD::SHL) {
2260     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2261       if (SHC->getAPIntValue().isPowerOf2()) {
2262         SDValue Add =
2263           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2264                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2265                                  VT));
2266         AddToWorklist(Add.getNode());
2267         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2268       }
2269     }
2270   }
2271
2272   // If X/C can be simplified by the division-by-constant logic, lower
2273   // X%C to the equivalent of X-X/C*C.
2274   if (N1C && !N1C->isNullValue()) {
2275     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2276     AddToWorklist(Div.getNode());
2277     SDValue OptimizedDiv = combine(Div.getNode());
2278     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2279       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2280                                 OptimizedDiv, N1);
2281       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2282       AddToWorklist(Mul.getNode());
2283       return Sub;
2284     }
2285   }
2286
2287   // undef % X -> 0
2288   if (N0.getOpcode() == ISD::UNDEF)
2289     return DAG.getConstant(0, VT);
2290   // X % undef -> undef
2291   if (N1.getOpcode() == ISD::UNDEF)
2292     return N1;
2293
2294   return SDValue();
2295 }
2296
2297 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2298   SDValue N0 = N->getOperand(0);
2299   SDValue N1 = N->getOperand(1);
2300   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2301   EVT VT = N->getValueType(0);
2302   SDLoc DL(N);
2303
2304   // fold (mulhs x, 0) -> 0
2305   if (N1C && N1C->isNullValue())
2306     return N1;
2307   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2308   if (N1C && N1C->getAPIntValue() == 1)
2309     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2310                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2311                                        getShiftAmountTy(N0.getValueType())));
2312   // fold (mulhs x, undef) -> 0
2313   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2314     return DAG.getConstant(0, VT);
2315
2316   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2317   // plus a shift.
2318   if (VT.isSimple() && !VT.isVector()) {
2319     MVT Simple = VT.getSimpleVT();
2320     unsigned SimpleSize = Simple.getSizeInBits();
2321     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2322     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2323       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2324       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2325       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2326       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2327             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2328       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2329     }
2330   }
2331
2332   return SDValue();
2333 }
2334
2335 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2336   SDValue N0 = N->getOperand(0);
2337   SDValue N1 = N->getOperand(1);
2338   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2339   EVT VT = N->getValueType(0);
2340   SDLoc DL(N);
2341
2342   // fold (mulhu x, 0) -> 0
2343   if (N1C && N1C->isNullValue())
2344     return N1;
2345   // fold (mulhu x, 1) -> 0
2346   if (N1C && N1C->getAPIntValue() == 1)
2347     return DAG.getConstant(0, N0.getValueType());
2348   // fold (mulhu x, undef) -> 0
2349   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2350     return DAG.getConstant(0, VT);
2351
2352   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2353   // plus a shift.
2354   if (VT.isSimple() && !VT.isVector()) {
2355     MVT Simple = VT.getSimpleVT();
2356     unsigned SimpleSize = Simple.getSizeInBits();
2357     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2360       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2361       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2362       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2363             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2364       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2365     }
2366   }
2367
2368   return SDValue();
2369 }
2370
2371 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2372 /// give the opcodes for the two computations that are being performed. Return
2373 /// true if a simplification was made.
2374 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2375                                                 unsigned HiOp) {
2376   // If the high half is not needed, just compute the low half.
2377   bool HiExists = N->hasAnyUseOfValue(1);
2378   if (!HiExists &&
2379       (!LegalOperations ||
2380        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2381     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2382     return CombineTo(N, Res, Res);
2383   }
2384
2385   // If the low half is not needed, just compute the high half.
2386   bool LoExists = N->hasAnyUseOfValue(0);
2387   if (!LoExists &&
2388       (!LegalOperations ||
2389        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2390     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2391     return CombineTo(N, Res, Res);
2392   }
2393
2394   // If both halves are used, return as it is.
2395   if (LoExists && HiExists)
2396     return SDValue();
2397
2398   // If the two computed results can be simplified separately, separate them.
2399   if (LoExists) {
2400     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2401     AddToWorklist(Lo.getNode());
2402     SDValue LoOpt = combine(Lo.getNode());
2403     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2404         (!LegalOperations ||
2405          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2406       return CombineTo(N, LoOpt, LoOpt);
2407   }
2408
2409   if (HiExists) {
2410     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2411     AddToWorklist(Hi.getNode());
2412     SDValue HiOpt = combine(Hi.getNode());
2413     if (HiOpt.getNode() && HiOpt != Hi &&
2414         (!LegalOperations ||
2415          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2416       return CombineTo(N, HiOpt, HiOpt);
2417   }
2418
2419   return SDValue();
2420 }
2421
2422 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2423   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2424   if (Res.getNode()) return Res;
2425
2426   EVT VT = N->getValueType(0);
2427   SDLoc DL(N);
2428
2429   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2430   // plus a shift.
2431   if (VT.isSimple() && !VT.isVector()) {
2432     MVT Simple = VT.getSimpleVT();
2433     unsigned SimpleSize = Simple.getSizeInBits();
2434     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2435     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2436       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2437       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2438       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2439       // Compute the high part as N1.
2440       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2441             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2442       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2443       // Compute the low part as N0.
2444       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2445       return CombineTo(N, Lo, Hi);
2446     }
2447   }
2448
2449   return SDValue();
2450 }
2451
2452 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2453   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2454   if (Res.getNode()) return Res;
2455
2456   EVT VT = N->getValueType(0);
2457   SDLoc DL(N);
2458
2459   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2460   // plus a shift.
2461   if (VT.isSimple() && !VT.isVector()) {
2462     MVT Simple = VT.getSimpleVT();
2463     unsigned SimpleSize = Simple.getSizeInBits();
2464     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2467       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2468       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2469       // Compute the high part as N1.
2470       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2471             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2472       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2473       // Compute the low part as N0.
2474       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2475       return CombineTo(N, Lo, Hi);
2476     }
2477   }
2478
2479   return SDValue();
2480 }
2481
2482 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2483   // (smulo x, 2) -> (saddo x, x)
2484   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2485     if (C2->getAPIntValue() == 2)
2486       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2487                          N->getOperand(0), N->getOperand(0));
2488
2489   return SDValue();
2490 }
2491
2492 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2493   // (umulo x, 2) -> (uaddo x, x)
2494   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2495     if (C2->getAPIntValue() == 2)
2496       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2497                          N->getOperand(0), N->getOperand(0));
2498
2499   return SDValue();
2500 }
2501
2502 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2503   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2504   if (Res.getNode()) return Res;
2505
2506   return SDValue();
2507 }
2508
2509 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2510   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2511   if (Res.getNode()) return Res;
2512
2513   return SDValue();
2514 }
2515
2516 /// If this is a binary operator with two operands of the same opcode, try to
2517 /// simplify it.
2518 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2519   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2520   EVT VT = N0.getValueType();
2521   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2522
2523   // Bail early if none of these transforms apply.
2524   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2525
2526   // For each of OP in AND/OR/XOR:
2527   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2528   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2529   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2530   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2531   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2532   //
2533   // do not sink logical op inside of a vector extend, since it may combine
2534   // into a vsetcc.
2535   EVT Op0VT = N0.getOperand(0).getValueType();
2536   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2537        N0.getOpcode() == ISD::SIGN_EXTEND ||
2538        N0.getOpcode() == ISD::BSWAP ||
2539        // Avoid infinite looping with PromoteIntBinOp.
2540        (N0.getOpcode() == ISD::ANY_EXTEND &&
2541         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2542        (N0.getOpcode() == ISD::TRUNCATE &&
2543         (!TLI.isZExtFree(VT, Op0VT) ||
2544          !TLI.isTruncateFree(Op0VT, VT)) &&
2545         TLI.isTypeLegal(Op0VT))) &&
2546       !VT.isVector() &&
2547       Op0VT == N1.getOperand(0).getValueType() &&
2548       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2549     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2550                                  N0.getOperand(0).getValueType(),
2551                                  N0.getOperand(0), N1.getOperand(0));
2552     AddToWorklist(ORNode.getNode());
2553     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2554   }
2555
2556   // For each of OP in SHL/SRL/SRA/AND...
2557   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2558   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2559   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2560   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2561        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2562       N0.getOperand(1) == N1.getOperand(1)) {
2563     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2564                                  N0.getOperand(0).getValueType(),
2565                                  N0.getOperand(0), N1.getOperand(0));
2566     AddToWorklist(ORNode.getNode());
2567     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2568                        ORNode, N0.getOperand(1));
2569   }
2570
2571   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2572   // Only perform this optimization after type legalization and before
2573   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2574   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2575   // we don't want to undo this promotion.
2576   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2577   // on scalars.
2578   if ((N0.getOpcode() == ISD::BITCAST ||
2579        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2580       Level == AfterLegalizeTypes) {
2581     SDValue In0 = N0.getOperand(0);
2582     SDValue In1 = N1.getOperand(0);
2583     EVT In0Ty = In0.getValueType();
2584     EVT In1Ty = In1.getValueType();
2585     SDLoc DL(N);
2586     // If both incoming values are integers, and the original types are the
2587     // same.
2588     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2589       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2590       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2591       AddToWorklist(Op.getNode());
2592       return BC;
2593     }
2594   }
2595
2596   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2597   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2598   // If both shuffles use the same mask, and both shuffle within a single
2599   // vector, then it is worthwhile to move the swizzle after the operation.
2600   // The type-legalizer generates this pattern when loading illegal
2601   // vector types from memory. In many cases this allows additional shuffle
2602   // optimizations.
2603   // There are other cases where moving the shuffle after the xor/and/or
2604   // is profitable even if shuffles don't perform a swizzle.
2605   // If both shuffles use the same mask, and both shuffles have the same first
2606   // or second operand, then it might still be profitable to move the shuffle
2607   // after the xor/and/or operation.
2608   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2609     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2610     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2611
2612     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2613            "Inputs to shuffles are not the same type");
2614
2615     // Check that both shuffles use the same mask. The masks are known to be of
2616     // the same length because the result vector type is the same.
2617     // Check also that shuffles have only one use to avoid introducing extra
2618     // instructions.
2619     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2620         SVN0->getMask().equals(SVN1->getMask())) {
2621       SDValue ShOp = N0->getOperand(1);
2622
2623       // Don't try to fold this node if it requires introducing a
2624       // build vector of all zeros that might be illegal at this stage.
2625       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2626         if (!LegalTypes)
2627           ShOp = DAG.getConstant(0, VT);
2628         else
2629           ShOp = SDValue();
2630       }
2631
2632       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2633       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2634       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2635       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2636         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2637                                       N0->getOperand(0), N1->getOperand(0));
2638         AddToWorklist(NewNode.getNode());
2639         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2640                                     &SVN0->getMask()[0]);
2641       }
2642
2643       // Don't try to fold this node if it requires introducing a
2644       // build vector of all zeros that might be illegal at this stage.
2645       ShOp = N0->getOperand(0);
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 (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2654       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2655       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2656       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2657         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2658                                       N0->getOperand(1), N1->getOperand(1));
2659         AddToWorklist(NewNode.getNode());
2660         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2661                                     &SVN0->getMask()[0]);
2662       }
2663     }
2664   }
2665
2666   return SDValue();
2667 }
2668
2669 SDValue DAGCombiner::visitAND(SDNode *N) {
2670   SDValue N0 = N->getOperand(0);
2671   SDValue N1 = N->getOperand(1);
2672   SDValue LL, LR, RL, RR, CC0, CC1;
2673   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2674   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2675   EVT VT = N1.getValueType();
2676   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2677
2678   // fold vector ops
2679   if (VT.isVector()) {
2680     SDValue FoldedVOp = SimplifyVBinOp(N);
2681     if (FoldedVOp.getNode()) return FoldedVOp;
2682
2683     // fold (and x, 0) -> 0, vector edition
2684     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2685       // do not return N0, because undef node may exist in N0
2686       return DAG.getConstant(
2687           APInt::getNullValue(
2688               N0.getValueType().getScalarType().getSizeInBits()),
2689           N0.getValueType());
2690     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2691       // do not return N1, because undef node may exist in N1
2692       return DAG.getConstant(
2693           APInt::getNullValue(
2694               N1.getValueType().getScalarType().getSizeInBits()),
2695           N1.getValueType());
2696
2697     // fold (and x, -1) -> x, vector edition
2698     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2699       return N1;
2700     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2701       return N0;
2702   }
2703
2704   // fold (and x, undef) -> 0
2705   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2706     return DAG.getConstant(0, VT);
2707   // fold (and c1, c2) -> c1&c2
2708   if (N0C && N1C)
2709     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2710   // canonicalize constant to RHS
2711   if (N0C && !N1C)
2712     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2713   // fold (and x, -1) -> x
2714   if (N1C && N1C->isAllOnesValue())
2715     return N0;
2716   // if (and x, c) is known to be zero, return 0
2717   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2718                                    APInt::getAllOnesValue(BitWidth)))
2719     return DAG.getConstant(0, VT);
2720   // reassociate and
2721   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2722   if (RAND.getNode())
2723     return RAND;
2724   // fold (and (or x, C), D) -> D if (C & D) == D
2725   if (N1C && N0.getOpcode() == ISD::OR)
2726     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2727       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2728         return N1;
2729   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2730   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2731     SDValue N0Op0 = N0.getOperand(0);
2732     APInt Mask = ~N1C->getAPIntValue();
2733     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2734     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2735       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2736                                  N0.getValueType(), N0Op0);
2737
2738       // Replace uses of the AND with uses of the Zero extend node.
2739       CombineTo(N, Zext);
2740
2741       // We actually want to replace all uses of the any_extend with the
2742       // zero_extend, to avoid duplicating things.  This will later cause this
2743       // AND to be folded.
2744       CombineTo(N0.getNode(), Zext);
2745       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2746     }
2747   }
2748   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2749   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2750   // already be zero by virtue of the width of the base type of the load.
2751   //
2752   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2753   // more cases.
2754   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2755        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2756       N0.getOpcode() == ISD::LOAD) {
2757     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2758                                          N0 : N0.getOperand(0) );
2759
2760     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2761     // This can be a pure constant or a vector splat, in which case we treat the
2762     // vector as a scalar and use the splat value.
2763     APInt Constant = APInt::getNullValue(1);
2764     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2765       Constant = C->getAPIntValue();
2766     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2767       APInt SplatValue, SplatUndef;
2768       unsigned SplatBitSize;
2769       bool HasAnyUndefs;
2770       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2771                                              SplatBitSize, HasAnyUndefs);
2772       if (IsSplat) {
2773         // Undef bits can contribute to a possible optimisation if set, so
2774         // set them.
2775         SplatValue |= SplatUndef;
2776
2777         // The splat value may be something like "0x00FFFFFF", which means 0 for
2778         // the first vector value and FF for the rest, repeating. We need a mask
2779         // that will apply equally to all members of the vector, so AND all the
2780         // lanes of the constant together.
2781         EVT VT = Vector->getValueType(0);
2782         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2783
2784         // If the splat value has been compressed to a bitlength lower
2785         // than the size of the vector lane, we need to re-expand it to
2786         // the lane size.
2787         if (BitWidth > SplatBitSize)
2788           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2789                SplatBitSize < BitWidth;
2790                SplatBitSize = SplatBitSize * 2)
2791             SplatValue |= SplatValue.shl(SplatBitSize);
2792
2793         Constant = APInt::getAllOnesValue(BitWidth);
2794         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2795           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2796       }
2797     }
2798
2799     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2800     // actually legal and isn't going to get expanded, else this is a false
2801     // optimisation.
2802     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2803                                                     Load->getMemoryVT());
2804
2805     // Resize the constant to the same size as the original memory access before
2806     // extension. If it is still the AllOnesValue then this AND is completely
2807     // unneeded.
2808     Constant =
2809       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2810
2811     bool B;
2812     switch (Load->getExtensionType()) {
2813     default: B = false; break;
2814     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2815     case ISD::ZEXTLOAD:
2816     case ISD::NON_EXTLOAD: B = true; break;
2817     }
2818
2819     if (B && Constant.isAllOnesValue()) {
2820       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2821       // preserve semantics once we get rid of the AND.
2822       SDValue NewLoad(Load, 0);
2823       if (Load->getExtensionType() == ISD::EXTLOAD) {
2824         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2825                               Load->getValueType(0), SDLoc(Load),
2826                               Load->getChain(), Load->getBasePtr(),
2827                               Load->getOffset(), Load->getMemoryVT(),
2828                               Load->getMemOperand());
2829         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2830         if (Load->getNumValues() == 3) {
2831           // PRE/POST_INC loads have 3 values.
2832           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2833                            NewLoad.getValue(2) };
2834           CombineTo(Load, To, 3, true);
2835         } else {
2836           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2837         }
2838       }
2839
2840       // Fold the AND away, taking care not to fold to the old load node if we
2841       // replaced it.
2842       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2843
2844       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2845     }
2846   }
2847   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2848   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2849     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2850     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2851
2852     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2853         LL.getValueType().isInteger()) {
2854       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2855       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2856         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2857                                      LR.getValueType(), LL, RL);
2858         AddToWorklist(ORNode.getNode());
2859         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2860       }
2861       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2862       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2863         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2864                                       LR.getValueType(), LL, RL);
2865         AddToWorklist(ANDNode.getNode());
2866         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2867       }
2868       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2869       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2870         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2871                                      LR.getValueType(), LL, RL);
2872         AddToWorklist(ORNode.getNode());
2873         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2874       }
2875     }
2876     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2877     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2878         Op0 == Op1 && LL.getValueType().isInteger() &&
2879       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2880                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2881                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2882                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2883       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2884                                     LL, DAG.getConstant(1, LL.getValueType()));
2885       AddToWorklist(ADDNode.getNode());
2886       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2887                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2888     }
2889     // canonicalize equivalent to ll == rl
2890     if (LL == RR && LR == RL) {
2891       Op1 = ISD::getSetCCSwappedOperands(Op1);
2892       std::swap(RL, RR);
2893     }
2894     if (LL == RL && LR == RR) {
2895       bool isInteger = LL.getValueType().isInteger();
2896       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2897       if (Result != ISD::SETCC_INVALID &&
2898           (!LegalOperations ||
2899            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2900             TLI.isOperationLegal(ISD::SETCC,
2901                             getSetCCResultType(N0.getSimpleValueType())))))
2902         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2903                             LL, LR, Result);
2904     }
2905   }
2906
2907   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2908   if (N0.getOpcode() == N1.getOpcode()) {
2909     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2910     if (Tmp.getNode()) return Tmp;
2911   }
2912
2913   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2914   // fold (and (sra)) -> (and (srl)) when possible.
2915   if (!VT.isVector() &&
2916       SimplifyDemandedBits(SDValue(N, 0)))
2917     return SDValue(N, 0);
2918
2919   // fold (zext_inreg (extload x)) -> (zextload x)
2920   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2921     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2922     EVT MemVT = LN0->getMemoryVT();
2923     // If we zero all the possible extended bits, then we can turn this into
2924     // a zextload if we are running before legalize or the operation is legal.
2925     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2926     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2927                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2928         ((!LegalOperations && !LN0->isVolatile()) ||
2929          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2930       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2931                                        LN0->getChain(), LN0->getBasePtr(),
2932                                        MemVT, LN0->getMemOperand());
2933       AddToWorklist(N);
2934       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2935       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2936     }
2937   }
2938   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2939   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2940       N0.hasOneUse()) {
2941     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2942     EVT MemVT = LN0->getMemoryVT();
2943     // If we zero all the possible extended bits, then we can turn this into
2944     // a zextload if we are running before legalize or the operation is legal.
2945     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2946     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2947                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2948         ((!LegalOperations && !LN0->isVolatile()) ||
2949          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2950       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2951                                        LN0->getChain(), LN0->getBasePtr(),
2952                                        MemVT, LN0->getMemOperand());
2953       AddToWorklist(N);
2954       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2955       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2956     }
2957   }
2958
2959   // fold (and (load x), 255) -> (zextload x, i8)
2960   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2961   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2962   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2963               (N0.getOpcode() == ISD::ANY_EXTEND &&
2964                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2965     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2966     LoadSDNode *LN0 = HasAnyExt
2967       ? cast<LoadSDNode>(N0.getOperand(0))
2968       : cast<LoadSDNode>(N0);
2969     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2970         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2971       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2972       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2973         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2974         EVT LoadedVT = LN0->getMemoryVT();
2975
2976         if (ExtVT == LoadedVT &&
2977             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2978           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2979
2980           SDValue NewLoad =
2981             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2982                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2983                            LN0->getMemOperand());
2984           AddToWorklist(N);
2985           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2986           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2987         }
2988
2989         // Do not change the width of a volatile load.
2990         // Do not generate loads of non-round integer types since these can
2991         // be expensive (and would be wrong if the type is not byte sized).
2992         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2993             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2994           EVT PtrType = LN0->getOperand(1).getValueType();
2995
2996           unsigned Alignment = LN0->getAlignment();
2997           SDValue NewPtr = LN0->getBasePtr();
2998
2999           // For big endian targets, we need to add an offset to the pointer
3000           // to load the correct bytes.  For little endian systems, we merely
3001           // need to read fewer bytes from the same pointer.
3002           if (TLI.isBigEndian()) {
3003             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3004             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3005             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3006             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3007                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3008             Alignment = MinAlign(Alignment, PtrOff);
3009           }
3010
3011           AddToWorklist(NewPtr.getNode());
3012
3013           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3014           SDValue Load =
3015             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3016                            LN0->getChain(), NewPtr,
3017                            LN0->getPointerInfo(),
3018                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3019                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3020           AddToWorklist(N);
3021           CombineTo(LN0, Load, Load.getValue(1));
3022           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3023         }
3024       }
3025     }
3026   }
3027
3028   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3029       VT.getSizeInBits() <= 64) {
3030     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3031       APInt ADDC = ADDI->getAPIntValue();
3032       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3033         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3034         // immediate for an add, but it is legal if its top c2 bits are set,
3035         // transform the ADD so the immediate doesn't need to be materialized
3036         // in a register.
3037         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3038           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3039                                              SRLI->getZExtValue());
3040           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3041             ADDC |= Mask;
3042             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3043               SDValue NewAdd =
3044                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3045                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3046               CombineTo(N0.getNode(), NewAdd);
3047               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3048             }
3049           }
3050         }
3051       }
3052     }
3053   }
3054
3055   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3056   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3057     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3058                                        N0.getOperand(1), false);
3059     if (BSwap.getNode())
3060       return BSwap;
3061   }
3062
3063   return SDValue();
3064 }
3065
3066 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3067 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3068                                         bool DemandHighBits) {
3069   if (!LegalOperations)
3070     return SDValue();
3071
3072   EVT VT = N->getValueType(0);
3073   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3074     return SDValue();
3075   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3076     return SDValue();
3077
3078   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3079   bool LookPassAnd0 = false;
3080   bool LookPassAnd1 = false;
3081   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3082       std::swap(N0, N1);
3083   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3084       std::swap(N0, N1);
3085   if (N0.getOpcode() == ISD::AND) {
3086     if (!N0.getNode()->hasOneUse())
3087       return SDValue();
3088     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3089     if (!N01C || N01C->getZExtValue() != 0xFF00)
3090       return SDValue();
3091     N0 = N0.getOperand(0);
3092     LookPassAnd0 = true;
3093   }
3094
3095   if (N1.getOpcode() == ISD::AND) {
3096     if (!N1.getNode()->hasOneUse())
3097       return SDValue();
3098     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3099     if (!N11C || N11C->getZExtValue() != 0xFF)
3100       return SDValue();
3101     N1 = N1.getOperand(0);
3102     LookPassAnd1 = true;
3103   }
3104
3105   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3106     std::swap(N0, N1);
3107   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3108     return SDValue();
3109   if (!N0.getNode()->hasOneUse() ||
3110       !N1.getNode()->hasOneUse())
3111     return SDValue();
3112
3113   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3115   if (!N01C || !N11C)
3116     return SDValue();
3117   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3118     return SDValue();
3119
3120   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3121   SDValue N00 = N0->getOperand(0);
3122   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3123     if (!N00.getNode()->hasOneUse())
3124       return SDValue();
3125     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3126     if (!N001C || N001C->getZExtValue() != 0xFF)
3127       return SDValue();
3128     N00 = N00.getOperand(0);
3129     LookPassAnd0 = true;
3130   }
3131
3132   SDValue N10 = N1->getOperand(0);
3133   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3134     if (!N10.getNode()->hasOneUse())
3135       return SDValue();
3136     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3137     if (!N101C || N101C->getZExtValue() != 0xFF00)
3138       return SDValue();
3139     N10 = N10.getOperand(0);
3140     LookPassAnd1 = true;
3141   }
3142
3143   if (N00 != N10)
3144     return SDValue();
3145
3146   // Make sure everything beyond the low halfword gets set to zero since the SRL
3147   // 16 will clear the top bits.
3148   unsigned OpSizeInBits = VT.getSizeInBits();
3149   if (DemandHighBits && OpSizeInBits > 16) {
3150     // If the left-shift isn't masked out then the only way this is a bswap is
3151     // if all bits beyond the low 8 are 0. In that case the entire pattern
3152     // reduces to a left shift anyway: leave it for other parts of the combiner.
3153     if (!LookPassAnd0)
3154       return SDValue();
3155
3156     // However, if the right shift isn't masked out then it might be because
3157     // it's not needed. See if we can spot that too.
3158     if (!LookPassAnd1 &&
3159         !DAG.MaskedValueIsZero(
3160             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3161       return SDValue();
3162   }
3163
3164   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3165   if (OpSizeInBits > 16)
3166     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3167                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3168   return Res;
3169 }
3170
3171 /// Return true if the specified node is an element that makes up a 32-bit
3172 /// packed halfword byteswap.
3173 /// ((x & 0x000000ff) << 8) |
3174 /// ((x & 0x0000ff00) >> 8) |
3175 /// ((x & 0x00ff0000) << 8) |
3176 /// ((x & 0xff000000) >> 8)
3177 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3178   if (!N.getNode()->hasOneUse())
3179     return false;
3180
3181   unsigned Opc = N.getOpcode();
3182   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3183     return false;
3184
3185   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3186   if (!N1C)
3187     return false;
3188
3189   unsigned Num;
3190   switch (N1C->getZExtValue()) {
3191   default:
3192     return false;
3193   case 0xFF:       Num = 0; break;
3194   case 0xFF00:     Num = 1; break;
3195   case 0xFF0000:   Num = 2; break;
3196   case 0xFF000000: Num = 3; break;
3197   }
3198
3199   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3200   SDValue N0 = N.getOperand(0);
3201   if (Opc == ISD::AND) {
3202     if (Num == 0 || Num == 2) {
3203       // (x >> 8) & 0xff
3204       // (x >> 8) & 0xff0000
3205       if (N0.getOpcode() != ISD::SRL)
3206         return false;
3207       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3208       if (!C || C->getZExtValue() != 8)
3209         return false;
3210     } else {
3211       // (x << 8) & 0xff00
3212       // (x << 8) & 0xff000000
3213       if (N0.getOpcode() != ISD::SHL)
3214         return false;
3215       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3216       if (!C || C->getZExtValue() != 8)
3217         return false;
3218     }
3219   } else if (Opc == ISD::SHL) {
3220     // (x & 0xff) << 8
3221     // (x & 0xff0000) << 8
3222     if (Num != 0 && Num != 2)
3223       return false;
3224     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3225     if (!C || C->getZExtValue() != 8)
3226       return false;
3227   } else { // Opc == ISD::SRL
3228     // (x & 0xff00) >> 8
3229     // (x & 0xff000000) >> 8
3230     if (Num != 1 && Num != 3)
3231       return false;
3232     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3233     if (!C || C->getZExtValue() != 8)
3234       return false;
3235   }
3236
3237   if (Parts[Num])
3238     return false;
3239
3240   Parts[Num] = N0.getOperand(0).getNode();
3241   return true;
3242 }
3243
3244 /// Match a 32-bit packed halfword bswap. That is
3245 /// ((x & 0x000000ff) << 8) |
3246 /// ((x & 0x0000ff00) >> 8) |
3247 /// ((x & 0x00ff0000) << 8) |
3248 /// ((x & 0xff000000) >> 8)
3249 /// => (rotl (bswap x), 16)
3250 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3251   if (!LegalOperations)
3252     return SDValue();
3253
3254   EVT VT = N->getValueType(0);
3255   if (VT != MVT::i32)
3256     return SDValue();
3257   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3258     return SDValue();
3259
3260   // Look for either
3261   // (or (or (and), (and)), (or (and), (and)))
3262   // (or (or (or (and), (and)), (and)), (and))
3263   if (N0.getOpcode() != ISD::OR)
3264     return SDValue();
3265   SDValue N00 = N0.getOperand(0);
3266   SDValue N01 = N0.getOperand(1);
3267   SDNode *Parts[4] = {};
3268
3269   if (N1.getOpcode() == ISD::OR &&
3270       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3271     // (or (or (and), (and)), (or (and), (and)))
3272     SDValue N000 = N00.getOperand(0);
3273     if (!isBSwapHWordElement(N000, Parts))
3274       return SDValue();
3275
3276     SDValue N001 = N00.getOperand(1);
3277     if (!isBSwapHWordElement(N001, Parts))
3278       return SDValue();
3279     SDValue N010 = N01.getOperand(0);
3280     if (!isBSwapHWordElement(N010, Parts))
3281       return SDValue();
3282     SDValue N011 = N01.getOperand(1);
3283     if (!isBSwapHWordElement(N011, Parts))
3284       return SDValue();
3285   } else {
3286     // (or (or (or (and), (and)), (and)), (and))
3287     if (!isBSwapHWordElement(N1, Parts))
3288       return SDValue();
3289     if (!isBSwapHWordElement(N01, Parts))
3290       return SDValue();
3291     if (N00.getOpcode() != ISD::OR)
3292       return SDValue();
3293     SDValue N000 = N00.getOperand(0);
3294     if (!isBSwapHWordElement(N000, Parts))
3295       return SDValue();
3296     SDValue N001 = N00.getOperand(1);
3297     if (!isBSwapHWordElement(N001, Parts))
3298       return SDValue();
3299   }
3300
3301   // Make sure the parts are all coming from the same node.
3302   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3303     return SDValue();
3304
3305   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3306                               SDValue(Parts[0],0));
3307
3308   // Result of the bswap should be rotated by 16. If it's not legal, then
3309   // do  (x << 16) | (x >> 16).
3310   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3311   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3312     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3313   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3314     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3315   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3316                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3317                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3318 }
3319
3320 SDValue DAGCombiner::visitOR(SDNode *N) {
3321   SDValue N0 = N->getOperand(0);
3322   SDValue N1 = N->getOperand(1);
3323   SDValue LL, LR, RL, RR, CC0, CC1;
3324   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3325   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3326   EVT VT = N1.getValueType();
3327
3328   // fold vector ops
3329   if (VT.isVector()) {
3330     SDValue FoldedVOp = SimplifyVBinOp(N);
3331     if (FoldedVOp.getNode()) return FoldedVOp;
3332
3333     // fold (or x, 0) -> x, vector edition
3334     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3335       return N1;
3336     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3337       return N0;
3338
3339     // fold (or x, -1) -> -1, vector edition
3340     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3341       // do not return N0, because undef node may exist in N0
3342       return DAG.getConstant(
3343           APInt::getAllOnesValue(
3344               N0.getValueType().getScalarType().getSizeInBits()),
3345           N0.getValueType());
3346     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3347       // do not return N1, because undef node may exist in N1
3348       return DAG.getConstant(
3349           APInt::getAllOnesValue(
3350               N1.getValueType().getScalarType().getSizeInBits()),
3351           N1.getValueType());
3352
3353     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3354     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3355     // Do this only if the resulting shuffle is legal.
3356     if (isa<ShuffleVectorSDNode>(N0) &&
3357         isa<ShuffleVectorSDNode>(N1) &&
3358         // Avoid folding a node with illegal type.
3359         TLI.isTypeLegal(VT) &&
3360         N0->getOperand(1) == N1->getOperand(1) &&
3361         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3362       bool CanFold = true;
3363       unsigned NumElts = VT.getVectorNumElements();
3364       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3365       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3366       // We construct two shuffle masks:
3367       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3368       // and N1 as the second operand.
3369       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3370       // and N0 as the second operand.
3371       // We do this because OR is commutable and therefore there might be
3372       // two ways to fold this node into a shuffle.
3373       SmallVector<int,4> Mask1;
3374       SmallVector<int,4> Mask2;
3375
3376       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3377         int M0 = SV0->getMaskElt(i);
3378         int M1 = SV1->getMaskElt(i);
3379
3380         // Both shuffle indexes are undef. Propagate Undef.
3381         if (M0 < 0 && M1 < 0) {
3382           Mask1.push_back(M0);
3383           Mask2.push_back(M0);
3384           continue;
3385         }
3386
3387         if (M0 < 0 || M1 < 0 ||
3388             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3389             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3390           CanFold = false;
3391           break;
3392         }
3393
3394         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3395         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3396       }
3397
3398       if (CanFold) {
3399         // Fold this sequence only if the resulting shuffle is 'legal'.
3400         if (TLI.isShuffleMaskLegal(Mask1, VT))
3401           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3402                                       N1->getOperand(0), &Mask1[0]);
3403         if (TLI.isShuffleMaskLegal(Mask2, VT))
3404           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3405                                       N0->getOperand(0), &Mask2[0]);
3406       }
3407     }
3408   }
3409
3410   // fold (or x, undef) -> -1
3411   if (!LegalOperations &&
3412       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3413     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3414     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3415   }
3416   // fold (or c1, c2) -> c1|c2
3417   if (N0C && N1C)
3418     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3419   // canonicalize constant to RHS
3420   if (N0C && !N1C)
3421     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3422   // fold (or x, 0) -> x
3423   if (N1C && N1C->isNullValue())
3424     return N0;
3425   // fold (or x, -1) -> -1
3426   if (N1C && N1C->isAllOnesValue())
3427     return N1;
3428   // fold (or x, c) -> c iff (x & ~c) == 0
3429   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3430     return N1;
3431
3432   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3433   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3434   if (BSwap.getNode())
3435     return BSwap;
3436   BSwap = MatchBSwapHWordLow(N, N0, N1);
3437   if (BSwap.getNode())
3438     return BSwap;
3439
3440   // reassociate or
3441   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3442   if (ROR.getNode())
3443     return ROR;
3444   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3445   // iff (c1 & c2) == 0.
3446   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3447              isa<ConstantSDNode>(N0.getOperand(1))) {
3448     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3449     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3450       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3451       if (!COR.getNode())
3452         return SDValue();
3453       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3454                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3455                                      N0.getOperand(0), N1), COR);
3456     }
3457   }
3458   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3459   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3460     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3461     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3462
3463     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3464         LL.getValueType().isInteger()) {
3465       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3466       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3467       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3468           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3469         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3470                                      LR.getValueType(), LL, RL);
3471         AddToWorklist(ORNode.getNode());
3472         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3473       }
3474       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3475       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3476       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3477           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3478         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3479                                       LR.getValueType(), LL, RL);
3480         AddToWorklist(ANDNode.getNode());
3481         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3482       }
3483     }
3484     // canonicalize equivalent to ll == rl
3485     if (LL == RR && LR == RL) {
3486       Op1 = ISD::getSetCCSwappedOperands(Op1);
3487       std::swap(RL, RR);
3488     }
3489     if (LL == RL && LR == RR) {
3490       bool isInteger = LL.getValueType().isInteger();
3491       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3492       if (Result != ISD::SETCC_INVALID &&
3493           (!LegalOperations ||
3494            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3495             TLI.isOperationLegal(ISD::SETCC,
3496               getSetCCResultType(N0.getValueType())))))
3497         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3498                             LL, LR, Result);
3499     }
3500   }
3501
3502   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3503   if (N0.getOpcode() == N1.getOpcode()) {
3504     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3505     if (Tmp.getNode()) return Tmp;
3506   }
3507
3508   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3509   if (N0.getOpcode() == ISD::AND &&
3510       N1.getOpcode() == ISD::AND &&
3511       N0.getOperand(1).getOpcode() == ISD::Constant &&
3512       N1.getOperand(1).getOpcode() == ISD::Constant &&
3513       // Don't increase # computations.
3514       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3515     // We can only do this xform if we know that bits from X that are set in C2
3516     // but not in C1 are already zero.  Likewise for Y.
3517     const APInt &LHSMask =
3518       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3519     const APInt &RHSMask =
3520       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3521
3522     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3523         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3524       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3525                               N0.getOperand(0), N1.getOperand(0));
3526       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3527                          DAG.getConstant(LHSMask | RHSMask, VT));
3528     }
3529   }
3530
3531   // See if this is some rotate idiom.
3532   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3533     return SDValue(Rot, 0);
3534
3535   // Simplify the operands using demanded-bits information.
3536   if (!VT.isVector() &&
3537       SimplifyDemandedBits(SDValue(N, 0)))
3538     return SDValue(N, 0);
3539
3540   return SDValue();
3541 }
3542
3543 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3544 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3545   if (Op.getOpcode() == ISD::AND) {
3546     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3547       Mask = Op.getOperand(1);
3548       Op = Op.getOperand(0);
3549     } else {
3550       return false;
3551     }
3552   }
3553
3554   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3555     Shift = Op;
3556     return true;
3557   }
3558
3559   return false;
3560 }
3561
3562 // Return true if we can prove that, whenever Neg and Pos are both in the
3563 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3564 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3565 //
3566 //     (or (shift1 X, Neg), (shift2 X, Pos))
3567 //
3568 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3569 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3570 // to consider shift amounts with defined behavior.
3571 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3572   // If OpSize is a power of 2 then:
3573   //
3574   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3575   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3576   //
3577   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3578   // for the stronger condition:
3579   //
3580   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3581   //
3582   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3583   // we can just replace Neg with Neg' for the rest of the function.
3584   //
3585   // In other cases we check for the even stronger condition:
3586   //
3587   //     Neg == OpSize - Pos                                    [B]
3588   //
3589   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3590   // behavior if Pos == 0 (and consequently Neg == OpSize).
3591   //
3592   // We could actually use [A] whenever OpSize is a power of 2, but the
3593   // only extra cases that it would match are those uninteresting ones
3594   // where Neg and Pos are never in range at the same time.  E.g. for
3595   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3596   // as well as (sub 32, Pos), but:
3597   //
3598   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3599   //
3600   // always invokes undefined behavior for 32-bit X.
3601   //
3602   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3603   unsigned MaskLoBits = 0;
3604   if (Neg.getOpcode() == ISD::AND &&
3605       isPowerOf2_64(OpSize) &&
3606       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3607       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3608     Neg = Neg.getOperand(0);
3609     MaskLoBits = Log2_64(OpSize);
3610   }
3611
3612   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3613   if (Neg.getOpcode() != ISD::SUB)
3614     return 0;
3615   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3616   if (!NegC)
3617     return 0;
3618   SDValue NegOp1 = Neg.getOperand(1);
3619
3620   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3621   // Pos'.  The truncation is redundant for the purpose of the equality.
3622   if (MaskLoBits &&
3623       Pos.getOpcode() == ISD::AND &&
3624       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3625       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3626     Pos = Pos.getOperand(0);
3627
3628   // The condition we need is now:
3629   //
3630   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3631   //
3632   // If NegOp1 == Pos then we need:
3633   //
3634   //              OpSize & Mask == NegC & Mask
3635   //
3636   // (because "x & Mask" is a truncation and distributes through subtraction).
3637   APInt Width;
3638   if (Pos == NegOp1)
3639     Width = NegC->getAPIntValue();
3640   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3641   // Then the condition we want to prove becomes:
3642   //
3643   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3644   //
3645   // which, again because "x & Mask" is a truncation, becomes:
3646   //
3647   //                NegC & Mask == (OpSize - PosC) & Mask
3648   //              OpSize & Mask == (NegC + PosC) & Mask
3649   else if (Pos.getOpcode() == ISD::ADD &&
3650            Pos.getOperand(0) == NegOp1 &&
3651            Pos.getOperand(1).getOpcode() == ISD::Constant)
3652     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3653              NegC->getAPIntValue());
3654   else
3655     return false;
3656
3657   // Now we just need to check that OpSize & Mask == Width & Mask.
3658   if (MaskLoBits)
3659     // Opsize & Mask is 0 since Mask is Opsize - 1.
3660     return Width.getLoBits(MaskLoBits) == 0;
3661   return Width == OpSize;
3662 }
3663
3664 // A subroutine of MatchRotate used once we have found an OR of two opposite
3665 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3666 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3667 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3668 // Neg with outer conversions stripped away.
3669 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3670                                        SDValue Neg, SDValue InnerPos,
3671                                        SDValue InnerNeg, unsigned PosOpcode,
3672                                        unsigned NegOpcode, SDLoc DL) {
3673   // fold (or (shl x, (*ext y)),
3674   //          (srl x, (*ext (sub 32, y)))) ->
3675   //   (rotl x, y) or (rotr x, (sub 32, y))
3676   //
3677   // fold (or (shl x, (*ext (sub 32, y))),
3678   //          (srl x, (*ext y))) ->
3679   //   (rotr x, y) or (rotl x, (sub 32, y))
3680   EVT VT = Shifted.getValueType();
3681   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3682     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3683     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3684                        HasPos ? Pos : Neg).getNode();
3685   }
3686
3687   return nullptr;
3688 }
3689
3690 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3691 // idioms for rotate, and if the target supports rotation instructions, generate
3692 // a rot[lr].
3693 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3694   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3695   EVT VT = LHS.getValueType();
3696   if (!TLI.isTypeLegal(VT)) return nullptr;
3697
3698   // The target must have at least one rotate flavor.
3699   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3700   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3701   if (!HasROTL && !HasROTR) return nullptr;
3702
3703   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3704   SDValue LHSShift;   // The shift.
3705   SDValue LHSMask;    // AND value if any.
3706   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3707     return nullptr; // Not part of a rotate.
3708
3709   SDValue RHSShift;   // The shift.
3710   SDValue RHSMask;    // AND value if any.
3711   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3712     return nullptr; // Not part of a rotate.
3713
3714   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3715     return nullptr;   // Not shifting the same value.
3716
3717   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3718     return nullptr;   // Shifts must disagree.
3719
3720   // Canonicalize shl to left side in a shl/srl pair.
3721   if (RHSShift.getOpcode() == ISD::SHL) {
3722     std::swap(LHS, RHS);
3723     std::swap(LHSShift, RHSShift);
3724     std::swap(LHSMask , RHSMask );
3725   }
3726
3727   unsigned OpSizeInBits = VT.getSizeInBits();
3728   SDValue LHSShiftArg = LHSShift.getOperand(0);
3729   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3730   SDValue RHSShiftArg = RHSShift.getOperand(0);
3731   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3732
3733   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3734   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3735   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3736       RHSShiftAmt.getOpcode() == ISD::Constant) {
3737     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3738     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3739     if ((LShVal + RShVal) != OpSizeInBits)
3740       return nullptr;
3741
3742     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3743                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3744
3745     // If there is an AND of either shifted operand, apply it to the result.
3746     if (LHSMask.getNode() || RHSMask.getNode()) {
3747       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3748
3749       if (LHSMask.getNode()) {
3750         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3751         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3752       }
3753       if (RHSMask.getNode()) {
3754         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3755         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3756       }
3757
3758       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3759     }
3760
3761     return Rot.getNode();
3762   }
3763
3764   // If there is a mask here, and we have a variable shift, we can't be sure
3765   // that we're masking out the right stuff.
3766   if (LHSMask.getNode() || RHSMask.getNode())
3767     return nullptr;
3768
3769   // If the shift amount is sign/zext/any-extended just peel it off.
3770   SDValue LExtOp0 = LHSShiftAmt;
3771   SDValue RExtOp0 = RHSShiftAmt;
3772   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3773        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3774        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3775        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3776       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3777        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3778        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3779        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3780     LExtOp0 = LHSShiftAmt.getOperand(0);
3781     RExtOp0 = RHSShiftAmt.getOperand(0);
3782   }
3783
3784   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3785                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3786   if (TryL)
3787     return TryL;
3788
3789   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3790                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3791   if (TryR)
3792     return TryR;
3793
3794   return nullptr;
3795 }
3796
3797 SDValue DAGCombiner::visitXOR(SDNode *N) {
3798   SDValue N0 = N->getOperand(0);
3799   SDValue N1 = N->getOperand(1);
3800   SDValue LHS, RHS, CC;
3801   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3802   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3803   EVT VT = N0.getValueType();
3804
3805   // fold vector ops
3806   if (VT.isVector()) {
3807     SDValue FoldedVOp = SimplifyVBinOp(N);
3808     if (FoldedVOp.getNode()) return FoldedVOp;
3809
3810     // fold (xor x, 0) -> x, vector edition
3811     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3812       return N1;
3813     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3814       return N0;
3815   }
3816
3817   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3818   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3819     return DAG.getConstant(0, VT);
3820   // fold (xor x, undef) -> undef
3821   if (N0.getOpcode() == ISD::UNDEF)
3822     return N0;
3823   if (N1.getOpcode() == ISD::UNDEF)
3824     return N1;
3825   // fold (xor c1, c2) -> c1^c2
3826   if (N0C && N1C)
3827     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3828   // canonicalize constant to RHS
3829   if (N0C && !N1C)
3830     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3831   // fold (xor x, 0) -> x
3832   if (N1C && N1C->isNullValue())
3833     return N0;
3834   // reassociate xor
3835   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3836   if (RXOR.getNode())
3837     return RXOR;
3838
3839   // fold !(x cc y) -> (x !cc y)
3840   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3841     bool isInt = LHS.getValueType().isInteger();
3842     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3843                                                isInt);
3844
3845     if (!LegalOperations ||
3846         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3847       switch (N0.getOpcode()) {
3848       default:
3849         llvm_unreachable("Unhandled SetCC Equivalent!");
3850       case ISD::SETCC:
3851         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3852       case ISD::SELECT_CC:
3853         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3854                                N0.getOperand(3), NotCC);
3855       }
3856     }
3857   }
3858
3859   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3860   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3861       N0.getNode()->hasOneUse() &&
3862       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3863     SDValue V = N0.getOperand(0);
3864     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3865                     DAG.getConstant(1, V.getValueType()));
3866     AddToWorklist(V.getNode());
3867     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3868   }
3869
3870   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3871   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3872       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3873     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3874     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3875       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3876       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3877       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3878       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3879       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3880     }
3881   }
3882   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3883   if (N1C && N1C->isAllOnesValue() &&
3884       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3885     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3886     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3887       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3888       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3889       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3890       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3891       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3892     }
3893   }
3894   // fold (xor (and x, y), y) -> (and (not x), y)
3895   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3896       N0->getOperand(1) == N1) {
3897     SDValue X = N0->getOperand(0);
3898     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3899     AddToWorklist(NotX.getNode());
3900     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3901   }
3902   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3903   if (N1C && N0.getOpcode() == ISD::XOR) {
3904     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3905     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3906     if (N00C)
3907       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3908                          DAG.getConstant(N1C->getAPIntValue() ^
3909                                          N00C->getAPIntValue(), VT));
3910     if (N01C)
3911       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3912                          DAG.getConstant(N1C->getAPIntValue() ^
3913                                          N01C->getAPIntValue(), VT));
3914   }
3915   // fold (xor x, x) -> 0
3916   if (N0 == N1)
3917     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3918
3919   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3920   if (N0.getOpcode() == N1.getOpcode()) {
3921     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3922     if (Tmp.getNode()) return Tmp;
3923   }
3924
3925   // Simplify the expression using non-local knowledge.
3926   if (!VT.isVector() &&
3927       SimplifyDemandedBits(SDValue(N, 0)))
3928     return SDValue(N, 0);
3929
3930   return SDValue();
3931 }
3932
3933 /// Handle transforms common to the three shifts, when the shift amount is a
3934 /// constant.
3935 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3936   // We can't and shouldn't fold opaque constants.
3937   if (Amt->isOpaque())
3938     return SDValue();
3939
3940   SDNode *LHS = N->getOperand(0).getNode();
3941   if (!LHS->hasOneUse()) return SDValue();
3942
3943   // We want to pull some binops through shifts, so that we have (and (shift))
3944   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3945   // thing happens with address calculations, so it's important to canonicalize
3946   // it.
3947   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3948
3949   switch (LHS->getOpcode()) {
3950   default: return SDValue();
3951   case ISD::OR:
3952   case ISD::XOR:
3953     HighBitSet = false; // We can only transform sra if the high bit is clear.
3954     break;
3955   case ISD::AND:
3956     HighBitSet = true;  // We can only transform sra if the high bit is set.
3957     break;
3958   case ISD::ADD:
3959     if (N->getOpcode() != ISD::SHL)
3960       return SDValue(); // only shl(add) not sr[al](add).
3961     HighBitSet = false; // We can only transform sra if the high bit is clear.
3962     break;
3963   }
3964
3965   // We require the RHS of the binop to be a constant and not opaque as well.
3966   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3967   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3968
3969   // FIXME: disable this unless the input to the binop is a shift by a constant.
3970   // If it is not a shift, it pessimizes some common cases like:
3971   //
3972   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3973   //    int bar(int *X, int i) { return X[i & 255]; }
3974   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3975   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3976        BinOpLHSVal->getOpcode() != ISD::SRA &&
3977        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3978       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3979     return SDValue();
3980
3981   EVT VT = N->getValueType(0);
3982
3983   // If this is a signed shift right, and the high bit is modified by the
3984   // logical operation, do not perform the transformation. The highBitSet
3985   // boolean indicates the value of the high bit of the constant which would
3986   // cause it to be modified for this operation.
3987   if (N->getOpcode() == ISD::SRA) {
3988     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3989     if (BinOpRHSSignSet != HighBitSet)
3990       return SDValue();
3991   }
3992
3993   if (!TLI.isDesirableToCommuteWithShift(LHS))
3994     return SDValue();
3995
3996   // Fold the constants, shifting the binop RHS by the shift amount.
3997   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3998                                N->getValueType(0),
3999                                LHS->getOperand(1), N->getOperand(1));
4000   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4001
4002   // Create the new shift.
4003   SDValue NewShift = DAG.getNode(N->getOpcode(),
4004                                  SDLoc(LHS->getOperand(0)),
4005                                  VT, LHS->getOperand(0), N->getOperand(1));
4006
4007   // Create the new binop.
4008   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4009 }
4010
4011 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4012   assert(N->getOpcode() == ISD::TRUNCATE);
4013   assert(N->getOperand(0).getOpcode() == ISD::AND);
4014
4015   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4016   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4017     SDValue N01 = N->getOperand(0).getOperand(1);
4018
4019     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4020       EVT TruncVT = N->getValueType(0);
4021       SDValue N00 = N->getOperand(0).getOperand(0);
4022       APInt TruncC = N01C->getAPIntValue();
4023       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4024
4025       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4026                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4027                          DAG.getConstant(TruncC, TruncVT));
4028     }
4029   }
4030
4031   return SDValue();
4032 }
4033
4034 SDValue DAGCombiner::visitRotate(SDNode *N) {
4035   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4036   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4037       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4038     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4039     if (NewOp1.getNode())
4040       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4041                          N->getOperand(0), NewOp1);
4042   }
4043   return SDValue();
4044 }
4045
4046 SDValue DAGCombiner::visitSHL(SDNode *N) {
4047   SDValue N0 = N->getOperand(0);
4048   SDValue N1 = N->getOperand(1);
4049   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4050   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4051   EVT VT = N0.getValueType();
4052   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4053
4054   // fold vector ops
4055   if (VT.isVector()) {
4056     SDValue FoldedVOp = SimplifyVBinOp(N);
4057     if (FoldedVOp.getNode()) return FoldedVOp;
4058
4059     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4060     // If setcc produces all-one true value then:
4061     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4062     if (N1CV && N1CV->isConstant()) {
4063       if (N0.getOpcode() == ISD::AND) {
4064         SDValue N00 = N0->getOperand(0);
4065         SDValue N01 = N0->getOperand(1);
4066         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4067
4068         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4069             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4070                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4071           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4072           if (C.getNode())
4073             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4074         }
4075       } else {
4076         N1C = isConstOrConstSplat(N1);
4077       }
4078     }
4079   }
4080
4081   // fold (shl c1, c2) -> c1<<c2
4082   if (N0C && N1C)
4083     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4084   // fold (shl 0, x) -> 0
4085   if (N0C && N0C->isNullValue())
4086     return N0;
4087   // fold (shl x, c >= size(x)) -> undef
4088   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4089     return DAG.getUNDEF(VT);
4090   // fold (shl x, 0) -> x
4091   if (N1C && N1C->isNullValue())
4092     return N0;
4093   // fold (shl undef, x) -> 0
4094   if (N0.getOpcode() == ISD::UNDEF)
4095     return DAG.getConstant(0, VT);
4096   // if (shl x, c) is known to be zero, return 0
4097   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4098                             APInt::getAllOnesValue(OpSizeInBits)))
4099     return DAG.getConstant(0, VT);
4100   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4101   if (N1.getOpcode() == ISD::TRUNCATE &&
4102       N1.getOperand(0).getOpcode() == ISD::AND) {
4103     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4104     if (NewOp1.getNode())
4105       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4106   }
4107
4108   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4109     return SDValue(N, 0);
4110
4111   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4112   if (N1C && N0.getOpcode() == ISD::SHL) {
4113     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4114       uint64_t c1 = N0C1->getZExtValue();
4115       uint64_t c2 = N1C->getZExtValue();
4116       if (c1 + c2 >= OpSizeInBits)
4117         return DAG.getConstant(0, VT);
4118       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4119                          DAG.getConstant(c1 + c2, N1.getValueType()));
4120     }
4121   }
4122
4123   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4124   // For this to be valid, the second form must not preserve any of the bits
4125   // that are shifted out by the inner shift in the first form.  This means
4126   // the outer shift size must be >= the number of bits added by the ext.
4127   // As a corollary, we don't care what kind of ext it is.
4128   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4129               N0.getOpcode() == ISD::ANY_EXTEND ||
4130               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4131       N0.getOperand(0).getOpcode() == ISD::SHL) {
4132     SDValue N0Op0 = N0.getOperand(0);
4133     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4134       uint64_t c1 = N0Op0C1->getZExtValue();
4135       uint64_t c2 = N1C->getZExtValue();
4136       EVT InnerShiftVT = N0Op0.getValueType();
4137       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4138       if (c2 >= OpSizeInBits - InnerShiftSize) {
4139         if (c1 + c2 >= OpSizeInBits)
4140           return DAG.getConstant(0, VT);
4141         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4142                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4143                                        N0Op0->getOperand(0)),
4144                            DAG.getConstant(c1 + c2, N1.getValueType()));
4145       }
4146     }
4147   }
4148
4149   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4150   // Only fold this if the inner zext has no other uses to avoid increasing
4151   // the total number of instructions.
4152   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4153       N0.getOperand(0).getOpcode() == ISD::SRL) {
4154     SDValue N0Op0 = N0.getOperand(0);
4155     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4156       uint64_t c1 = N0Op0C1->getZExtValue();
4157       if (c1 < VT.getScalarSizeInBits()) {
4158         uint64_t c2 = N1C->getZExtValue();
4159         if (c1 == c2) {
4160           SDValue NewOp0 = N0.getOperand(0);
4161           EVT CountVT = NewOp0.getOperand(1).getValueType();
4162           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4163                                        NewOp0, DAG.getConstant(c2, CountVT));
4164           AddToWorklist(NewSHL.getNode());
4165           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4166         }
4167       }
4168     }
4169   }
4170
4171   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4172   //                               (and (srl x, (sub c1, c2), MASK)
4173   // Only fold this if the inner shift has no other uses -- if it does, folding
4174   // this will increase the total number of instructions.
4175   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4176     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4177       uint64_t c1 = N0C1->getZExtValue();
4178       if (c1 < OpSizeInBits) {
4179         uint64_t c2 = N1C->getZExtValue();
4180         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4181         SDValue Shift;
4182         if (c2 > c1) {
4183           Mask = Mask.shl(c2 - c1);
4184           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4185                               DAG.getConstant(c2 - c1, N1.getValueType()));
4186         } else {
4187           Mask = Mask.lshr(c1 - c2);
4188           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4189                               DAG.getConstant(c1 - c2, N1.getValueType()));
4190         }
4191         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4192                            DAG.getConstant(Mask, VT));
4193       }
4194     }
4195   }
4196   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4197   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4198     unsigned BitSize = VT.getScalarSizeInBits();
4199     SDValue HiBitsMask =
4200       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4201                                             BitSize - N1C->getZExtValue()), VT);
4202     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4203                        HiBitsMask);
4204   }
4205
4206   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4207   // Variant of version done on multiply, except mul by a power of 2 is turned
4208   // into a shift.
4209   APInt Val;
4210   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4211       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4212        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4213     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4214     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4215     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4216   }
4217
4218   if (N1C) {
4219     SDValue NewSHL = visitShiftByConstant(N, N1C);
4220     if (NewSHL.getNode())
4221       return NewSHL;
4222   }
4223
4224   return SDValue();
4225 }
4226
4227 SDValue DAGCombiner::visitSRA(SDNode *N) {
4228   SDValue N0 = N->getOperand(0);
4229   SDValue N1 = N->getOperand(1);
4230   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4231   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4232   EVT VT = N0.getValueType();
4233   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4234
4235   // fold vector ops
4236   if (VT.isVector()) {
4237     SDValue FoldedVOp = SimplifyVBinOp(N);
4238     if (FoldedVOp.getNode()) return FoldedVOp;
4239
4240     N1C = isConstOrConstSplat(N1);
4241   }
4242
4243   // fold (sra c1, c2) -> (sra c1, c2)
4244   if (N0C && N1C)
4245     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4246   // fold (sra 0, x) -> 0
4247   if (N0C && N0C->isNullValue())
4248     return N0;
4249   // fold (sra -1, x) -> -1
4250   if (N0C && N0C->isAllOnesValue())
4251     return N0;
4252   // fold (sra x, (setge c, size(x))) -> undef
4253   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4254     return DAG.getUNDEF(VT);
4255   // fold (sra x, 0) -> x
4256   if (N1C && N1C->isNullValue())
4257     return N0;
4258   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4259   // sext_inreg.
4260   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4261     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4262     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4263     if (VT.isVector())
4264       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4265                                ExtVT, VT.getVectorNumElements());
4266     if ((!LegalOperations ||
4267          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4268       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4269                          N0.getOperand(0), DAG.getValueType(ExtVT));
4270   }
4271
4272   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4273   if (N1C && N0.getOpcode() == ISD::SRA) {
4274     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4275       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4276       if (Sum >= OpSizeInBits)
4277         Sum = OpSizeInBits - 1;
4278       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4279                          DAG.getConstant(Sum, N1.getValueType()));
4280     }
4281   }
4282
4283   // fold (sra (shl X, m), (sub result_size, n))
4284   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4285   // result_size - n != m.
4286   // If truncate is free for the target sext(shl) is likely to result in better
4287   // code.
4288   if (N0.getOpcode() == ISD::SHL && N1C) {
4289     // Get the two constanst of the shifts, CN0 = m, CN = n.
4290     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4291     if (N01C) {
4292       LLVMContext &Ctx = *DAG.getContext();
4293       // Determine what the truncate's result bitsize and type would be.
4294       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4295
4296       if (VT.isVector())
4297         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4298
4299       // Determine the residual right-shift amount.
4300       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4301
4302       // If the shift is not a no-op (in which case this should be just a sign
4303       // extend already), the truncated to type is legal, sign_extend is legal
4304       // on that type, and the truncate to that type is both legal and free,
4305       // perform the transform.
4306       if ((ShiftAmt > 0) &&
4307           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4308           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4309           TLI.isTruncateFree(VT, TruncVT)) {
4310
4311           SDValue Amt = DAG.getConstant(ShiftAmt,
4312               getShiftAmountTy(N0.getOperand(0).getValueType()));
4313           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4314                                       N0.getOperand(0), Amt);
4315           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4316                                       Shift);
4317           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4318                              N->getValueType(0), Trunc);
4319       }
4320     }
4321   }
4322
4323   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4324   if (N1.getOpcode() == ISD::TRUNCATE &&
4325       N1.getOperand(0).getOpcode() == ISD::AND) {
4326     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4327     if (NewOp1.getNode())
4328       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4329   }
4330
4331   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4332   //      if c1 is equal to the number of bits the trunc removes
4333   if (N0.getOpcode() == ISD::TRUNCATE &&
4334       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4335        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4336       N0.getOperand(0).hasOneUse() &&
4337       N0.getOperand(0).getOperand(1).hasOneUse() &&
4338       N1C) {
4339     SDValue N0Op0 = N0.getOperand(0);
4340     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4341       unsigned LargeShiftVal = LargeShift->getZExtValue();
4342       EVT LargeVT = N0Op0.getValueType();
4343
4344       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4345         SDValue Amt =
4346           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4347                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4348         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4349                                   N0Op0.getOperand(0), Amt);
4350         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4351       }
4352     }
4353   }
4354
4355   // Simplify, based on bits shifted out of the LHS.
4356   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4357     return SDValue(N, 0);
4358
4359
4360   // If the sign bit is known to be zero, switch this to a SRL.
4361   if (DAG.SignBitIsZero(N0))
4362     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4363
4364   if (N1C) {
4365     SDValue NewSRA = visitShiftByConstant(N, N1C);
4366     if (NewSRA.getNode())
4367       return NewSRA;
4368   }
4369
4370   return SDValue();
4371 }
4372
4373 SDValue DAGCombiner::visitSRL(SDNode *N) {
4374   SDValue N0 = N->getOperand(0);
4375   SDValue N1 = N->getOperand(1);
4376   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4377   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4378   EVT VT = N0.getValueType();
4379   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4380
4381   // fold vector ops
4382   if (VT.isVector()) {
4383     SDValue FoldedVOp = SimplifyVBinOp(N);
4384     if (FoldedVOp.getNode()) return FoldedVOp;
4385
4386     N1C = isConstOrConstSplat(N1);
4387   }
4388
4389   // fold (srl c1, c2) -> c1 >>u c2
4390   if (N0C && N1C)
4391     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4392   // fold (srl 0, x) -> 0
4393   if (N0C && N0C->isNullValue())
4394     return N0;
4395   // fold (srl x, c >= size(x)) -> undef
4396   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4397     return DAG.getUNDEF(VT);
4398   // fold (srl x, 0) -> x
4399   if (N1C && N1C->isNullValue())
4400     return N0;
4401   // if (srl x, c) is known to be zero, return 0
4402   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4403                                    APInt::getAllOnesValue(OpSizeInBits)))
4404     return DAG.getConstant(0, VT);
4405
4406   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4407   if (N1C && N0.getOpcode() == ISD::SRL) {
4408     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4409       uint64_t c1 = N01C->getZExtValue();
4410       uint64_t c2 = N1C->getZExtValue();
4411       if (c1 + c2 >= OpSizeInBits)
4412         return DAG.getConstant(0, VT);
4413       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4414                          DAG.getConstant(c1 + c2, N1.getValueType()));
4415     }
4416   }
4417
4418   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4419   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4420       N0.getOperand(0).getOpcode() == ISD::SRL &&
4421       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4422     uint64_t c1 =
4423       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4424     uint64_t c2 = N1C->getZExtValue();
4425     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4426     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4427     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4428     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4429     if (c1 + OpSizeInBits == InnerShiftSize) {
4430       if (c1 + c2 >= InnerShiftSize)
4431         return DAG.getConstant(0, VT);
4432       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4433                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4434                                      N0.getOperand(0)->getOperand(0),
4435                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4436     }
4437   }
4438
4439   // fold (srl (shl x, c), c) -> (and x, cst2)
4440   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4441     unsigned BitSize = N0.getScalarValueSizeInBits();
4442     if (BitSize <= 64) {
4443       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4444       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4445                          DAG.getConstant(~0ULL >> ShAmt, VT));
4446     }
4447   }
4448
4449   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4450   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4451     // Shifting in all undef bits?
4452     EVT SmallVT = N0.getOperand(0).getValueType();
4453     unsigned BitSize = SmallVT.getScalarSizeInBits();
4454     if (N1C->getZExtValue() >= BitSize)
4455       return DAG.getUNDEF(VT);
4456
4457     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4458       uint64_t ShiftAmt = N1C->getZExtValue();
4459       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4460                                        N0.getOperand(0),
4461                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4462       AddToWorklist(SmallShift.getNode());
4463       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4464       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4465                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4466                          DAG.getConstant(Mask, VT));
4467     }
4468   }
4469
4470   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4471   // bit, which is unmodified by sra.
4472   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4473     if (N0.getOpcode() == ISD::SRA)
4474       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4475   }
4476
4477   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4478   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4479       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4480     APInt KnownZero, KnownOne;
4481     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4482
4483     // If any of the input bits are KnownOne, then the input couldn't be all
4484     // zeros, thus the result of the srl will always be zero.
4485     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4486
4487     // If all of the bits input the to ctlz node are known to be zero, then
4488     // the result of the ctlz is "32" and the result of the shift is one.
4489     APInt UnknownBits = ~KnownZero;
4490     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4491
4492     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4493     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4494       // Okay, we know that only that the single bit specified by UnknownBits
4495       // could be set on input to the CTLZ node. If this bit is set, the SRL
4496       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4497       // to an SRL/XOR pair, which is likely to simplify more.
4498       unsigned ShAmt = UnknownBits.countTrailingZeros();
4499       SDValue Op = N0.getOperand(0);
4500
4501       if (ShAmt) {
4502         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4503                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4504         AddToWorklist(Op.getNode());
4505       }
4506
4507       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4508                          Op, DAG.getConstant(1, VT));
4509     }
4510   }
4511
4512   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4513   if (N1.getOpcode() == ISD::TRUNCATE &&
4514       N1.getOperand(0).getOpcode() == ISD::AND) {
4515     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4516     if (NewOp1.getNode())
4517       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4518   }
4519
4520   // fold operands of srl based on knowledge that the low bits are not
4521   // demanded.
4522   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4523     return SDValue(N, 0);
4524
4525   if (N1C) {
4526     SDValue NewSRL = visitShiftByConstant(N, N1C);
4527     if (NewSRL.getNode())
4528       return NewSRL;
4529   }
4530
4531   // Attempt to convert a srl of a load into a narrower zero-extending load.
4532   SDValue NarrowLoad = ReduceLoadWidth(N);
4533   if (NarrowLoad.getNode())
4534     return NarrowLoad;
4535
4536   // Here is a common situation. We want to optimize:
4537   //
4538   //   %a = ...
4539   //   %b = and i32 %a, 2
4540   //   %c = srl i32 %b, 1
4541   //   brcond i32 %c ...
4542   //
4543   // into
4544   //
4545   //   %a = ...
4546   //   %b = and %a, 2
4547   //   %c = setcc eq %b, 0
4548   //   brcond %c ...
4549   //
4550   // However when after the source operand of SRL is optimized into AND, the SRL
4551   // itself may not be optimized further. Look for it and add the BRCOND into
4552   // the worklist.
4553   if (N->hasOneUse()) {
4554     SDNode *Use = *N->use_begin();
4555     if (Use->getOpcode() == ISD::BRCOND)
4556       AddToWorklist(Use);
4557     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4558       // Also look pass the truncate.
4559       Use = *Use->use_begin();
4560       if (Use->getOpcode() == ISD::BRCOND)
4561         AddToWorklist(Use);
4562     }
4563   }
4564
4565   return SDValue();
4566 }
4567
4568 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4569   SDValue N0 = N->getOperand(0);
4570   EVT VT = N->getValueType(0);
4571
4572   // fold (ctlz c1) -> c2
4573   if (isa<ConstantSDNode>(N0))
4574     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4575   return SDValue();
4576 }
4577
4578 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4579   SDValue N0 = N->getOperand(0);
4580   EVT VT = N->getValueType(0);
4581
4582   // fold (ctlz_zero_undef c1) -> c2
4583   if (isa<ConstantSDNode>(N0))
4584     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4585   return SDValue();
4586 }
4587
4588 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4589   SDValue N0 = N->getOperand(0);
4590   EVT VT = N->getValueType(0);
4591
4592   // fold (cttz c1) -> c2
4593   if (isa<ConstantSDNode>(N0))
4594     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4595   return SDValue();
4596 }
4597
4598 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4599   SDValue N0 = N->getOperand(0);
4600   EVT VT = N->getValueType(0);
4601
4602   // fold (cttz_zero_undef c1) -> c2
4603   if (isa<ConstantSDNode>(N0))
4604     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4605   return SDValue();
4606 }
4607
4608 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4609   SDValue N0 = N->getOperand(0);
4610   EVT VT = N->getValueType(0);
4611
4612   // fold (ctpop c1) -> c2
4613   if (isa<ConstantSDNode>(N0))
4614     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4615   return SDValue();
4616 }
4617
4618 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4619   SDValue N0 = N->getOperand(0);
4620   SDValue N1 = N->getOperand(1);
4621   SDValue N2 = N->getOperand(2);
4622   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4623   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4624   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4625   EVT VT = N->getValueType(0);
4626   EVT VT0 = N0.getValueType();
4627
4628   // fold (select C, X, X) -> X
4629   if (N1 == N2)
4630     return N1;
4631   // fold (select true, X, Y) -> X
4632   if (N0C && !N0C->isNullValue())
4633     return N1;
4634   // fold (select false, X, Y) -> Y
4635   if (N0C && N0C->isNullValue())
4636     return N2;
4637   // fold (select C, 1, X) -> (or C, X)
4638   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4639     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4640   // fold (select C, 0, 1) -> (xor C, 1)
4641   // We can't do this reliably if integer based booleans have different contents
4642   // to floating point based booleans. This is because we can't tell whether we
4643   // have an integer-based boolean or a floating-point-based boolean unless we
4644   // can find the SETCC that produced it and inspect its operands. This is
4645   // fairly easy if C is the SETCC node, but it can potentially be
4646   // undiscoverable (or not reasonably discoverable). For example, it could be
4647   // in another basic block or it could require searching a complicated
4648   // expression.
4649   if (VT.isInteger() &&
4650       (VT0 == MVT::i1 || (VT0.isInteger() &&
4651                           TLI.getBooleanContents(false, false) ==
4652                               TLI.getBooleanContents(false, true) &&
4653                           TLI.getBooleanContents(false, false) ==
4654                               TargetLowering::ZeroOrOneBooleanContent)) &&
4655       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4656     SDValue XORNode;
4657     if (VT == VT0)
4658       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4659                          N0, DAG.getConstant(1, VT0));
4660     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4661                           N0, DAG.getConstant(1, VT0));
4662     AddToWorklist(XORNode.getNode());
4663     if (VT.bitsGT(VT0))
4664       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4665     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4666   }
4667   // fold (select C, 0, X) -> (and (not C), X)
4668   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4669     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4670     AddToWorklist(NOTNode.getNode());
4671     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4672   }
4673   // fold (select C, X, 1) -> (or (not C), X)
4674   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4675     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4676     AddToWorklist(NOTNode.getNode());
4677     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4678   }
4679   // fold (select C, X, 0) -> (and C, X)
4680   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4681     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4682   // fold (select X, X, Y) -> (or X, Y)
4683   // fold (select X, 1, Y) -> (or X, Y)
4684   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4685     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4686   // fold (select X, Y, X) -> (and X, Y)
4687   // fold (select X, Y, 0) -> (and X, Y)
4688   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4689     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4690
4691   // If we can fold this based on the true/false value, do so.
4692   if (SimplifySelectOps(N, N1, N2))
4693     return SDValue(N, 0);  // Don't revisit N.
4694
4695   // fold selects based on a setcc into other things, such as min/max/abs
4696   if (N0.getOpcode() == ISD::SETCC) {
4697     if ((!LegalOperations &&
4698          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4699         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4700       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4701                          N0.getOperand(0), N0.getOperand(1),
4702                          N1, N2, N0.getOperand(2));
4703     return SimplifySelect(SDLoc(N), N0, N1, N2);
4704   }
4705
4706   return SDValue();
4707 }
4708
4709 static
4710 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4711   SDLoc DL(N);
4712   EVT LoVT, HiVT;
4713   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4714
4715   // Split the inputs.
4716   SDValue Lo, Hi, LL, LH, RL, RH;
4717   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4718   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4719
4720   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4721   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4722
4723   return std::make_pair(Lo, Hi);
4724 }
4725
4726 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4727 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4728 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4729   SDLoc dl(N);
4730   SDValue Cond = N->getOperand(0);
4731   SDValue LHS = N->getOperand(1);
4732   SDValue RHS = N->getOperand(2);
4733   EVT VT = N->getValueType(0);
4734   int NumElems = VT.getVectorNumElements();
4735   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4736          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4737          Cond.getOpcode() == ISD::BUILD_VECTOR);
4738
4739   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4740   // binary ones here.
4741   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4742     return SDValue();
4743
4744   // We're sure we have an even number of elements due to the
4745   // concat_vectors we have as arguments to vselect.
4746   // Skip BV elements until we find one that's not an UNDEF
4747   // After we find an UNDEF element, keep looping until we get to half the
4748   // length of the BV and see if all the non-undef nodes are the same.
4749   ConstantSDNode *BottomHalf = nullptr;
4750   for (int i = 0; i < NumElems / 2; ++i) {
4751     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4752       continue;
4753
4754     if (BottomHalf == nullptr)
4755       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4756     else if (Cond->getOperand(i).getNode() != BottomHalf)
4757       return SDValue();
4758   }
4759
4760   // Do the same for the second half of the BuildVector
4761   ConstantSDNode *TopHalf = nullptr;
4762   for (int i = NumElems / 2; i < NumElems; ++i) {
4763     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4764       continue;
4765
4766     if (TopHalf == nullptr)
4767       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4768     else if (Cond->getOperand(i).getNode() != TopHalf)
4769       return SDValue();
4770   }
4771
4772   assert(TopHalf && BottomHalf &&
4773          "One half of the selector was all UNDEFs and the other was all the "
4774          "same value. This should have been addressed before this function.");
4775   return DAG.getNode(
4776       ISD::CONCAT_VECTORS, dl, VT,
4777       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4778       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4779 }
4780
4781 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4782
4783   if (Level >= AfterLegalizeTypes)
4784     return SDValue();
4785
4786   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4787   SDValue Mask = MST->getMask();
4788   SDValue Data  = MST->getData();
4789   SDLoc DL(N);
4790
4791   // If the MSTORE data type requires splitting and the mask is provided by a
4792   // SETCC, then split both nodes and its operands before legalization. This
4793   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4794   // and enables future optimizations (e.g. min/max pattern matching on X86).
4795   if (Mask.getOpcode() == ISD::SETCC) {
4796
4797     // Check if any splitting is required.
4798     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4799         TargetLowering::TypeSplitVector)
4800       return SDValue();
4801
4802     SDValue MaskLo, MaskHi, Lo, Hi;
4803     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4804
4805     EVT LoVT, HiVT;
4806     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4807
4808     SDValue Chain = MST->getChain();
4809     SDValue Ptr   = MST->getBasePtr();
4810
4811     EVT MemoryVT = MST->getMemoryVT();
4812     unsigned Alignment = MST->getOriginalAlignment();
4813
4814     // if Alignment is equal to the vector size,
4815     // take the half of it for the second part
4816     unsigned SecondHalfAlignment =
4817       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4818          Alignment/2 : Alignment;
4819
4820     EVT LoMemVT, HiMemVT;
4821     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4822
4823     SDValue DataLo, DataHi;
4824     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4825
4826     MachineMemOperand *MMO = DAG.getMachineFunction().
4827       getMachineMemOperand(MST->getPointerInfo(), 
4828                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4829                            Alignment, MST->getAAInfo(), MST->getRanges());
4830
4831     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4832
4833     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4834     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4835                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4836
4837     MMO = DAG.getMachineFunction().
4838       getMachineMemOperand(MST->getPointerInfo(), 
4839                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4840                            SecondHalfAlignment, MST->getAAInfo(),
4841                            MST->getRanges());
4842
4843     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4844
4845     AddToWorklist(Lo.getNode());
4846     AddToWorklist(Hi.getNode());
4847
4848     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4849   }
4850   return SDValue();
4851 }
4852
4853 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4854
4855   if (Level >= AfterLegalizeTypes)
4856     return SDValue();
4857
4858   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4859   SDValue Mask = MLD->getMask();
4860   SDLoc DL(N);
4861
4862   // If the MLOAD result requires splitting and the mask is provided by a
4863   // SETCC, then split both nodes and its operands before legalization. This
4864   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4865   // and enables future optimizations (e.g. min/max pattern matching on X86).
4866
4867   if (Mask.getOpcode() == ISD::SETCC) {
4868     EVT VT = N->getValueType(0);
4869
4870     // Check if any splitting is required.
4871     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4872         TargetLowering::TypeSplitVector)
4873       return SDValue();
4874
4875     SDValue MaskLo, MaskHi, Lo, Hi;
4876     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4877
4878     SDValue Src0 = MLD->getSrc0();
4879     SDValue Src0Lo, Src0Hi;
4880     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4881
4882     EVT LoVT, HiVT;
4883     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4884
4885     SDValue Chain = MLD->getChain();
4886     SDValue Ptr   = MLD->getBasePtr();
4887     EVT MemoryVT = MLD->getMemoryVT();
4888     unsigned Alignment = MLD->getOriginalAlignment();
4889
4890     // if Alignment is equal to the vector size,
4891     // take the half of it for the second part
4892     unsigned SecondHalfAlignment =
4893       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4894          Alignment/2 : Alignment;
4895
4896     EVT LoMemVT, HiMemVT;
4897     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4898
4899     MachineMemOperand *MMO = DAG.getMachineFunction().
4900     getMachineMemOperand(MLD->getPointerInfo(), 
4901                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4902                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4903
4904     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4905
4906     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4907     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4908                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4909
4910     MMO = DAG.getMachineFunction().
4911     getMachineMemOperand(MLD->getPointerInfo(), 
4912                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
4913                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4914
4915     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4916
4917     AddToWorklist(Lo.getNode());
4918     AddToWorklist(Hi.getNode());
4919
4920     // Build a factor node to remember that this load is independent of the
4921     // other one.
4922     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4923                         Hi.getValue(1));
4924
4925     // Legalized the chain result - switch anything that used the old chain to
4926     // use the new one.
4927     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4928
4929     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4930
4931     SDValue RetOps[] = { LoadRes, Chain };
4932     return DAG.getMergeValues(RetOps, DL);
4933   }
4934   return SDValue();
4935 }
4936
4937 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4938   SDValue N0 = N->getOperand(0);
4939   SDValue N1 = N->getOperand(1);
4940   SDValue N2 = N->getOperand(2);
4941   SDLoc DL(N);
4942
4943   // Canonicalize integer abs.
4944   // vselect (setg[te] X,  0),  X, -X ->
4945   // vselect (setgt    X, -1),  X, -X ->
4946   // vselect (setl[te] X,  0), -X,  X ->
4947   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4948   if (N0.getOpcode() == ISD::SETCC) {
4949     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4950     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4951     bool isAbs = false;
4952     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4953
4954     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4955          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4956         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4957       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4958     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4959              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4960       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4961
4962     if (isAbs) {
4963       EVT VT = LHS.getValueType();
4964       SDValue Shift = DAG.getNode(
4965           ISD::SRA, DL, VT, LHS,
4966           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4967       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4968       AddToWorklist(Shift.getNode());
4969       AddToWorklist(Add.getNode());
4970       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4971     }
4972   }
4973
4974   // If the VSELECT result requires splitting and the mask is provided by a
4975   // SETCC, then split both nodes and its operands before legalization. This
4976   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4977   // and enables future optimizations (e.g. min/max pattern matching on X86).
4978   if (N0.getOpcode() == ISD::SETCC) {
4979     EVT VT = N->getValueType(0);
4980
4981     // Check if any splitting is required.
4982     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4983         TargetLowering::TypeSplitVector)
4984       return SDValue();
4985
4986     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4987     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4988     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4989     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4990
4991     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4992     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4993
4994     // Add the new VSELECT nodes to the work list in case they need to be split
4995     // again.
4996     AddToWorklist(Lo.getNode());
4997     AddToWorklist(Hi.getNode());
4998
4999     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5000   }
5001
5002   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5003   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5004     return N1;
5005   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5006   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5007     return N2;
5008
5009   // The ConvertSelectToConcatVector function is assuming both the above
5010   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5011   // and addressed.
5012   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5013       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5014       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5015     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5016     if (CV.getNode())
5017       return CV;
5018   }
5019
5020   return SDValue();
5021 }
5022
5023 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5024   SDValue N0 = N->getOperand(0);
5025   SDValue N1 = N->getOperand(1);
5026   SDValue N2 = N->getOperand(2);
5027   SDValue N3 = N->getOperand(3);
5028   SDValue N4 = N->getOperand(4);
5029   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5030
5031   // fold select_cc lhs, rhs, x, x, cc -> x
5032   if (N2 == N3)
5033     return N2;
5034
5035   // Determine if the condition we're dealing with is constant
5036   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5037                               N0, N1, CC, SDLoc(N), false);
5038   if (SCC.getNode()) {
5039     AddToWorklist(SCC.getNode());
5040
5041     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5042       if (!SCCC->isNullValue())
5043         return N2;    // cond always true -> true val
5044       else
5045         return N3;    // cond always false -> false val
5046     }
5047
5048     // Fold to a simpler select_cc
5049     if (SCC.getOpcode() == ISD::SETCC)
5050       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5051                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5052                          SCC.getOperand(2));
5053   }
5054
5055   // If we can fold this based on the true/false value, do so.
5056   if (SimplifySelectOps(N, N2, N3))
5057     return SDValue(N, 0);  // Don't revisit N.
5058
5059   // fold select_cc into other things, such as min/max/abs
5060   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5061 }
5062
5063 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5064   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5065                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5066                        SDLoc(N));
5067 }
5068
5069 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5070 // dag node into a ConstantSDNode or a build_vector of constants.
5071 // This function is called by the DAGCombiner when visiting sext/zext/aext
5072 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5073 // Vector extends are not folded if operations are legal; this is to
5074 // avoid introducing illegal build_vector dag nodes.
5075 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5076                                          SelectionDAG &DAG, bool LegalTypes,
5077                                          bool LegalOperations) {
5078   unsigned Opcode = N->getOpcode();
5079   SDValue N0 = N->getOperand(0);
5080   EVT VT = N->getValueType(0);
5081
5082   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5083          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5084
5085   // fold (sext c1) -> c1
5086   // fold (zext c1) -> c1
5087   // fold (aext c1) -> c1
5088   if (isa<ConstantSDNode>(N0))
5089     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5090
5091   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5092   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5093   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5094   EVT SVT = VT.getScalarType();
5095   if (!(VT.isVector() &&
5096       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5097       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5098     return nullptr;
5099
5100   // We can fold this node into a build_vector.
5101   unsigned VTBits = SVT.getSizeInBits();
5102   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5103   unsigned ShAmt = VTBits - EVTBits;
5104   SmallVector<SDValue, 8> Elts;
5105   unsigned NumElts = N0->getNumOperands();
5106   SDLoc DL(N);
5107
5108   for (unsigned i=0; i != NumElts; ++i) {
5109     SDValue Op = N0->getOperand(i);
5110     if (Op->getOpcode() == ISD::UNDEF) {
5111       Elts.push_back(DAG.getUNDEF(SVT));
5112       continue;
5113     }
5114
5115     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5116     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5117     if (Opcode == ISD::SIGN_EXTEND)
5118       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5119                                      SVT));
5120     else
5121       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5122                                      SVT));
5123   }
5124
5125   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5126 }
5127
5128 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5129 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5130 // transformation. Returns true if extension are possible and the above
5131 // mentioned transformation is profitable.
5132 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5133                                     unsigned ExtOpc,
5134                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5135                                     const TargetLowering &TLI) {
5136   bool HasCopyToRegUses = false;
5137   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5138   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5139                             UE = N0.getNode()->use_end();
5140        UI != UE; ++UI) {
5141     SDNode *User = *UI;
5142     if (User == N)
5143       continue;
5144     if (UI.getUse().getResNo() != N0.getResNo())
5145       continue;
5146     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5147     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5148       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5149       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5150         // Sign bits will be lost after a zext.
5151         return false;
5152       bool Add = false;
5153       for (unsigned i = 0; i != 2; ++i) {
5154         SDValue UseOp = User->getOperand(i);
5155         if (UseOp == N0)
5156           continue;
5157         if (!isa<ConstantSDNode>(UseOp))
5158           return false;
5159         Add = true;
5160       }
5161       if (Add)
5162         ExtendNodes.push_back(User);
5163       continue;
5164     }
5165     // If truncates aren't free and there are users we can't
5166     // extend, it isn't worthwhile.
5167     if (!isTruncFree)
5168       return false;
5169     // Remember if this value is live-out.
5170     if (User->getOpcode() == ISD::CopyToReg)
5171       HasCopyToRegUses = true;
5172   }
5173
5174   if (HasCopyToRegUses) {
5175     bool BothLiveOut = false;
5176     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5177          UI != UE; ++UI) {
5178       SDUse &Use = UI.getUse();
5179       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5180         BothLiveOut = true;
5181         break;
5182       }
5183     }
5184     if (BothLiveOut)
5185       // Both unextended and extended values are live out. There had better be
5186       // a good reason for the transformation.
5187       return ExtendNodes.size();
5188   }
5189   return true;
5190 }
5191
5192 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5193                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5194                                   ISD::NodeType ExtType) {
5195   // Extend SetCC uses if necessary.
5196   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5197     SDNode *SetCC = SetCCs[i];
5198     SmallVector<SDValue, 4> Ops;
5199
5200     for (unsigned j = 0; j != 2; ++j) {
5201       SDValue SOp = SetCC->getOperand(j);
5202       if (SOp == Trunc)
5203         Ops.push_back(ExtLoad);
5204       else
5205         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5206     }
5207
5208     Ops.push_back(SetCC->getOperand(2));
5209     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5210   }
5211 }
5212
5213 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5214   SDValue N0 = N->getOperand(0);
5215   EVT VT = N->getValueType(0);
5216
5217   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5218                                               LegalOperations))
5219     return SDValue(Res, 0);
5220
5221   // fold (sext (sext x)) -> (sext x)
5222   // fold (sext (aext x)) -> (sext x)
5223   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5224     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5225                        N0.getOperand(0));
5226
5227   if (N0.getOpcode() == ISD::TRUNCATE) {
5228     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5229     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5230     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5231     if (NarrowLoad.getNode()) {
5232       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5233       if (NarrowLoad.getNode() != N0.getNode()) {
5234         CombineTo(N0.getNode(), NarrowLoad);
5235         // CombineTo deleted the truncate, if needed, but not what's under it.
5236         AddToWorklist(oye);
5237       }
5238       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5239     }
5240
5241     // See if the value being truncated is already sign extended.  If so, just
5242     // eliminate the trunc/sext pair.
5243     SDValue Op = N0.getOperand(0);
5244     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5245     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5246     unsigned DestBits = VT.getScalarType().getSizeInBits();
5247     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5248
5249     if (OpBits == DestBits) {
5250       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5251       // bits, it is already ready.
5252       if (NumSignBits > DestBits-MidBits)
5253         return Op;
5254     } else if (OpBits < DestBits) {
5255       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5256       // bits, just sext from i32.
5257       if (NumSignBits > OpBits-MidBits)
5258         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5259     } else {
5260       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5261       // bits, just truncate to i32.
5262       if (NumSignBits > OpBits-MidBits)
5263         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5264     }
5265
5266     // fold (sext (truncate x)) -> (sextinreg x).
5267     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5268                                                  N0.getValueType())) {
5269       if (OpBits < DestBits)
5270         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5271       else if (OpBits > DestBits)
5272         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5273       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5274                          DAG.getValueType(N0.getValueType()));
5275     }
5276   }
5277
5278   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5279   // None of the supported targets knows how to perform load and sign extend
5280   // on vectors in one instruction.  We only perform this transformation on
5281   // scalars.
5282   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5283       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5284       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5285        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5286     bool DoXform = true;
5287     SmallVector<SDNode*, 4> SetCCs;
5288     if (!N0.hasOneUse())
5289       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5290     if (DoXform) {
5291       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5292       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5293                                        LN0->getChain(),
5294                                        LN0->getBasePtr(), N0.getValueType(),
5295                                        LN0->getMemOperand());
5296       CombineTo(N, ExtLoad);
5297       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5298                                   N0.getValueType(), ExtLoad);
5299       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5300       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5301                       ISD::SIGN_EXTEND);
5302       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5303     }
5304   }
5305
5306   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5307   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5308   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5309       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5310     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5311     EVT MemVT = LN0->getMemoryVT();
5312     if ((!LegalOperations && !LN0->isVolatile()) ||
5313         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5314       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5315                                        LN0->getChain(),
5316                                        LN0->getBasePtr(), MemVT,
5317                                        LN0->getMemOperand());
5318       CombineTo(N, ExtLoad);
5319       CombineTo(N0.getNode(),
5320                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5321                             N0.getValueType(), ExtLoad),
5322                 ExtLoad.getValue(1));
5323       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5324     }
5325   }
5326
5327   // fold (sext (and/or/xor (load x), cst)) ->
5328   //      (and/or/xor (sextload x), (sext cst))
5329   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5330        N0.getOpcode() == ISD::XOR) &&
5331       isa<LoadSDNode>(N0.getOperand(0)) &&
5332       N0.getOperand(1).getOpcode() == ISD::Constant &&
5333       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5334       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5335     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5336     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5337       bool DoXform = true;
5338       SmallVector<SDNode*, 4> SetCCs;
5339       if (!N0.hasOneUse())
5340         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5341                                           SetCCs, TLI);
5342       if (DoXform) {
5343         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5344                                          LN0->getChain(), LN0->getBasePtr(),
5345                                          LN0->getMemoryVT(),
5346                                          LN0->getMemOperand());
5347         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5348         Mask = Mask.sext(VT.getSizeInBits());
5349         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5350                                   ExtLoad, DAG.getConstant(Mask, VT));
5351         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5352                                     SDLoc(N0.getOperand(0)),
5353                                     N0.getOperand(0).getValueType(), ExtLoad);
5354         CombineTo(N, And);
5355         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5356         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5357                         ISD::SIGN_EXTEND);
5358         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5359       }
5360     }
5361   }
5362
5363   if (N0.getOpcode() == ISD::SETCC) {
5364     EVT N0VT = N0.getOperand(0).getValueType();
5365     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5366     // Only do this before legalize for now.
5367     if (VT.isVector() && !LegalOperations &&
5368         TLI.getBooleanContents(N0VT) ==
5369             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5370       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5371       // of the same size as the compared operands. Only optimize sext(setcc())
5372       // if this is the case.
5373       EVT SVT = getSetCCResultType(N0VT);
5374
5375       // We know that the # elements of the results is the same as the
5376       // # elements of the compare (and the # elements of the compare result
5377       // for that matter).  Check to see that they are the same size.  If so,
5378       // we know that the element size of the sext'd result matches the
5379       // element size of the compare operands.
5380       if (VT.getSizeInBits() == SVT.getSizeInBits())
5381         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5382                              N0.getOperand(1),
5383                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5384
5385       // If the desired elements are smaller or larger than the source
5386       // elements we can use a matching integer vector type and then
5387       // truncate/sign extend
5388       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5389       if (SVT == MatchingVectorType) {
5390         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5391                                N0.getOperand(0), N0.getOperand(1),
5392                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5393         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5394       }
5395     }
5396
5397     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5398     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5399     SDValue NegOne =
5400       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5401     SDValue SCC =
5402       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5403                        NegOne, DAG.getConstant(0, VT),
5404                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5405     if (SCC.getNode()) return SCC;
5406
5407     if (!VT.isVector()) {
5408       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5409       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5410         SDLoc DL(N);
5411         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5412         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5413                                      N0.getOperand(0), N0.getOperand(1), CC);
5414         return DAG.getSelect(DL, VT, SetCC,
5415                              NegOne, DAG.getConstant(0, VT));
5416       }
5417     }
5418   }
5419
5420   // fold (sext x) -> (zext x) if the sign bit is known zero.
5421   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5422       DAG.SignBitIsZero(N0))
5423     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5424
5425   return SDValue();
5426 }
5427
5428 // isTruncateOf - If N is a truncate of some other value, return true, record
5429 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5430 // This function computes KnownZero to avoid a duplicated call to
5431 // computeKnownBits in the caller.
5432 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5433                          APInt &KnownZero) {
5434   APInt KnownOne;
5435   if (N->getOpcode() == ISD::TRUNCATE) {
5436     Op = N->getOperand(0);
5437     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5438     return true;
5439   }
5440
5441   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5442       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5443     return false;
5444
5445   SDValue Op0 = N->getOperand(0);
5446   SDValue Op1 = N->getOperand(1);
5447   assert(Op0.getValueType() == Op1.getValueType());
5448
5449   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5450   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5451   if (COp0 && COp0->isNullValue())
5452     Op = Op1;
5453   else if (COp1 && COp1->isNullValue())
5454     Op = Op0;
5455   else
5456     return false;
5457
5458   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5459
5460   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5461     return false;
5462
5463   return true;
5464 }
5465
5466 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5467   SDValue N0 = N->getOperand(0);
5468   EVT VT = N->getValueType(0);
5469
5470   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5471                                               LegalOperations))
5472     return SDValue(Res, 0);
5473
5474   // fold (zext (zext x)) -> (zext x)
5475   // fold (zext (aext x)) -> (zext x)
5476   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5477     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5478                        N0.getOperand(0));
5479
5480   // fold (zext (truncate x)) -> (zext x) or
5481   //      (zext (truncate x)) -> (truncate x)
5482   // This is valid when the truncated bits of x are already zero.
5483   // FIXME: We should extend this to work for vectors too.
5484   SDValue Op;
5485   APInt KnownZero;
5486   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5487     APInt TruncatedBits =
5488       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5489       APInt(Op.getValueSizeInBits(), 0) :
5490       APInt::getBitsSet(Op.getValueSizeInBits(),
5491                         N0.getValueSizeInBits(),
5492                         std::min(Op.getValueSizeInBits(),
5493                                  VT.getSizeInBits()));
5494     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5495       if (VT.bitsGT(Op.getValueType()))
5496         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5497       if (VT.bitsLT(Op.getValueType()))
5498         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5499
5500       return Op;
5501     }
5502   }
5503
5504   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5505   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5506   if (N0.getOpcode() == ISD::TRUNCATE) {
5507     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5508     if (NarrowLoad.getNode()) {
5509       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5510       if (NarrowLoad.getNode() != N0.getNode()) {
5511         CombineTo(N0.getNode(), NarrowLoad);
5512         // CombineTo deleted the truncate, if needed, but not what's under it.
5513         AddToWorklist(oye);
5514       }
5515       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5516     }
5517   }
5518
5519   // fold (zext (truncate x)) -> (and x, mask)
5520   if (N0.getOpcode() == ISD::TRUNCATE &&
5521       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5522
5523     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5524     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5525     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5526     if (NarrowLoad.getNode()) {
5527       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5528       if (NarrowLoad.getNode() != N0.getNode()) {
5529         CombineTo(N0.getNode(), NarrowLoad);
5530         // CombineTo deleted the truncate, if needed, but not what's under it.
5531         AddToWorklist(oye);
5532       }
5533       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5534     }
5535
5536     SDValue Op = N0.getOperand(0);
5537     if (Op.getValueType().bitsLT(VT)) {
5538       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5539       AddToWorklist(Op.getNode());
5540     } else if (Op.getValueType().bitsGT(VT)) {
5541       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5542       AddToWorklist(Op.getNode());
5543     }
5544     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5545                                   N0.getValueType().getScalarType());
5546   }
5547
5548   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5549   // if either of the casts is not free.
5550   if (N0.getOpcode() == ISD::AND &&
5551       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5552       N0.getOperand(1).getOpcode() == ISD::Constant &&
5553       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5554                            N0.getValueType()) ||
5555        !TLI.isZExtFree(N0.getValueType(), VT))) {
5556     SDValue X = N0.getOperand(0).getOperand(0);
5557     if (X.getValueType().bitsLT(VT)) {
5558       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5559     } else if (X.getValueType().bitsGT(VT)) {
5560       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5561     }
5562     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5563     Mask = Mask.zext(VT.getSizeInBits());
5564     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5565                        X, DAG.getConstant(Mask, VT));
5566   }
5567
5568   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5569   // None of the supported targets knows how to perform load and vector_zext
5570   // on vectors in one instruction.  We only perform this transformation on
5571   // scalars.
5572   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5573       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5574       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5575        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5576     bool DoXform = true;
5577     SmallVector<SDNode*, 4> SetCCs;
5578     if (!N0.hasOneUse())
5579       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5580     if (DoXform) {
5581       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5582       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5583                                        LN0->getChain(),
5584                                        LN0->getBasePtr(), N0.getValueType(),
5585                                        LN0->getMemOperand());
5586       CombineTo(N, ExtLoad);
5587       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5588                                   N0.getValueType(), ExtLoad);
5589       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5590
5591       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5592                       ISD::ZERO_EXTEND);
5593       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5594     }
5595   }
5596
5597   // fold (zext (and/or/xor (load x), cst)) ->
5598   //      (and/or/xor (zextload x), (zext cst))
5599   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5600        N0.getOpcode() == ISD::XOR) &&
5601       isa<LoadSDNode>(N0.getOperand(0)) &&
5602       N0.getOperand(1).getOpcode() == ISD::Constant &&
5603       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5604       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5605     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5606     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5607       bool DoXform = true;
5608       SmallVector<SDNode*, 4> SetCCs;
5609       if (!N0.hasOneUse())
5610         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5611                                           SetCCs, TLI);
5612       if (DoXform) {
5613         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5614                                          LN0->getChain(), LN0->getBasePtr(),
5615                                          LN0->getMemoryVT(),
5616                                          LN0->getMemOperand());
5617         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5618         Mask = Mask.zext(VT.getSizeInBits());
5619         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5620                                   ExtLoad, DAG.getConstant(Mask, VT));
5621         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5622                                     SDLoc(N0.getOperand(0)),
5623                                     N0.getOperand(0).getValueType(), ExtLoad);
5624         CombineTo(N, And);
5625         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5626         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5627                         ISD::ZERO_EXTEND);
5628         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5629       }
5630     }
5631   }
5632
5633   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5634   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5635   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5636       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5637     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5638     EVT MemVT = LN0->getMemoryVT();
5639     if ((!LegalOperations && !LN0->isVolatile()) ||
5640         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5641       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5642                                        LN0->getChain(),
5643                                        LN0->getBasePtr(), MemVT,
5644                                        LN0->getMemOperand());
5645       CombineTo(N, ExtLoad);
5646       CombineTo(N0.getNode(),
5647                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5648                             ExtLoad),
5649                 ExtLoad.getValue(1));
5650       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5651     }
5652   }
5653
5654   if (N0.getOpcode() == ISD::SETCC) {
5655     if (!LegalOperations && VT.isVector() &&
5656         N0.getValueType().getVectorElementType() == MVT::i1) {
5657       EVT N0VT = N0.getOperand(0).getValueType();
5658       if (getSetCCResultType(N0VT) == N0.getValueType())
5659         return SDValue();
5660
5661       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5662       // Only do this before legalize for now.
5663       EVT EltVT = VT.getVectorElementType();
5664       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5665                                     DAG.getConstant(1, EltVT));
5666       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5667         // We know that the # elements of the results is the same as the
5668         // # elements of the compare (and the # elements of the compare result
5669         // for that matter).  Check to see that they are the same size.  If so,
5670         // we know that the element size of the sext'd result matches the
5671         // element size of the compare operands.
5672         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5673                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5674                                          N0.getOperand(1),
5675                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5676                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5677                                        OneOps));
5678
5679       // If the desired elements are smaller or larger than the source
5680       // elements we can use a matching integer vector type and then
5681       // truncate/sign extend
5682       EVT MatchingElementType =
5683         EVT::getIntegerVT(*DAG.getContext(),
5684                           N0VT.getScalarType().getSizeInBits());
5685       EVT MatchingVectorType =
5686         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5687                          N0VT.getVectorNumElements());
5688       SDValue VsetCC =
5689         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5690                       N0.getOperand(1),
5691                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5692       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5693                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5694                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5695     }
5696
5697     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5698     SDValue SCC =
5699       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5700                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5701                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5702     if (SCC.getNode()) return SCC;
5703   }
5704
5705   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5706   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5707       isa<ConstantSDNode>(N0.getOperand(1)) &&
5708       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5709       N0.hasOneUse()) {
5710     SDValue ShAmt = N0.getOperand(1);
5711     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5712     if (N0.getOpcode() == ISD::SHL) {
5713       SDValue InnerZExt = N0.getOperand(0);
5714       // If the original shl may be shifting out bits, do not perform this
5715       // transformation.
5716       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5717         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5718       if (ShAmtVal > KnownZeroBits)
5719         return SDValue();
5720     }
5721
5722     SDLoc DL(N);
5723
5724     // Ensure that the shift amount is wide enough for the shifted value.
5725     if (VT.getSizeInBits() >= 256)
5726       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5727
5728     return DAG.getNode(N0.getOpcode(), DL, VT,
5729                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5730                        ShAmt);
5731   }
5732
5733   return SDValue();
5734 }
5735
5736 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5737   SDValue N0 = N->getOperand(0);
5738   EVT VT = N->getValueType(0);
5739
5740   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5741                                               LegalOperations))
5742     return SDValue(Res, 0);
5743
5744   // fold (aext (aext x)) -> (aext x)
5745   // fold (aext (zext x)) -> (zext x)
5746   // fold (aext (sext x)) -> (sext x)
5747   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5748       N0.getOpcode() == ISD::ZERO_EXTEND ||
5749       N0.getOpcode() == ISD::SIGN_EXTEND)
5750     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5751
5752   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5753   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5754   if (N0.getOpcode() == ISD::TRUNCATE) {
5755     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5756     if (NarrowLoad.getNode()) {
5757       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5758       if (NarrowLoad.getNode() != N0.getNode()) {
5759         CombineTo(N0.getNode(), NarrowLoad);
5760         // CombineTo deleted the truncate, if needed, but not what's under it.
5761         AddToWorklist(oye);
5762       }
5763       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5764     }
5765   }
5766
5767   // fold (aext (truncate x))
5768   if (N0.getOpcode() == ISD::TRUNCATE) {
5769     SDValue TruncOp = N0.getOperand(0);
5770     if (TruncOp.getValueType() == VT)
5771       return TruncOp; // x iff x size == zext size.
5772     if (TruncOp.getValueType().bitsGT(VT))
5773       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5774     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5775   }
5776
5777   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5778   // if the trunc is not free.
5779   if (N0.getOpcode() == ISD::AND &&
5780       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5781       N0.getOperand(1).getOpcode() == ISD::Constant &&
5782       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5783                           N0.getValueType())) {
5784     SDValue X = N0.getOperand(0).getOperand(0);
5785     if (X.getValueType().bitsLT(VT)) {
5786       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5787     } else if (X.getValueType().bitsGT(VT)) {
5788       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5789     }
5790     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5791     Mask = Mask.zext(VT.getSizeInBits());
5792     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5793                        X, DAG.getConstant(Mask, VT));
5794   }
5795
5796   // fold (aext (load x)) -> (aext (truncate (extload x)))
5797   // None of the supported targets knows how to perform load and any_ext
5798   // on vectors in one instruction.  We only perform this transformation on
5799   // scalars.
5800   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5801       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5802       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5803     bool DoXform = true;
5804     SmallVector<SDNode*, 4> SetCCs;
5805     if (!N0.hasOneUse())
5806       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5807     if (DoXform) {
5808       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5809       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5810                                        LN0->getChain(),
5811                                        LN0->getBasePtr(), N0.getValueType(),
5812                                        LN0->getMemOperand());
5813       CombineTo(N, ExtLoad);
5814       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5815                                   N0.getValueType(), ExtLoad);
5816       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5817       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5818                       ISD::ANY_EXTEND);
5819       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5820     }
5821   }
5822
5823   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5824   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5825   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5826   if (N0.getOpcode() == ISD::LOAD &&
5827       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5828       N0.hasOneUse()) {
5829     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5830     ISD::LoadExtType ExtType = LN0->getExtensionType();
5831     EVT MemVT = LN0->getMemoryVT();
5832     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5833       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5834                                        VT, LN0->getChain(), LN0->getBasePtr(),
5835                                        MemVT, LN0->getMemOperand());
5836       CombineTo(N, ExtLoad);
5837       CombineTo(N0.getNode(),
5838                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5839                             N0.getValueType(), ExtLoad),
5840                 ExtLoad.getValue(1));
5841       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5842     }
5843   }
5844
5845   if (N0.getOpcode() == ISD::SETCC) {
5846     // For vectors:
5847     // aext(setcc) -> vsetcc
5848     // aext(setcc) -> truncate(vsetcc)
5849     // aext(setcc) -> aext(vsetcc)
5850     // Only do this before legalize for now.
5851     if (VT.isVector() && !LegalOperations) {
5852       EVT N0VT = N0.getOperand(0).getValueType();
5853         // We know that the # elements of the results is the same as the
5854         // # elements of the compare (and the # elements of the compare result
5855         // for that matter).  Check to see that they are the same size.  If so,
5856         // we know that the element size of the sext'd result matches the
5857         // element size of the compare operands.
5858       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5859         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5860                              N0.getOperand(1),
5861                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5862       // If the desired elements are smaller or larger than the source
5863       // elements we can use a matching integer vector type and then
5864       // truncate/any extend
5865       else {
5866         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5867         SDValue VsetCC =
5868           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5869                         N0.getOperand(1),
5870                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5871         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5872       }
5873     }
5874
5875     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5876     SDValue SCC =
5877       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5878                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5879                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5880     if (SCC.getNode())
5881       return SCC;
5882   }
5883
5884   return SDValue();
5885 }
5886
5887 /// See if the specified operand can be simplified with the knowledge that only
5888 /// the bits specified by Mask are used.  If so, return the simpler operand,
5889 /// otherwise return a null SDValue.
5890 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5891   switch (V.getOpcode()) {
5892   default: break;
5893   case ISD::Constant: {
5894     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5895     assert(CV && "Const value should be ConstSDNode.");
5896     const APInt &CVal = CV->getAPIntValue();
5897     APInt NewVal = CVal & Mask;
5898     if (NewVal != CVal)
5899       return DAG.getConstant(NewVal, V.getValueType());
5900     break;
5901   }
5902   case ISD::OR:
5903   case ISD::XOR:
5904     // If the LHS or RHS don't contribute bits to the or, drop them.
5905     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5906       return V.getOperand(1);
5907     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5908       return V.getOperand(0);
5909     break;
5910   case ISD::SRL:
5911     // Only look at single-use SRLs.
5912     if (!V.getNode()->hasOneUse())
5913       break;
5914     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5915       // See if we can recursively simplify the LHS.
5916       unsigned Amt = RHSC->getZExtValue();
5917
5918       // Watch out for shift count overflow though.
5919       if (Amt >= Mask.getBitWidth()) break;
5920       APInt NewMask = Mask << Amt;
5921       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5922       if (SimplifyLHS.getNode())
5923         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5924                            SimplifyLHS, V.getOperand(1));
5925     }
5926   }
5927   return SDValue();
5928 }
5929
5930 /// If the result of a wider load is shifted to right of N  bits and then
5931 /// truncated to a narrower type and where N is a multiple of number of bits of
5932 /// the narrower type, transform it to a narrower load from address + N / num of
5933 /// bits of new type. If the result is to be extended, also fold the extension
5934 /// to form a extending load.
5935 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5936   unsigned Opc = N->getOpcode();
5937
5938   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5939   SDValue N0 = N->getOperand(0);
5940   EVT VT = N->getValueType(0);
5941   EVT ExtVT = VT;
5942
5943   // This transformation isn't valid for vector loads.
5944   if (VT.isVector())
5945     return SDValue();
5946
5947   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5948   // extended to VT.
5949   if (Opc == ISD::SIGN_EXTEND_INREG) {
5950     ExtType = ISD::SEXTLOAD;
5951     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5952   } else if (Opc == ISD::SRL) {
5953     // Another special-case: SRL is basically zero-extending a narrower value.
5954     ExtType = ISD::ZEXTLOAD;
5955     N0 = SDValue(N, 0);
5956     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5957     if (!N01) return SDValue();
5958     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5959                               VT.getSizeInBits() - N01->getZExtValue());
5960   }
5961   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5962     return SDValue();
5963
5964   unsigned EVTBits = ExtVT.getSizeInBits();
5965
5966   // Do not generate loads of non-round integer types since these can
5967   // be expensive (and would be wrong if the type is not byte sized).
5968   if (!ExtVT.isRound())
5969     return SDValue();
5970
5971   unsigned ShAmt = 0;
5972   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5973     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5974       ShAmt = N01->getZExtValue();
5975       // Is the shift amount a multiple of size of VT?
5976       if ((ShAmt & (EVTBits-1)) == 0) {
5977         N0 = N0.getOperand(0);
5978         // Is the load width a multiple of size of VT?
5979         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5980           return SDValue();
5981       }
5982
5983       // At this point, we must have a load or else we can't do the transform.
5984       if (!isa<LoadSDNode>(N0)) return SDValue();
5985
5986       // Because a SRL must be assumed to *need* to zero-extend the high bits
5987       // (as opposed to anyext the high bits), we can't combine the zextload
5988       // lowering of SRL and an sextload.
5989       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5990         return SDValue();
5991
5992       // If the shift amount is larger than the input type then we're not
5993       // accessing any of the loaded bytes.  If the load was a zextload/extload
5994       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5995       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5996         return SDValue();
5997     }
5998   }
5999
6000   // If the load is shifted left (and the result isn't shifted back right),
6001   // we can fold the truncate through the shift.
6002   unsigned ShLeftAmt = 0;
6003   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6004       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6005     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6006       ShLeftAmt = N01->getZExtValue();
6007       N0 = N0.getOperand(0);
6008     }
6009   }
6010
6011   // If we haven't found a load, we can't narrow it.  Don't transform one with
6012   // multiple uses, this would require adding a new load.
6013   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6014     return SDValue();
6015
6016   // Don't change the width of a volatile load.
6017   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6018   if (LN0->isVolatile())
6019     return SDValue();
6020
6021   // Verify that we are actually reducing a load width here.
6022   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6023     return SDValue();
6024
6025   // For the transform to be legal, the load must produce only two values
6026   // (the value loaded and the chain).  Don't transform a pre-increment
6027   // load, for example, which produces an extra value.  Otherwise the
6028   // transformation is not equivalent, and the downstream logic to replace
6029   // uses gets things wrong.
6030   if (LN0->getNumValues() > 2)
6031     return SDValue();
6032
6033   // If the load that we're shrinking is an extload and we're not just
6034   // discarding the extension we can't simply shrink the load. Bail.
6035   // TODO: It would be possible to merge the extensions in some cases.
6036   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6037       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6038     return SDValue();
6039
6040   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6041     return SDValue();
6042
6043   EVT PtrType = N0.getOperand(1).getValueType();
6044
6045   if (PtrType == MVT::Untyped || PtrType.isExtended())
6046     // It's not possible to generate a constant of extended or untyped type.
6047     return SDValue();
6048
6049   // For big endian targets, we need to adjust the offset to the pointer to
6050   // load the correct bytes.
6051   if (TLI.isBigEndian()) {
6052     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6053     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6054     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6055   }
6056
6057   uint64_t PtrOff = ShAmt / 8;
6058   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6059   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6060                                PtrType, LN0->getBasePtr(),
6061                                DAG.getConstant(PtrOff, PtrType));
6062   AddToWorklist(NewPtr.getNode());
6063
6064   SDValue Load;
6065   if (ExtType == ISD::NON_EXTLOAD)
6066     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6067                         LN0->getPointerInfo().getWithOffset(PtrOff),
6068                         LN0->isVolatile(), LN0->isNonTemporal(),
6069                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6070   else
6071     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6072                           LN0->getPointerInfo().getWithOffset(PtrOff),
6073                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6074                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6075
6076   // Replace the old load's chain with the new load's chain.
6077   WorklistRemover DeadNodes(*this);
6078   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6079
6080   // Shift the result left, if we've swallowed a left shift.
6081   SDValue Result = Load;
6082   if (ShLeftAmt != 0) {
6083     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6084     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6085       ShImmTy = VT;
6086     // If the shift amount is as large as the result size (but, presumably,
6087     // no larger than the source) then the useful bits of the result are
6088     // zero; we can't simply return the shortened shift, because the result
6089     // of that operation is undefined.
6090     if (ShLeftAmt >= VT.getSizeInBits())
6091       Result = DAG.getConstant(0, VT);
6092     else
6093       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6094                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6095   }
6096
6097   // Return the new loaded value.
6098   return Result;
6099 }
6100
6101 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6102   SDValue N0 = N->getOperand(0);
6103   SDValue N1 = N->getOperand(1);
6104   EVT VT = N->getValueType(0);
6105   EVT EVT = cast<VTSDNode>(N1)->getVT();
6106   unsigned VTBits = VT.getScalarType().getSizeInBits();
6107   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6108
6109   // fold (sext_in_reg c1) -> c1
6110   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6111     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6112
6113   // If the input is already sign extended, just drop the extension.
6114   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6115     return N0;
6116
6117   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6118   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6119       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6120     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6121                        N0.getOperand(0), N1);
6122
6123   // fold (sext_in_reg (sext x)) -> (sext x)
6124   // fold (sext_in_reg (aext x)) -> (sext x)
6125   // if x is small enough.
6126   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6127     SDValue N00 = N0.getOperand(0);
6128     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6129         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6130       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6131   }
6132
6133   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6134   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6135     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6136
6137   // fold operands of sext_in_reg based on knowledge that the top bits are not
6138   // demanded.
6139   if (SimplifyDemandedBits(SDValue(N, 0)))
6140     return SDValue(N, 0);
6141
6142   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6143   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6144   SDValue NarrowLoad = ReduceLoadWidth(N);
6145   if (NarrowLoad.getNode())
6146     return NarrowLoad;
6147
6148   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6149   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6150   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6151   if (N0.getOpcode() == ISD::SRL) {
6152     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6153       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6154         // We can turn this into an SRA iff the input to the SRL is already sign
6155         // extended enough.
6156         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6157         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6158           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6159                              N0.getOperand(0), N0.getOperand(1));
6160       }
6161   }
6162
6163   // fold (sext_inreg (extload x)) -> (sextload x)
6164   if (ISD::isEXTLoad(N0.getNode()) &&
6165       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6166       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6167       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6168        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6169     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6170     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6171                                      LN0->getChain(),
6172                                      LN0->getBasePtr(), EVT,
6173                                      LN0->getMemOperand());
6174     CombineTo(N, ExtLoad);
6175     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6176     AddToWorklist(ExtLoad.getNode());
6177     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6178   }
6179   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6180   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6181       N0.hasOneUse() &&
6182       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6183       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6184        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6185     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6186     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6187                                      LN0->getChain(),
6188                                      LN0->getBasePtr(), EVT,
6189                                      LN0->getMemOperand());
6190     CombineTo(N, ExtLoad);
6191     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6192     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6193   }
6194
6195   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6196   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6197     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6198                                        N0.getOperand(1), false);
6199     if (BSwap.getNode())
6200       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6201                          BSwap, N1);
6202   }
6203
6204   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6205   // into a build_vector.
6206   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6207     SmallVector<SDValue, 8> Elts;
6208     unsigned NumElts = N0->getNumOperands();
6209     unsigned ShAmt = VTBits - EVTBits;
6210
6211     for (unsigned i = 0; i != NumElts; ++i) {
6212       SDValue Op = N0->getOperand(i);
6213       if (Op->getOpcode() == ISD::UNDEF) {
6214         Elts.push_back(Op);
6215         continue;
6216       }
6217
6218       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6219       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6220       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6221                                      Op.getValueType()));
6222     }
6223
6224     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6225   }
6226
6227   return SDValue();
6228 }
6229
6230 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6231   SDValue N0 = N->getOperand(0);
6232   EVT VT = N->getValueType(0);
6233   bool isLE = TLI.isLittleEndian();
6234
6235   // noop truncate
6236   if (N0.getValueType() == N->getValueType(0))
6237     return N0;
6238   // fold (truncate c1) -> c1
6239   if (isa<ConstantSDNode>(N0))
6240     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6241   // fold (truncate (truncate x)) -> (truncate x)
6242   if (N0.getOpcode() == ISD::TRUNCATE)
6243     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6244   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6245   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6246       N0.getOpcode() == ISD::SIGN_EXTEND ||
6247       N0.getOpcode() == ISD::ANY_EXTEND) {
6248     if (N0.getOperand(0).getValueType().bitsLT(VT))
6249       // if the source is smaller than the dest, we still need an extend
6250       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6251                          N0.getOperand(0));
6252     if (N0.getOperand(0).getValueType().bitsGT(VT))
6253       // if the source is larger than the dest, than we just need the truncate
6254       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6255     // if the source and dest are the same type, we can drop both the extend
6256     // and the truncate.
6257     return N0.getOperand(0);
6258   }
6259
6260   // Fold extract-and-trunc into a narrow extract. For example:
6261   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6262   //   i32 y = TRUNCATE(i64 x)
6263   //        -- becomes --
6264   //   v16i8 b = BITCAST (v2i64 val)
6265   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6266   //
6267   // Note: We only run this optimization after type legalization (which often
6268   // creates this pattern) and before operation legalization after which
6269   // we need to be more careful about the vector instructions that we generate.
6270   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6271       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6272
6273     EVT VecTy = N0.getOperand(0).getValueType();
6274     EVT ExTy = N0.getValueType();
6275     EVT TrTy = N->getValueType(0);
6276
6277     unsigned NumElem = VecTy.getVectorNumElements();
6278     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6279
6280     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6281     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6282
6283     SDValue EltNo = N0->getOperand(1);
6284     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6285       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6286       EVT IndexTy = TLI.getVectorIdxTy();
6287       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6288
6289       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6290                               NVT, N0.getOperand(0));
6291
6292       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6293                          SDLoc(N), TrTy, V,
6294                          DAG.getConstant(Index, IndexTy));
6295     }
6296   }
6297
6298   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6299   if (N0.getOpcode() == ISD::SELECT) {
6300     EVT SrcVT = N0.getValueType();
6301     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6302         TLI.isTruncateFree(SrcVT, VT)) {
6303       SDLoc SL(N0);
6304       SDValue Cond = N0.getOperand(0);
6305       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6306       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6307       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6308     }
6309   }
6310
6311   // Fold a series of buildvector, bitcast, and truncate if possible.
6312   // For example fold
6313   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6314   //   (2xi32 (buildvector x, y)).
6315   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6316       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6317       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6318       N0.getOperand(0).hasOneUse()) {
6319
6320     SDValue BuildVect = N0.getOperand(0);
6321     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6322     EVT TruncVecEltTy = VT.getVectorElementType();
6323
6324     // Check that the element types match.
6325     if (BuildVectEltTy == TruncVecEltTy) {
6326       // Now we only need to compute the offset of the truncated elements.
6327       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6328       unsigned TruncVecNumElts = VT.getVectorNumElements();
6329       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6330
6331       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6332              "Invalid number of elements");
6333
6334       SmallVector<SDValue, 8> Opnds;
6335       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6336         Opnds.push_back(BuildVect.getOperand(i));
6337
6338       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6339     }
6340   }
6341
6342   // See if we can simplify the input to this truncate through knowledge that
6343   // only the low bits are being used.
6344   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6345   // Currently we only perform this optimization on scalars because vectors
6346   // may have different active low bits.
6347   if (!VT.isVector()) {
6348     SDValue Shorter =
6349       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6350                                                VT.getSizeInBits()));
6351     if (Shorter.getNode())
6352       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6353   }
6354   // fold (truncate (load x)) -> (smaller load x)
6355   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6356   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6357     SDValue Reduced = ReduceLoadWidth(N);
6358     if (Reduced.getNode())
6359       return Reduced;
6360     // Handle the case where the load remains an extending load even
6361     // after truncation.
6362     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6363       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6364       if (!LN0->isVolatile() &&
6365           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6366         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6367                                          VT, LN0->getChain(), LN0->getBasePtr(),
6368                                          LN0->getMemoryVT(),
6369                                          LN0->getMemOperand());
6370         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6371         return NewLoad;
6372       }
6373     }
6374   }
6375   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6376   // where ... are all 'undef'.
6377   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6378     SmallVector<EVT, 8> VTs;
6379     SDValue V;
6380     unsigned Idx = 0;
6381     unsigned NumDefs = 0;
6382
6383     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6384       SDValue X = N0.getOperand(i);
6385       if (X.getOpcode() != ISD::UNDEF) {
6386         V = X;
6387         Idx = i;
6388         NumDefs++;
6389       }
6390       // Stop if more than one members are non-undef.
6391       if (NumDefs > 1)
6392         break;
6393       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6394                                      VT.getVectorElementType(),
6395                                      X.getValueType().getVectorNumElements()));
6396     }
6397
6398     if (NumDefs == 0)
6399       return DAG.getUNDEF(VT);
6400
6401     if (NumDefs == 1) {
6402       assert(V.getNode() && "The single defined operand is empty!");
6403       SmallVector<SDValue, 8> Opnds;
6404       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6405         if (i != Idx) {
6406           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6407           continue;
6408         }
6409         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6410         AddToWorklist(NV.getNode());
6411         Opnds.push_back(NV);
6412       }
6413       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6414     }
6415   }
6416
6417   // Simplify the operands using demanded-bits information.
6418   if (!VT.isVector() &&
6419       SimplifyDemandedBits(SDValue(N, 0)))
6420     return SDValue(N, 0);
6421
6422   return SDValue();
6423 }
6424
6425 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6426   SDValue Elt = N->getOperand(i);
6427   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6428     return Elt.getNode();
6429   return Elt.getOperand(Elt.getResNo()).getNode();
6430 }
6431
6432 /// build_pair (load, load) -> load
6433 /// if load locations are consecutive.
6434 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6435   assert(N->getOpcode() == ISD::BUILD_PAIR);
6436
6437   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6438   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6439   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6440       LD1->getAddressSpace() != LD2->getAddressSpace())
6441     return SDValue();
6442   EVT LD1VT = LD1->getValueType(0);
6443
6444   if (ISD::isNON_EXTLoad(LD2) &&
6445       LD2->hasOneUse() &&
6446       // If both are volatile this would reduce the number of volatile loads.
6447       // If one is volatile it might be ok, but play conservative and bail out.
6448       !LD1->isVolatile() &&
6449       !LD2->isVolatile() &&
6450       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6451     unsigned Align = LD1->getAlignment();
6452     unsigned NewAlign = TLI.getDataLayout()->
6453       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6454
6455     if (NewAlign <= Align &&
6456         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6457       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6458                          LD1->getBasePtr(), LD1->getPointerInfo(),
6459                          false, false, false, Align);
6460   }
6461
6462   return SDValue();
6463 }
6464
6465 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6466   SDValue N0 = N->getOperand(0);
6467   EVT VT = N->getValueType(0);
6468
6469   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6470   // Only do this before legalize, since afterward the target may be depending
6471   // on the bitconvert.
6472   // First check to see if this is all constant.
6473   if (!LegalTypes &&
6474       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6475       VT.isVector()) {
6476     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6477
6478     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6479     assert(!DestEltVT.isVector() &&
6480            "Element type of vector ValueType must not be vector!");
6481     if (isSimple)
6482       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6483   }
6484
6485   // If the input is a constant, let getNode fold it.
6486   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6487     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6488     if (Res.getNode() != N) {
6489       if (!LegalOperations ||
6490           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6491         return Res;
6492
6493       // Folding it resulted in an illegal node, and it's too late to
6494       // do that. Clean up the old node and forego the transformation.
6495       // Ideally this won't happen very often, because instcombine
6496       // and the earlier dagcombine runs (where illegal nodes are
6497       // permitted) should have folded most of them already.
6498       deleteAndRecombine(Res.getNode());
6499     }
6500   }
6501
6502   // (conv (conv x, t1), t2) -> (conv x, t2)
6503   if (N0.getOpcode() == ISD::BITCAST)
6504     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6505                        N0.getOperand(0));
6506
6507   // fold (conv (load x)) -> (load (conv*)x)
6508   // If the resultant load doesn't need a higher alignment than the original!
6509   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6510       // Do not change the width of a volatile load.
6511       !cast<LoadSDNode>(N0)->isVolatile() &&
6512       // Do not remove the cast if the types differ in endian layout.
6513       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6514       TLI.hasBigEndianPartOrdering(VT) &&
6515       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6516       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6517     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6518     unsigned Align = TLI.getDataLayout()->
6519       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6520     unsigned OrigAlign = LN0->getAlignment();
6521
6522     if (Align <= OrigAlign) {
6523       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6524                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6525                                  LN0->isVolatile(), LN0->isNonTemporal(),
6526                                  LN0->isInvariant(), OrigAlign,
6527                                  LN0->getAAInfo());
6528       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6529       return Load;
6530     }
6531   }
6532
6533   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6534   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6535   // This often reduces constant pool loads.
6536   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6537        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6538       N0.getNode()->hasOneUse() && VT.isInteger() &&
6539       !VT.isVector() && !N0.getValueType().isVector()) {
6540     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6541                                   N0.getOperand(0));
6542     AddToWorklist(NewConv.getNode());
6543
6544     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6545     if (N0.getOpcode() == ISD::FNEG)
6546       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6547                          NewConv, DAG.getConstant(SignBit, VT));
6548     assert(N0.getOpcode() == ISD::FABS);
6549     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6550                        NewConv, DAG.getConstant(~SignBit, VT));
6551   }
6552
6553   // fold (bitconvert (fcopysign cst, x)) ->
6554   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6555   // Note that we don't handle (copysign x, cst) because this can always be
6556   // folded to an fneg or fabs.
6557   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6558       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6559       VT.isInteger() && !VT.isVector()) {
6560     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6561     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6562     if (isTypeLegal(IntXVT)) {
6563       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6564                               IntXVT, N0.getOperand(1));
6565       AddToWorklist(X.getNode());
6566
6567       // If X has a different width than the result/lhs, sext it or truncate it.
6568       unsigned VTWidth = VT.getSizeInBits();
6569       if (OrigXWidth < VTWidth) {
6570         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6571         AddToWorklist(X.getNode());
6572       } else if (OrigXWidth > VTWidth) {
6573         // To get the sign bit in the right place, we have to shift it right
6574         // before truncating.
6575         X = DAG.getNode(ISD::SRL, SDLoc(X),
6576                         X.getValueType(), X,
6577                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6578         AddToWorklist(X.getNode());
6579         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6580         AddToWorklist(X.getNode());
6581       }
6582
6583       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6584       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6585                       X, DAG.getConstant(SignBit, VT));
6586       AddToWorklist(X.getNode());
6587
6588       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6589                                 VT, N0.getOperand(0));
6590       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6591                         Cst, DAG.getConstant(~SignBit, VT));
6592       AddToWorklist(Cst.getNode());
6593
6594       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6595     }
6596   }
6597
6598   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6599   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6600     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6601     if (CombineLD.getNode())
6602       return CombineLD;
6603   }
6604
6605   return SDValue();
6606 }
6607
6608 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6609   EVT VT = N->getValueType(0);
6610   return CombineConsecutiveLoads(N, VT);
6611 }
6612
6613 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6614 /// operands. DstEltVT indicates the destination element value type.
6615 SDValue DAGCombiner::
6616 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6617   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6618
6619   // If this is already the right type, we're done.
6620   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6621
6622   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6623   unsigned DstBitSize = DstEltVT.getSizeInBits();
6624
6625   // If this is a conversion of N elements of one type to N elements of another
6626   // type, convert each element.  This handles FP<->INT cases.
6627   if (SrcBitSize == DstBitSize) {
6628     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6629                               BV->getValueType(0).getVectorNumElements());
6630
6631     // Due to the FP element handling below calling this routine recursively,
6632     // we can end up with a scalar-to-vector node here.
6633     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6634       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6635                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6636                                      DstEltVT, BV->getOperand(0)));
6637
6638     SmallVector<SDValue, 8> Ops;
6639     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6640       SDValue Op = BV->getOperand(i);
6641       // If the vector element type is not legal, the BUILD_VECTOR operands
6642       // are promoted and implicitly truncated.  Make that explicit here.
6643       if (Op.getValueType() != SrcEltVT)
6644         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6645       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6646                                 DstEltVT, Op));
6647       AddToWorklist(Ops.back().getNode());
6648     }
6649     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6650   }
6651
6652   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6653   // handle annoying details of growing/shrinking FP values, we convert them to
6654   // int first.
6655   if (SrcEltVT.isFloatingPoint()) {
6656     // Convert the input float vector to a int vector where the elements are the
6657     // same sizes.
6658     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6659     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6660     SrcEltVT = IntVT;
6661   }
6662
6663   // Now we know the input is an integer vector.  If the output is a FP type,
6664   // convert to integer first, then to FP of the right size.
6665   if (DstEltVT.isFloatingPoint()) {
6666     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6667     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6668
6669     // Next, convert to FP elements of the same size.
6670     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6671   }
6672
6673   // Okay, we know the src/dst types are both integers of differing types.
6674   // Handling growing first.
6675   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6676   if (SrcBitSize < DstBitSize) {
6677     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6678
6679     SmallVector<SDValue, 8> Ops;
6680     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6681          i += NumInputsPerOutput) {
6682       bool isLE = TLI.isLittleEndian();
6683       APInt NewBits = APInt(DstBitSize, 0);
6684       bool EltIsUndef = true;
6685       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6686         // Shift the previously computed bits over.
6687         NewBits <<= SrcBitSize;
6688         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6689         if (Op.getOpcode() == ISD::UNDEF) continue;
6690         EltIsUndef = false;
6691
6692         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6693                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6694       }
6695
6696       if (EltIsUndef)
6697         Ops.push_back(DAG.getUNDEF(DstEltVT));
6698       else
6699         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6700     }
6701
6702     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6703     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6704   }
6705
6706   // Finally, this must be the case where we are shrinking elements: each input
6707   // turns into multiple outputs.
6708   bool isS2V = ISD::isScalarToVector(BV);
6709   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6710   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6711                             NumOutputsPerInput*BV->getNumOperands());
6712   SmallVector<SDValue, 8> Ops;
6713
6714   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6715     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6716       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6717         Ops.push_back(DAG.getUNDEF(DstEltVT));
6718       continue;
6719     }
6720
6721     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6722                   getAPIntValue().zextOrTrunc(SrcBitSize);
6723
6724     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6725       APInt ThisVal = OpVal.trunc(DstBitSize);
6726       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6727       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6728         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6729         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6730                            Ops[0]);
6731       OpVal = OpVal.lshr(DstBitSize);
6732     }
6733
6734     // For big endian targets, swap the order of the pieces of each element.
6735     if (TLI.isBigEndian())
6736       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6737   }
6738
6739   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6740 }
6741
6742 SDValue DAGCombiner::visitFADD(SDNode *N) {
6743   SDValue N0 = N->getOperand(0);
6744   SDValue N1 = N->getOperand(1);
6745   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6746   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6747   EVT VT = N->getValueType(0);
6748   const TargetOptions &Options = DAG.getTarget().Options;
6749
6750   // fold vector ops
6751   if (VT.isVector()) {
6752     SDValue FoldedVOp = SimplifyVBinOp(N);
6753     if (FoldedVOp.getNode()) return FoldedVOp;
6754   }
6755
6756   // fold (fadd c1, c2) -> c1 + c2
6757   if (N0CFP && N1CFP)
6758     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6759
6760   // canonicalize constant to RHS
6761   if (N0CFP && !N1CFP)
6762     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6763
6764   // fold (fadd A, (fneg B)) -> (fsub A, B)
6765   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6766       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6767     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6768                        GetNegatedExpression(N1, DAG, LegalOperations));
6769
6770   // fold (fadd (fneg A), B) -> (fsub B, A)
6771   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6772       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6773     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6774                        GetNegatedExpression(N0, DAG, LegalOperations));
6775
6776   // If 'unsafe math' is enabled, fold lots of things.
6777   if (Options.UnsafeFPMath) {
6778     // No FP constant should be created after legalization as Instruction
6779     // Selection pass has a hard time dealing with FP constants.
6780     bool AllowNewConst = (Level < AfterLegalizeDAG);
6781
6782     // fold (fadd A, 0) -> A
6783     if (N1CFP && N1CFP->getValueAPF().isZero())
6784       return N0;
6785
6786     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6787     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6788         isa<ConstantFPSDNode>(N0.getOperand(1)))
6789       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6790                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6791                                      N0.getOperand(1), N1));
6792
6793     // If allowed, fold (fadd (fneg x), x) -> 0.0
6794     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6795       return DAG.getConstantFP(0.0, VT);
6796
6797     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6798     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6799       return DAG.getConstantFP(0.0, VT);
6800
6801     // We can fold chains of FADD's of the same value into multiplications.
6802     // This transform is not safe in general because we are reducing the number
6803     // of rounding steps.
6804     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6805       if (N0.getOpcode() == ISD::FMUL) {
6806         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6807         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6808
6809         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6810         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6811           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6812                                        SDValue(CFP01, 0),
6813                                        DAG.getConstantFP(1.0, VT));
6814           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6815         }
6816
6817         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6818         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6819             N1.getOperand(0) == N1.getOperand(1) &&
6820             N0.getOperand(0) == N1.getOperand(0)) {
6821           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6822                                        SDValue(CFP01, 0),
6823                                        DAG.getConstantFP(2.0, VT));
6824           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6825                              N0.getOperand(0), NewCFP);
6826         }
6827       }
6828
6829       if (N1.getOpcode() == ISD::FMUL) {
6830         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6831         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6832
6833         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6834         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6835           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6836                                        SDValue(CFP11, 0),
6837                                        DAG.getConstantFP(1.0, VT));
6838           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6839         }
6840
6841         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6842         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6843             N0.getOperand(0) == N0.getOperand(1) &&
6844             N1.getOperand(0) == N0.getOperand(0)) {
6845           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6846                                        SDValue(CFP11, 0),
6847                                        DAG.getConstantFP(2.0, VT));
6848           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6849         }
6850       }
6851
6852       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6853         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6854         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6855         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6856             (N0.getOperand(0) == N1))
6857           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6858                              N1, DAG.getConstantFP(3.0, VT));
6859       }
6860
6861       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6862         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6863         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6864         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6865             N1.getOperand(0) == N0)
6866           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6867                              N0, DAG.getConstantFP(3.0, VT));
6868       }
6869
6870       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6871       if (AllowNewConst &&
6872           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6873           N0.getOperand(0) == N0.getOperand(1) &&
6874           N1.getOperand(0) == N1.getOperand(1) &&
6875           N0.getOperand(0) == N1.getOperand(0))
6876         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6877                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6878     }
6879   } // enable-unsafe-fp-math
6880
6881   // FADD -> FMA combines:
6882   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6883       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6884       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6885
6886     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6887     if (N0.getOpcode() == ISD::FMUL &&
6888         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6889       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6890                          N0.getOperand(0), N0.getOperand(1), N1);
6891
6892     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6893     // Note: Commutes FADD operands.
6894     if (N1.getOpcode() == ISD::FMUL &&
6895         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6896       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6897                          N1.getOperand(0), N1.getOperand(1), N0);
6898   }
6899
6900   return SDValue();
6901 }
6902
6903 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6904   SDValue N0 = N->getOperand(0);
6905   SDValue N1 = N->getOperand(1);
6906   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6907   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6908   EVT VT = N->getValueType(0);
6909   SDLoc dl(N);
6910   const TargetOptions &Options = DAG.getTarget().Options;
6911
6912   // fold vector ops
6913   if (VT.isVector()) {
6914     SDValue FoldedVOp = SimplifyVBinOp(N);
6915     if (FoldedVOp.getNode()) return FoldedVOp;
6916   }
6917
6918   // fold (fsub c1, c2) -> c1-c2
6919   if (N0CFP && N1CFP)
6920     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6921
6922   // fold (fsub A, (fneg B)) -> (fadd A, B)
6923   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6924     return DAG.getNode(ISD::FADD, dl, VT, N0,
6925                        GetNegatedExpression(N1, DAG, LegalOperations));
6926
6927   // If 'unsafe math' is enabled, fold lots of things.
6928   if (Options.UnsafeFPMath) {
6929     // (fsub A, 0) -> A
6930     if (N1CFP && N1CFP->getValueAPF().isZero())
6931       return N0;
6932
6933     // (fsub 0, B) -> -B
6934     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6935       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6936         return GetNegatedExpression(N1, DAG, LegalOperations);
6937       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6938         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6939     }
6940
6941     // (fsub x, x) -> 0.0
6942     if (N0 == N1)
6943       return DAG.getConstantFP(0.0f, VT);
6944
6945     // (fsub x, (fadd x, y)) -> (fneg y)
6946     // (fsub x, (fadd y, x)) -> (fneg y)
6947     if (N1.getOpcode() == ISD::FADD) {
6948       SDValue N10 = N1->getOperand(0);
6949       SDValue N11 = N1->getOperand(1);
6950
6951       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6952         return GetNegatedExpression(N11, DAG, LegalOperations);
6953
6954       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6955         return GetNegatedExpression(N10, DAG, LegalOperations);
6956     }
6957   }
6958
6959   // FSUB -> FMA combines:
6960   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6961       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6962       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6963
6964     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6965     if (N0.getOpcode() == ISD::FMUL &&
6966         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6967       return DAG.getNode(ISD::FMA, dl, VT,
6968                          N0.getOperand(0), N0.getOperand(1),
6969                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6970
6971     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6972     // Note: Commutes FSUB operands.
6973     if (N1.getOpcode() == ISD::FMUL &&
6974         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6975       return DAG.getNode(ISD::FMA, dl, VT,
6976                          DAG.getNode(ISD::FNEG, dl, VT,
6977                          N1.getOperand(0)),
6978                          N1.getOperand(1), N0);
6979
6980     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6981     if (N0.getOpcode() == ISD::FNEG &&
6982         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6983         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6984             TLI.enableAggressiveFMAFusion(VT))) {
6985       SDValue N00 = N0.getOperand(0).getOperand(0);
6986       SDValue N01 = N0.getOperand(0).getOperand(1);
6987       return DAG.getNode(ISD::FMA, dl, VT,
6988                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6989                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6990     }
6991   }
6992
6993   return SDValue();
6994 }
6995
6996 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6997   SDValue N0 = N->getOperand(0);
6998   SDValue N1 = N->getOperand(1);
6999   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7000   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7001   EVT VT = N->getValueType(0);
7002   const TargetOptions &Options = DAG.getTarget().Options;
7003
7004   // fold vector ops
7005   if (VT.isVector()) {
7006     // This just handles C1 * C2 for vectors. Other vector folds are below.
7007     SDValue FoldedVOp = SimplifyVBinOp(N);
7008     if (FoldedVOp.getNode())
7009       return FoldedVOp;
7010     // Canonicalize vector constant to RHS.
7011     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7012         N1.getOpcode() != ISD::BUILD_VECTOR)
7013       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7014         if (BV0->isConstant())
7015           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7016   }
7017
7018   // fold (fmul c1, c2) -> c1*c2
7019   if (N0CFP && N1CFP)
7020     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7021
7022   // canonicalize constant to RHS
7023   if (N0CFP && !N1CFP)
7024     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7025
7026   // fold (fmul A, 1.0) -> A
7027   if (N1CFP && N1CFP->isExactlyValue(1.0))
7028     return N0;
7029
7030   if (Options.UnsafeFPMath) {
7031     // fold (fmul A, 0) -> 0
7032     if (N1CFP && N1CFP->getValueAPF().isZero())
7033       return N1;
7034
7035     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7036     if (N0.getOpcode() == ISD::FMUL) {
7037       // Fold scalars or any vector constants (not just splats).
7038       // This fold is done in general by InstCombine, but extra fmul insts
7039       // may have been generated during lowering.
7040       SDValue N01 = N0.getOperand(1);
7041       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7042       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7043       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7044           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7045         SDLoc SL(N);
7046         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7047         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7048       }
7049     }
7050
7051     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7052     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7053     // during an early run of DAGCombiner can prevent folding with fmuls
7054     // inserted during lowering.
7055     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7056       SDLoc SL(N);
7057       const SDValue Two = DAG.getConstantFP(2.0, VT);
7058       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7059       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7060     }
7061   }
7062
7063   // fold (fmul X, 2.0) -> (fadd X, X)
7064   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7065     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7066
7067   // fold (fmul X, -1.0) -> (fneg X)
7068   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7069     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7070       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7071
7072   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7073   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7074     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7075       // Both can be negated for free, check to see if at least one is cheaper
7076       // negated.
7077       if (LHSNeg == 2 || RHSNeg == 2)
7078         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7079                            GetNegatedExpression(N0, DAG, LegalOperations),
7080                            GetNegatedExpression(N1, DAG, LegalOperations));
7081     }
7082   }
7083
7084   return SDValue();
7085 }
7086
7087 SDValue DAGCombiner::visitFMA(SDNode *N) {
7088   SDValue N0 = N->getOperand(0);
7089   SDValue N1 = N->getOperand(1);
7090   SDValue N2 = N->getOperand(2);
7091   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7092   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7093   EVT VT = N->getValueType(0);
7094   SDLoc dl(N);
7095   const TargetOptions &Options = DAG.getTarget().Options;
7096
7097   // Constant fold FMA.
7098   if (isa<ConstantFPSDNode>(N0) &&
7099       isa<ConstantFPSDNode>(N1) &&
7100       isa<ConstantFPSDNode>(N2)) {
7101     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7102   }
7103
7104   if (Options.UnsafeFPMath) {
7105     if (N0CFP && N0CFP->isZero())
7106       return N2;
7107     if (N1CFP && N1CFP->isZero())
7108       return N2;
7109   }
7110   if (N0CFP && N0CFP->isExactlyValue(1.0))
7111     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7112   if (N1CFP && N1CFP->isExactlyValue(1.0))
7113     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7114
7115   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7116   if (N0CFP && !N1CFP)
7117     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7118
7119   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7120   if (Options.UnsafeFPMath && N1CFP &&
7121       N2.getOpcode() == ISD::FMUL &&
7122       N0 == N2.getOperand(0) &&
7123       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7124     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7125                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7126   }
7127
7128
7129   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7130   if (Options.UnsafeFPMath &&
7131       N0.getOpcode() == ISD::FMUL && N1CFP &&
7132       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7133     return DAG.getNode(ISD::FMA, dl, VT,
7134                        N0.getOperand(0),
7135                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7136                        N2);
7137   }
7138
7139   // (fma x, 1, y) -> (fadd x, y)
7140   // (fma x, -1, y) -> (fadd (fneg x), y)
7141   if (N1CFP) {
7142     if (N1CFP->isExactlyValue(1.0))
7143       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7144
7145     if (N1CFP->isExactlyValue(-1.0) &&
7146         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7147       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7148       AddToWorklist(RHSNeg.getNode());
7149       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7150     }
7151   }
7152
7153   // (fma x, c, x) -> (fmul x, (c+1))
7154   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7155     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7156                        DAG.getNode(ISD::FADD, dl, VT,
7157                                    N1, DAG.getConstantFP(1.0, VT)));
7158
7159   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7160   if (Options.UnsafeFPMath && N1CFP &&
7161       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7162     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7163                        DAG.getNode(ISD::FADD, dl, VT,
7164                                    N1, DAG.getConstantFP(-1.0, VT)));
7165
7166
7167   return SDValue();
7168 }
7169
7170 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7171   SDValue N0 = N->getOperand(0);
7172   SDValue N1 = N->getOperand(1);
7173   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7174   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7175   EVT VT = N->getValueType(0);
7176   SDLoc DL(N);
7177   const TargetOptions &Options = DAG.getTarget().Options;
7178
7179   // fold vector ops
7180   if (VT.isVector()) {
7181     SDValue FoldedVOp = SimplifyVBinOp(N);
7182     if (FoldedVOp.getNode()) return FoldedVOp;
7183   }
7184
7185   // fold (fdiv c1, c2) -> c1/c2
7186   if (N0CFP && N1CFP)
7187     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7188
7189   if (Options.UnsafeFPMath) {
7190     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7191     if (N1CFP) {
7192       // Compute the reciprocal 1.0 / c2.
7193       APFloat N1APF = N1CFP->getValueAPF();
7194       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7195       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7196       // Only do the transform if the reciprocal is a legal fp immediate that
7197       // isn't too nasty (eg NaN, denormal, ...).
7198       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7199           (!LegalOperations ||
7200            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7201            // backend)... we should handle this gracefully after Legalize.
7202            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7203            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7204            TLI.isFPImmLegal(Recip, VT)))
7205         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7206                            DAG.getConstantFP(Recip, VT));
7207     }
7208
7209     // If this FDIV is part of a reciprocal square root, it may be folded
7210     // into a target-specific square root estimate instruction.
7211     if (N1.getOpcode() == ISD::FSQRT) {
7212       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7213         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7214       }
7215     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7216                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7217       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7218         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7219         AddToWorklist(RV.getNode());
7220         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7221       }
7222     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7223                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7224       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7225         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7226         AddToWorklist(RV.getNode());
7227         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7228       }
7229     } else if (N1.getOpcode() == ISD::FMUL) {
7230       // Look through an FMUL. Even though this won't remove the FDIV directly,
7231       // it's still worthwhile to get rid of the FSQRT if possible.
7232       SDValue SqrtOp;
7233       SDValue OtherOp;
7234       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7235         SqrtOp = N1.getOperand(0);
7236         OtherOp = N1.getOperand(1);
7237       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7238         SqrtOp = N1.getOperand(1);
7239         OtherOp = N1.getOperand(0);
7240       }
7241       if (SqrtOp.getNode()) {
7242         // We found a FSQRT, so try to make this fold:
7243         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7244         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7245           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7246           AddToWorklist(RV.getNode());
7247           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7248         }
7249       }
7250     }
7251
7252     // Fold into a reciprocal estimate and multiply instead of a real divide.
7253     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7254       AddToWorklist(RV.getNode());
7255       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7256     }
7257   }
7258
7259   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7260   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7261     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7262       // Both can be negated for free, check to see if at least one is cheaper
7263       // negated.
7264       if (LHSNeg == 2 || RHSNeg == 2)
7265         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7266                            GetNegatedExpression(N0, DAG, LegalOperations),
7267                            GetNegatedExpression(N1, DAG, LegalOperations));
7268     }
7269   }
7270
7271   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7272   // reciprocal.
7273   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7274   // Notice that this is not always beneficial. One reason is different target
7275   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7276   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7277   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7278   if (Options.UnsafeFPMath) {
7279     // Skip if current node is a reciprocal.
7280     if (N0CFP && N0CFP->isExactlyValue(1.0))
7281       return SDValue();
7282
7283     SmallVector<SDNode *, 4> Users;
7284     // Find all FDIV users of the same divisor.
7285     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7286                               UE = N1.getNode()->use_end();
7287          UI != UE; ++UI) {
7288       SDNode *User = UI.getUse().getUser();
7289       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7290         Users.push_back(User);
7291     }
7292
7293     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7294       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7295       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7296
7297       // Dividend / Divisor -> Dividend * Reciprocal
7298       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7299         if ((*I)->getOperand(0) != FPOne) {
7300           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7301                                         (*I)->getOperand(0), Reciprocal);
7302           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7303         }
7304       }
7305       return SDValue();
7306     }
7307   }
7308
7309   return SDValue();
7310 }
7311
7312 SDValue DAGCombiner::visitFREM(SDNode *N) {
7313   SDValue N0 = N->getOperand(0);
7314   SDValue N1 = N->getOperand(1);
7315   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7316   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7317   EVT VT = N->getValueType(0);
7318
7319   // fold (frem c1, c2) -> fmod(c1,c2)
7320   if (N0CFP && N1CFP)
7321     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7322
7323   return SDValue();
7324 }
7325
7326 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7327   if (DAG.getTarget().Options.UnsafeFPMath) {
7328     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7329     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7330       EVT VT = RV.getValueType();
7331       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7332       AddToWorklist(RV.getNode());
7333
7334       // Unfortunately, RV is now NaN if the input was exactly 0.
7335       // Select out this case and force the answer to 0.
7336       SDValue Zero = DAG.getConstantFP(0.0, VT);
7337       SDValue ZeroCmp =
7338         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7339                      N->getOperand(0), Zero, ISD::SETEQ);
7340       AddToWorklist(ZeroCmp.getNode());
7341       AddToWorklist(RV.getNode());
7342
7343       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7344                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7345       return RV;
7346     }
7347   }
7348   return SDValue();
7349 }
7350
7351 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7352   SDValue N0 = N->getOperand(0);
7353   SDValue N1 = N->getOperand(1);
7354   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7355   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7356   EVT VT = N->getValueType(0);
7357
7358   if (N0CFP && N1CFP)  // Constant fold
7359     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7360
7361   if (N1CFP) {
7362     const APFloat& V = N1CFP->getValueAPF();
7363     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7364     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7365     if (!V.isNegative()) {
7366       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7367         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7368     } else {
7369       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7370         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7371                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7372     }
7373   }
7374
7375   // copysign(fabs(x), y) -> copysign(x, y)
7376   // copysign(fneg(x), y) -> copysign(x, y)
7377   // copysign(copysign(x,z), y) -> copysign(x, y)
7378   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7379       N0.getOpcode() == ISD::FCOPYSIGN)
7380     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7381                        N0.getOperand(0), N1);
7382
7383   // copysign(x, abs(y)) -> abs(x)
7384   if (N1.getOpcode() == ISD::FABS)
7385     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7386
7387   // copysign(x, copysign(y,z)) -> copysign(x, z)
7388   if (N1.getOpcode() == ISD::FCOPYSIGN)
7389     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7390                        N0, N1.getOperand(1));
7391
7392   // copysign(x, fp_extend(y)) -> copysign(x, y)
7393   // copysign(x, fp_round(y)) -> copysign(x, y)
7394   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7395     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7396                        N0, N1.getOperand(0));
7397
7398   return SDValue();
7399 }
7400
7401 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7402   SDValue N0 = N->getOperand(0);
7403   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7404   EVT VT = N->getValueType(0);
7405   EVT OpVT = N0.getValueType();
7406
7407   // fold (sint_to_fp c1) -> c1fp
7408   if (N0C &&
7409       // ...but only if the target supports immediate floating-point values
7410       (!LegalOperations ||
7411        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7412     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7413
7414   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7415   // but UINT_TO_FP is legal on this target, try to convert.
7416   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7417       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7418     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7419     if (DAG.SignBitIsZero(N0))
7420       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7421   }
7422
7423   // The next optimizations are desirable only if SELECT_CC can be lowered.
7424   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7425     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7426     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7427         !VT.isVector() &&
7428         (!LegalOperations ||
7429          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7430       SDValue Ops[] =
7431         { N0.getOperand(0), N0.getOperand(1),
7432           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7433           N0.getOperand(2) };
7434       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7435     }
7436
7437     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7438     //      (select_cc x, y, 1.0, 0.0,, cc)
7439     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7440         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7441         (!LegalOperations ||
7442          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7443       SDValue Ops[] =
7444         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7445           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7446           N0.getOperand(0).getOperand(2) };
7447       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7448     }
7449   }
7450
7451   return SDValue();
7452 }
7453
7454 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7455   SDValue N0 = N->getOperand(0);
7456   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7457   EVT VT = N->getValueType(0);
7458   EVT OpVT = N0.getValueType();
7459
7460   // fold (uint_to_fp c1) -> c1fp
7461   if (N0C &&
7462       // ...but only if the target supports immediate floating-point values
7463       (!LegalOperations ||
7464        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7465     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7466
7467   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7468   // but SINT_TO_FP is legal on this target, try to convert.
7469   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7470       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7471     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7472     if (DAG.SignBitIsZero(N0))
7473       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7474   }
7475
7476   // The next optimizations are desirable only if SELECT_CC can be lowered.
7477   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7478     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7479
7480     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7481         (!LegalOperations ||
7482          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7483       SDValue Ops[] =
7484         { N0.getOperand(0), N0.getOperand(1),
7485           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7486           N0.getOperand(2) };
7487       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7488     }
7489   }
7490
7491   return SDValue();
7492 }
7493
7494 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7495   SDValue N0 = N->getOperand(0);
7496   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7497   EVT VT = N->getValueType(0);
7498
7499   // fold (fp_to_sint c1fp) -> c1
7500   if (N0CFP)
7501     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7502
7503   return SDValue();
7504 }
7505
7506 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7507   SDValue N0 = N->getOperand(0);
7508   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7509   EVT VT = N->getValueType(0);
7510
7511   // fold (fp_to_uint c1fp) -> c1
7512   if (N0CFP)
7513     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7514
7515   return SDValue();
7516 }
7517
7518 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7519   SDValue N0 = N->getOperand(0);
7520   SDValue N1 = N->getOperand(1);
7521   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7522   EVT VT = N->getValueType(0);
7523
7524   // fold (fp_round c1fp) -> c1fp
7525   if (N0CFP)
7526     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7527
7528   // fold (fp_round (fp_extend x)) -> x
7529   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7530     return N0.getOperand(0);
7531
7532   // fold (fp_round (fp_round x)) -> (fp_round x)
7533   if (N0.getOpcode() == ISD::FP_ROUND) {
7534     // This is a value preserving truncation if both round's are.
7535     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7536                    N0.getNode()->getConstantOperandVal(1) == 1;
7537     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7538                        DAG.getIntPtrConstant(IsTrunc));
7539   }
7540
7541   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7542   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7543     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7544                               N0.getOperand(0), N1);
7545     AddToWorklist(Tmp.getNode());
7546     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7547                        Tmp, N0.getOperand(1));
7548   }
7549
7550   return SDValue();
7551 }
7552
7553 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7554   SDValue N0 = N->getOperand(0);
7555   EVT VT = N->getValueType(0);
7556   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7557   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7558
7559   // fold (fp_round_inreg c1fp) -> c1fp
7560   if (N0CFP && isTypeLegal(EVT)) {
7561     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7562     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7563   }
7564
7565   return SDValue();
7566 }
7567
7568 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7569   SDValue N0 = N->getOperand(0);
7570   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7571   EVT VT = N->getValueType(0);
7572
7573   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7574   if (N->hasOneUse() &&
7575       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7576     return SDValue();
7577
7578   // fold (fp_extend c1fp) -> c1fp
7579   if (N0CFP)
7580     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7581
7582   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7583   // value of X.
7584   if (N0.getOpcode() == ISD::FP_ROUND
7585       && N0.getNode()->getConstantOperandVal(1) == 1) {
7586     SDValue In = N0.getOperand(0);
7587     if (In.getValueType() == VT) return In;
7588     if (VT.bitsLT(In.getValueType()))
7589       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7590                          In, N0.getOperand(1));
7591     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7592   }
7593
7594   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7595   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7596        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7597     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7598     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7599                                      LN0->getChain(),
7600                                      LN0->getBasePtr(), N0.getValueType(),
7601                                      LN0->getMemOperand());
7602     CombineTo(N, ExtLoad);
7603     CombineTo(N0.getNode(),
7604               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7605                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7606               ExtLoad.getValue(1));
7607     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7608   }
7609
7610   return SDValue();
7611 }
7612
7613 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7614   SDValue N0 = N->getOperand(0);
7615   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7616   EVT VT = N->getValueType(0);
7617
7618   // fold (fceil c1) -> fceil(c1)
7619   if (N0CFP)
7620     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7621
7622   return SDValue();
7623 }
7624
7625 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7626   SDValue N0 = N->getOperand(0);
7627   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7628   EVT VT = N->getValueType(0);
7629
7630   // fold (ftrunc c1) -> ftrunc(c1)
7631   if (N0CFP)
7632     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7633
7634   return SDValue();
7635 }
7636
7637 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7638   SDValue N0 = N->getOperand(0);
7639   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7640   EVT VT = N->getValueType(0);
7641
7642   // fold (ffloor c1) -> ffloor(c1)
7643   if (N0CFP)
7644     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7645
7646   return SDValue();
7647 }
7648
7649 // FIXME: FNEG and FABS have a lot in common; refactor.
7650 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7651   SDValue N0 = N->getOperand(0);
7652   EVT VT = N->getValueType(0);
7653
7654   if (VT.isVector()) {
7655     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7656     if (FoldedVOp.getNode()) return FoldedVOp;
7657   }
7658
7659   // Constant fold FNEG.
7660   if (isa<ConstantFPSDNode>(N0))
7661     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7662
7663   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7664                          &DAG.getTarget().Options))
7665     return GetNegatedExpression(N0, DAG, LegalOperations);
7666
7667   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7668   // constant pool values.
7669   if (!TLI.isFNegFree(VT) &&
7670       N0.getOpcode() == ISD::BITCAST &&
7671       N0.getNode()->hasOneUse()) {
7672     SDValue Int = N0.getOperand(0);
7673     EVT IntVT = Int.getValueType();
7674     if (IntVT.isInteger() && !IntVT.isVector()) {
7675       APInt SignMask;
7676       if (N0.getValueType().isVector()) {
7677         // For a vector, get a mask such as 0x80... per scalar element
7678         // and splat it.
7679         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7680         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7681       } else {
7682         // For a scalar, just generate 0x80...
7683         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7684       }
7685       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7686                         DAG.getConstant(SignMask, IntVT));
7687       AddToWorklist(Int.getNode());
7688       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7689     }
7690   }
7691
7692   // (fneg (fmul c, x)) -> (fmul -c, x)
7693   if (N0.getOpcode() == ISD::FMUL) {
7694     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7695     if (CFP1) {
7696       APFloat CVal = CFP1->getValueAPF();
7697       CVal.changeSign();
7698       if (Level >= AfterLegalizeDAG &&
7699           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7700            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7701         return DAG.getNode(
7702             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7703             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7704     }
7705   }
7706
7707   return SDValue();
7708 }
7709
7710 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7711   SDValue N0 = N->getOperand(0);
7712   SDValue N1 = N->getOperand(1);
7713   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7714   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7715
7716   if (N0CFP && N1CFP) {
7717     const APFloat &C0 = N0CFP->getValueAPF();
7718     const APFloat &C1 = N1CFP->getValueAPF();
7719     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7720   }
7721
7722   if (N0CFP) {
7723     EVT VT = N->getValueType(0);
7724     // Canonicalize to constant on RHS.
7725     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7726   }
7727
7728   return SDValue();
7729 }
7730
7731 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7732   SDValue N0 = N->getOperand(0);
7733   SDValue N1 = N->getOperand(1);
7734   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7735   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7736
7737   if (N0CFP && N1CFP) {
7738     const APFloat &C0 = N0CFP->getValueAPF();
7739     const APFloat &C1 = N1CFP->getValueAPF();
7740     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7741   }
7742
7743   if (N0CFP) {
7744     EVT VT = N->getValueType(0);
7745     // Canonicalize to constant on RHS.
7746     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7747   }
7748
7749   return SDValue();
7750 }
7751
7752 SDValue DAGCombiner::visitFABS(SDNode *N) {
7753   SDValue N0 = N->getOperand(0);
7754   EVT VT = N->getValueType(0);
7755
7756   if (VT.isVector()) {
7757     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7758     if (FoldedVOp.getNode()) return FoldedVOp;
7759   }
7760
7761   // fold (fabs c1) -> fabs(c1)
7762   if (isa<ConstantFPSDNode>(N0))
7763     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7764
7765   // fold (fabs (fabs x)) -> (fabs x)
7766   if (N0.getOpcode() == ISD::FABS)
7767     return N->getOperand(0);
7768
7769   // fold (fabs (fneg x)) -> (fabs x)
7770   // fold (fabs (fcopysign x, y)) -> (fabs x)
7771   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7772     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7773
7774   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7775   // constant pool values.
7776   if (!TLI.isFAbsFree(VT) &&
7777       N0.getOpcode() == ISD::BITCAST &&
7778       N0.getNode()->hasOneUse()) {
7779     SDValue Int = N0.getOperand(0);
7780     EVT IntVT = Int.getValueType();
7781     if (IntVT.isInteger() && !IntVT.isVector()) {
7782       APInt SignMask;
7783       if (N0.getValueType().isVector()) {
7784         // For a vector, get a mask such as 0x7f... per scalar element
7785         // and splat it.
7786         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7787         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7788       } else {
7789         // For a scalar, just generate 0x7f...
7790         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7791       }
7792       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7793                         DAG.getConstant(SignMask, IntVT));
7794       AddToWorklist(Int.getNode());
7795       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7796     }
7797   }
7798
7799   return SDValue();
7800 }
7801
7802 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7803   SDValue Chain = N->getOperand(0);
7804   SDValue N1 = N->getOperand(1);
7805   SDValue N2 = N->getOperand(2);
7806
7807   // If N is a constant we could fold this into a fallthrough or unconditional
7808   // branch. However that doesn't happen very often in normal code, because
7809   // Instcombine/SimplifyCFG should have handled the available opportunities.
7810   // If we did this folding here, it would be necessary to update the
7811   // MachineBasicBlock CFG, which is awkward.
7812
7813   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7814   // on the target.
7815   if (N1.getOpcode() == ISD::SETCC &&
7816       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7817                                    N1.getOperand(0).getValueType())) {
7818     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7819                        Chain, N1.getOperand(2),
7820                        N1.getOperand(0), N1.getOperand(1), N2);
7821   }
7822
7823   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7824       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7825        (N1.getOperand(0).hasOneUse() &&
7826         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7827     SDNode *Trunc = nullptr;
7828     if (N1.getOpcode() == ISD::TRUNCATE) {
7829       // Look pass the truncate.
7830       Trunc = N1.getNode();
7831       N1 = N1.getOperand(0);
7832     }
7833
7834     // Match this pattern so that we can generate simpler code:
7835     //
7836     //   %a = ...
7837     //   %b = and i32 %a, 2
7838     //   %c = srl i32 %b, 1
7839     //   brcond i32 %c ...
7840     //
7841     // into
7842     //
7843     //   %a = ...
7844     //   %b = and i32 %a, 2
7845     //   %c = setcc eq %b, 0
7846     //   brcond %c ...
7847     //
7848     // This applies only when the AND constant value has one bit set and the
7849     // SRL constant is equal to the log2 of the AND constant. The back-end is
7850     // smart enough to convert the result into a TEST/JMP sequence.
7851     SDValue Op0 = N1.getOperand(0);
7852     SDValue Op1 = N1.getOperand(1);
7853
7854     if (Op0.getOpcode() == ISD::AND &&
7855         Op1.getOpcode() == ISD::Constant) {
7856       SDValue AndOp1 = Op0.getOperand(1);
7857
7858       if (AndOp1.getOpcode() == ISD::Constant) {
7859         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7860
7861         if (AndConst.isPowerOf2() &&
7862             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7863           SDValue SetCC =
7864             DAG.getSetCC(SDLoc(N),
7865                          getSetCCResultType(Op0.getValueType()),
7866                          Op0, DAG.getConstant(0, Op0.getValueType()),
7867                          ISD::SETNE);
7868
7869           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7870                                           MVT::Other, Chain, SetCC, N2);
7871           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7872           // will convert it back to (X & C1) >> C2.
7873           CombineTo(N, NewBRCond, false);
7874           // Truncate is dead.
7875           if (Trunc)
7876             deleteAndRecombine(Trunc);
7877           // Replace the uses of SRL with SETCC
7878           WorklistRemover DeadNodes(*this);
7879           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7880           deleteAndRecombine(N1.getNode());
7881           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7882         }
7883       }
7884     }
7885
7886     if (Trunc)
7887       // Restore N1 if the above transformation doesn't match.
7888       N1 = N->getOperand(1);
7889   }
7890
7891   // Transform br(xor(x, y)) -> br(x != y)
7892   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7893   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7894     SDNode *TheXor = N1.getNode();
7895     SDValue Op0 = TheXor->getOperand(0);
7896     SDValue Op1 = TheXor->getOperand(1);
7897     if (Op0.getOpcode() == Op1.getOpcode()) {
7898       // Avoid missing important xor optimizations.
7899       SDValue Tmp = visitXOR(TheXor);
7900       if (Tmp.getNode()) {
7901         if (Tmp.getNode() != TheXor) {
7902           DEBUG(dbgs() << "\nReplacing.8 ";
7903                 TheXor->dump(&DAG);
7904                 dbgs() << "\nWith: ";
7905                 Tmp.getNode()->dump(&DAG);
7906                 dbgs() << '\n');
7907           WorklistRemover DeadNodes(*this);
7908           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7909           deleteAndRecombine(TheXor);
7910           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7911                              MVT::Other, Chain, Tmp, N2);
7912         }
7913
7914         // visitXOR has changed XOR's operands or replaced the XOR completely,
7915         // bail out.
7916         return SDValue(N, 0);
7917       }
7918     }
7919
7920     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7921       bool Equal = false;
7922       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7923         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7924             Op0.getOpcode() == ISD::XOR) {
7925           TheXor = Op0.getNode();
7926           Equal = true;
7927         }
7928
7929       EVT SetCCVT = N1.getValueType();
7930       if (LegalTypes)
7931         SetCCVT = getSetCCResultType(SetCCVT);
7932       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7933                                    SetCCVT,
7934                                    Op0, Op1,
7935                                    Equal ? ISD::SETEQ : ISD::SETNE);
7936       // Replace the uses of XOR with SETCC
7937       WorklistRemover DeadNodes(*this);
7938       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7939       deleteAndRecombine(N1.getNode());
7940       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7941                          MVT::Other, Chain, SetCC, N2);
7942     }
7943   }
7944
7945   return SDValue();
7946 }
7947
7948 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7949 //
7950 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7951   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7952   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7953
7954   // If N is a constant we could fold this into a fallthrough or unconditional
7955   // branch. However that doesn't happen very often in normal code, because
7956   // Instcombine/SimplifyCFG should have handled the available opportunities.
7957   // If we did this folding here, it would be necessary to update the
7958   // MachineBasicBlock CFG, which is awkward.
7959
7960   // Use SimplifySetCC to simplify SETCC's.
7961   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7962                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7963                                false);
7964   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7965
7966   // fold to a simpler setcc
7967   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7968     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7969                        N->getOperand(0), Simp.getOperand(2),
7970                        Simp.getOperand(0), Simp.getOperand(1),
7971                        N->getOperand(4));
7972
7973   return SDValue();
7974 }
7975
7976 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7977 /// and that N may be folded in the load / store addressing mode.
7978 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7979                                     SelectionDAG &DAG,
7980                                     const TargetLowering &TLI) {
7981   EVT VT;
7982   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7983     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7984       return false;
7985     VT = Use->getValueType(0);
7986   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7987     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7988       return false;
7989     VT = ST->getValue().getValueType();
7990   } else
7991     return false;
7992
7993   TargetLowering::AddrMode AM;
7994   if (N->getOpcode() == ISD::ADD) {
7995     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7996     if (Offset)
7997       // [reg +/- imm]
7998       AM.BaseOffs = Offset->getSExtValue();
7999     else
8000       // [reg +/- reg]
8001       AM.Scale = 1;
8002   } else if (N->getOpcode() == ISD::SUB) {
8003     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8004     if (Offset)
8005       // [reg +/- imm]
8006       AM.BaseOffs = -Offset->getSExtValue();
8007     else
8008       // [reg +/- reg]
8009       AM.Scale = 1;
8010   } else
8011     return false;
8012
8013   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8014 }
8015
8016 /// Try turning a load/store into a pre-indexed load/store when the base
8017 /// pointer is an add or subtract and it has other uses besides the load/store.
8018 /// After the transformation, the new indexed load/store has effectively folded
8019 /// the add/subtract in and all of its other uses are redirected to the
8020 /// new load/store.
8021 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8022   if (Level < AfterLegalizeDAG)
8023     return false;
8024
8025   bool isLoad = true;
8026   SDValue Ptr;
8027   EVT VT;
8028   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8029     if (LD->isIndexed())
8030       return false;
8031     VT = LD->getMemoryVT();
8032     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8033         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8034       return false;
8035     Ptr = LD->getBasePtr();
8036   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8037     if (ST->isIndexed())
8038       return false;
8039     VT = ST->getMemoryVT();
8040     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8041         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8042       return false;
8043     Ptr = ST->getBasePtr();
8044     isLoad = false;
8045   } else {
8046     return false;
8047   }
8048
8049   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8050   // out.  There is no reason to make this a preinc/predec.
8051   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8052       Ptr.getNode()->hasOneUse())
8053     return false;
8054
8055   // Ask the target to do addressing mode selection.
8056   SDValue BasePtr;
8057   SDValue Offset;
8058   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8059   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8060     return false;
8061
8062   // Backends without true r+i pre-indexed forms may need to pass a
8063   // constant base with a variable offset so that constant coercion
8064   // will work with the patterns in canonical form.
8065   bool Swapped = false;
8066   if (isa<ConstantSDNode>(BasePtr)) {
8067     std::swap(BasePtr, Offset);
8068     Swapped = true;
8069   }
8070
8071   // Don't create a indexed load / store with zero offset.
8072   if (isa<ConstantSDNode>(Offset) &&
8073       cast<ConstantSDNode>(Offset)->isNullValue())
8074     return false;
8075
8076   // Try turning it into a pre-indexed load / store except when:
8077   // 1) The new base ptr is a frame index.
8078   // 2) If N is a store and the new base ptr is either the same as or is a
8079   //    predecessor of the value being stored.
8080   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8081   //    that would create a cycle.
8082   // 4) All uses are load / store ops that use it as old base ptr.
8083
8084   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8085   // (plus the implicit offset) to a register to preinc anyway.
8086   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8087     return false;
8088
8089   // Check #2.
8090   if (!isLoad) {
8091     SDValue Val = cast<StoreSDNode>(N)->getValue();
8092     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8093       return false;
8094   }
8095
8096   // If the offset is a constant, there may be other adds of constants that
8097   // can be folded with this one. We should do this to avoid having to keep
8098   // a copy of the original base pointer.
8099   SmallVector<SDNode *, 16> OtherUses;
8100   if (isa<ConstantSDNode>(Offset))
8101     for (SDNode *Use : BasePtr.getNode()->uses()) {
8102       if (Use == Ptr.getNode())
8103         continue;
8104
8105       if (Use->isPredecessorOf(N))
8106         continue;
8107
8108       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8109         OtherUses.clear();
8110         break;
8111       }
8112
8113       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8114       if (Op1.getNode() == BasePtr.getNode())
8115         std::swap(Op0, Op1);
8116       assert(Op0.getNode() == BasePtr.getNode() &&
8117              "Use of ADD/SUB but not an operand");
8118
8119       if (!isa<ConstantSDNode>(Op1)) {
8120         OtherUses.clear();
8121         break;
8122       }
8123
8124       // FIXME: In some cases, we can be smarter about this.
8125       if (Op1.getValueType() != Offset.getValueType()) {
8126         OtherUses.clear();
8127         break;
8128       }
8129
8130       OtherUses.push_back(Use);
8131     }
8132
8133   if (Swapped)
8134     std::swap(BasePtr, Offset);
8135
8136   // Now check for #3 and #4.
8137   bool RealUse = false;
8138
8139   // Caches for hasPredecessorHelper
8140   SmallPtrSet<const SDNode *, 32> Visited;
8141   SmallVector<const SDNode *, 16> Worklist;
8142
8143   for (SDNode *Use : Ptr.getNode()->uses()) {
8144     if (Use == N)
8145       continue;
8146     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8147       return false;
8148
8149     // If Ptr may be folded in addressing mode of other use, then it's
8150     // not profitable to do this transformation.
8151     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8152       RealUse = true;
8153   }
8154
8155   if (!RealUse)
8156     return false;
8157
8158   SDValue Result;
8159   if (isLoad)
8160     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8161                                 BasePtr, Offset, AM);
8162   else
8163     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8164                                  BasePtr, Offset, AM);
8165   ++PreIndexedNodes;
8166   ++NodesCombined;
8167   DEBUG(dbgs() << "\nReplacing.4 ";
8168         N->dump(&DAG);
8169         dbgs() << "\nWith: ";
8170         Result.getNode()->dump(&DAG);
8171         dbgs() << '\n');
8172   WorklistRemover DeadNodes(*this);
8173   if (isLoad) {
8174     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8175     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8176   } else {
8177     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8178   }
8179
8180   // Finally, since the node is now dead, remove it from the graph.
8181   deleteAndRecombine(N);
8182
8183   if (Swapped)
8184     std::swap(BasePtr, Offset);
8185
8186   // Replace other uses of BasePtr that can be updated to use Ptr
8187   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8188     unsigned OffsetIdx = 1;
8189     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8190       OffsetIdx = 0;
8191     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8192            BasePtr.getNode() && "Expected BasePtr operand");
8193
8194     // We need to replace ptr0 in the following expression:
8195     //   x0 * offset0 + y0 * ptr0 = t0
8196     // knowing that
8197     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8198     //
8199     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8200     // indexed load/store and the expresion that needs to be re-written.
8201     //
8202     // Therefore, we have:
8203     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8204
8205     ConstantSDNode *CN =
8206       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8207     int X0, X1, Y0, Y1;
8208     APInt Offset0 = CN->getAPIntValue();
8209     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8210
8211     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8212     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8213     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8214     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8215
8216     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8217
8218     APInt CNV = Offset0;
8219     if (X0 < 0) CNV = -CNV;
8220     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8221     else CNV = CNV - Offset1;
8222
8223     // We can now generate the new expression.
8224     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8225     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8226
8227     SDValue NewUse = DAG.getNode(Opcode,
8228                                  SDLoc(OtherUses[i]),
8229                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8230     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8231     deleteAndRecombine(OtherUses[i]);
8232   }
8233
8234   // Replace the uses of Ptr with uses of the updated base value.
8235   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8236   deleteAndRecombine(Ptr.getNode());
8237
8238   return true;
8239 }
8240
8241 /// Try to combine a load/store with a add/sub of the base pointer node into a
8242 /// post-indexed load/store. The transformation folded the add/subtract into the
8243 /// new indexed load/store effectively and all of its uses are redirected to the
8244 /// new load/store.
8245 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8246   if (Level < AfterLegalizeDAG)
8247     return false;
8248
8249   bool isLoad = true;
8250   SDValue Ptr;
8251   EVT VT;
8252   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8253     if (LD->isIndexed())
8254       return false;
8255     VT = LD->getMemoryVT();
8256     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8257         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8258       return false;
8259     Ptr = LD->getBasePtr();
8260   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8261     if (ST->isIndexed())
8262       return false;
8263     VT = ST->getMemoryVT();
8264     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8265         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8266       return false;
8267     Ptr = ST->getBasePtr();
8268     isLoad = false;
8269   } else {
8270     return false;
8271   }
8272
8273   if (Ptr.getNode()->hasOneUse())
8274     return false;
8275
8276   for (SDNode *Op : Ptr.getNode()->uses()) {
8277     if (Op == N ||
8278         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8279       continue;
8280
8281     SDValue BasePtr;
8282     SDValue Offset;
8283     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8284     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8285       // Don't create a indexed load / store with zero offset.
8286       if (isa<ConstantSDNode>(Offset) &&
8287           cast<ConstantSDNode>(Offset)->isNullValue())
8288         continue;
8289
8290       // Try turning it into a post-indexed load / store except when
8291       // 1) All uses are load / store ops that use it as base ptr (and
8292       //    it may be folded as addressing mmode).
8293       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8294       //    nor a successor of N. Otherwise, if Op is folded that would
8295       //    create a cycle.
8296
8297       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8298         continue;
8299
8300       // Check for #1.
8301       bool TryNext = false;
8302       for (SDNode *Use : BasePtr.getNode()->uses()) {
8303         if (Use == Ptr.getNode())
8304           continue;
8305
8306         // If all the uses are load / store addresses, then don't do the
8307         // transformation.
8308         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8309           bool RealUse = false;
8310           for (SDNode *UseUse : Use->uses()) {
8311             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8312               RealUse = true;
8313           }
8314
8315           if (!RealUse) {
8316             TryNext = true;
8317             break;
8318           }
8319         }
8320       }
8321
8322       if (TryNext)
8323         continue;
8324
8325       // Check for #2
8326       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8327         SDValue Result = isLoad
8328           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8329                                BasePtr, Offset, AM)
8330           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8331                                 BasePtr, Offset, AM);
8332         ++PostIndexedNodes;
8333         ++NodesCombined;
8334         DEBUG(dbgs() << "\nReplacing.5 ";
8335               N->dump(&DAG);
8336               dbgs() << "\nWith: ";
8337               Result.getNode()->dump(&DAG);
8338               dbgs() << '\n');
8339         WorklistRemover DeadNodes(*this);
8340         if (isLoad) {
8341           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8342           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8343         } else {
8344           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8345         }
8346
8347         // Finally, since the node is now dead, remove it from the graph.
8348         deleteAndRecombine(N);
8349
8350         // Replace the uses of Use with uses of the updated base value.
8351         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8352                                       Result.getValue(isLoad ? 1 : 0));
8353         deleteAndRecombine(Op);
8354         return true;
8355       }
8356     }
8357   }
8358
8359   return false;
8360 }
8361
8362 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8363 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8364   ISD::MemIndexedMode AM = LD->getAddressingMode();
8365   assert(AM != ISD::UNINDEXED);
8366   SDValue BP = LD->getOperand(1);
8367   SDValue Inc = LD->getOperand(2);
8368
8369   // Some backends use TargetConstants for load offsets, but don't expect
8370   // TargetConstants in general ADD nodes. We can convert these constants into
8371   // regular Constants (if the constant is not opaque).
8372   assert((Inc.getOpcode() != ISD::TargetConstant ||
8373           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8374          "Cannot split out indexing using opaque target constants");
8375   if (Inc.getOpcode() == ISD::TargetConstant) {
8376     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8377     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8378                           ConstInc->getValueType(0));
8379   }
8380
8381   unsigned Opc =
8382       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8383   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8384 }
8385
8386 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8387   LoadSDNode *LD  = cast<LoadSDNode>(N);
8388   SDValue Chain = LD->getChain();
8389   SDValue Ptr   = LD->getBasePtr();
8390
8391   // If load is not volatile and there are no uses of the loaded value (and
8392   // the updated indexed value in case of indexed loads), change uses of the
8393   // chain value into uses of the chain input (i.e. delete the dead load).
8394   if (!LD->isVolatile()) {
8395     if (N->getValueType(1) == MVT::Other) {
8396       // Unindexed loads.
8397       if (!N->hasAnyUseOfValue(0)) {
8398         // It's not safe to use the two value CombineTo variant here. e.g.
8399         // v1, chain2 = load chain1, loc
8400         // v2, chain3 = load chain2, loc
8401         // v3         = add v2, c
8402         // Now we replace use of chain2 with chain1.  This makes the second load
8403         // isomorphic to the one we are deleting, and thus makes this load live.
8404         DEBUG(dbgs() << "\nReplacing.6 ";
8405               N->dump(&DAG);
8406               dbgs() << "\nWith chain: ";
8407               Chain.getNode()->dump(&DAG);
8408               dbgs() << "\n");
8409         WorklistRemover DeadNodes(*this);
8410         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8411
8412         if (N->use_empty())
8413           deleteAndRecombine(N);
8414
8415         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8416       }
8417     } else {
8418       // Indexed loads.
8419       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8420
8421       // If this load has an opaque TargetConstant offset, then we cannot split
8422       // the indexing into an add/sub directly (that TargetConstant may not be
8423       // valid for a different type of node, and we cannot convert an opaque
8424       // target constant into a regular constant).
8425       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8426                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8427
8428       if (!N->hasAnyUseOfValue(0) &&
8429           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8430         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8431         SDValue Index;
8432         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8433           Index = SplitIndexingFromLoad(LD);
8434           // Try to fold the base pointer arithmetic into subsequent loads and
8435           // stores.
8436           AddUsersToWorklist(N);
8437         } else
8438           Index = DAG.getUNDEF(N->getValueType(1));
8439         DEBUG(dbgs() << "\nReplacing.7 ";
8440               N->dump(&DAG);
8441               dbgs() << "\nWith: ";
8442               Undef.getNode()->dump(&DAG);
8443               dbgs() << " and 2 other values\n");
8444         WorklistRemover DeadNodes(*this);
8445         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8446         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8447         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8448         deleteAndRecombine(N);
8449         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8450       }
8451     }
8452   }
8453
8454   // If this load is directly stored, replace the load value with the stored
8455   // value.
8456   // TODO: Handle store large -> read small portion.
8457   // TODO: Handle TRUNCSTORE/LOADEXT
8458   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8459     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8460       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8461       if (PrevST->getBasePtr() == Ptr &&
8462           PrevST->getValue().getValueType() == N->getValueType(0))
8463       return CombineTo(N, Chain.getOperand(1), Chain);
8464     }
8465   }
8466
8467   // Try to infer better alignment information than the load already has.
8468   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8469     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8470       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8471         SDValue NewLoad =
8472                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8473                               LD->getValueType(0),
8474                               Chain, Ptr, LD->getPointerInfo(),
8475                               LD->getMemoryVT(),
8476                               LD->isVolatile(), LD->isNonTemporal(),
8477                               LD->isInvariant(), Align, LD->getAAInfo());
8478         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8479       }
8480     }
8481   }
8482
8483   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8484                                                   : DAG.getSubtarget().useAA();
8485 #ifndef NDEBUG
8486   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8487       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8488     UseAA = false;
8489 #endif
8490   if (UseAA && LD->isUnindexed()) {
8491     // Walk up chain skipping non-aliasing memory nodes.
8492     SDValue BetterChain = FindBetterChain(N, Chain);
8493
8494     // If there is a better chain.
8495     if (Chain != BetterChain) {
8496       SDValue ReplLoad;
8497
8498       // Replace the chain to void dependency.
8499       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8500         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8501                                BetterChain, Ptr, LD->getMemOperand());
8502       } else {
8503         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8504                                   LD->getValueType(0),
8505                                   BetterChain, Ptr, LD->getMemoryVT(),
8506                                   LD->getMemOperand());
8507       }
8508
8509       // Create token factor to keep old chain connected.
8510       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8511                                   MVT::Other, Chain, ReplLoad.getValue(1));
8512
8513       // Make sure the new and old chains are cleaned up.
8514       AddToWorklist(Token.getNode());
8515
8516       // Replace uses with load result and token factor. Don't add users
8517       // to work list.
8518       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8519     }
8520   }
8521
8522   // Try transforming N to an indexed load.
8523   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8524     return SDValue(N, 0);
8525
8526   // Try to slice up N to more direct loads if the slices are mapped to
8527   // different register banks or pairing can take place.
8528   if (SliceUpLoad(N))
8529     return SDValue(N, 0);
8530
8531   return SDValue();
8532 }
8533
8534 namespace {
8535 /// \brief Helper structure used to slice a load in smaller loads.
8536 /// Basically a slice is obtained from the following sequence:
8537 /// Origin = load Ty1, Base
8538 /// Shift = srl Ty1 Origin, CstTy Amount
8539 /// Inst = trunc Shift to Ty2
8540 ///
8541 /// Then, it will be rewriten into:
8542 /// Slice = load SliceTy, Base + SliceOffset
8543 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8544 ///
8545 /// SliceTy is deduced from the number of bits that are actually used to
8546 /// build Inst.
8547 struct LoadedSlice {
8548   /// \brief Helper structure used to compute the cost of a slice.
8549   struct Cost {
8550     /// Are we optimizing for code size.
8551     bool ForCodeSize;
8552     /// Various cost.
8553     unsigned Loads;
8554     unsigned Truncates;
8555     unsigned CrossRegisterBanksCopies;
8556     unsigned ZExts;
8557     unsigned Shift;
8558
8559     Cost(bool ForCodeSize = false)
8560         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8561           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8562
8563     /// \brief Get the cost of one isolated slice.
8564     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8565         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8566           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8567       EVT TruncType = LS.Inst->getValueType(0);
8568       EVT LoadedType = LS.getLoadedType();
8569       if (TruncType != LoadedType &&
8570           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8571         ZExts = 1;
8572     }
8573
8574     /// \brief Account for slicing gain in the current cost.
8575     /// Slicing provide a few gains like removing a shift or a
8576     /// truncate. This method allows to grow the cost of the original
8577     /// load with the gain from this slice.
8578     void addSliceGain(const LoadedSlice &LS) {
8579       // Each slice saves a truncate.
8580       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8581       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8582                               LS.Inst->getOperand(0).getValueType()))
8583         ++Truncates;
8584       // If there is a shift amount, this slice gets rid of it.
8585       if (LS.Shift)
8586         ++Shift;
8587       // If this slice can merge a cross register bank copy, account for it.
8588       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8589         ++CrossRegisterBanksCopies;
8590     }
8591
8592     Cost &operator+=(const Cost &RHS) {
8593       Loads += RHS.Loads;
8594       Truncates += RHS.Truncates;
8595       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8596       ZExts += RHS.ZExts;
8597       Shift += RHS.Shift;
8598       return *this;
8599     }
8600
8601     bool operator==(const Cost &RHS) const {
8602       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8603              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8604              ZExts == RHS.ZExts && Shift == RHS.Shift;
8605     }
8606
8607     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8608
8609     bool operator<(const Cost &RHS) const {
8610       // Assume cross register banks copies are as expensive as loads.
8611       // FIXME: Do we want some more target hooks?
8612       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8613       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8614       // Unless we are optimizing for code size, consider the
8615       // expensive operation first.
8616       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8617         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8618       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8619              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8620     }
8621
8622     bool operator>(const Cost &RHS) const { return RHS < *this; }
8623
8624     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8625
8626     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8627   };
8628   // The last instruction that represent the slice. This should be a
8629   // truncate instruction.
8630   SDNode *Inst;
8631   // The original load instruction.
8632   LoadSDNode *Origin;
8633   // The right shift amount in bits from the original load.
8634   unsigned Shift;
8635   // The DAG from which Origin came from.
8636   // This is used to get some contextual information about legal types, etc.
8637   SelectionDAG *DAG;
8638
8639   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8640               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8641       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8642
8643   LoadedSlice(const LoadedSlice &LS)
8644       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8645
8646   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8647   /// \return Result is \p BitWidth and has used bits set to 1 and
8648   ///         not used bits set to 0.
8649   APInt getUsedBits() const {
8650     // Reproduce the trunc(lshr) sequence:
8651     // - Start from the truncated value.
8652     // - Zero extend to the desired bit width.
8653     // - Shift left.
8654     assert(Origin && "No original load to compare against.");
8655     unsigned BitWidth = Origin->getValueSizeInBits(0);
8656     assert(Inst && "This slice is not bound to an instruction");
8657     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8658            "Extracted slice is bigger than the whole type!");
8659     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8660     UsedBits.setAllBits();
8661     UsedBits = UsedBits.zext(BitWidth);
8662     UsedBits <<= Shift;
8663     return UsedBits;
8664   }
8665
8666   /// \brief Get the size of the slice to be loaded in bytes.
8667   unsigned getLoadedSize() const {
8668     unsigned SliceSize = getUsedBits().countPopulation();
8669     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8670     return SliceSize / 8;
8671   }
8672
8673   /// \brief Get the type that will be loaded for this slice.
8674   /// Note: This may not be the final type for the slice.
8675   EVT getLoadedType() const {
8676     assert(DAG && "Missing context");
8677     LLVMContext &Ctxt = *DAG->getContext();
8678     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8679   }
8680
8681   /// \brief Get the alignment of the load used for this slice.
8682   unsigned getAlignment() const {
8683     unsigned Alignment = Origin->getAlignment();
8684     unsigned Offset = getOffsetFromBase();
8685     if (Offset != 0)
8686       Alignment = MinAlign(Alignment, Alignment + Offset);
8687     return Alignment;
8688   }
8689
8690   /// \brief Check if this slice can be rewritten with legal operations.
8691   bool isLegal() const {
8692     // An invalid slice is not legal.
8693     if (!Origin || !Inst || !DAG)
8694       return false;
8695
8696     // Offsets are for indexed load only, we do not handle that.
8697     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8698       return false;
8699
8700     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8701
8702     // Check that the type is legal.
8703     EVT SliceType = getLoadedType();
8704     if (!TLI.isTypeLegal(SliceType))
8705       return false;
8706
8707     // Check that the load is legal for this type.
8708     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8709       return false;
8710
8711     // Check that the offset can be computed.
8712     // 1. Check its type.
8713     EVT PtrType = Origin->getBasePtr().getValueType();
8714     if (PtrType == MVT::Untyped || PtrType.isExtended())
8715       return false;
8716
8717     // 2. Check that it fits in the immediate.
8718     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8719       return false;
8720
8721     // 3. Check that the computation is legal.
8722     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8723       return false;
8724
8725     // Check that the zext is legal if it needs one.
8726     EVT TruncateType = Inst->getValueType(0);
8727     if (TruncateType != SliceType &&
8728         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8729       return false;
8730
8731     return true;
8732   }
8733
8734   /// \brief Get the offset in bytes of this slice in the original chunk of
8735   /// bits.
8736   /// \pre DAG != nullptr.
8737   uint64_t getOffsetFromBase() const {
8738     assert(DAG && "Missing context.");
8739     bool IsBigEndian =
8740         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8741     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8742     uint64_t Offset = Shift / 8;
8743     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8744     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8745            "The size of the original loaded type is not a multiple of a"
8746            " byte.");
8747     // If Offset is bigger than TySizeInBytes, it means we are loading all
8748     // zeros. This should have been optimized before in the process.
8749     assert(TySizeInBytes > Offset &&
8750            "Invalid shift amount for given loaded size");
8751     if (IsBigEndian)
8752       Offset = TySizeInBytes - Offset - getLoadedSize();
8753     return Offset;
8754   }
8755
8756   /// \brief Generate the sequence of instructions to load the slice
8757   /// represented by this object and redirect the uses of this slice to
8758   /// this new sequence of instructions.
8759   /// \pre this->Inst && this->Origin are valid Instructions and this
8760   /// object passed the legal check: LoadedSlice::isLegal returned true.
8761   /// \return The last instruction of the sequence used to load the slice.
8762   SDValue loadSlice() const {
8763     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8764     const SDValue &OldBaseAddr = Origin->getBasePtr();
8765     SDValue BaseAddr = OldBaseAddr;
8766     // Get the offset in that chunk of bytes w.r.t. the endianess.
8767     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8768     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8769     if (Offset) {
8770       // BaseAddr = BaseAddr + Offset.
8771       EVT ArithType = BaseAddr.getValueType();
8772       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8773                               DAG->getConstant(Offset, ArithType));
8774     }
8775
8776     // Create the type of the loaded slice according to its size.
8777     EVT SliceType = getLoadedType();
8778
8779     // Create the load for the slice.
8780     SDValue LastInst = DAG->getLoad(
8781         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8782         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8783         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8784     // If the final type is not the same as the loaded type, this means that
8785     // we have to pad with zero. Create a zero extend for that.
8786     EVT FinalType = Inst->getValueType(0);
8787     if (SliceType != FinalType)
8788       LastInst =
8789           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8790     return LastInst;
8791   }
8792
8793   /// \brief Check if this slice can be merged with an expensive cross register
8794   /// bank copy. E.g.,
8795   /// i = load i32
8796   /// f = bitcast i32 i to float
8797   bool canMergeExpensiveCrossRegisterBankCopy() const {
8798     if (!Inst || !Inst->hasOneUse())
8799       return false;
8800     SDNode *Use = *Inst->use_begin();
8801     if (Use->getOpcode() != ISD::BITCAST)
8802       return false;
8803     assert(DAG && "Missing context");
8804     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8805     EVT ResVT = Use->getValueType(0);
8806     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8807     const TargetRegisterClass *ArgRC =
8808         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8809     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8810       return false;
8811
8812     // At this point, we know that we perform a cross-register-bank copy.
8813     // Check if it is expensive.
8814     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8815     // Assume bitcasts are cheap, unless both register classes do not
8816     // explicitly share a common sub class.
8817     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8818       return false;
8819
8820     // Check if it will be merged with the load.
8821     // 1. Check the alignment constraint.
8822     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8823         ResVT.getTypeForEVT(*DAG->getContext()));
8824
8825     if (RequiredAlignment > getAlignment())
8826       return false;
8827
8828     // 2. Check that the load is a legal operation for that type.
8829     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8830       return false;
8831
8832     // 3. Check that we do not have a zext in the way.
8833     if (Inst->getValueType(0) != getLoadedType())
8834       return false;
8835
8836     return true;
8837   }
8838 };
8839 }
8840
8841 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8842 /// \p UsedBits looks like 0..0 1..1 0..0.
8843 static bool areUsedBitsDense(const APInt &UsedBits) {
8844   // If all the bits are one, this is dense!
8845   if (UsedBits.isAllOnesValue())
8846     return true;
8847
8848   // Get rid of the unused bits on the right.
8849   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8850   // Get rid of the unused bits on the left.
8851   if (NarrowedUsedBits.countLeadingZeros())
8852     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8853   // Check that the chunk of bits is completely used.
8854   return NarrowedUsedBits.isAllOnesValue();
8855 }
8856
8857 /// \brief Check whether or not \p First and \p Second are next to each other
8858 /// in memory. This means that there is no hole between the bits loaded
8859 /// by \p First and the bits loaded by \p Second.
8860 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8861                                      const LoadedSlice &Second) {
8862   assert(First.Origin == Second.Origin && First.Origin &&
8863          "Unable to match different memory origins.");
8864   APInt UsedBits = First.getUsedBits();
8865   assert((UsedBits & Second.getUsedBits()) == 0 &&
8866          "Slices are not supposed to overlap.");
8867   UsedBits |= Second.getUsedBits();
8868   return areUsedBitsDense(UsedBits);
8869 }
8870
8871 /// \brief Adjust the \p GlobalLSCost according to the target
8872 /// paring capabilities and the layout of the slices.
8873 /// \pre \p GlobalLSCost should account for at least as many loads as
8874 /// there is in the slices in \p LoadedSlices.
8875 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8876                                  LoadedSlice::Cost &GlobalLSCost) {
8877   unsigned NumberOfSlices = LoadedSlices.size();
8878   // If there is less than 2 elements, no pairing is possible.
8879   if (NumberOfSlices < 2)
8880     return;
8881
8882   // Sort the slices so that elements that are likely to be next to each
8883   // other in memory are next to each other in the list.
8884   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8885             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8886     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8887     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8888   });
8889   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8890   // First (resp. Second) is the first (resp. Second) potentially candidate
8891   // to be placed in a paired load.
8892   const LoadedSlice *First = nullptr;
8893   const LoadedSlice *Second = nullptr;
8894   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8895                 // Set the beginning of the pair.
8896                                                            First = Second) {
8897
8898     Second = &LoadedSlices[CurrSlice];
8899
8900     // If First is NULL, it means we start a new pair.
8901     // Get to the next slice.
8902     if (!First)
8903       continue;
8904
8905     EVT LoadedType = First->getLoadedType();
8906
8907     // If the types of the slices are different, we cannot pair them.
8908     if (LoadedType != Second->getLoadedType())
8909       continue;
8910
8911     // Check if the target supplies paired loads for this type.
8912     unsigned RequiredAlignment = 0;
8913     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8914       // move to the next pair, this type is hopeless.
8915       Second = nullptr;
8916       continue;
8917     }
8918     // Check if we meet the alignment requirement.
8919     if (RequiredAlignment > First->getAlignment())
8920       continue;
8921
8922     // Check that both loads are next to each other in memory.
8923     if (!areSlicesNextToEachOther(*First, *Second))
8924       continue;
8925
8926     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8927     --GlobalLSCost.Loads;
8928     // Move to the next pair.
8929     Second = nullptr;
8930   }
8931 }
8932
8933 /// \brief Check the profitability of all involved LoadedSlice.
8934 /// Currently, it is considered profitable if there is exactly two
8935 /// involved slices (1) which are (2) next to each other in memory, and
8936 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8937 ///
8938 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8939 /// the elements themselves.
8940 ///
8941 /// FIXME: When the cost model will be mature enough, we can relax
8942 /// constraints (1) and (2).
8943 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8944                                 const APInt &UsedBits, bool ForCodeSize) {
8945   unsigned NumberOfSlices = LoadedSlices.size();
8946   if (StressLoadSlicing)
8947     return NumberOfSlices > 1;
8948
8949   // Check (1).
8950   if (NumberOfSlices != 2)
8951     return false;
8952
8953   // Check (2).
8954   if (!areUsedBitsDense(UsedBits))
8955     return false;
8956
8957   // Check (3).
8958   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8959   // The original code has one big load.
8960   OrigCost.Loads = 1;
8961   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8962     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8963     // Accumulate the cost of all the slices.
8964     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8965     GlobalSlicingCost += SliceCost;
8966
8967     // Account as cost in the original configuration the gain obtained
8968     // with the current slices.
8969     OrigCost.addSliceGain(LS);
8970   }
8971
8972   // If the target supports paired load, adjust the cost accordingly.
8973   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8974   return OrigCost > GlobalSlicingCost;
8975 }
8976
8977 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8978 /// operations, split it in the various pieces being extracted.
8979 ///
8980 /// This sort of thing is introduced by SROA.
8981 /// This slicing takes care not to insert overlapping loads.
8982 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8983 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8984   if (Level < AfterLegalizeDAG)
8985     return false;
8986
8987   LoadSDNode *LD = cast<LoadSDNode>(N);
8988   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8989       !LD->getValueType(0).isInteger())
8990     return false;
8991
8992   // Keep track of already used bits to detect overlapping values.
8993   // In that case, we will just abort the transformation.
8994   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8995
8996   SmallVector<LoadedSlice, 4> LoadedSlices;
8997
8998   // Check if this load is used as several smaller chunks of bits.
8999   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9000   // of computation for each trunc.
9001   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9002        UI != UIEnd; ++UI) {
9003     // Skip the uses of the chain.
9004     if (UI.getUse().getResNo() != 0)
9005       continue;
9006
9007     SDNode *User = *UI;
9008     unsigned Shift = 0;
9009
9010     // Check if this is a trunc(lshr).
9011     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9012         isa<ConstantSDNode>(User->getOperand(1))) {
9013       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9014       User = *User->use_begin();
9015     }
9016
9017     // At this point, User is a Truncate, iff we encountered, trunc or
9018     // trunc(lshr).
9019     if (User->getOpcode() != ISD::TRUNCATE)
9020       return false;
9021
9022     // The width of the type must be a power of 2 and greater than 8-bits.
9023     // Otherwise the load cannot be represented in LLVM IR.
9024     // Moreover, if we shifted with a non-8-bits multiple, the slice
9025     // will be across several bytes. We do not support that.
9026     unsigned Width = User->getValueSizeInBits(0);
9027     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9028       return 0;
9029
9030     // Build the slice for this chain of computations.
9031     LoadedSlice LS(User, LD, Shift, &DAG);
9032     APInt CurrentUsedBits = LS.getUsedBits();
9033
9034     // Check if this slice overlaps with another.
9035     if ((CurrentUsedBits & UsedBits) != 0)
9036       return false;
9037     // Update the bits used globally.
9038     UsedBits |= CurrentUsedBits;
9039
9040     // Check if the new slice would be legal.
9041     if (!LS.isLegal())
9042       return false;
9043
9044     // Record the slice.
9045     LoadedSlices.push_back(LS);
9046   }
9047
9048   // Abort slicing if it does not seem to be profitable.
9049   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9050     return false;
9051
9052   ++SlicedLoads;
9053
9054   // Rewrite each chain to use an independent load.
9055   // By construction, each chain can be represented by a unique load.
9056
9057   // Prepare the argument for the new token factor for all the slices.
9058   SmallVector<SDValue, 8> ArgChains;
9059   for (SmallVectorImpl<LoadedSlice>::const_iterator
9060            LSIt = LoadedSlices.begin(),
9061            LSItEnd = LoadedSlices.end();
9062        LSIt != LSItEnd; ++LSIt) {
9063     SDValue SliceInst = LSIt->loadSlice();
9064     CombineTo(LSIt->Inst, SliceInst, true);
9065     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9066       SliceInst = SliceInst.getOperand(0);
9067     assert(SliceInst->getOpcode() == ISD::LOAD &&
9068            "It takes more than a zext to get to the loaded slice!!");
9069     ArgChains.push_back(SliceInst.getValue(1));
9070   }
9071
9072   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9073                               ArgChains);
9074   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9075   return true;
9076 }
9077
9078 /// Check to see if V is (and load (ptr), imm), where the load is having
9079 /// specific bytes cleared out.  If so, return the byte size being masked out
9080 /// and the shift amount.
9081 static std::pair<unsigned, unsigned>
9082 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9083   std::pair<unsigned, unsigned> Result(0, 0);
9084
9085   // Check for the structure we're looking for.
9086   if (V->getOpcode() != ISD::AND ||
9087       !isa<ConstantSDNode>(V->getOperand(1)) ||
9088       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9089     return Result;
9090
9091   // Check the chain and pointer.
9092   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9093   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9094
9095   // The store should be chained directly to the load or be an operand of a
9096   // tokenfactor.
9097   if (LD == Chain.getNode())
9098     ; // ok.
9099   else if (Chain->getOpcode() != ISD::TokenFactor)
9100     return Result; // Fail.
9101   else {
9102     bool isOk = false;
9103     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9104       if (Chain->getOperand(i).getNode() == LD) {
9105         isOk = true;
9106         break;
9107       }
9108     if (!isOk) return Result;
9109   }
9110
9111   // This only handles simple types.
9112   if (V.getValueType() != MVT::i16 &&
9113       V.getValueType() != MVT::i32 &&
9114       V.getValueType() != MVT::i64)
9115     return Result;
9116
9117   // Check the constant mask.  Invert it so that the bits being masked out are
9118   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9119   // follow the sign bit for uniformity.
9120   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9121   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9122   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9123   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9124   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9125   if (NotMaskLZ == 64) return Result;  // All zero mask.
9126
9127   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9128   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9129     return Result;
9130
9131   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9132   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9133     NotMaskLZ -= 64-V.getValueSizeInBits();
9134
9135   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9136   switch (MaskedBytes) {
9137   case 1:
9138   case 2:
9139   case 4: break;
9140   default: return Result; // All one mask, or 5-byte mask.
9141   }
9142
9143   // Verify that the first bit starts at a multiple of mask so that the access
9144   // is aligned the same as the access width.
9145   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9146
9147   Result.first = MaskedBytes;
9148   Result.second = NotMaskTZ/8;
9149   return Result;
9150 }
9151
9152
9153 /// Check to see if IVal is something that provides a value as specified by
9154 /// MaskInfo. If so, replace the specified store with a narrower store of
9155 /// truncated IVal.
9156 static SDNode *
9157 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9158                                 SDValue IVal, StoreSDNode *St,
9159                                 DAGCombiner *DC) {
9160   unsigned NumBytes = MaskInfo.first;
9161   unsigned ByteShift = MaskInfo.second;
9162   SelectionDAG &DAG = DC->getDAG();
9163
9164   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9165   // that uses this.  If not, this is not a replacement.
9166   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9167                                   ByteShift*8, (ByteShift+NumBytes)*8);
9168   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9169
9170   // Check that it is legal on the target to do this.  It is legal if the new
9171   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9172   // legalization.
9173   MVT VT = MVT::getIntegerVT(NumBytes*8);
9174   if (!DC->isTypeLegal(VT))
9175     return nullptr;
9176
9177   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9178   // shifted by ByteShift and truncated down to NumBytes.
9179   if (ByteShift)
9180     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9181                        DAG.getConstant(ByteShift*8,
9182                                     DC->getShiftAmountTy(IVal.getValueType())));
9183
9184   // Figure out the offset for the store and the alignment of the access.
9185   unsigned StOffset;
9186   unsigned NewAlign = St->getAlignment();
9187
9188   if (DAG.getTargetLoweringInfo().isLittleEndian())
9189     StOffset = ByteShift;
9190   else
9191     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9192
9193   SDValue Ptr = St->getBasePtr();
9194   if (StOffset) {
9195     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9196                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9197     NewAlign = MinAlign(NewAlign, StOffset);
9198   }
9199
9200   // Truncate down to the new size.
9201   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9202
9203   ++OpsNarrowed;
9204   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9205                       St->getPointerInfo().getWithOffset(StOffset),
9206                       false, false, NewAlign).getNode();
9207 }
9208
9209
9210 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9211 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9212 /// narrowing the load and store if it would end up being a win for performance
9213 /// or code size.
9214 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9215   StoreSDNode *ST  = cast<StoreSDNode>(N);
9216   if (ST->isVolatile())
9217     return SDValue();
9218
9219   SDValue Chain = ST->getChain();
9220   SDValue Value = ST->getValue();
9221   SDValue Ptr   = ST->getBasePtr();
9222   EVT VT = Value.getValueType();
9223
9224   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9225     return SDValue();
9226
9227   unsigned Opc = Value.getOpcode();
9228
9229   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9230   // is a byte mask indicating a consecutive number of bytes, check to see if
9231   // Y is known to provide just those bytes.  If so, we try to replace the
9232   // load + replace + store sequence with a single (narrower) store, which makes
9233   // the load dead.
9234   if (Opc == ISD::OR) {
9235     std::pair<unsigned, unsigned> MaskedLoad;
9236     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9237     if (MaskedLoad.first)
9238       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9239                                                   Value.getOperand(1), ST,this))
9240         return SDValue(NewST, 0);
9241
9242     // Or is commutative, so try swapping X and Y.
9243     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9244     if (MaskedLoad.first)
9245       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9246                                                   Value.getOperand(0), ST,this))
9247         return SDValue(NewST, 0);
9248   }
9249
9250   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9251       Value.getOperand(1).getOpcode() != ISD::Constant)
9252     return SDValue();
9253
9254   SDValue N0 = Value.getOperand(0);
9255   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9256       Chain == SDValue(N0.getNode(), 1)) {
9257     LoadSDNode *LD = cast<LoadSDNode>(N0);
9258     if (LD->getBasePtr() != Ptr ||
9259         LD->getPointerInfo().getAddrSpace() !=
9260         ST->getPointerInfo().getAddrSpace())
9261       return SDValue();
9262
9263     // Find the type to narrow it the load / op / store to.
9264     SDValue N1 = Value.getOperand(1);
9265     unsigned BitWidth = N1.getValueSizeInBits();
9266     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9267     if (Opc == ISD::AND)
9268       Imm ^= APInt::getAllOnesValue(BitWidth);
9269     if (Imm == 0 || Imm.isAllOnesValue())
9270       return SDValue();
9271     unsigned ShAmt = Imm.countTrailingZeros();
9272     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9273     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9274     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9275     while (NewBW < BitWidth &&
9276            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9277              TLI.isNarrowingProfitable(VT, NewVT))) {
9278       NewBW = NextPowerOf2(NewBW);
9279       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9280     }
9281     if (NewBW >= BitWidth)
9282       return SDValue();
9283
9284     // If the lsb changed does not start at the type bitwidth boundary,
9285     // start at the previous one.
9286     if (ShAmt % NewBW)
9287       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9288     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9289                                    std::min(BitWidth, ShAmt + NewBW));
9290     if ((Imm & Mask) == Imm) {
9291       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9292       if (Opc == ISD::AND)
9293         NewImm ^= APInt::getAllOnesValue(NewBW);
9294       uint64_t PtrOff = ShAmt / 8;
9295       // For big endian targets, we need to adjust the offset to the pointer to
9296       // load the correct bytes.
9297       if (TLI.isBigEndian())
9298         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9299
9300       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9301       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9302       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9303         return SDValue();
9304
9305       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9306                                    Ptr.getValueType(), Ptr,
9307                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9308       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9309                                   LD->getChain(), NewPtr,
9310                                   LD->getPointerInfo().getWithOffset(PtrOff),
9311                                   LD->isVolatile(), LD->isNonTemporal(),
9312                                   LD->isInvariant(), NewAlign,
9313                                   LD->getAAInfo());
9314       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9315                                    DAG.getConstant(NewImm, NewVT));
9316       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9317                                    NewVal, NewPtr,
9318                                    ST->getPointerInfo().getWithOffset(PtrOff),
9319                                    false, false, NewAlign);
9320
9321       AddToWorklist(NewPtr.getNode());
9322       AddToWorklist(NewLD.getNode());
9323       AddToWorklist(NewVal.getNode());
9324       WorklistRemover DeadNodes(*this);
9325       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9326       ++OpsNarrowed;
9327       return NewST;
9328     }
9329   }
9330
9331   return SDValue();
9332 }
9333
9334 /// For a given floating point load / store pair, if the load value isn't used
9335 /// by any other operations, then consider transforming the pair to integer
9336 /// load / store operations if the target deems the transformation profitable.
9337 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9338   StoreSDNode *ST  = cast<StoreSDNode>(N);
9339   SDValue Chain = ST->getChain();
9340   SDValue Value = ST->getValue();
9341   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9342       Value.hasOneUse() &&
9343       Chain == SDValue(Value.getNode(), 1)) {
9344     LoadSDNode *LD = cast<LoadSDNode>(Value);
9345     EVT VT = LD->getMemoryVT();
9346     if (!VT.isFloatingPoint() ||
9347         VT != ST->getMemoryVT() ||
9348         LD->isNonTemporal() ||
9349         ST->isNonTemporal() ||
9350         LD->getPointerInfo().getAddrSpace() != 0 ||
9351         ST->getPointerInfo().getAddrSpace() != 0)
9352       return SDValue();
9353
9354     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9355     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9356         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9357         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9358         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9359       return SDValue();
9360
9361     unsigned LDAlign = LD->getAlignment();
9362     unsigned STAlign = ST->getAlignment();
9363     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9364     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9365     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9366       return SDValue();
9367
9368     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9369                                 LD->getChain(), LD->getBasePtr(),
9370                                 LD->getPointerInfo(),
9371                                 false, false, false, LDAlign);
9372
9373     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9374                                  NewLD, ST->getBasePtr(),
9375                                  ST->getPointerInfo(),
9376                                  false, false, STAlign);
9377
9378     AddToWorklist(NewLD.getNode());
9379     AddToWorklist(NewST.getNode());
9380     WorklistRemover DeadNodes(*this);
9381     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9382     ++LdStFP2Int;
9383     return NewST;
9384   }
9385
9386   return SDValue();
9387 }
9388
9389 /// Helper struct to parse and store a memory address as base + index + offset.
9390 /// We ignore sign extensions when it is safe to do so.
9391 /// The following two expressions are not equivalent. To differentiate we need
9392 /// to store whether there was a sign extension involved in the index
9393 /// computation.
9394 ///  (load (i64 add (i64 copyfromreg %c)
9395 ///                 (i64 signextend (add (i8 load %index)
9396 ///                                      (i8 1))))
9397 /// vs
9398 ///
9399 /// (load (i64 add (i64 copyfromreg %c)
9400 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9401 ///                                         (i32 1)))))
9402 struct BaseIndexOffset {
9403   SDValue Base;
9404   SDValue Index;
9405   int64_t Offset;
9406   bool IsIndexSignExt;
9407
9408   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9409
9410   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9411                   bool IsIndexSignExt) :
9412     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9413
9414   bool equalBaseIndex(const BaseIndexOffset &Other) {
9415     return Other.Base == Base && Other.Index == Index &&
9416       Other.IsIndexSignExt == IsIndexSignExt;
9417   }
9418
9419   /// Parses tree in Ptr for base, index, offset addresses.
9420   static BaseIndexOffset match(SDValue Ptr) {
9421     bool IsIndexSignExt = false;
9422
9423     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9424     // instruction, then it could be just the BASE or everything else we don't
9425     // know how to handle. Just use Ptr as BASE and give up.
9426     if (Ptr->getOpcode() != ISD::ADD)
9427       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9428
9429     // We know that we have at least an ADD instruction. Try to pattern match
9430     // the simple case of BASE + OFFSET.
9431     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9432       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9433       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9434                               IsIndexSignExt);
9435     }
9436
9437     // Inside a loop the current BASE pointer is calculated using an ADD and a
9438     // MUL instruction. In this case Ptr is the actual BASE pointer.
9439     // (i64 add (i64 %array_ptr)
9440     //          (i64 mul (i64 %induction_var)
9441     //                   (i64 %element_size)))
9442     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9443       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9444
9445     // Look at Base + Index + Offset cases.
9446     SDValue Base = Ptr->getOperand(0);
9447     SDValue IndexOffset = Ptr->getOperand(1);
9448
9449     // Skip signextends.
9450     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9451       IndexOffset = IndexOffset->getOperand(0);
9452       IsIndexSignExt = true;
9453     }
9454
9455     // Either the case of Base + Index (no offset) or something else.
9456     if (IndexOffset->getOpcode() != ISD::ADD)
9457       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9458
9459     // Now we have the case of Base + Index + offset.
9460     SDValue Index = IndexOffset->getOperand(0);
9461     SDValue Offset = IndexOffset->getOperand(1);
9462
9463     if (!isa<ConstantSDNode>(Offset))
9464       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9465
9466     // Ignore signextends.
9467     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9468       Index = Index->getOperand(0);
9469       IsIndexSignExt = true;
9470     } else IsIndexSignExt = false;
9471
9472     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9473     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9474   }
9475 };
9476
9477 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9478 /// is located in a sequence of memory operations connected by a chain.
9479 struct MemOpLink {
9480   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9481     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9482   // Ptr to the mem node.
9483   LSBaseSDNode *MemNode;
9484   // Offset from the base ptr.
9485   int64_t OffsetFromBase;
9486   // What is the sequence number of this mem node.
9487   // Lowest mem operand in the DAG starts at zero.
9488   unsigned SequenceNum;
9489 };
9490
9491 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9492   EVT MemVT = St->getMemoryVT();
9493   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9494   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9495     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9496
9497   // Don't merge vectors into wider inputs.
9498   if (MemVT.isVector() || !MemVT.isSimple())
9499     return false;
9500
9501   // Perform an early exit check. Do not bother looking at stored values that
9502   // are not constants, loads, or extracted vector elements.
9503   SDValue StoredVal = St->getValue();
9504   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9505   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
9506                        isa<ConstantFPSDNode>(StoredVal);
9507   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
9508    
9509   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
9510     return false;
9511
9512   // Only look at ends of store sequences.
9513   SDValue Chain = SDValue(St, 0);
9514   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9515     return false;
9516
9517   // This holds the base pointer, index, and the offset in bytes from the base
9518   // pointer.
9519   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9520
9521   // We must have a base and an offset.
9522   if (!BasePtr.Base.getNode())
9523     return false;
9524
9525   // Do not handle stores to undef base pointers.
9526   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9527     return false;
9528
9529   // Save the LoadSDNodes that we find in the chain.
9530   // We need to make sure that these nodes do not interfere with
9531   // any of the store nodes.
9532   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9533
9534   // Save the StoreSDNodes that we find in the chain.
9535   SmallVector<MemOpLink, 8> StoreNodes;
9536
9537   // Walk up the chain and look for nodes with offsets from the same
9538   // base pointer. Stop when reaching an instruction with a different kind
9539   // or instruction which has a different base pointer.
9540   unsigned Seq = 0;
9541   StoreSDNode *Index = St;
9542   while (Index) {
9543     // If the chain has more than one use, then we can't reorder the mem ops.
9544     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9545       break;
9546
9547     // Find the base pointer and offset for this memory node.
9548     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9549
9550     // Check that the base pointer is the same as the original one.
9551     if (!Ptr.equalBaseIndex(BasePtr))
9552       break;
9553
9554     // Check that the alignment is the same.
9555     if (Index->getAlignment() != St->getAlignment())
9556       break;
9557
9558     // The memory operands must not be volatile.
9559     if (Index->isVolatile() || Index->isIndexed())
9560       break;
9561
9562     // No truncation.
9563     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9564       if (St->isTruncatingStore())
9565         break;
9566
9567     // The stored memory type must be the same.
9568     if (Index->getMemoryVT() != MemVT)
9569       break;
9570
9571     // We do not allow unaligned stores because we want to prevent overriding
9572     // stores.
9573     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9574       break;
9575
9576     // We found a potential memory operand to merge.
9577     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9578
9579     // Find the next memory operand in the chain. If the next operand in the
9580     // chain is a store then move up and continue the scan with the next
9581     // memory operand. If the next operand is a load save it and use alias
9582     // information to check if it interferes with anything.
9583     SDNode *NextInChain = Index->getChain().getNode();
9584     while (1) {
9585       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9586         // We found a store node. Use it for the next iteration.
9587         Index = STn;
9588         break;
9589       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9590         if (Ldn->isVolatile()) {
9591           Index = nullptr;
9592           break;
9593         }
9594
9595         // Save the load node for later. Continue the scan.
9596         AliasLoadNodes.push_back(Ldn);
9597         NextInChain = Ldn->getChain().getNode();
9598         continue;
9599       } else {
9600         Index = nullptr;
9601         break;
9602       }
9603     }
9604   }
9605
9606   // Check if there is anything to merge.
9607   if (StoreNodes.size() < 2)
9608     return false;
9609
9610   // Sort the memory operands according to their distance from the base pointer.
9611   std::sort(StoreNodes.begin(), StoreNodes.end(),
9612             [](MemOpLink LHS, MemOpLink RHS) {
9613     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9614            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9615             LHS.SequenceNum > RHS.SequenceNum);
9616   });
9617
9618   // Scan the memory operations on the chain and find the first non-consecutive
9619   // store memory address.
9620   unsigned LastConsecutiveStore = 0;
9621   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9622   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9623
9624     // Check that the addresses are consecutive starting from the second
9625     // element in the list of stores.
9626     if (i > 0) {
9627       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9628       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9629         break;
9630     }
9631
9632     bool Alias = false;
9633     // Check if this store interferes with any of the loads that we found.
9634     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9635       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9636         Alias = true;
9637         break;
9638       }
9639     // We found a load that alias with this store. Stop the sequence.
9640     if (Alias)
9641       break;
9642
9643     // Mark this node as useful.
9644     LastConsecutiveStore = i;
9645   }
9646
9647   // The node with the lowest store address.
9648   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9649
9650   // Store the constants into memory as one consecutive store.
9651   if (IsConstantSrc) {
9652     unsigned LastLegalType = 0;
9653     unsigned LastLegalVectorType = 0;
9654     bool NonZero = false;
9655     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9656       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9657       SDValue StoredVal = St->getValue();
9658
9659       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9660         NonZero |= !C->isNullValue();
9661       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9662         NonZero |= !C->getConstantFPValue()->isNullValue();
9663       } else {
9664         // Non-constant.
9665         break;
9666       }
9667
9668       // Find a legal type for the constant store.
9669       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9670       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9671       if (TLI.isTypeLegal(StoreTy))
9672         LastLegalType = i+1;
9673       // Or check whether a truncstore is legal.
9674       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9675                TargetLowering::TypePromoteInteger) {
9676         EVT LegalizedStoredValueTy =
9677           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9678         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9679           LastLegalType = i+1;
9680       }
9681
9682       // Find a legal type for the vector store.
9683       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9684       if (TLI.isTypeLegal(Ty))
9685         LastLegalVectorType = i + 1;
9686     }
9687
9688     // We only use vectors if the constant is known to be zero and the
9689     // function is not marked with the noimplicitfloat attribute.
9690     if (NonZero || NoVectors)
9691       LastLegalVectorType = 0;
9692
9693     // Check if we found a legal integer type to store.
9694     if (LastLegalType == 0 && LastLegalVectorType == 0)
9695       return false;
9696
9697     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9698     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9699
9700     // Make sure we have something to merge.
9701     if (NumElem < 2)
9702       return false;
9703
9704     unsigned EarliestNodeUsed = 0;
9705     for (unsigned i=0; i < NumElem; ++i) {
9706       // Find a chain for the new wide-store operand. Notice that some
9707       // of the store nodes that we found may not be selected for inclusion
9708       // in the wide store. The chain we use needs to be the chain of the
9709       // earliest store node which is *used* and replaced by the wide store.
9710       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9711         EarliestNodeUsed = i;
9712     }
9713
9714     // The earliest Node in the DAG.
9715     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9716     SDLoc DL(StoreNodes[0].MemNode);
9717
9718     SDValue StoredVal;
9719     if (UseVector) {
9720       // Find a legal type for the vector store.
9721       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9722       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9723       StoredVal = DAG.getConstant(0, Ty);
9724     } else {
9725       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9726       APInt StoreInt(StoreBW, 0);
9727
9728       // Construct a single integer constant which is made of the smaller
9729       // constant inputs.
9730       bool IsLE = TLI.isLittleEndian();
9731       for (unsigned i = 0; i < NumElem ; ++i) {
9732         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9733         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9734         SDValue Val = St->getValue();
9735         StoreInt<<=ElementSizeBytes*8;
9736         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9737           StoreInt|=C->getAPIntValue().zext(StoreBW);
9738         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9739           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9740         } else {
9741           assert(false && "Invalid constant element type");
9742         }
9743       }
9744
9745       // Create the new Load and Store operations.
9746       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9747       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9748     }
9749
9750     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9751                                     FirstInChain->getBasePtr(),
9752                                     FirstInChain->getPointerInfo(),
9753                                     false, false,
9754                                     FirstInChain->getAlignment());
9755
9756     // Replace the first store with the new store
9757     CombineTo(EarliestOp, NewStore);
9758     // Erase all other stores.
9759     for (unsigned i = 0; i < NumElem ; ++i) {
9760       if (StoreNodes[i].MemNode == EarliestOp)
9761         continue;
9762       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9763       // ReplaceAllUsesWith will replace all uses that existed when it was
9764       // called, but graph optimizations may cause new ones to appear. For
9765       // example, the case in pr14333 looks like
9766       //
9767       //  St's chain -> St -> another store -> X
9768       //
9769       // And the only difference from St to the other store is the chain.
9770       // When we change it's chain to be St's chain they become identical,
9771       // get CSEed and the net result is that X is now a use of St.
9772       // Since we know that St is redundant, just iterate.
9773       while (!St->use_empty())
9774         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9775       deleteAndRecombine(St);
9776     }
9777
9778     return true;
9779   }
9780
9781   // When extracting multiple vector elements, try to store them
9782   // in one vector store rather than a sequence of scalar stores.
9783   if (IsExtractVecEltSrc) {
9784     unsigned NumElem = 0;
9785     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
9786       // Find a legal type for the vector store.
9787       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9788       if (TLI.isTypeLegal(Ty))
9789         NumElem = i + 1;
9790     }
9791
9792     // Make sure we have a legal type and something to merge.
9793     if (NumElem < 2)
9794       return false;
9795
9796     unsigned EarliestNodeUsed = 0;
9797     for (unsigned i=0; i < NumElem; ++i) {
9798       // Find a chain for the new wide-store operand. Notice that some
9799       // of the store nodes that we found may not be selected for inclusion
9800       // in the wide store. The chain we use needs to be the chain of the
9801       // earliest store node which is *used* and replaced by the wide store.
9802       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9803         EarliestNodeUsed = i;
9804     }
9805    
9806     // The earliest Node in the DAG.
9807     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9808     SDLoc DL(StoreNodes[0].MemNode);
9809    
9810     SDValue StoredVal;
9811
9812     // Find a legal type for the vector store.
9813     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9814
9815     SmallVector<SDValue, 8> Ops;
9816     for (unsigned i = 0; i < NumElem ; ++i) {
9817       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9818       SDValue Val = St->getValue();
9819       // All of the operands of a BUILD_VECTOR must have the same type.
9820       if (Val.getValueType() != MemVT)
9821         return false;
9822       Ops.push_back(Val);
9823     }
9824    
9825     // Build the extracted vector elements back into a vector.
9826     StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
9827
9828     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9829                                     FirstInChain->getBasePtr(),
9830                                     FirstInChain->getPointerInfo(),
9831                                     false, false,
9832                                     FirstInChain->getAlignment());
9833
9834     // Replace the first store with the new store
9835     CombineTo(EarliestOp, NewStore);
9836     // Erase all other stores.
9837     for (unsigned i = 0; i < NumElem ; ++i) {
9838       if (StoreNodes[i].MemNode == EarliestOp)
9839         continue;
9840       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9841       while (!St->use_empty())
9842         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9843       deleteAndRecombine(St);
9844     }
9845
9846     return true;
9847   }
9848
9849   // Below we handle the case of multiple consecutive stores that
9850   // come from multiple consecutive loads. We merge them into a single
9851   // wide load and a single wide store.
9852
9853   // Look for load nodes which are used by the stored values.
9854   SmallVector<MemOpLink, 8> LoadNodes;
9855
9856   // Find acceptable loads. Loads need to have the same chain (token factor),
9857   // must not be zext, volatile, indexed, and they must be consecutive.
9858   BaseIndexOffset LdBasePtr;
9859   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9860     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9861     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9862     if (!Ld) break;
9863
9864     // Loads must only have one use.
9865     if (!Ld->hasNUsesOfValue(1, 0))
9866       break;
9867
9868     // Check that the alignment is the same as the stores.
9869     if (Ld->getAlignment() != St->getAlignment())
9870       break;
9871
9872     // The memory operands must not be volatile.
9873     if (Ld->isVolatile() || Ld->isIndexed())
9874       break;
9875
9876     // We do not accept ext loads.
9877     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9878       break;
9879
9880     // The stored memory type must be the same.
9881     if (Ld->getMemoryVT() != MemVT)
9882       break;
9883
9884     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9885     // If this is not the first ptr that we check.
9886     if (LdBasePtr.Base.getNode()) {
9887       // The base ptr must be the same.
9888       if (!LdPtr.equalBaseIndex(LdBasePtr))
9889         break;
9890     } else {
9891       // Check that all other base pointers are the same as this one.
9892       LdBasePtr = LdPtr;
9893     }
9894
9895     // We found a potential memory operand to merge.
9896     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9897   }
9898
9899   if (LoadNodes.size() < 2)
9900     return false;
9901
9902   // If we have load/store pair instructions and we only have two values,
9903   // don't bother.
9904   unsigned RequiredAlignment;
9905   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9906       St->getAlignment() >= RequiredAlignment)
9907     return false;
9908
9909   // Scan the memory operations on the chain and find the first non-consecutive
9910   // load memory address. These variables hold the index in the store node
9911   // array.
9912   unsigned LastConsecutiveLoad = 0;
9913   // This variable refers to the size and not index in the array.
9914   unsigned LastLegalVectorType = 0;
9915   unsigned LastLegalIntegerType = 0;
9916   StartAddress = LoadNodes[0].OffsetFromBase;
9917   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9918   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9919     // All loads much share the same chain.
9920     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9921       break;
9922
9923     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9924     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9925       break;
9926     LastConsecutiveLoad = i;
9927
9928     // Find a legal type for the vector store.
9929     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9930     if (TLI.isTypeLegal(StoreTy))
9931       LastLegalVectorType = i + 1;
9932
9933     // Find a legal type for the integer store.
9934     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9935     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9936     if (TLI.isTypeLegal(StoreTy))
9937       LastLegalIntegerType = i + 1;
9938     // Or check whether a truncstore and extload is legal.
9939     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9940              TargetLowering::TypePromoteInteger) {
9941       EVT LegalizedStoredValueTy =
9942         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9943       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9944           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9945           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9946           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9947         LastLegalIntegerType = i+1;
9948     }
9949   }
9950
9951   // Only use vector types if the vector type is larger than the integer type.
9952   // If they are the same, use integers.
9953   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9954   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9955
9956   // We add +1 here because the LastXXX variables refer to location while
9957   // the NumElem refers to array/index size.
9958   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9959   NumElem = std::min(LastLegalType, NumElem);
9960
9961   if (NumElem < 2)
9962     return false;
9963
9964   // The earliest Node in the DAG.
9965   unsigned EarliestNodeUsed = 0;
9966   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9967   for (unsigned i=1; i<NumElem; ++i) {
9968     // Find a chain for the new wide-store operand. Notice that some
9969     // of the store nodes that we found may not be selected for inclusion
9970     // in the wide store. The chain we use needs to be the chain of the
9971     // earliest store node which is *used* and replaced by the wide store.
9972     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9973       EarliestNodeUsed = i;
9974   }
9975
9976   // Find if it is better to use vectors or integers to load and store
9977   // to memory.
9978   EVT JointMemOpVT;
9979   if (UseVectorTy) {
9980     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9981   } else {
9982     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9983     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9984   }
9985
9986   SDLoc LoadDL(LoadNodes[0].MemNode);
9987   SDLoc StoreDL(StoreNodes[0].MemNode);
9988
9989   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9990   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9991                                 FirstLoad->getChain(),
9992                                 FirstLoad->getBasePtr(),
9993                                 FirstLoad->getPointerInfo(),
9994                                 false, false, false,
9995                                 FirstLoad->getAlignment());
9996
9997   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9998                                   FirstInChain->getBasePtr(),
9999                                   FirstInChain->getPointerInfo(), false, false,
10000                                   FirstInChain->getAlignment());
10001
10002   // Replace one of the loads with the new load.
10003   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10004   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10005                                 SDValue(NewLoad.getNode(), 1));
10006
10007   // Remove the rest of the load chains.
10008   for (unsigned i = 1; i < NumElem ; ++i) {
10009     // Replace all chain users of the old load nodes with the chain of the new
10010     // load node.
10011     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10012     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10013   }
10014
10015   // Replace the first store with the new store.
10016   CombineTo(EarliestOp, NewStore);
10017   // Erase all other stores.
10018   for (unsigned i = 0; i < NumElem ; ++i) {
10019     // Remove all Store nodes.
10020     if (StoreNodes[i].MemNode == EarliestOp)
10021       continue;
10022     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10023     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10024     deleteAndRecombine(St);
10025   }
10026
10027   return true;
10028 }
10029
10030 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10031   StoreSDNode *ST  = cast<StoreSDNode>(N);
10032   SDValue Chain = ST->getChain();
10033   SDValue Value = ST->getValue();
10034   SDValue Ptr   = ST->getBasePtr();
10035
10036   // If this is a store of a bit convert, store the input value if the
10037   // resultant store does not need a higher alignment than the original.
10038   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10039       ST->isUnindexed()) {
10040     unsigned OrigAlign = ST->getAlignment();
10041     EVT SVT = Value.getOperand(0).getValueType();
10042     unsigned Align = TLI.getDataLayout()->
10043       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10044     if (Align <= OrigAlign &&
10045         ((!LegalOperations && !ST->isVolatile()) ||
10046          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10047       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10048                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10049                           ST->isNonTemporal(), OrigAlign,
10050                           ST->getAAInfo());
10051   }
10052
10053   // Turn 'store undef, Ptr' -> nothing.
10054   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10055     return Chain;
10056
10057   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10058   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10059     // NOTE: If the original store is volatile, this transform must not increase
10060     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10061     // processor operation but an i64 (which is not legal) requires two.  So the
10062     // transform should not be done in this case.
10063     if (Value.getOpcode() != ISD::TargetConstantFP) {
10064       SDValue Tmp;
10065       switch (CFP->getSimpleValueType(0).SimpleTy) {
10066       default: llvm_unreachable("Unknown FP type");
10067       case MVT::f16:    // We don't do this for these yet.
10068       case MVT::f80:
10069       case MVT::f128:
10070       case MVT::ppcf128:
10071         break;
10072       case MVT::f32:
10073         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10074             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10075           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10076                               bitcastToAPInt().getZExtValue(), MVT::i32);
10077           return DAG.getStore(Chain, SDLoc(N), Tmp,
10078                               Ptr, ST->getMemOperand());
10079         }
10080         break;
10081       case MVT::f64:
10082         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10083              !ST->isVolatile()) ||
10084             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10085           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10086                                 getZExtValue(), MVT::i64);
10087           return DAG.getStore(Chain, SDLoc(N), Tmp,
10088                               Ptr, ST->getMemOperand());
10089         }
10090
10091         if (!ST->isVolatile() &&
10092             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10093           // Many FP stores are not made apparent until after legalize, e.g. for
10094           // argument passing.  Since this is so common, custom legalize the
10095           // 64-bit integer store into two 32-bit stores.
10096           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10097           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10098           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10099           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10100
10101           unsigned Alignment = ST->getAlignment();
10102           bool isVolatile = ST->isVolatile();
10103           bool isNonTemporal = ST->isNonTemporal();
10104           AAMDNodes AAInfo = ST->getAAInfo();
10105
10106           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10107                                      Ptr, ST->getPointerInfo(),
10108                                      isVolatile, isNonTemporal,
10109                                      ST->getAlignment(), AAInfo);
10110           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10111                             DAG.getConstant(4, Ptr.getValueType()));
10112           Alignment = MinAlign(Alignment, 4U);
10113           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10114                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10115                                      isVolatile, isNonTemporal,
10116                                      Alignment, AAInfo);
10117           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10118                              St0, St1);
10119         }
10120
10121         break;
10122       }
10123     }
10124   }
10125
10126   // Try to infer better alignment information than the store already has.
10127   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10128     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10129       if (Align > ST->getAlignment())
10130         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10131                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10132                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10133                                  ST->getAAInfo());
10134     }
10135   }
10136
10137   // Try transforming a pair floating point load / store ops to integer
10138   // load / store ops.
10139   SDValue NewST = TransformFPLoadStorePair(N);
10140   if (NewST.getNode())
10141     return NewST;
10142
10143   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10144                                                   : DAG.getSubtarget().useAA();
10145 #ifndef NDEBUG
10146   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10147       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10148     UseAA = false;
10149 #endif
10150   if (UseAA && ST->isUnindexed()) {
10151     // Walk up chain skipping non-aliasing memory nodes.
10152     SDValue BetterChain = FindBetterChain(N, Chain);
10153
10154     // If there is a better chain.
10155     if (Chain != BetterChain) {
10156       SDValue ReplStore;
10157
10158       // Replace the chain to avoid dependency.
10159       if (ST->isTruncatingStore()) {
10160         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10161                                       ST->getMemoryVT(), ST->getMemOperand());
10162       } else {
10163         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10164                                  ST->getMemOperand());
10165       }
10166
10167       // Create token to keep both nodes around.
10168       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10169                                   MVT::Other, Chain, ReplStore);
10170
10171       // Make sure the new and old chains are cleaned up.
10172       AddToWorklist(Token.getNode());
10173
10174       // Don't add users to work list.
10175       return CombineTo(N, Token, false);
10176     }
10177   }
10178
10179   // Try transforming N to an indexed store.
10180   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10181     return SDValue(N, 0);
10182
10183   // FIXME: is there such a thing as a truncating indexed store?
10184   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10185       Value.getValueType().isInteger()) {
10186     // See if we can simplify the input to this truncstore with knowledge that
10187     // only the low bits are being used.  For example:
10188     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10189     SDValue Shorter =
10190       GetDemandedBits(Value,
10191                       APInt::getLowBitsSet(
10192                         Value.getValueType().getScalarType().getSizeInBits(),
10193                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10194     AddToWorklist(Value.getNode());
10195     if (Shorter.getNode())
10196       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10197                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10198
10199     // Otherwise, see if we can simplify the operation with
10200     // SimplifyDemandedBits, which only works if the value has a single use.
10201     if (SimplifyDemandedBits(Value,
10202                         APInt::getLowBitsSet(
10203                           Value.getValueType().getScalarType().getSizeInBits(),
10204                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10205       return SDValue(N, 0);
10206   }
10207
10208   // If this is a load followed by a store to the same location, then the store
10209   // is dead/noop.
10210   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10211     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10212         ST->isUnindexed() && !ST->isVolatile() &&
10213         // There can't be any side effects between the load and store, such as
10214         // a call or store.
10215         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10216       // The store is dead, remove it.
10217       return Chain;
10218     }
10219   }
10220
10221   // If this is a store followed by a store with the same value to the same
10222   // location, then the store is dead/noop.
10223   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10224     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10225         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10226         ST1->isUnindexed() && !ST1->isVolatile()) {
10227       // The store is dead, remove it.
10228       return Chain;
10229     }
10230   }
10231
10232   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10233   // truncating store.  We can do this even if this is already a truncstore.
10234   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10235       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10236       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10237                             ST->getMemoryVT())) {
10238     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10239                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10240   }
10241
10242   // Only perform this optimization before the types are legal, because we
10243   // don't want to perform this optimization on every DAGCombine invocation.
10244   if (!LegalTypes) {
10245     bool EverChanged = false;
10246
10247     do {
10248       // There can be multiple store sequences on the same chain.
10249       // Keep trying to merge store sequences until we are unable to do so
10250       // or until we merge the last store on the chain.
10251       bool Changed = MergeConsecutiveStores(ST);
10252       EverChanged |= Changed;
10253       if (!Changed) break;
10254     } while (ST->getOpcode() != ISD::DELETED_NODE);
10255
10256     if (EverChanged)
10257       return SDValue(N, 0);
10258   }
10259
10260   return ReduceLoadOpStoreWidth(N);
10261 }
10262
10263 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10264   SDValue InVec = N->getOperand(0);
10265   SDValue InVal = N->getOperand(1);
10266   SDValue EltNo = N->getOperand(2);
10267   SDLoc dl(N);
10268
10269   // If the inserted element is an UNDEF, just use the input vector.
10270   if (InVal.getOpcode() == ISD::UNDEF)
10271     return InVec;
10272
10273   EVT VT = InVec.getValueType();
10274
10275   // If we can't generate a legal BUILD_VECTOR, exit
10276   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10277     return SDValue();
10278
10279   // Check that we know which element is being inserted
10280   if (!isa<ConstantSDNode>(EltNo))
10281     return SDValue();
10282   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10283
10284   // Canonicalize insert_vector_elt dag nodes.
10285   // Example:
10286   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10287   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10288   //
10289   // Do this only if the child insert_vector node has one use; also
10290   // do this only if indices are both constants and Idx1 < Idx0.
10291   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10292       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10293     unsigned OtherElt =
10294       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10295     if (Elt < OtherElt) {
10296       // Swap nodes.
10297       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10298                                   InVec.getOperand(0), InVal, EltNo);
10299       AddToWorklist(NewOp.getNode());
10300       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10301                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10302     }
10303   }
10304
10305   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10306   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10307   // vector elements.
10308   SmallVector<SDValue, 8> Ops;
10309   // Do not combine these two vectors if the output vector will not replace
10310   // the input vector.
10311   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10312     Ops.append(InVec.getNode()->op_begin(),
10313                InVec.getNode()->op_end());
10314   } else if (InVec.getOpcode() == ISD::UNDEF) {
10315     unsigned NElts = VT.getVectorNumElements();
10316     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10317   } else {
10318     return SDValue();
10319   }
10320
10321   // Insert the element
10322   if (Elt < Ops.size()) {
10323     // All the operands of BUILD_VECTOR must have the same type;
10324     // we enforce that here.
10325     EVT OpVT = Ops[0].getValueType();
10326     if (InVal.getValueType() != OpVT)
10327       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10328                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10329                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10330     Ops[Elt] = InVal;
10331   }
10332
10333   // Return the new vector
10334   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10335 }
10336
10337 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10338     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10339   EVT ResultVT = EVE->getValueType(0);
10340   EVT VecEltVT = InVecVT.getVectorElementType();
10341   unsigned Align = OriginalLoad->getAlignment();
10342   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10343       VecEltVT.getTypeForEVT(*DAG.getContext()));
10344
10345   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10346     return SDValue();
10347
10348   Align = NewAlign;
10349
10350   SDValue NewPtr = OriginalLoad->getBasePtr();
10351   SDValue Offset;
10352   EVT PtrType = NewPtr.getValueType();
10353   MachinePointerInfo MPI;
10354   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10355     int Elt = ConstEltNo->getZExtValue();
10356     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10357     if (TLI.isBigEndian())
10358       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10359     Offset = DAG.getConstant(PtrOff, PtrType);
10360     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10361   } else {
10362     Offset = DAG.getNode(
10363         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10364         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10365     if (TLI.isBigEndian())
10366       Offset = DAG.getNode(
10367           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10368           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10369     MPI = OriginalLoad->getPointerInfo();
10370   }
10371   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10372
10373   // The replacement we need to do here is a little tricky: we need to
10374   // replace an extractelement of a load with a load.
10375   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10376   // Note that this replacement assumes that the extractvalue is the only
10377   // use of the load; that's okay because we don't want to perform this
10378   // transformation in other cases anyway.
10379   SDValue Load;
10380   SDValue Chain;
10381   if (ResultVT.bitsGT(VecEltVT)) {
10382     // If the result type of vextract is wider than the load, then issue an
10383     // extending load instead.
10384     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10385                                    ? ISD::ZEXTLOAD
10386                                    : ISD::EXTLOAD;
10387     Load = DAG.getExtLoad(
10388         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10389         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10390         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10391     Chain = Load.getValue(1);
10392   } else {
10393     Load = DAG.getLoad(
10394         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10395         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10396         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10397     Chain = Load.getValue(1);
10398     if (ResultVT.bitsLT(VecEltVT))
10399       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10400     else
10401       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10402   }
10403   WorklistRemover DeadNodes(*this);
10404   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10405   SDValue To[] = { Load, Chain };
10406   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10407   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10408   // worklist explicitly as well.
10409   AddToWorklist(Load.getNode());
10410   AddUsersToWorklist(Load.getNode()); // Add users too
10411   // Make sure to revisit this node to clean it up; it will usually be dead.
10412   AddToWorklist(EVE);
10413   ++OpsNarrowed;
10414   return SDValue(EVE, 0);
10415 }
10416
10417 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10418   // (vextract (scalar_to_vector val, 0) -> val
10419   SDValue InVec = N->getOperand(0);
10420   EVT VT = InVec.getValueType();
10421   EVT NVT = N->getValueType(0);
10422
10423   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10424     // Check if the result type doesn't match the inserted element type. A
10425     // SCALAR_TO_VECTOR may truncate the inserted element and the
10426     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10427     SDValue InOp = InVec.getOperand(0);
10428     if (InOp.getValueType() != NVT) {
10429       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10430       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10431     }
10432     return InOp;
10433   }
10434
10435   SDValue EltNo = N->getOperand(1);
10436   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10437
10438   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10439   // We only perform this optimization before the op legalization phase because
10440   // we may introduce new vector instructions which are not backed by TD
10441   // patterns. For example on AVX, extracting elements from a wide vector
10442   // without using extract_subvector. However, if we can find an underlying
10443   // scalar value, then we can always use that.
10444   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10445       && ConstEltNo) {
10446     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10447     int NumElem = VT.getVectorNumElements();
10448     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10449     // Find the new index to extract from.
10450     int OrigElt = SVOp->getMaskElt(Elt);
10451
10452     // Extracting an undef index is undef.
10453     if (OrigElt == -1)
10454       return DAG.getUNDEF(NVT);
10455
10456     // Select the right vector half to extract from.
10457     SDValue SVInVec;
10458     if (OrigElt < NumElem) {
10459       SVInVec = InVec->getOperand(0);
10460     } else {
10461       SVInVec = InVec->getOperand(1);
10462       OrigElt -= NumElem;
10463     }
10464
10465     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10466       SDValue InOp = SVInVec.getOperand(OrigElt);
10467       if (InOp.getValueType() != NVT) {
10468         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10469         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10470       }
10471
10472       return InOp;
10473     }
10474
10475     // FIXME: We should handle recursing on other vector shuffles and
10476     // scalar_to_vector here as well.
10477
10478     if (!LegalOperations) {
10479       EVT IndexTy = TLI.getVectorIdxTy();
10480       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10481                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10482     }
10483   }
10484
10485   bool BCNumEltsChanged = false;
10486   EVT ExtVT = VT.getVectorElementType();
10487   EVT LVT = ExtVT;
10488
10489   // If the result of load has to be truncated, then it's not necessarily
10490   // profitable.
10491   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10492     return SDValue();
10493
10494   if (InVec.getOpcode() == ISD::BITCAST) {
10495     // Don't duplicate a load with other uses.
10496     if (!InVec.hasOneUse())
10497       return SDValue();
10498
10499     EVT BCVT = InVec.getOperand(0).getValueType();
10500     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10501       return SDValue();
10502     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10503       BCNumEltsChanged = true;
10504     InVec = InVec.getOperand(0);
10505     ExtVT = BCVT.getVectorElementType();
10506   }
10507
10508   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10509   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10510       ISD::isNormalLoad(InVec.getNode()) &&
10511       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10512     SDValue Index = N->getOperand(1);
10513     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10514       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10515                                                            OrigLoad);
10516   }
10517
10518   // Perform only after legalization to ensure build_vector / vector_shuffle
10519   // optimizations have already been done.
10520   if (!LegalOperations) return SDValue();
10521
10522   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10523   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10524   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10525
10526   if (ConstEltNo) {
10527     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10528
10529     LoadSDNode *LN0 = nullptr;
10530     const ShuffleVectorSDNode *SVN = nullptr;
10531     if (ISD::isNormalLoad(InVec.getNode())) {
10532       LN0 = cast<LoadSDNode>(InVec);
10533     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10534                InVec.getOperand(0).getValueType() == ExtVT &&
10535                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10536       // Don't duplicate a load with other uses.
10537       if (!InVec.hasOneUse())
10538         return SDValue();
10539
10540       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10541     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10542       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10543       // =>
10544       // (load $addr+1*size)
10545
10546       // Don't duplicate a load with other uses.
10547       if (!InVec.hasOneUse())
10548         return SDValue();
10549
10550       // If the bit convert changed the number of elements, it is unsafe
10551       // to examine the mask.
10552       if (BCNumEltsChanged)
10553         return SDValue();
10554
10555       // Select the input vector, guarding against out of range extract vector.
10556       unsigned NumElems = VT.getVectorNumElements();
10557       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10558       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10559
10560       if (InVec.getOpcode() == ISD::BITCAST) {
10561         // Don't duplicate a load with other uses.
10562         if (!InVec.hasOneUse())
10563           return SDValue();
10564
10565         InVec = InVec.getOperand(0);
10566       }
10567       if (ISD::isNormalLoad(InVec.getNode())) {
10568         LN0 = cast<LoadSDNode>(InVec);
10569         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10570         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10571       }
10572     }
10573
10574     // Make sure we found a non-volatile load and the extractelement is
10575     // the only use.
10576     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10577       return SDValue();
10578
10579     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10580     if (Elt == -1)
10581       return DAG.getUNDEF(LVT);
10582
10583     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10584   }
10585
10586   return SDValue();
10587 }
10588
10589 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10590 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10591   // We perform this optimization post type-legalization because
10592   // the type-legalizer often scalarizes integer-promoted vectors.
10593   // Performing this optimization before may create bit-casts which
10594   // will be type-legalized to complex code sequences.
10595   // We perform this optimization only before the operation legalizer because we
10596   // may introduce illegal operations.
10597   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10598     return SDValue();
10599
10600   unsigned NumInScalars = N->getNumOperands();
10601   SDLoc dl(N);
10602   EVT VT = N->getValueType(0);
10603
10604   // Check to see if this is a BUILD_VECTOR of a bunch of values
10605   // which come from any_extend or zero_extend nodes. If so, we can create
10606   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10607   // optimizations. We do not handle sign-extend because we can't fill the sign
10608   // using shuffles.
10609   EVT SourceType = MVT::Other;
10610   bool AllAnyExt = true;
10611
10612   for (unsigned i = 0; i != NumInScalars; ++i) {
10613     SDValue In = N->getOperand(i);
10614     // Ignore undef inputs.
10615     if (In.getOpcode() == ISD::UNDEF) continue;
10616
10617     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10618     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10619
10620     // Abort if the element is not an extension.
10621     if (!ZeroExt && !AnyExt) {
10622       SourceType = MVT::Other;
10623       break;
10624     }
10625
10626     // The input is a ZeroExt or AnyExt. Check the original type.
10627     EVT InTy = In.getOperand(0).getValueType();
10628
10629     // Check that all of the widened source types are the same.
10630     if (SourceType == MVT::Other)
10631       // First time.
10632       SourceType = InTy;
10633     else if (InTy != SourceType) {
10634       // Multiple income types. Abort.
10635       SourceType = MVT::Other;
10636       break;
10637     }
10638
10639     // Check if all of the extends are ANY_EXTENDs.
10640     AllAnyExt &= AnyExt;
10641   }
10642
10643   // In order to have valid types, all of the inputs must be extended from the
10644   // same source type and all of the inputs must be any or zero extend.
10645   // Scalar sizes must be a power of two.
10646   EVT OutScalarTy = VT.getScalarType();
10647   bool ValidTypes = SourceType != MVT::Other &&
10648                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10649                  isPowerOf2_32(SourceType.getSizeInBits());
10650
10651   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10652   // turn into a single shuffle instruction.
10653   if (!ValidTypes)
10654     return SDValue();
10655
10656   bool isLE = TLI.isLittleEndian();
10657   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10658   assert(ElemRatio > 1 && "Invalid element size ratio");
10659   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10660                                DAG.getConstant(0, SourceType);
10661
10662   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10663   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10664
10665   // Populate the new build_vector
10666   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10667     SDValue Cast = N->getOperand(i);
10668     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10669             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10670             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10671     SDValue In;
10672     if (Cast.getOpcode() == ISD::UNDEF)
10673       In = DAG.getUNDEF(SourceType);
10674     else
10675       In = Cast->getOperand(0);
10676     unsigned Index = isLE ? (i * ElemRatio) :
10677                             (i * ElemRatio + (ElemRatio - 1));
10678
10679     assert(Index < Ops.size() && "Invalid index");
10680     Ops[Index] = In;
10681   }
10682
10683   // The type of the new BUILD_VECTOR node.
10684   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10685   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10686          "Invalid vector size");
10687   // Check if the new vector type is legal.
10688   if (!isTypeLegal(VecVT)) return SDValue();
10689
10690   // Make the new BUILD_VECTOR.
10691   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10692
10693   // The new BUILD_VECTOR node has the potential to be further optimized.
10694   AddToWorklist(BV.getNode());
10695   // Bitcast to the desired type.
10696   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10697 }
10698
10699 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10700   EVT VT = N->getValueType(0);
10701
10702   unsigned NumInScalars = N->getNumOperands();
10703   SDLoc dl(N);
10704
10705   EVT SrcVT = MVT::Other;
10706   unsigned Opcode = ISD::DELETED_NODE;
10707   unsigned NumDefs = 0;
10708
10709   for (unsigned i = 0; i != NumInScalars; ++i) {
10710     SDValue In = N->getOperand(i);
10711     unsigned Opc = In.getOpcode();
10712
10713     if (Opc == ISD::UNDEF)
10714       continue;
10715
10716     // If all scalar values are floats and converted from integers.
10717     if (Opcode == ISD::DELETED_NODE &&
10718         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10719       Opcode = Opc;
10720     }
10721
10722     if (Opc != Opcode)
10723       return SDValue();
10724
10725     EVT InVT = In.getOperand(0).getValueType();
10726
10727     // If all scalar values are typed differently, bail out. It's chosen to
10728     // simplify BUILD_VECTOR of integer types.
10729     if (SrcVT == MVT::Other)
10730       SrcVT = InVT;
10731     if (SrcVT != InVT)
10732       return SDValue();
10733     NumDefs++;
10734   }
10735
10736   // If the vector has just one element defined, it's not worth to fold it into
10737   // a vectorized one.
10738   if (NumDefs < 2)
10739     return SDValue();
10740
10741   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10742          && "Should only handle conversion from integer to float.");
10743   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10744
10745   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10746
10747   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10748     return SDValue();
10749
10750   SmallVector<SDValue, 8> Opnds;
10751   for (unsigned i = 0; i != NumInScalars; ++i) {
10752     SDValue In = N->getOperand(i);
10753
10754     if (In.getOpcode() == ISD::UNDEF)
10755       Opnds.push_back(DAG.getUNDEF(SrcVT));
10756     else
10757       Opnds.push_back(In.getOperand(0));
10758   }
10759   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10760   AddToWorklist(BV.getNode());
10761
10762   return DAG.getNode(Opcode, dl, VT, BV);
10763 }
10764
10765 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10766   unsigned NumInScalars = N->getNumOperands();
10767   SDLoc dl(N);
10768   EVT VT = N->getValueType(0);
10769
10770   // A vector built entirely of undefs is undef.
10771   if (ISD::allOperandsUndef(N))
10772     return DAG.getUNDEF(VT);
10773
10774   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10775   if (V.getNode())
10776     return V;
10777
10778   V = reduceBuildVecConvertToConvertBuildVec(N);
10779   if (V.getNode())
10780     return V;
10781
10782   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10783   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10784   // at most two distinct vectors, turn this into a shuffle node.
10785
10786   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10787   if (!isTypeLegal(VT))
10788     return SDValue();
10789
10790   // May only combine to shuffle after legalize if shuffle is legal.
10791   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10792     return SDValue();
10793
10794   SDValue VecIn1, VecIn2;
10795   bool UsesZeroVector = false;
10796   for (unsigned i = 0; i != NumInScalars; ++i) {
10797     SDValue Op = N->getOperand(i);
10798     // Ignore undef inputs.
10799     if (Op.getOpcode() == ISD::UNDEF) continue;
10800
10801     // See if we can combine this build_vector into a blend with a zero vector.
10802     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10803         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10804         (Op.getOpcode() == ISD::ConstantFP &&
10805         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10806       UsesZeroVector = true;
10807       continue;
10808     }
10809
10810     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10811     // constant index, bail out.
10812     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10813         !isa<ConstantSDNode>(Op.getOperand(1))) {
10814       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10815       break;
10816     }
10817
10818     // We allow up to two distinct input vectors.
10819     SDValue ExtractedFromVec = Op.getOperand(0);
10820     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10821       continue;
10822
10823     if (!VecIn1.getNode()) {
10824       VecIn1 = ExtractedFromVec;
10825     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10826       VecIn2 = ExtractedFromVec;
10827     } else {
10828       // Too many inputs.
10829       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10830       break;
10831     }
10832   }
10833
10834   // If everything is good, we can make a shuffle operation.
10835   if (VecIn1.getNode()) {
10836     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
10837     SmallVector<int, 8> Mask;
10838     for (unsigned i = 0; i != NumInScalars; ++i) {
10839       unsigned Opcode = N->getOperand(i).getOpcode();
10840       if (Opcode == ISD::UNDEF) {
10841         Mask.push_back(-1);
10842         continue;
10843       }
10844
10845       // Operands can also be zero.
10846       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10847         assert(UsesZeroVector &&
10848                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10849                "Unexpected node found!");
10850         Mask.push_back(NumInScalars+i);
10851         continue;
10852       }
10853
10854       // If extracting from the first vector, just use the index directly.
10855       SDValue Extract = N->getOperand(i);
10856       SDValue ExtVal = Extract.getOperand(1);
10857       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10858       if (Extract.getOperand(0) == VecIn1) {
10859         Mask.push_back(ExtIndex);
10860         continue;
10861       }
10862
10863       // Otherwise, use InIdx + InputVecSize
10864       Mask.push_back(InNumElements + ExtIndex);
10865     }
10866
10867     // Avoid introducing illegal shuffles with zero.
10868     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10869       return SDValue();
10870
10871     // We can't generate a shuffle node with mismatched input and output types.
10872     // Attempt to transform a single input vector to the correct type.
10873     if ((VT != VecIn1.getValueType())) {
10874       // If the input vector type has a different base type to the output
10875       // vector type, bail out.
10876       EVT VTElemType = VT.getVectorElementType();
10877       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
10878           (VecIn2.getNode() &&
10879            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
10880         return SDValue();
10881
10882       // If the input vector is too small, widen it.
10883       // We only support widening of vectors which are half the size of the
10884       // output registers. For example XMM->YMM widening on X86 with AVX.
10885       EVT VecInT = VecIn1.getValueType();
10886       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
10887         // If we only have one small input, widen it by adding undef values.
10888         if (!VecIn2.getNode())
10889           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
10890                                DAG.getUNDEF(VecIn1.getValueType()));
10891         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
10892           // If we have two small inputs of the same type, try to concat them.
10893           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
10894           VecIn2 = SDValue(nullptr, 0);
10895         } else
10896           return SDValue();
10897       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
10898         // If the input vector is too large, try to split it.
10899         // We don't support having two input vectors that are too large.
10900         if (VecIn2.getNode())
10901           return SDValue();
10902
10903         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
10904           return SDValue();
10905         
10906         // Try to replace VecIn1 with two extract_subvectors
10907         // No need to update the masks, they should still be correct.
10908         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 
10909           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
10910         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
10911           DAG.getConstant(0, TLI.getVectorIdxTy()));
10912         UsesZeroVector = false;
10913       } else
10914         return SDValue();
10915     }
10916
10917     if (UsesZeroVector)
10918       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10919                                 DAG.getConstantFP(0.0, VT);
10920     else
10921       // If VecIn2 is unused then change it to undef.
10922       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10923
10924     // Check that we were able to transform all incoming values to the same
10925     // type.
10926     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10927         VecIn1.getValueType() != VT)
10928           return SDValue();
10929
10930     // Return the new VECTOR_SHUFFLE node.
10931     SDValue Ops[2];
10932     Ops[0] = VecIn1;
10933     Ops[1] = VecIn2;
10934     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10935   }
10936
10937   return SDValue();
10938 }
10939
10940 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10941   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10942   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10943   // inputs come from at most two distinct vectors, turn this into a shuffle
10944   // node.
10945
10946   // If we only have one input vector, we don't need to do any concatenation.
10947   if (N->getNumOperands() == 1)
10948     return N->getOperand(0);
10949
10950   // Check if all of the operands are undefs.
10951   EVT VT = N->getValueType(0);
10952   if (ISD::allOperandsUndef(N))
10953     return DAG.getUNDEF(VT);
10954
10955   // Optimize concat_vectors where one of the vectors is undef.
10956   if (N->getNumOperands() == 2 &&
10957       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10958     SDValue In = N->getOperand(0);
10959     assert(In.getValueType().isVector() && "Must concat vectors");
10960
10961     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10962     if (In->getOpcode() == ISD::BITCAST &&
10963         !In->getOperand(0)->getValueType(0).isVector()) {
10964       SDValue Scalar = In->getOperand(0);
10965       EVT SclTy = Scalar->getValueType(0);
10966
10967       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10968         return SDValue();
10969
10970       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10971                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10972       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10973         return SDValue();
10974
10975       SDLoc dl = SDLoc(N);
10976       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10977       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10978     }
10979   }
10980
10981   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10982   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10983   if (N->getNumOperands() == 2 &&
10984       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10985       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10986     EVT VT = N->getValueType(0);
10987     SDValue N0 = N->getOperand(0);
10988     SDValue N1 = N->getOperand(1);
10989     SmallVector<SDValue, 8> Opnds;
10990     unsigned BuildVecNumElts =  N0.getNumOperands();
10991
10992     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10993     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10994     if (SclTy0.isFloatingPoint()) {
10995       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10996         Opnds.push_back(N0.getOperand(i));
10997       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10998         Opnds.push_back(N1.getOperand(i));
10999     } else {
11000       // If BUILD_VECTOR are from built from integer, they may have different
11001       // operand types. Get the smaller type and truncate all operands to it.
11002       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11003       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11004         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11005                         N0.getOperand(i)));
11006       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11007         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11008                         N1.getOperand(i)));
11009     }
11010
11011     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11012   }
11013
11014   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11015   // nodes often generate nop CONCAT_VECTOR nodes.
11016   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11017   // place the incoming vectors at the exact same location.
11018   SDValue SingleSource = SDValue();
11019   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11020
11021   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11022     SDValue Op = N->getOperand(i);
11023
11024     if (Op.getOpcode() == ISD::UNDEF)
11025       continue;
11026
11027     // Check if this is the identity extract:
11028     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11029       return SDValue();
11030
11031     // Find the single incoming vector for the extract_subvector.
11032     if (SingleSource.getNode()) {
11033       if (Op.getOperand(0) != SingleSource)
11034         return SDValue();
11035     } else {
11036       SingleSource = Op.getOperand(0);
11037
11038       // Check the source type is the same as the type of the result.
11039       // If not, this concat may extend the vector, so we can not
11040       // optimize it away.
11041       if (SingleSource.getValueType() != N->getValueType(0))
11042         return SDValue();
11043     }
11044
11045     unsigned IdentityIndex = i * PartNumElem;
11046     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11047     // The extract index must be constant.
11048     if (!CS)
11049       return SDValue();
11050
11051     // Check that we are reading from the identity index.
11052     if (CS->getZExtValue() != IdentityIndex)
11053       return SDValue();
11054   }
11055
11056   if (SingleSource.getNode())
11057     return SingleSource;
11058
11059   return SDValue();
11060 }
11061
11062 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11063   EVT NVT = N->getValueType(0);
11064   SDValue V = N->getOperand(0);
11065
11066   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11067     // Combine:
11068     //    (extract_subvec (concat V1, V2, ...), i)
11069     // Into:
11070     //    Vi if possible
11071     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11072     // type.
11073     if (V->getOperand(0).getValueType() != NVT)
11074       return SDValue();
11075     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11076     unsigned NumElems = NVT.getVectorNumElements();
11077     assert((Idx % NumElems) == 0 &&
11078            "IDX in concat is not a multiple of the result vector length.");
11079     return V->getOperand(Idx / NumElems);
11080   }
11081
11082   // Skip bitcasting
11083   if (V->getOpcode() == ISD::BITCAST)
11084     V = V.getOperand(0);
11085
11086   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11087     SDLoc dl(N);
11088     // Handle only simple case where vector being inserted and vector
11089     // being extracted are of same type, and are half size of larger vectors.
11090     EVT BigVT = V->getOperand(0).getValueType();
11091     EVT SmallVT = V->getOperand(1).getValueType();
11092     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11093       return SDValue();
11094
11095     // Only handle cases where both indexes are constants with the same type.
11096     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11097     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11098
11099     if (InsIdx && ExtIdx &&
11100         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11101         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11102       // Combine:
11103       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11104       // Into:
11105       //    indices are equal or bit offsets are equal => V1
11106       //    otherwise => (extract_subvec V1, ExtIdx)
11107       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11108           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11109         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11110       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11111                          DAG.getNode(ISD::BITCAST, dl,
11112                                      N->getOperand(0).getValueType(),
11113                                      V->getOperand(0)), N->getOperand(1));
11114     }
11115   }
11116
11117   return SDValue();
11118 }
11119
11120 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11121                                                  SDValue V, SelectionDAG &DAG) {
11122   SDLoc DL(V);
11123   EVT VT = V.getValueType();
11124
11125   switch (V.getOpcode()) {
11126   default:
11127     return V;
11128
11129   case ISD::CONCAT_VECTORS: {
11130     EVT OpVT = V->getOperand(0).getValueType();
11131     int OpSize = OpVT.getVectorNumElements();
11132     SmallBitVector OpUsedElements(OpSize, false);
11133     bool FoundSimplification = false;
11134     SmallVector<SDValue, 4> NewOps;
11135     NewOps.reserve(V->getNumOperands());
11136     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11137       SDValue Op = V->getOperand(i);
11138       bool OpUsed = false;
11139       for (int j = 0; j < OpSize; ++j)
11140         if (UsedElements[i * OpSize + j]) {
11141           OpUsedElements[j] = true;
11142           OpUsed = true;
11143         }
11144       NewOps.push_back(
11145           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11146                  : DAG.getUNDEF(OpVT));
11147       FoundSimplification |= Op == NewOps.back();
11148       OpUsedElements.reset();
11149     }
11150     if (FoundSimplification)
11151       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11152     return V;
11153   }
11154
11155   case ISD::INSERT_SUBVECTOR: {
11156     SDValue BaseV = V->getOperand(0);
11157     SDValue SubV = V->getOperand(1);
11158     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11159     if (!IdxN)
11160       return V;
11161
11162     int SubSize = SubV.getValueType().getVectorNumElements();
11163     int Idx = IdxN->getZExtValue();
11164     bool SubVectorUsed = false;
11165     SmallBitVector SubUsedElements(SubSize, false);
11166     for (int i = 0; i < SubSize; ++i)
11167       if (UsedElements[i + Idx]) {
11168         SubVectorUsed = true;
11169         SubUsedElements[i] = true;
11170         UsedElements[i + Idx] = false;
11171       }
11172
11173     // Now recurse on both the base and sub vectors.
11174     SDValue SimplifiedSubV =
11175         SubVectorUsed
11176             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11177             : DAG.getUNDEF(SubV.getValueType());
11178     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11179     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11180       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11181                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11182     return V;
11183   }
11184   }
11185 }
11186
11187 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11188                                        SDValue N1, SelectionDAG &DAG) {
11189   EVT VT = SVN->getValueType(0);
11190   int NumElts = VT.getVectorNumElements();
11191   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11192   for (int M : SVN->getMask())
11193     if (M >= 0 && M < NumElts)
11194       N0UsedElements[M] = true;
11195     else if (M >= NumElts)
11196       N1UsedElements[M - NumElts] = true;
11197
11198   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11199   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11200   if (S0 == N0 && S1 == N1)
11201     return SDValue();
11202
11203   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11204 }
11205
11206 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11207 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11208   EVT VT = N->getValueType(0);
11209   unsigned NumElts = VT.getVectorNumElements();
11210
11211   SDValue N0 = N->getOperand(0);
11212   SDValue N1 = N->getOperand(1);
11213   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11214
11215   SmallVector<SDValue, 4> Ops;
11216   EVT ConcatVT = N0.getOperand(0).getValueType();
11217   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11218   unsigned NumConcats = NumElts / NumElemsPerConcat;
11219
11220   // Look at every vector that's inserted. We're looking for exact
11221   // subvector-sized copies from a concatenated vector
11222   for (unsigned I = 0; I != NumConcats; ++I) {
11223     // Make sure we're dealing with a copy.
11224     unsigned Begin = I * NumElemsPerConcat;
11225     bool AllUndef = true, NoUndef = true;
11226     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11227       if (SVN->getMaskElt(J) >= 0)
11228         AllUndef = false;
11229       else
11230         NoUndef = false;
11231     }
11232
11233     if (NoUndef) {
11234       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11235         return SDValue();
11236
11237       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11238         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11239           return SDValue();
11240
11241       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11242       if (FirstElt < N0.getNumOperands())
11243         Ops.push_back(N0.getOperand(FirstElt));
11244       else
11245         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11246
11247     } else if (AllUndef) {
11248       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11249     } else { // Mixed with general masks and undefs, can't do optimization.
11250       return SDValue();
11251     }
11252   }
11253
11254   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11255 }
11256
11257 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11258   EVT VT = N->getValueType(0);
11259   unsigned NumElts = VT.getVectorNumElements();
11260
11261   SDValue N0 = N->getOperand(0);
11262   SDValue N1 = N->getOperand(1);
11263
11264   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11265
11266   // Canonicalize shuffle undef, undef -> undef
11267   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11268     return DAG.getUNDEF(VT);
11269
11270   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11271
11272   // Canonicalize shuffle v, v -> v, undef
11273   if (N0 == N1) {
11274     SmallVector<int, 8> NewMask;
11275     for (unsigned i = 0; i != NumElts; ++i) {
11276       int Idx = SVN->getMaskElt(i);
11277       if (Idx >= (int)NumElts) Idx -= NumElts;
11278       NewMask.push_back(Idx);
11279     }
11280     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11281                                 &NewMask[0]);
11282   }
11283
11284   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11285   if (N0.getOpcode() == ISD::UNDEF) {
11286     SmallVector<int, 8> NewMask;
11287     for (unsigned i = 0; i != NumElts; ++i) {
11288       int Idx = SVN->getMaskElt(i);
11289       if (Idx >= 0) {
11290         if (Idx >= (int)NumElts)
11291           Idx -= NumElts;
11292         else
11293           Idx = -1; // remove reference to lhs
11294       }
11295       NewMask.push_back(Idx);
11296     }
11297     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11298                                 &NewMask[0]);
11299   }
11300
11301   // Remove references to rhs if it is undef
11302   if (N1.getOpcode() == ISD::UNDEF) {
11303     bool Changed = false;
11304     SmallVector<int, 8> NewMask;
11305     for (unsigned i = 0; i != NumElts; ++i) {
11306       int Idx = SVN->getMaskElt(i);
11307       if (Idx >= (int)NumElts) {
11308         Idx = -1;
11309         Changed = true;
11310       }
11311       NewMask.push_back(Idx);
11312     }
11313     if (Changed)
11314       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11315   }
11316
11317   // If it is a splat, check if the argument vector is another splat or a
11318   // build_vector with all scalar elements the same.
11319   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11320     SDNode *V = N0.getNode();
11321
11322     // If this is a bit convert that changes the element type of the vector but
11323     // not the number of vector elements, look through it.  Be careful not to
11324     // look though conversions that change things like v4f32 to v2f64.
11325     if (V->getOpcode() == ISD::BITCAST) {
11326       SDValue ConvInput = V->getOperand(0);
11327       if (ConvInput.getValueType().isVector() &&
11328           ConvInput.getValueType().getVectorNumElements() == NumElts)
11329         V = ConvInput.getNode();
11330     }
11331
11332     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11333       assert(V->getNumOperands() == NumElts &&
11334              "BUILD_VECTOR has wrong number of operands");
11335       SDValue Base;
11336       bool AllSame = true;
11337       for (unsigned i = 0; i != NumElts; ++i) {
11338         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11339           Base = V->getOperand(i);
11340           break;
11341         }
11342       }
11343       // Splat of <u, u, u, u>, return <u, u, u, u>
11344       if (!Base.getNode())
11345         return N0;
11346       for (unsigned i = 0; i != NumElts; ++i) {
11347         if (V->getOperand(i) != Base) {
11348           AllSame = false;
11349           break;
11350         }
11351       }
11352       // Splat of <x, x, x, x>, return <x, x, x, x>
11353       if (AllSame)
11354         return N0;
11355     }
11356   }
11357
11358   // There are various patterns used to build up a vector from smaller vectors,
11359   // subvectors, or elements. Scan chains of these and replace unused insertions
11360   // or components with undef.
11361   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11362     return S;
11363
11364   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11365       Level < AfterLegalizeVectorOps &&
11366       (N1.getOpcode() == ISD::UNDEF ||
11367       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11368        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11369     SDValue V = partitionShuffleOfConcats(N, DAG);
11370
11371     if (V.getNode())
11372       return V;
11373   }
11374
11375   // Canonicalize shuffles according to rules:
11376   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11377   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11378   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11379   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11380       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11381       TLI.isTypeLegal(VT)) {
11382     // The incoming shuffle must be of the same type as the result of the
11383     // current shuffle.
11384     assert(N1->getOperand(0).getValueType() == VT &&
11385            "Shuffle types don't match");
11386
11387     SDValue SV0 = N1->getOperand(0);
11388     SDValue SV1 = N1->getOperand(1);
11389     bool HasSameOp0 = N0 == SV0;
11390     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11391     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11392       // Commute the operands of this shuffle so that next rule
11393       // will trigger.
11394       return DAG.getCommutedVectorShuffle(*SVN);
11395   }
11396
11397   // Try to fold according to rules:
11398   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11399   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11400   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11401   // Don't try to fold shuffles with illegal type.
11402   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11403       TLI.isTypeLegal(VT)) {
11404     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11405
11406     // The incoming shuffle must be of the same type as the result of the
11407     // current shuffle.
11408     assert(OtherSV->getOperand(0).getValueType() == VT &&
11409            "Shuffle types don't match");
11410
11411     SDValue SV0, SV1;
11412     SmallVector<int, 4> Mask;
11413     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11414     // operand, and SV1 as the second operand.
11415     for (unsigned i = 0; i != NumElts; ++i) {
11416       int Idx = SVN->getMaskElt(i);
11417       if (Idx < 0) {
11418         // Propagate Undef.
11419         Mask.push_back(Idx);
11420         continue;
11421       }
11422
11423       SDValue CurrentVec;
11424       if (Idx < (int)NumElts) {
11425         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11426         // shuffle mask to identify which vector is actually referenced.
11427         Idx = OtherSV->getMaskElt(Idx);
11428         if (Idx < 0) {
11429           // Propagate Undef.
11430           Mask.push_back(Idx);
11431           continue;
11432         }
11433
11434         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11435                                            : OtherSV->getOperand(1);
11436       } else {
11437         // This shuffle index references an element within N1.
11438         CurrentVec = N1;
11439       }
11440
11441       // Simple case where 'CurrentVec' is UNDEF.
11442       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11443         Mask.push_back(-1);
11444         continue;
11445       }
11446
11447       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11448       // will be the first or second operand of the combined shuffle.
11449       Idx = Idx % NumElts;
11450       if (!SV0.getNode() || SV0 == CurrentVec) {
11451         // Ok. CurrentVec is the left hand side.
11452         // Update the mask accordingly.
11453         SV0 = CurrentVec;
11454         Mask.push_back(Idx);
11455         continue;
11456       }
11457
11458       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11459       if (SV1.getNode() && SV1 != CurrentVec)
11460         return SDValue();
11461
11462       // Ok. CurrentVec is the right hand side.
11463       // Update the mask accordingly.
11464       SV1 = CurrentVec;
11465       Mask.push_back(Idx + NumElts);
11466     }
11467
11468     // Check if all indices in Mask are Undef. In case, propagate Undef.
11469     bool isUndefMask = true;
11470     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11471       isUndefMask &= Mask[i] < 0;
11472
11473     if (isUndefMask)
11474       return DAG.getUNDEF(VT);
11475
11476     if (!SV0.getNode())
11477       SV0 = DAG.getUNDEF(VT);
11478     if (!SV1.getNode())
11479       SV1 = DAG.getUNDEF(VT);
11480
11481     // Avoid introducing shuffles with illegal mask.
11482     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11483       // Compute the commuted shuffle mask and test again.
11484       for (unsigned i = 0; i != NumElts; ++i) {
11485         int idx = Mask[i];
11486         if (idx < 0)
11487           continue;
11488         else if (idx < (int)NumElts)
11489           Mask[i] = idx + NumElts;
11490         else
11491           Mask[i] = idx - NumElts;
11492       }
11493
11494       if (!TLI.isShuffleMaskLegal(Mask, VT))
11495         return SDValue();
11496  
11497       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11498       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11499       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11500       std::swap(SV0, SV1);
11501     }
11502
11503     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11504     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11505     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11506     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11507   }
11508
11509   return SDValue();
11510 }
11511
11512 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11513   SDValue N0 = N->getOperand(0);
11514   SDValue N2 = N->getOperand(2);
11515
11516   // If the input vector is a concatenation, and the insert replaces
11517   // one of the halves, we can optimize into a single concat_vectors.
11518   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11519       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11520     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11521     EVT VT = N->getValueType(0);
11522
11523     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11524     // (concat_vectors Z, Y)
11525     if (InsIdx == 0)
11526       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11527                          N->getOperand(1), N0.getOperand(1));
11528
11529     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11530     // (concat_vectors X, Z)
11531     if (InsIdx == VT.getVectorNumElements()/2)
11532       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11533                          N0.getOperand(0), N->getOperand(1));
11534   }
11535
11536   return SDValue();
11537 }
11538
11539 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11540 /// with the destination vector and a zero vector.
11541 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11542 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11543 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11544   EVT VT = N->getValueType(0);
11545   SDLoc dl(N);
11546   SDValue LHS = N->getOperand(0);
11547   SDValue RHS = N->getOperand(1);
11548   if (N->getOpcode() == ISD::AND) {
11549     if (RHS.getOpcode() == ISD::BITCAST)
11550       RHS = RHS.getOperand(0);
11551     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11552       SmallVector<int, 8> Indices;
11553       unsigned NumElts = RHS.getNumOperands();
11554       for (unsigned i = 0; i != NumElts; ++i) {
11555         SDValue Elt = RHS.getOperand(i);
11556         if (!isa<ConstantSDNode>(Elt))
11557           return SDValue();
11558
11559         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11560           Indices.push_back(i);
11561         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11562           Indices.push_back(NumElts+i);
11563         else
11564           return SDValue();
11565       }
11566
11567       // Let's see if the target supports this vector_shuffle.
11568       EVT RVT = RHS.getValueType();
11569       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11570         return SDValue();
11571
11572       // Return the new VECTOR_SHUFFLE node.
11573       EVT EltVT = RVT.getVectorElementType();
11574       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11575                                      DAG.getConstant(0, EltVT));
11576       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11577       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11578       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11579       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11580     }
11581   }
11582
11583   return SDValue();
11584 }
11585
11586 /// Visit a binary vector operation, like ADD.
11587 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11588   assert(N->getValueType(0).isVector() &&
11589          "SimplifyVBinOp only works on vectors!");
11590
11591   SDValue LHS = N->getOperand(0);
11592   SDValue RHS = N->getOperand(1);
11593   SDValue Shuffle = XformToShuffleWithZero(N);
11594   if (Shuffle.getNode()) return Shuffle;
11595
11596   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11597   // this operation.
11598   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11599       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11600     // Check if both vectors are constants. If not bail out.
11601     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11602           cast<BuildVectorSDNode>(RHS)->isConstant()))
11603       return SDValue();
11604
11605     SmallVector<SDValue, 8> Ops;
11606     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11607       SDValue LHSOp = LHS.getOperand(i);
11608       SDValue RHSOp = RHS.getOperand(i);
11609
11610       // Can't fold divide by zero.
11611       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11612           N->getOpcode() == ISD::FDIV) {
11613         if ((RHSOp.getOpcode() == ISD::Constant &&
11614              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11615             (RHSOp.getOpcode() == ISD::ConstantFP &&
11616              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11617           break;
11618       }
11619
11620       EVT VT = LHSOp.getValueType();
11621       EVT RVT = RHSOp.getValueType();
11622       if (RVT != VT) {
11623         // Integer BUILD_VECTOR operands may have types larger than the element
11624         // size (e.g., when the element type is not legal).  Prior to type
11625         // legalization, the types may not match between the two BUILD_VECTORS.
11626         // Truncate one of the operands to make them match.
11627         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11628           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11629         } else {
11630           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11631           VT = RVT;
11632         }
11633       }
11634       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11635                                    LHSOp, RHSOp);
11636       if (FoldOp.getOpcode() != ISD::UNDEF &&
11637           FoldOp.getOpcode() != ISD::Constant &&
11638           FoldOp.getOpcode() != ISD::ConstantFP)
11639         break;
11640       Ops.push_back(FoldOp);
11641       AddToWorklist(FoldOp.getNode());
11642     }
11643
11644     if (Ops.size() == LHS.getNumOperands())
11645       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11646   }
11647
11648   // Type legalization might introduce new shuffles in the DAG.
11649   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11650   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11651   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11652       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11653       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11654       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11655     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11656     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11657
11658     if (SVN0->getMask().equals(SVN1->getMask())) {
11659       EVT VT = N->getValueType(0);
11660       SDValue UndefVector = LHS.getOperand(1);
11661       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11662                                      LHS.getOperand(0), RHS.getOperand(0));
11663       AddUsersToWorklist(N);
11664       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11665                                   &SVN0->getMask()[0]);
11666     }
11667   }
11668
11669   return SDValue();
11670 }
11671
11672 /// Visit a binary vector operation, like FABS/FNEG.
11673 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11674   assert(N->getValueType(0).isVector() &&
11675          "SimplifyVUnaryOp only works on vectors!");
11676
11677   SDValue N0 = N->getOperand(0);
11678
11679   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11680     return SDValue();
11681
11682   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11683   SmallVector<SDValue, 8> Ops;
11684   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11685     SDValue Op = N0.getOperand(i);
11686     if (Op.getOpcode() != ISD::UNDEF &&
11687         Op.getOpcode() != ISD::ConstantFP)
11688       break;
11689     EVT EltVT = Op.getValueType();
11690     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11691     if (FoldOp.getOpcode() != ISD::UNDEF &&
11692         FoldOp.getOpcode() != ISD::ConstantFP)
11693       break;
11694     Ops.push_back(FoldOp);
11695     AddToWorklist(FoldOp.getNode());
11696   }
11697
11698   if (Ops.size() != N0.getNumOperands())
11699     return SDValue();
11700
11701   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11702 }
11703
11704 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11705                                     SDValue N1, SDValue N2){
11706   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11707
11708   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11709                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11710
11711   // If we got a simplified select_cc node back from SimplifySelectCC, then
11712   // break it down into a new SETCC node, and a new SELECT node, and then return
11713   // the SELECT node, since we were called with a SELECT node.
11714   if (SCC.getNode()) {
11715     // Check to see if we got a select_cc back (to turn into setcc/select).
11716     // Otherwise, just return whatever node we got back, like fabs.
11717     if (SCC.getOpcode() == ISD::SELECT_CC) {
11718       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11719                                   N0.getValueType(),
11720                                   SCC.getOperand(0), SCC.getOperand(1),
11721                                   SCC.getOperand(4));
11722       AddToWorklist(SETCC.getNode());
11723       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11724                            SCC.getOperand(2), SCC.getOperand(3));
11725     }
11726
11727     return SCC;
11728   }
11729   return SDValue();
11730 }
11731
11732 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11733 /// being selected between, see if we can simplify the select.  Callers of this
11734 /// should assume that TheSelect is deleted if this returns true.  As such, they
11735 /// should return the appropriate thing (e.g. the node) back to the top-level of
11736 /// the DAG combiner loop to avoid it being looked at.
11737 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11738                                     SDValue RHS) {
11739
11740   // Cannot simplify select with vector condition
11741   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11742
11743   // If this is a select from two identical things, try to pull the operation
11744   // through the select.
11745   if (LHS.getOpcode() != RHS.getOpcode() ||
11746       !LHS.hasOneUse() || !RHS.hasOneUse())
11747     return false;
11748
11749   // If this is a load and the token chain is identical, replace the select
11750   // of two loads with a load through a select of the address to load from.
11751   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11752   // constants have been dropped into the constant pool.
11753   if (LHS.getOpcode() == ISD::LOAD) {
11754     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11755     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11756
11757     // Token chains must be identical.
11758     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11759         // Do not let this transformation reduce the number of volatile loads.
11760         LLD->isVolatile() || RLD->isVolatile() ||
11761         // If this is an EXTLOAD, the VT's must match.
11762         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11763         // If this is an EXTLOAD, the kind of extension must match.
11764         (LLD->getExtensionType() != RLD->getExtensionType() &&
11765          // The only exception is if one of the extensions is anyext.
11766          LLD->getExtensionType() != ISD::EXTLOAD &&
11767          RLD->getExtensionType() != ISD::EXTLOAD) ||
11768         // FIXME: this discards src value information.  This is
11769         // over-conservative. It would be beneficial to be able to remember
11770         // both potential memory locations.  Since we are discarding
11771         // src value info, don't do the transformation if the memory
11772         // locations are not in the default address space.
11773         LLD->getPointerInfo().getAddrSpace() != 0 ||
11774         RLD->getPointerInfo().getAddrSpace() != 0 ||
11775         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11776                                       LLD->getBasePtr().getValueType()))
11777       return false;
11778
11779     // Check that the select condition doesn't reach either load.  If so,
11780     // folding this will induce a cycle into the DAG.  If not, this is safe to
11781     // xform, so create a select of the addresses.
11782     SDValue Addr;
11783     if (TheSelect->getOpcode() == ISD::SELECT) {
11784       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11785       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11786           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11787         return false;
11788       // The loads must not depend on one another.
11789       if (LLD->isPredecessorOf(RLD) ||
11790           RLD->isPredecessorOf(LLD))
11791         return false;
11792       Addr = DAG.getSelect(SDLoc(TheSelect),
11793                            LLD->getBasePtr().getValueType(),
11794                            TheSelect->getOperand(0), LLD->getBasePtr(),
11795                            RLD->getBasePtr());
11796     } else {  // Otherwise SELECT_CC
11797       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11798       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11799
11800       if ((LLD->hasAnyUseOfValue(1) &&
11801            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11802           (RLD->hasAnyUseOfValue(1) &&
11803            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11804         return false;
11805
11806       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11807                          LLD->getBasePtr().getValueType(),
11808                          TheSelect->getOperand(0),
11809                          TheSelect->getOperand(1),
11810                          LLD->getBasePtr(), RLD->getBasePtr(),
11811                          TheSelect->getOperand(4));
11812     }
11813
11814     SDValue Load;
11815     // It is safe to replace the two loads if they have different alignments,
11816     // but the new load must be the minimum (most restrictive) alignment of the
11817     // inputs.
11818     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11819     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11820     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11821       Load = DAG.getLoad(TheSelect->getValueType(0),
11822                          SDLoc(TheSelect),
11823                          // FIXME: Discards pointer and AA info.
11824                          LLD->getChain(), Addr, MachinePointerInfo(),
11825                          LLD->isVolatile(), LLD->isNonTemporal(),
11826                          isInvariant, Alignment);
11827     } else {
11828       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11829                             RLD->getExtensionType() : LLD->getExtensionType(),
11830                             SDLoc(TheSelect),
11831                             TheSelect->getValueType(0),
11832                             // FIXME: Discards pointer and AA info.
11833                             LLD->getChain(), Addr, MachinePointerInfo(),
11834                             LLD->getMemoryVT(), LLD->isVolatile(),
11835                             LLD->isNonTemporal(), isInvariant, Alignment);
11836     }
11837
11838     // Users of the select now use the result of the load.
11839     CombineTo(TheSelect, Load);
11840
11841     // Users of the old loads now use the new load's chain.  We know the
11842     // old-load value is dead now.
11843     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11844     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11845     return true;
11846   }
11847
11848   return false;
11849 }
11850
11851 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11852 /// where 'cond' is the comparison specified by CC.
11853 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11854                                       SDValue N2, SDValue N3,
11855                                       ISD::CondCode CC, bool NotExtCompare) {
11856   // (x ? y : y) -> y.
11857   if (N2 == N3) return N2;
11858
11859   EVT VT = N2.getValueType();
11860   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11861   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11862   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11863
11864   // Determine if the condition we're dealing with is constant
11865   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11866                               N0, N1, CC, DL, false);
11867   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11868   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11869
11870   // fold select_cc true, x, y -> x
11871   if (SCCC && !SCCC->isNullValue())
11872     return N2;
11873   // fold select_cc false, x, y -> y
11874   if (SCCC && SCCC->isNullValue())
11875     return N3;
11876
11877   // Check to see if we can simplify the select into an fabs node
11878   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11879     // Allow either -0.0 or 0.0
11880     if (CFP->getValueAPF().isZero()) {
11881       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11882       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11883           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11884           N2 == N3.getOperand(0))
11885         return DAG.getNode(ISD::FABS, DL, VT, N0);
11886
11887       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11888       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11889           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11890           N2.getOperand(0) == N3)
11891         return DAG.getNode(ISD::FABS, DL, VT, N3);
11892     }
11893   }
11894
11895   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11896   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11897   // in it.  This is a win when the constant is not otherwise available because
11898   // it replaces two constant pool loads with one.  We only do this if the FP
11899   // type is known to be legal, because if it isn't, then we are before legalize
11900   // types an we want the other legalization to happen first (e.g. to avoid
11901   // messing with soft float) and if the ConstantFP is not legal, because if
11902   // it is legal, we may not need to store the FP constant in a constant pool.
11903   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11904     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11905       if (TLI.isTypeLegal(N2.getValueType()) &&
11906           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11907                TargetLowering::Legal &&
11908            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11909            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11910           // If both constants have multiple uses, then we won't need to do an
11911           // extra load, they are likely around in registers for other users.
11912           (TV->hasOneUse() || FV->hasOneUse())) {
11913         Constant *Elts[] = {
11914           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11915           const_cast<ConstantFP*>(TV->getConstantFPValue())
11916         };
11917         Type *FPTy = Elts[0]->getType();
11918         const DataLayout &TD = *TLI.getDataLayout();
11919
11920         // Create a ConstantArray of the two constants.
11921         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11922         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11923                                             TD.getPrefTypeAlignment(FPTy));
11924         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11925
11926         // Get the offsets to the 0 and 1 element of the array so that we can
11927         // select between them.
11928         SDValue Zero = DAG.getIntPtrConstant(0);
11929         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11930         SDValue One = DAG.getIntPtrConstant(EltSize);
11931
11932         SDValue Cond = DAG.getSetCC(DL,
11933                                     getSetCCResultType(N0.getValueType()),
11934                                     N0, N1, CC);
11935         AddToWorklist(Cond.getNode());
11936         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11937                                           Cond, One, Zero);
11938         AddToWorklist(CstOffset.getNode());
11939         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11940                             CstOffset);
11941         AddToWorklist(CPIdx.getNode());
11942         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11943                            MachinePointerInfo::getConstantPool(), false,
11944                            false, false, Alignment);
11945
11946       }
11947     }
11948
11949   // Check to see if we can perform the "gzip trick", transforming
11950   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11951   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11952       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11953        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11954     EVT XType = N0.getValueType();
11955     EVT AType = N2.getValueType();
11956     if (XType.bitsGE(AType)) {
11957       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11958       // single-bit constant.
11959       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11960         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11961         ShCtV = XType.getSizeInBits()-ShCtV-1;
11962         SDValue ShCt = DAG.getConstant(ShCtV,
11963                                        getShiftAmountTy(N0.getValueType()));
11964         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11965                                     XType, N0, ShCt);
11966         AddToWorklist(Shift.getNode());
11967
11968         if (XType.bitsGT(AType)) {
11969           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11970           AddToWorklist(Shift.getNode());
11971         }
11972
11973         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11974       }
11975
11976       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11977                                   XType, N0,
11978                                   DAG.getConstant(XType.getSizeInBits()-1,
11979                                          getShiftAmountTy(N0.getValueType())));
11980       AddToWorklist(Shift.getNode());
11981
11982       if (XType.bitsGT(AType)) {
11983         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11984         AddToWorklist(Shift.getNode());
11985       }
11986
11987       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11988     }
11989   }
11990
11991   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11992   // where y is has a single bit set.
11993   // A plaintext description would be, we can turn the SELECT_CC into an AND
11994   // when the condition can be materialized as an all-ones register.  Any
11995   // single bit-test can be materialized as an all-ones register with
11996   // shift-left and shift-right-arith.
11997   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11998       N0->getValueType(0) == VT &&
11999       N1C && N1C->isNullValue() &&
12000       N2C && N2C->isNullValue()) {
12001     SDValue AndLHS = N0->getOperand(0);
12002     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12003     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12004       // Shift the tested bit over the sign bit.
12005       APInt AndMask = ConstAndRHS->getAPIntValue();
12006       SDValue ShlAmt =
12007         DAG.getConstant(AndMask.countLeadingZeros(),
12008                         getShiftAmountTy(AndLHS.getValueType()));
12009       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12010
12011       // Now arithmetic right shift it all the way over, so the result is either
12012       // all-ones, or zero.
12013       SDValue ShrAmt =
12014         DAG.getConstant(AndMask.getBitWidth()-1,
12015                         getShiftAmountTy(Shl.getValueType()));
12016       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12017
12018       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12019     }
12020   }
12021
12022   // fold select C, 16, 0 -> shl C, 4
12023   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12024       TLI.getBooleanContents(N0.getValueType()) ==
12025           TargetLowering::ZeroOrOneBooleanContent) {
12026
12027     // If the caller doesn't want us to simplify this into a zext of a compare,
12028     // don't do it.
12029     if (NotExtCompare && N2C->getAPIntValue() == 1)
12030       return SDValue();
12031
12032     // Get a SetCC of the condition
12033     // NOTE: Don't create a SETCC if it's not legal on this target.
12034     if (!LegalOperations ||
12035         TLI.isOperationLegal(ISD::SETCC,
12036           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12037       SDValue Temp, SCC;
12038       // cast from setcc result type to select result type
12039       if (LegalTypes) {
12040         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12041                             N0, N1, CC);
12042         if (N2.getValueType().bitsLT(SCC.getValueType()))
12043           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12044                                         N2.getValueType());
12045         else
12046           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12047                              N2.getValueType(), SCC);
12048       } else {
12049         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12050         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12051                            N2.getValueType(), SCC);
12052       }
12053
12054       AddToWorklist(SCC.getNode());
12055       AddToWorklist(Temp.getNode());
12056
12057       if (N2C->getAPIntValue() == 1)
12058         return Temp;
12059
12060       // shl setcc result by log2 n2c
12061       return DAG.getNode(
12062           ISD::SHL, DL, N2.getValueType(), Temp,
12063           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12064                           getShiftAmountTy(Temp.getValueType())));
12065     }
12066   }
12067
12068   // Check to see if this is the equivalent of setcc
12069   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12070   // otherwise, go ahead with the folds.
12071   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12072     EVT XType = N0.getValueType();
12073     if (!LegalOperations ||
12074         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12075       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12076       if (Res.getValueType() != VT)
12077         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12078       return Res;
12079     }
12080
12081     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12082     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12083         (!LegalOperations ||
12084          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12085       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12086       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12087                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12088                                        getShiftAmountTy(Ctlz.getValueType())));
12089     }
12090     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12091     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12092       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12093                                   XType, DAG.getConstant(0, XType), N0);
12094       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12095       return DAG.getNode(ISD::SRL, DL, XType,
12096                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12097                          DAG.getConstant(XType.getSizeInBits()-1,
12098                                          getShiftAmountTy(XType)));
12099     }
12100     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12101     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12102       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12103                                  DAG.getConstant(XType.getSizeInBits()-1,
12104                                          getShiftAmountTy(N0.getValueType())));
12105       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12106     }
12107   }
12108
12109   // Check to see if this is an integer abs.
12110   // select_cc setg[te] X,  0,  X, -X ->
12111   // select_cc setgt    X, -1,  X, -X ->
12112   // select_cc setl[te] X,  0, -X,  X ->
12113   // select_cc setlt    X,  1, -X,  X ->
12114   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12115   if (N1C) {
12116     ConstantSDNode *SubC = nullptr;
12117     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12118          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12119         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12120       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12121     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12122               (N1C->isOne() && CC == ISD::SETLT)) &&
12123              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12124       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12125
12126     EVT XType = N0.getValueType();
12127     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12128       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12129                                   N0,
12130                                   DAG.getConstant(XType.getSizeInBits()-1,
12131                                          getShiftAmountTy(N0.getValueType())));
12132       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12133                                 XType, N0, Shift);
12134       AddToWorklist(Shift.getNode());
12135       AddToWorklist(Add.getNode());
12136       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12137     }
12138   }
12139
12140   return SDValue();
12141 }
12142
12143 /// This is a stub for TargetLowering::SimplifySetCC.
12144 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12145                                    SDValue N1, ISD::CondCode Cond,
12146                                    SDLoc DL, bool foldBooleans) {
12147   TargetLowering::DAGCombinerInfo
12148     DagCombineInfo(DAG, Level, false, this);
12149   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12150 }
12151
12152 /// Given an ISD::SDIV node expressing a divide by constant, return
12153 /// a DAG expression to select that will generate the same value by multiplying
12154 /// by a magic number.
12155 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12156 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12157   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12158   if (!C)
12159     return SDValue();
12160
12161   // Avoid division by zero.
12162   if (!C->getAPIntValue())
12163     return SDValue();
12164
12165   std::vector<SDNode*> Built;
12166   SDValue S =
12167       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12168
12169   for (SDNode *N : Built)
12170     AddToWorklist(N);
12171   return S;
12172 }
12173
12174 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12175 /// DAG expression that will generate the same value by right shifting.
12176 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12177   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12178   if (!C)
12179     return SDValue();
12180
12181   // Avoid division by zero.
12182   if (!C->getAPIntValue())
12183     return SDValue();
12184
12185   std::vector<SDNode *> Built;
12186   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12187
12188   for (SDNode *N : Built)
12189     AddToWorklist(N);
12190   return S;
12191 }
12192
12193 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12194 /// expression that will generate the same value by multiplying by a magic
12195 /// number.
12196 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12197 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12198   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12199   if (!C)
12200     return SDValue();
12201
12202   // Avoid division by zero.
12203   if (!C->getAPIntValue())
12204     return SDValue();
12205
12206   std::vector<SDNode*> Built;
12207   SDValue S =
12208       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12209
12210   for (SDNode *N : Built)
12211     AddToWorklist(N);
12212   return S;
12213 }
12214
12215 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12216   if (Level >= AfterLegalizeDAG)
12217     return SDValue();
12218
12219   // Expose the DAG combiner to the target combiner implementations.
12220   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12221
12222   unsigned Iterations = 0;
12223   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12224     if (Iterations) {
12225       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12226       // For the reciprocal, we need to find the zero of the function:
12227       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12228       //     =>
12229       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12230       //     does not require additional intermediate precision]
12231       EVT VT = Op.getValueType();
12232       SDLoc DL(Op);
12233       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12234
12235       AddToWorklist(Est.getNode());
12236
12237       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12238       for (unsigned i = 0; i < Iterations; ++i) {
12239         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12240         AddToWorklist(NewEst.getNode());
12241
12242         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12243         AddToWorklist(NewEst.getNode());
12244
12245         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12246         AddToWorklist(NewEst.getNode());
12247
12248         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12249         AddToWorklist(Est.getNode());
12250       }
12251     }
12252     return Est;
12253   }
12254
12255   return SDValue();
12256 }
12257
12258 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12259 /// For the reciprocal sqrt, we need to find the zero of the function:
12260 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12261 ///     =>
12262 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12263 /// As a result, we precompute A/2 prior to the iteration loop.
12264 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12265                                           unsigned Iterations) {
12266   EVT VT = Arg.getValueType();
12267   SDLoc DL(Arg);
12268   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12269
12270   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12271   // this entire sequence requires only one FP constant.
12272   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12273   AddToWorklist(HalfArg.getNode());
12274
12275   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12276   AddToWorklist(HalfArg.getNode());
12277
12278   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12279   for (unsigned i = 0; i < Iterations; ++i) {
12280     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12281     AddToWorklist(NewEst.getNode());
12282
12283     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12284     AddToWorklist(NewEst.getNode());
12285
12286     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12287     AddToWorklist(NewEst.getNode());
12288
12289     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12290     AddToWorklist(Est.getNode());
12291   }
12292   return Est;
12293 }
12294
12295 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12296 /// For the reciprocal sqrt, we need to find the zero of the function:
12297 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12298 ///     =>
12299 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12300 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12301                                           unsigned Iterations) {
12302   EVT VT = Arg.getValueType();
12303   SDLoc DL(Arg);
12304   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12305   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12306
12307   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12308   for (unsigned i = 0; i < Iterations; ++i) {
12309     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12310     AddToWorklist(HalfEst.getNode());
12311
12312     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12313     AddToWorklist(Est.getNode());
12314
12315     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12316     AddToWorklist(Est.getNode());
12317
12318     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12319     AddToWorklist(Est.getNode());
12320
12321     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12322     AddToWorklist(Est.getNode());
12323   }
12324   return Est;
12325 }
12326
12327 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12328   if (Level >= AfterLegalizeDAG)
12329     return SDValue();
12330
12331   // Expose the DAG combiner to the target combiner implementations.
12332   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12333   unsigned Iterations = 0;
12334   bool UseOneConstNR = false;
12335   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12336     AddToWorklist(Est.getNode());
12337     if (Iterations) {
12338       Est = UseOneConstNR ?
12339         BuildRsqrtNROneConst(Op, Est, Iterations) :
12340         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12341     }
12342     return Est;
12343   }
12344
12345   return SDValue();
12346 }
12347
12348 /// Return true if base is a frame index, which is known not to alias with
12349 /// anything but itself.  Provides base object and offset as results.
12350 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12351                            const GlobalValue *&GV, const void *&CV) {
12352   // Assume it is a primitive operation.
12353   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12354
12355   // If it's an adding a simple constant then integrate the offset.
12356   if (Base.getOpcode() == ISD::ADD) {
12357     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12358       Base = Base.getOperand(0);
12359       Offset += C->getZExtValue();
12360     }
12361   }
12362
12363   // Return the underlying GlobalValue, and update the Offset.  Return false
12364   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12365   // by multiple nodes with different offsets.
12366   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12367     GV = G->getGlobal();
12368     Offset += G->getOffset();
12369     return false;
12370   }
12371
12372   // Return the underlying Constant value, and update the Offset.  Return false
12373   // for ConstantSDNodes since the same constant pool entry may be represented
12374   // by multiple nodes with different offsets.
12375   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12376     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12377                                          : (const void *)C->getConstVal();
12378     Offset += C->getOffset();
12379     return false;
12380   }
12381   // If it's any of the following then it can't alias with anything but itself.
12382   return isa<FrameIndexSDNode>(Base);
12383 }
12384
12385 /// Return true if there is any possibility that the two addresses overlap.
12386 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12387   // If they are the same then they must be aliases.
12388   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12389
12390   // If they are both volatile then they cannot be reordered.
12391   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12392
12393   // Gather base node and offset information.
12394   SDValue Base1, Base2;
12395   int64_t Offset1, Offset2;
12396   const GlobalValue *GV1, *GV2;
12397   const void *CV1, *CV2;
12398   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12399                                       Base1, Offset1, GV1, CV1);
12400   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12401                                       Base2, Offset2, GV2, CV2);
12402
12403   // If they have a same base address then check to see if they overlap.
12404   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12405     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12406              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12407
12408   // It is possible for different frame indices to alias each other, mostly
12409   // when tail call optimization reuses return address slots for arguments.
12410   // To catch this case, look up the actual index of frame indices to compute
12411   // the real alias relationship.
12412   if (isFrameIndex1 && isFrameIndex2) {
12413     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12414     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12415     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12416     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12417              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12418   }
12419
12420   // Otherwise, if we know what the bases are, and they aren't identical, then
12421   // we know they cannot alias.
12422   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12423     return false;
12424
12425   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12426   // compared to the size and offset of the access, we may be able to prove they
12427   // do not alias.  This check is conservative for now to catch cases created by
12428   // splitting vector types.
12429   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12430       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12431       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12432        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12433       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12434     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12435     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12436
12437     // There is no overlap between these relatively aligned accesses of similar
12438     // size, return no alias.
12439     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12440         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12441       return false;
12442   }
12443
12444   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12445                    ? CombinerGlobalAA
12446                    : DAG.getSubtarget().useAA();
12447 #ifndef NDEBUG
12448   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12449       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12450     UseAA = false;
12451 #endif
12452   if (UseAA &&
12453       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12454     // Use alias analysis information.
12455     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12456                                  Op1->getSrcValueOffset());
12457     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12458         Op0->getSrcValueOffset() - MinOffset;
12459     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12460         Op1->getSrcValueOffset() - MinOffset;
12461     AliasAnalysis::AliasResult AAResult =
12462         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12463                                          Overlap1,
12464                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12465                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12466                                          Overlap2,
12467                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12468     if (AAResult == AliasAnalysis::NoAlias)
12469       return false;
12470   }
12471
12472   // Otherwise we have to assume they alias.
12473   return true;
12474 }
12475
12476 /// Walk up chain skipping non-aliasing memory nodes,
12477 /// looking for aliasing nodes and adding them to the Aliases vector.
12478 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12479                                    SmallVectorImpl<SDValue> &Aliases) {
12480   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12481   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12482
12483   // Get alias information for node.
12484   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12485
12486   // Starting off.
12487   Chains.push_back(OriginalChain);
12488   unsigned Depth = 0;
12489
12490   // Look at each chain and determine if it is an alias.  If so, add it to the
12491   // aliases list.  If not, then continue up the chain looking for the next
12492   // candidate.
12493   while (!Chains.empty()) {
12494     SDValue Chain = Chains.back();
12495     Chains.pop_back();
12496
12497     // For TokenFactor nodes, look at each operand and only continue up the
12498     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12499     // find more and revert to original chain since the xform is unlikely to be
12500     // profitable.
12501     //
12502     // FIXME: The depth check could be made to return the last non-aliasing
12503     // chain we found before we hit a tokenfactor rather than the original
12504     // chain.
12505     if (Depth > 6 || Aliases.size() == 2) {
12506       Aliases.clear();
12507       Aliases.push_back(OriginalChain);
12508       return;
12509     }
12510
12511     // Don't bother if we've been before.
12512     if (!Visited.insert(Chain.getNode()).second)
12513       continue;
12514
12515     switch (Chain.getOpcode()) {
12516     case ISD::EntryToken:
12517       // Entry token is ideal chain operand, but handled in FindBetterChain.
12518       break;
12519
12520     case ISD::LOAD:
12521     case ISD::STORE: {
12522       // Get alias information for Chain.
12523       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12524           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12525
12526       // If chain is alias then stop here.
12527       if (!(IsLoad && IsOpLoad) &&
12528           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12529         Aliases.push_back(Chain);
12530       } else {
12531         // Look further up the chain.
12532         Chains.push_back(Chain.getOperand(0));
12533         ++Depth;
12534       }
12535       break;
12536     }
12537
12538     case ISD::TokenFactor:
12539       // We have to check each of the operands of the token factor for "small"
12540       // token factors, so we queue them up.  Adding the operands to the queue
12541       // (stack) in reverse order maintains the original order and increases the
12542       // likelihood that getNode will find a matching token factor (CSE.)
12543       if (Chain.getNumOperands() > 16) {
12544         Aliases.push_back(Chain);
12545         break;
12546       }
12547       for (unsigned n = Chain.getNumOperands(); n;)
12548         Chains.push_back(Chain.getOperand(--n));
12549       ++Depth;
12550       break;
12551
12552     default:
12553       // For all other instructions we will just have to take what we can get.
12554       Aliases.push_back(Chain);
12555       break;
12556     }
12557   }
12558
12559   // We need to be careful here to also search for aliases through the
12560   // value operand of a store, etc. Consider the following situation:
12561   //   Token1 = ...
12562   //   L1 = load Token1, %52
12563   //   S1 = store Token1, L1, %51
12564   //   L2 = load Token1, %52+8
12565   //   S2 = store Token1, L2, %51+8
12566   //   Token2 = Token(S1, S2)
12567   //   L3 = load Token2, %53
12568   //   S3 = store Token2, L3, %52
12569   //   L4 = load Token2, %53+8
12570   //   S4 = store Token2, L4, %52+8
12571   // If we search for aliases of S3 (which loads address %52), and we look
12572   // only through the chain, then we'll miss the trivial dependence on L1
12573   // (which also loads from %52). We then might change all loads and
12574   // stores to use Token1 as their chain operand, which could result in
12575   // copying %53 into %52 before copying %52 into %51 (which should
12576   // happen first).
12577   //
12578   // The problem is, however, that searching for such data dependencies
12579   // can become expensive, and the cost is not directly related to the
12580   // chain depth. Instead, we'll rule out such configurations here by
12581   // insisting that we've visited all chain users (except for users
12582   // of the original chain, which is not necessary). When doing this,
12583   // we need to look through nodes we don't care about (otherwise, things
12584   // like register copies will interfere with trivial cases).
12585
12586   SmallVector<const SDNode *, 16> Worklist;
12587   for (const SDNode *N : Visited)
12588     if (N != OriginalChain.getNode())
12589       Worklist.push_back(N);
12590
12591   while (!Worklist.empty()) {
12592     const SDNode *M = Worklist.pop_back_val();
12593
12594     // We have already visited M, and want to make sure we've visited any uses
12595     // of M that we care about. For uses that we've not visisted, and don't
12596     // care about, queue them to the worklist.
12597
12598     for (SDNode::use_iterator UI = M->use_begin(),
12599          UIE = M->use_end(); UI != UIE; ++UI)
12600       if (UI.getUse().getValueType() == MVT::Other &&
12601           Visited.insert(*UI).second) {
12602         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12603           // We've not visited this use, and we care about it (it could have an
12604           // ordering dependency with the original node).
12605           Aliases.clear();
12606           Aliases.push_back(OriginalChain);
12607           return;
12608         }
12609
12610         // We've not visited this use, but we don't care about it. Mark it as
12611         // visited and enqueue it to the worklist.
12612         Worklist.push_back(*UI);
12613       }
12614   }
12615 }
12616
12617 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12618 /// (aliasing node.)
12619 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12620   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12621
12622   // Accumulate all the aliases to this node.
12623   GatherAllAliases(N, OldChain, Aliases);
12624
12625   // If no operands then chain to entry token.
12626   if (Aliases.size() == 0)
12627     return DAG.getEntryNode();
12628
12629   // If a single operand then chain to it.  We don't need to revisit it.
12630   if (Aliases.size() == 1)
12631     return Aliases[0];
12632
12633   // Construct a custom tailored token factor.
12634   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12635 }
12636
12637 /// This is the entry point for the file.
12638 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12639                            CodeGenOpt::Level OptLevel) {
12640   /// This is the main entry point to this class.
12641   DAGCombiner(*this, AA, OptLevel).Run(Level);
12642 }