38a06618a8c38bd3a09b062ec7f10bcd6fa1a32f
[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   WorklistRemover DeadNodes(*this);
796   DAG.ReplaceAllUsesWith(N, To);
797   if (AddTo) {
798     // Push the new nodes and any users onto the worklist
799     for (unsigned i = 0, e = NumTo; i != e; ++i) {
800       if (To[i].getNode()) {
801         AddToWorklist(To[i].getNode());
802         AddUsersToWorklist(To[i].getNode());
803       }
804     }
805   }
806
807   // Finally, if the node is now dead, remove it from the graph.  The node
808   // may not be dead if the replacement process recursively simplified to
809   // something else needing this node.
810   if (N->use_empty())
811     deleteAndRecombine(N);
812   return SDValue(N, 0);
813 }
814
815 void DAGCombiner::
816 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
817   // Replace all uses.  If any nodes become isomorphic to other nodes and
818   // are deleted, make sure to remove them from our worklist.
819   WorklistRemover DeadNodes(*this);
820   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
821
822   // Push the new node and any (possibly new) users onto the worklist.
823   AddToWorklist(TLO.New.getNode());
824   AddUsersToWorklist(TLO.New.getNode());
825
826   // Finally, if the node is now dead, remove it from the graph.  The node
827   // may not be dead if the replacement process recursively simplified to
828   // something else needing this node.
829   if (TLO.Old.getNode()->use_empty())
830     deleteAndRecombine(TLO.Old.getNode());
831 }
832
833 /// Check the specified integer node value to see if it can be simplified or if
834 /// things it uses can be simplified by bit propagation. If so, return true.
835 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
836   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
837   APInt KnownZero, KnownOne;
838   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
839     return false;
840
841   // Revisit the node.
842   AddToWorklist(Op.getNode());
843
844   // Replace the old value with the new one.
845   ++NodesCombined;
846   DEBUG(dbgs() << "\nReplacing.2 ";
847         TLO.Old.getNode()->dump(&DAG);
848         dbgs() << "\nWith: ";
849         TLO.New.getNode()->dump(&DAG);
850         dbgs() << '\n');
851
852   CommitTargetLoweringOpt(TLO);
853   return true;
854 }
855
856 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
857   SDLoc dl(Load);
858   EVT VT = Load->getValueType(0);
859   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
860
861   DEBUG(dbgs() << "\nReplacing.9 ";
862         Load->dump(&DAG);
863         dbgs() << "\nWith: ";
864         Trunc.getNode()->dump(&DAG);
865         dbgs() << '\n');
866   WorklistRemover DeadNodes(*this);
867   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
868   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
869   deleteAndRecombine(Load);
870   AddToWorklist(Trunc.getNode());
871 }
872
873 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
874   Replace = false;
875   SDLoc dl(Op);
876   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
877     EVT MemVT = LD->getMemoryVT();
878     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
879       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
880                                                   : ISD::EXTLOAD)
881       : LD->getExtensionType();
882     Replace = true;
883     return DAG.getExtLoad(ExtType, dl, PVT,
884                           LD->getChain(), LD->getBasePtr(),
885                           MemVT, LD->getMemOperand());
886   }
887
888   unsigned Opc = Op.getOpcode();
889   switch (Opc) {
890   default: break;
891   case ISD::AssertSext:
892     return DAG.getNode(ISD::AssertSext, dl, PVT,
893                        SExtPromoteOperand(Op.getOperand(0), PVT),
894                        Op.getOperand(1));
895   case ISD::AssertZext:
896     return DAG.getNode(ISD::AssertZext, dl, PVT,
897                        ZExtPromoteOperand(Op.getOperand(0), PVT),
898                        Op.getOperand(1));
899   case ISD::Constant: {
900     unsigned ExtOpc =
901       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
902     return DAG.getNode(ExtOpc, dl, PVT, Op);
903   }
904   }
905
906   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
907     return SDValue();
908   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
909 }
910
911 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
912   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
913     return SDValue();
914   EVT OldVT = Op.getValueType();
915   SDLoc dl(Op);
916   bool Replace = false;
917   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
918   if (!NewOp.getNode())
919     return SDValue();
920   AddToWorklist(NewOp.getNode());
921
922   if (Replace)
923     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
924   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
925                      DAG.getValueType(OldVT));
926 }
927
928 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
929   EVT OldVT = Op.getValueType();
930   SDLoc dl(Op);
931   bool Replace = false;
932   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
933   if (!NewOp.getNode())
934     return SDValue();
935   AddToWorklist(NewOp.getNode());
936
937   if (Replace)
938     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
939   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
940 }
941
942 /// Promote the specified integer binary operation if the target indicates it is
943 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
944 /// i32 since i16 instructions are longer.
945 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
946   if (!LegalOperations)
947     return SDValue();
948
949   EVT VT = Op.getValueType();
950   if (VT.isVector() || !VT.isInteger())
951     return SDValue();
952
953   // If operation type is 'undesirable', e.g. i16 on x86, consider
954   // promoting it.
955   unsigned Opc = Op.getOpcode();
956   if (TLI.isTypeDesirableForOp(Opc, VT))
957     return SDValue();
958
959   EVT PVT = VT;
960   // Consult target whether it is a good idea to promote this operation and
961   // what's the right type to promote it to.
962   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
963     assert(PVT != VT && "Don't know what type to promote to!");
964
965     bool Replace0 = false;
966     SDValue N0 = Op.getOperand(0);
967     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
968     if (!NN0.getNode())
969       return SDValue();
970
971     bool Replace1 = false;
972     SDValue N1 = Op.getOperand(1);
973     SDValue NN1;
974     if (N0 == N1)
975       NN1 = NN0;
976     else {
977       NN1 = PromoteOperand(N1, PVT, Replace1);
978       if (!NN1.getNode())
979         return SDValue();
980     }
981
982     AddToWorklist(NN0.getNode());
983     if (NN1.getNode())
984       AddToWorklist(NN1.getNode());
985
986     if (Replace0)
987       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
988     if (Replace1)
989       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
990
991     DEBUG(dbgs() << "\nPromoting ";
992           Op.getNode()->dump(&DAG));
993     SDLoc dl(Op);
994     return DAG.getNode(ISD::TRUNCATE, dl, VT,
995                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
996   }
997   return SDValue();
998 }
999
1000 /// Promote the specified integer shift operation if the target indicates it is
1001 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1002 /// i32 since i16 instructions are longer.
1003 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1004   if (!LegalOperations)
1005     return SDValue();
1006
1007   EVT VT = Op.getValueType();
1008   if (VT.isVector() || !VT.isInteger())
1009     return SDValue();
1010
1011   // If operation type is 'undesirable', e.g. i16 on x86, consider
1012   // promoting it.
1013   unsigned Opc = Op.getOpcode();
1014   if (TLI.isTypeDesirableForOp(Opc, VT))
1015     return SDValue();
1016
1017   EVT PVT = VT;
1018   // Consult target whether it is a good idea to promote this operation and
1019   // what's the right type to promote it to.
1020   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1021     assert(PVT != VT && "Don't know what type to promote to!");
1022
1023     bool Replace = false;
1024     SDValue N0 = Op.getOperand(0);
1025     if (Opc == ISD::SRA)
1026       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1027     else if (Opc == ISD::SRL)
1028       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1029     else
1030       N0 = PromoteOperand(N0, PVT, Replace);
1031     if (!N0.getNode())
1032       return SDValue();
1033
1034     AddToWorklist(N0.getNode());
1035     if (Replace)
1036       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1037
1038     DEBUG(dbgs() << "\nPromoting ";
1039           Op.getNode()->dump(&DAG));
1040     SDLoc dl(Op);
1041     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1042                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1043   }
1044   return SDValue();
1045 }
1046
1047 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1048   if (!LegalOperations)
1049     return SDValue();
1050
1051   EVT VT = Op.getValueType();
1052   if (VT.isVector() || !VT.isInteger())
1053     return SDValue();
1054
1055   // If operation type is 'undesirable', e.g. i16 on x86, consider
1056   // promoting it.
1057   unsigned Opc = Op.getOpcode();
1058   if (TLI.isTypeDesirableForOp(Opc, VT))
1059     return SDValue();
1060
1061   EVT PVT = VT;
1062   // Consult target whether it is a good idea to promote this operation and
1063   // what's the right type to promote it to.
1064   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1065     assert(PVT != VT && "Don't know what type to promote to!");
1066     // fold (aext (aext x)) -> (aext x)
1067     // fold (aext (zext x)) -> (zext x)
1068     // fold (aext (sext x)) -> (sext x)
1069     DEBUG(dbgs() << "\nPromoting ";
1070           Op.getNode()->dump(&DAG));
1071     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1072   }
1073   return SDValue();
1074 }
1075
1076 bool DAGCombiner::PromoteLoad(SDValue Op) {
1077   if (!LegalOperations)
1078     return false;
1079
1080   EVT VT = Op.getValueType();
1081   if (VT.isVector() || !VT.isInteger())
1082     return false;
1083
1084   // If operation type is 'undesirable', e.g. i16 on x86, consider
1085   // promoting it.
1086   unsigned Opc = Op.getOpcode();
1087   if (TLI.isTypeDesirableForOp(Opc, VT))
1088     return false;
1089
1090   EVT PVT = VT;
1091   // Consult target whether it is a good idea to promote this operation and
1092   // what's the right type to promote it to.
1093   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1094     assert(PVT != VT && "Don't know what type to promote to!");
1095
1096     SDLoc dl(Op);
1097     SDNode *N = Op.getNode();
1098     LoadSDNode *LD = cast<LoadSDNode>(N);
1099     EVT MemVT = LD->getMemoryVT();
1100     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1101       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1102                                                   : ISD::EXTLOAD)
1103       : LD->getExtensionType();
1104     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1105                                    LD->getChain(), LD->getBasePtr(),
1106                                    MemVT, LD->getMemOperand());
1107     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1108
1109     DEBUG(dbgs() << "\nPromoting ";
1110           N->dump(&DAG);
1111           dbgs() << "\nTo: ";
1112           Result.getNode()->dump(&DAG);
1113           dbgs() << '\n');
1114     WorklistRemover DeadNodes(*this);
1115     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1116     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1117     deleteAndRecombine(N);
1118     AddToWorklist(Result.getNode());
1119     return true;
1120   }
1121   return false;
1122 }
1123
1124 /// \brief Recursively delete a node which has no uses and any operands for
1125 /// which it is the only use.
1126 ///
1127 /// Note that this both deletes the nodes and removes them from the worklist.
1128 /// It also adds any nodes who have had a user deleted to the worklist as they
1129 /// may now have only one use and subject to other combines.
1130 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1131   if (!N->use_empty())
1132     return false;
1133
1134   SmallSetVector<SDNode *, 16> Nodes;
1135   Nodes.insert(N);
1136   do {
1137     N = Nodes.pop_back_val();
1138     if (!N)
1139       continue;
1140
1141     if (N->use_empty()) {
1142       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1143         Nodes.insert(N->getOperand(i).getNode());
1144
1145       removeFromWorklist(N);
1146       DAG.DeleteNode(N);
1147     } else {
1148       AddToWorklist(N);
1149     }
1150   } while (!Nodes.empty());
1151   return true;
1152 }
1153
1154 //===----------------------------------------------------------------------===//
1155 //  Main DAG Combiner implementation
1156 //===----------------------------------------------------------------------===//
1157
1158 void DAGCombiner::Run(CombineLevel AtLevel) {
1159   // set the instance variables, so that the various visit routines may use it.
1160   Level = AtLevel;
1161   LegalOperations = Level >= AfterLegalizeVectorOps;
1162   LegalTypes = Level >= AfterLegalizeTypes;
1163
1164   // Early exit if this basic block is in an optnone function.
1165   AttributeSet FnAttrs =
1166     DAG.getMachineFunction().getFunction()->getAttributes();
1167   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1168                            Attribute::OptimizeNone))
1169     return;
1170
1171   // Add all the dag nodes to the worklist.
1172   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1173        E = DAG.allnodes_end(); I != E; ++I)
1174     AddToWorklist(I);
1175
1176   // Create a dummy node (which is not added to allnodes), that adds a reference
1177   // to the root node, preventing it from being deleted, and tracking any
1178   // changes of the root.
1179   HandleSDNode Dummy(DAG.getRoot());
1180
1181   // while the worklist isn't empty, find a node and
1182   // try and combine it.
1183   while (!WorklistMap.empty()) {
1184     SDNode *N;
1185     // The Worklist holds the SDNodes in order, but it may contain null entries.
1186     do {
1187       N = Worklist.pop_back_val();
1188     } while (!N);
1189
1190     bool GoodWorklistEntry = WorklistMap.erase(N);
1191     (void)GoodWorklistEntry;
1192     assert(GoodWorklistEntry &&
1193            "Found a worklist entry without a corresponding map entry!");
1194
1195     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1196     // N is deleted from the DAG, since they too may now be dead or may have a
1197     // reduced number of uses, allowing other xforms.
1198     if (recursivelyDeleteUnusedNodes(N))
1199       continue;
1200
1201     WorklistRemover DeadNodes(*this);
1202
1203     // If this combine is running after legalizing the DAG, re-legalize any
1204     // nodes pulled off the worklist.
1205     if (Level == AfterLegalizeDAG) {
1206       SmallSetVector<SDNode *, 16> UpdatedNodes;
1207       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1208
1209       for (SDNode *LN : UpdatedNodes) {
1210         AddToWorklist(LN);
1211         AddUsersToWorklist(LN);
1212       }
1213       if (!NIsValid)
1214         continue;
1215     }
1216
1217     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1218
1219     // Add any operands of the new node which have not yet been combined to the
1220     // worklist as well. Because the worklist uniques things already, this
1221     // won't repeatedly process the same operand.
1222     CombinedNodes.insert(N);
1223     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1224       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1225         AddToWorklist(N->getOperand(i).getNode());
1226
1227     SDValue RV = combine(N);
1228
1229     if (!RV.getNode())
1230       continue;
1231
1232     ++NodesCombined;
1233
1234     // If we get back the same node we passed in, rather than a new node or
1235     // zero, we know that the node must have defined multiple values and
1236     // CombineTo was used.  Since CombineTo takes care of the worklist
1237     // mechanics for us, we have no work to do in this case.
1238     if (RV.getNode() == N)
1239       continue;
1240
1241     assert(N->getOpcode() != ISD::DELETED_NODE &&
1242            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1243            "Node was deleted but visit returned new node!");
1244
1245     DEBUG(dbgs() << " ... into: ";
1246           RV.getNode()->dump(&DAG));
1247
1248     // Transfer debug value.
1249     DAG.TransferDbgValues(SDValue(N, 0), RV);
1250     if (N->getNumValues() == RV.getNode()->getNumValues())
1251       DAG.ReplaceAllUsesWith(N, RV.getNode());
1252     else {
1253       assert(N->getValueType(0) == RV.getValueType() &&
1254              N->getNumValues() == 1 && "Type mismatch");
1255       SDValue OpV = RV;
1256       DAG.ReplaceAllUsesWith(N, &OpV);
1257     }
1258
1259     // Push the new node and any users onto the worklist
1260     AddToWorklist(RV.getNode());
1261     AddUsersToWorklist(RV.getNode());
1262
1263     // Finally, if the node is now dead, remove it from the graph.  The node
1264     // may not be dead if the replacement process recursively simplified to
1265     // something else needing this node. This will also take care of adding any
1266     // operands which have lost a user to the worklist.
1267     recursivelyDeleteUnusedNodes(N);
1268   }
1269
1270   // If the root changed (e.g. it was a dead load, update the root).
1271   DAG.setRoot(Dummy.getValue());
1272   DAG.RemoveDeadNodes();
1273 }
1274
1275 SDValue DAGCombiner::visit(SDNode *N) {
1276   switch (N->getOpcode()) {
1277   default: break;
1278   case ISD::TokenFactor:        return visitTokenFactor(N);
1279   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1280   case ISD::ADD:                return visitADD(N);
1281   case ISD::SUB:                return visitSUB(N);
1282   case ISD::ADDC:               return visitADDC(N);
1283   case ISD::SUBC:               return visitSUBC(N);
1284   case ISD::ADDE:               return visitADDE(N);
1285   case ISD::SUBE:               return visitSUBE(N);
1286   case ISD::MUL:                return visitMUL(N);
1287   case ISD::SDIV:               return visitSDIV(N);
1288   case ISD::UDIV:               return visitUDIV(N);
1289   case ISD::SREM:               return visitSREM(N);
1290   case ISD::UREM:               return visitUREM(N);
1291   case ISD::MULHU:              return visitMULHU(N);
1292   case ISD::MULHS:              return visitMULHS(N);
1293   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1294   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1295   case ISD::SMULO:              return visitSMULO(N);
1296   case ISD::UMULO:              return visitUMULO(N);
1297   case ISD::SDIVREM:            return visitSDIVREM(N);
1298   case ISD::UDIVREM:            return visitUDIVREM(N);
1299   case ISD::AND:                return visitAND(N);
1300   case ISD::OR:                 return visitOR(N);
1301   case ISD::XOR:                return visitXOR(N);
1302   case ISD::SHL:                return visitSHL(N);
1303   case ISD::SRA:                return visitSRA(N);
1304   case ISD::SRL:                return visitSRL(N);
1305   case ISD::ROTR:
1306   case ISD::ROTL:               return visitRotate(N);
1307   case ISD::CTLZ:               return visitCTLZ(N);
1308   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1309   case ISD::CTTZ:               return visitCTTZ(N);
1310   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1311   case ISD::CTPOP:              return visitCTPOP(N);
1312   case ISD::SELECT:             return visitSELECT(N);
1313   case ISD::VSELECT:            return visitVSELECT(N);
1314   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1315   case ISD::SETCC:              return visitSETCC(N);
1316   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1317   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1318   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1319   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1320   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1321   case ISD::BITCAST:            return visitBITCAST(N);
1322   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1323   case ISD::FADD:               return visitFADD(N);
1324   case ISD::FSUB:               return visitFSUB(N);
1325   case ISD::FMUL:               return visitFMUL(N);
1326   case ISD::FMA:                return visitFMA(N);
1327   case ISD::FDIV:               return visitFDIV(N);
1328   case ISD::FREM:               return visitFREM(N);
1329   case ISD::FSQRT:              return visitFSQRT(N);
1330   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1331   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1332   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1333   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1334   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1335   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1336   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1337   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1338   case ISD::FNEG:               return visitFNEG(N);
1339   case ISD::FABS:               return visitFABS(N);
1340   case ISD::FFLOOR:             return visitFFLOOR(N);
1341   case ISD::FMINNUM:            return visitFMINNUM(N);
1342   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1343   case ISD::FCEIL:              return visitFCEIL(N);
1344   case ISD::FTRUNC:             return visitFTRUNC(N);
1345   case ISD::BRCOND:             return visitBRCOND(N);
1346   case ISD::BR_CC:              return visitBR_CC(N);
1347   case ISD::LOAD:               return visitLOAD(N);
1348   case ISD::STORE:              return visitSTORE(N);
1349   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1350   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1351   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1352   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1353   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1354   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1355   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1356   case ISD::MLOAD:              return visitMLOAD(N);
1357   case ISD::MSTORE:             return visitMSTORE(N);
1358   }
1359   return SDValue();
1360 }
1361
1362 SDValue DAGCombiner::combine(SDNode *N) {
1363   SDValue RV = visit(N);
1364
1365   // If nothing happened, try a target-specific DAG combine.
1366   if (!RV.getNode()) {
1367     assert(N->getOpcode() != ISD::DELETED_NODE &&
1368            "Node was deleted but visit returned NULL!");
1369
1370     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1371         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1372
1373       // Expose the DAG combiner to the target combiner impls.
1374       TargetLowering::DAGCombinerInfo
1375         DagCombineInfo(DAG, Level, false, this);
1376
1377       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1378     }
1379   }
1380
1381   // If nothing happened still, try promoting the operation.
1382   if (!RV.getNode()) {
1383     switch (N->getOpcode()) {
1384     default: break;
1385     case ISD::ADD:
1386     case ISD::SUB:
1387     case ISD::MUL:
1388     case ISD::AND:
1389     case ISD::OR:
1390     case ISD::XOR:
1391       RV = PromoteIntBinOp(SDValue(N, 0));
1392       break;
1393     case ISD::SHL:
1394     case ISD::SRA:
1395     case ISD::SRL:
1396       RV = PromoteIntShiftOp(SDValue(N, 0));
1397       break;
1398     case ISD::SIGN_EXTEND:
1399     case ISD::ZERO_EXTEND:
1400     case ISD::ANY_EXTEND:
1401       RV = PromoteExtend(SDValue(N, 0));
1402       break;
1403     case ISD::LOAD:
1404       if (PromoteLoad(SDValue(N, 0)))
1405         RV = SDValue(N, 0);
1406       break;
1407     }
1408   }
1409
1410   // If N is a commutative binary node, try commuting it to enable more
1411   // sdisel CSE.
1412   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1413       N->getNumValues() == 1) {
1414     SDValue N0 = N->getOperand(0);
1415     SDValue N1 = N->getOperand(1);
1416
1417     // Constant operands are canonicalized to RHS.
1418     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1419       SDValue Ops[] = {N1, N0};
1420       SDNode *CSENode;
1421       if (const BinaryWithFlagsSDNode *BinNode =
1422               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1423         CSENode = DAG.getNodeIfExists(
1424             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1425             BinNode->hasNoSignedWrap(), BinNode->isExact());
1426       } else {
1427         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1428       }
1429       if (CSENode)
1430         return SDValue(CSENode, 0);
1431     }
1432   }
1433
1434   return RV;
1435 }
1436
1437 /// Given a node, return its input chain if it has one, otherwise return a null
1438 /// sd operand.
1439 static SDValue getInputChainForNode(SDNode *N) {
1440   if (unsigned NumOps = N->getNumOperands()) {
1441     if (N->getOperand(0).getValueType() == MVT::Other)
1442       return N->getOperand(0);
1443     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1444       return N->getOperand(NumOps-1);
1445     for (unsigned i = 1; i < NumOps-1; ++i)
1446       if (N->getOperand(i).getValueType() == MVT::Other)
1447         return N->getOperand(i);
1448   }
1449   return SDValue();
1450 }
1451
1452 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1453   // If N has two operands, where one has an input chain equal to the other,
1454   // the 'other' chain is redundant.
1455   if (N->getNumOperands() == 2) {
1456     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1457       return N->getOperand(0);
1458     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1459       return N->getOperand(1);
1460   }
1461
1462   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1463   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1464   SmallPtrSet<SDNode*, 16> SeenOps;
1465   bool Changed = false;             // If we should replace this token factor.
1466
1467   // Start out with this token factor.
1468   TFs.push_back(N);
1469
1470   // Iterate through token factors.  The TFs grows when new token factors are
1471   // encountered.
1472   for (unsigned i = 0; i < TFs.size(); ++i) {
1473     SDNode *TF = TFs[i];
1474
1475     // Check each of the operands.
1476     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1477       SDValue Op = TF->getOperand(i);
1478
1479       switch (Op.getOpcode()) {
1480       case ISD::EntryToken:
1481         // Entry tokens don't need to be added to the list. They are
1482         // rededundant.
1483         Changed = true;
1484         break;
1485
1486       case ISD::TokenFactor:
1487         if (Op.hasOneUse() &&
1488             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1489           // Queue up for processing.
1490           TFs.push_back(Op.getNode());
1491           // Clean up in case the token factor is removed.
1492           AddToWorklist(Op.getNode());
1493           Changed = true;
1494           break;
1495         }
1496         // Fall thru
1497
1498       default:
1499         // Only add if it isn't already in the list.
1500         if (SeenOps.insert(Op.getNode()).second)
1501           Ops.push_back(Op);
1502         else
1503           Changed = true;
1504         break;
1505       }
1506     }
1507   }
1508
1509   SDValue Result;
1510
1511   // If we've change things around then replace token factor.
1512   if (Changed) {
1513     if (Ops.empty()) {
1514       // The entry token is the only possible outcome.
1515       Result = DAG.getEntryNode();
1516     } else {
1517       // New and improved token factor.
1518       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1519     }
1520
1521     // Don't add users to work list.
1522     return CombineTo(N, Result, false);
1523   }
1524
1525   return Result;
1526 }
1527
1528 /// MERGE_VALUES can always be eliminated.
1529 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1530   WorklistRemover DeadNodes(*this);
1531   // Replacing results may cause a different MERGE_VALUES to suddenly
1532   // be CSE'd with N, and carry its uses with it. Iterate until no
1533   // uses remain, to ensure that the node can be safely deleted.
1534   // First add the users of this node to the work list so that they
1535   // can be tried again once they have new operands.
1536   AddUsersToWorklist(N);
1537   do {
1538     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1539       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1540   } while (!N->use_empty());
1541   deleteAndRecombine(N);
1542   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1543 }
1544
1545 SDValue DAGCombiner::visitADD(SDNode *N) {
1546   SDValue N0 = N->getOperand(0);
1547   SDValue N1 = N->getOperand(1);
1548   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1549   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1550   EVT VT = N0.getValueType();
1551
1552   // fold vector ops
1553   if (VT.isVector()) {
1554     SDValue FoldedVOp = SimplifyVBinOp(N);
1555     if (FoldedVOp.getNode()) return FoldedVOp;
1556
1557     // fold (add x, 0) -> x, vector edition
1558     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1559       return N0;
1560     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1561       return N1;
1562   }
1563
1564   // fold (add x, undef) -> undef
1565   if (N0.getOpcode() == ISD::UNDEF)
1566     return N0;
1567   if (N1.getOpcode() == ISD::UNDEF)
1568     return N1;
1569   // fold (add c1, c2) -> c1+c2
1570   if (N0C && N1C)
1571     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1572   // canonicalize constant to RHS
1573   if (N0C && !N1C)
1574     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1575   // fold (add x, 0) -> x
1576   if (N1C && N1C->isNullValue())
1577     return N0;
1578   // fold (add Sym, c) -> Sym+c
1579   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1580     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1581         GA->getOpcode() == ISD::GlobalAddress)
1582       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1583                                   GA->getOffset() +
1584                                     (uint64_t)N1C->getSExtValue());
1585   // fold ((c1-A)+c2) -> (c1+c2)-A
1586   if (N1C && N0.getOpcode() == ISD::SUB)
1587     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1588       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1589                          DAG.getConstant(N1C->getAPIntValue()+
1590                                          N0C->getAPIntValue(), VT),
1591                          N0.getOperand(1));
1592   // reassociate add
1593   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1594   if (RADD.getNode())
1595     return RADD;
1596   // fold ((0-A) + B) -> B-A
1597   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1598       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1599     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1600   // fold (A + (0-B)) -> A-B
1601   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1602       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1603     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1604   // fold (A+(B-A)) -> B
1605   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1606     return N1.getOperand(0);
1607   // fold ((B-A)+A) -> B
1608   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1609     return N0.getOperand(0);
1610   // fold (A+(B-(A+C))) to (B-C)
1611   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1612       N0 == N1.getOperand(1).getOperand(0))
1613     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1614                        N1.getOperand(1).getOperand(1));
1615   // fold (A+(B-(C+A))) to (B-C)
1616   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1617       N0 == N1.getOperand(1).getOperand(1))
1618     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1619                        N1.getOperand(1).getOperand(0));
1620   // fold (A+((B-A)+or-C)) to (B+or-C)
1621   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1622       N1.getOperand(0).getOpcode() == ISD::SUB &&
1623       N0 == N1.getOperand(0).getOperand(1))
1624     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1625                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1626
1627   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1628   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1629     SDValue N00 = N0.getOperand(0);
1630     SDValue N01 = N0.getOperand(1);
1631     SDValue N10 = N1.getOperand(0);
1632     SDValue N11 = N1.getOperand(1);
1633
1634     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1635       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1636                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1637                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1638   }
1639
1640   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1641     return SDValue(N, 0);
1642
1643   // fold (a+b) -> (a|b) iff a and b share no bits.
1644   if (VT.isInteger() && !VT.isVector()) {
1645     APInt LHSZero, LHSOne;
1646     APInt RHSZero, RHSOne;
1647     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1648
1649     if (LHSZero.getBoolValue()) {
1650       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1651
1652       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1653       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1654       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1655         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1656           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1657       }
1658     }
1659   }
1660
1661   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1662   if (N1.getOpcode() == ISD::SHL &&
1663       N1.getOperand(0).getOpcode() == ISD::SUB)
1664     if (ConstantSDNode *C =
1665           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1666       if (C->getAPIntValue() == 0)
1667         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1668                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1669                                        N1.getOperand(0).getOperand(1),
1670                                        N1.getOperand(1)));
1671   if (N0.getOpcode() == ISD::SHL &&
1672       N0.getOperand(0).getOpcode() == ISD::SUB)
1673     if (ConstantSDNode *C =
1674           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1675       if (C->getAPIntValue() == 0)
1676         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1677                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1678                                        N0.getOperand(0).getOperand(1),
1679                                        N0.getOperand(1)));
1680
1681   if (N1.getOpcode() == ISD::AND) {
1682     SDValue AndOp0 = N1.getOperand(0);
1683     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1684     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1685     unsigned DestBits = VT.getScalarType().getSizeInBits();
1686
1687     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1688     // and similar xforms where the inner op is either ~0 or 0.
1689     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1690       SDLoc DL(N);
1691       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1692     }
1693   }
1694
1695   // add (sext i1), X -> sub X, (zext i1)
1696   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1697       N0.getOperand(0).getValueType() == MVT::i1 &&
1698       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1699     SDLoc DL(N);
1700     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1701     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1702   }
1703
1704   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1705   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1706     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1707     if (TN->getVT() == MVT::i1) {
1708       SDLoc DL(N);
1709       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1710                                  DAG.getConstant(1, VT));
1711       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1712     }
1713   }
1714
1715   return SDValue();
1716 }
1717
1718 SDValue DAGCombiner::visitADDC(SDNode *N) {
1719   SDValue N0 = N->getOperand(0);
1720   SDValue N1 = N->getOperand(1);
1721   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1722   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1723   EVT VT = N0.getValueType();
1724
1725   // If the flag result is dead, turn this into an ADD.
1726   if (!N->hasAnyUseOfValue(1))
1727     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1728                      DAG.getNode(ISD::CARRY_FALSE,
1729                                  SDLoc(N), MVT::Glue));
1730
1731   // canonicalize constant to RHS.
1732   if (N0C && !N1C)
1733     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1734
1735   // fold (addc x, 0) -> x + no carry out
1736   if (N1C && N1C->isNullValue())
1737     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1738                                         SDLoc(N), MVT::Glue));
1739
1740   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1741   APInt LHSZero, LHSOne;
1742   APInt RHSZero, RHSOne;
1743   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1744
1745   if (LHSZero.getBoolValue()) {
1746     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1747
1748     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1749     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1750     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1751       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1752                        DAG.getNode(ISD::CARRY_FALSE,
1753                                    SDLoc(N), MVT::Glue));
1754   }
1755
1756   return SDValue();
1757 }
1758
1759 SDValue DAGCombiner::visitADDE(SDNode *N) {
1760   SDValue N0 = N->getOperand(0);
1761   SDValue N1 = N->getOperand(1);
1762   SDValue CarryIn = N->getOperand(2);
1763   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1765
1766   // canonicalize constant to RHS
1767   if (N0C && !N1C)
1768     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1769                        N1, N0, CarryIn);
1770
1771   // fold (adde x, y, false) -> (addc x, y)
1772   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1773     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1774
1775   return SDValue();
1776 }
1777
1778 // Since it may not be valid to emit a fold to zero for vector initializers
1779 // check if we can before folding.
1780 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1781                              SelectionDAG &DAG,
1782                              bool LegalOperations, bool LegalTypes) {
1783   if (!VT.isVector())
1784     return DAG.getConstant(0, VT);
1785   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1786     return DAG.getConstant(0, VT);
1787   return SDValue();
1788 }
1789
1790 SDValue DAGCombiner::visitSUB(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1794   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1795   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1796     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1797   EVT VT = N0.getValueType();
1798
1799   // fold vector ops
1800   if (VT.isVector()) {
1801     SDValue FoldedVOp = SimplifyVBinOp(N);
1802     if (FoldedVOp.getNode()) return FoldedVOp;
1803
1804     // fold (sub x, 0) -> x, vector edition
1805     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1806       return N0;
1807   }
1808
1809   // fold (sub x, x) -> 0
1810   // FIXME: Refactor this and xor and other similar operations together.
1811   if (N0 == N1)
1812     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1813   // fold (sub c1, c2) -> c1-c2
1814   if (N0C && N1C)
1815     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1816   // fold (sub x, c) -> (add x, -c)
1817   if (N1C)
1818     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1819                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1820   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1821   if (N0C && N0C->isAllOnesValue())
1822     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1823   // fold A-(A-B) -> B
1824   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1825     return N1.getOperand(1);
1826   // fold (A+B)-A -> B
1827   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1828     return N0.getOperand(1);
1829   // fold (A+B)-B -> A
1830   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1831     return N0.getOperand(0);
1832   // fold C2-(A+C1) -> (C2-C1)-A
1833   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1834     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1835                                    VT);
1836     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1837                        N1.getOperand(0));
1838   }
1839   // fold ((A+(B+or-C))-B) -> A+or-C
1840   if (N0.getOpcode() == ISD::ADD &&
1841       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1842        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1843       N0.getOperand(1).getOperand(0) == N1)
1844     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1845                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1846   // fold ((A+(C+B))-B) -> A+C
1847   if (N0.getOpcode() == ISD::ADD &&
1848       N0.getOperand(1).getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOperand(1) == N1)
1850     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1851                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1852   // fold ((A-(B-C))-C) -> A-B
1853   if (N0.getOpcode() == ISD::SUB &&
1854       N0.getOperand(1).getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOperand(1) == N1)
1856     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1857                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1858
1859   // If either operand of a sub is undef, the result is undef
1860   if (N0.getOpcode() == ISD::UNDEF)
1861     return N0;
1862   if (N1.getOpcode() == ISD::UNDEF)
1863     return N1;
1864
1865   // If the relocation model supports it, consider symbol offsets.
1866   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1867     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1868       // fold (sub Sym, c) -> Sym-c
1869       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1870         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1871                                     GA->getOffset() -
1872                                       (uint64_t)N1C->getSExtValue());
1873       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1874       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1875         if (GA->getGlobal() == GB->getGlobal())
1876           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1877                                  VT);
1878     }
1879
1880   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1881   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1882     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1883     if (TN->getVT() == MVT::i1) {
1884       SDLoc DL(N);
1885       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1886                                  DAG.getConstant(1, VT));
1887       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1888     }
1889   }
1890
1891   return SDValue();
1892 }
1893
1894 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1895   SDValue N0 = N->getOperand(0);
1896   SDValue N1 = N->getOperand(1);
1897   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1898   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1899   EVT VT = N0.getValueType();
1900
1901   // If the flag result is dead, turn this into an SUB.
1902   if (!N->hasAnyUseOfValue(1))
1903     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1904                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1905                                  MVT::Glue));
1906
1907   // fold (subc x, x) -> 0 + no borrow
1908   if (N0 == N1)
1909     return CombineTo(N, DAG.getConstant(0, VT),
1910                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1911                                  MVT::Glue));
1912
1913   // fold (subc x, 0) -> x + no borrow
1914   if (N1C && N1C->isNullValue())
1915     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1916                                         MVT::Glue));
1917
1918   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1919   if (N0C && N0C->isAllOnesValue())
1920     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1921                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1922                                  MVT::Glue));
1923
1924   return SDValue();
1925 }
1926
1927 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1928   SDValue N0 = N->getOperand(0);
1929   SDValue N1 = N->getOperand(1);
1930   SDValue CarryIn = N->getOperand(2);
1931
1932   // fold (sube x, y, false) -> (subc x, y)
1933   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1934     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1935
1936   return SDValue();
1937 }
1938
1939 SDValue DAGCombiner::visitMUL(SDNode *N) {
1940   SDValue N0 = N->getOperand(0);
1941   SDValue N1 = N->getOperand(1);
1942   EVT VT = N0.getValueType();
1943
1944   // fold (mul x, undef) -> 0
1945   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1946     return DAG.getConstant(0, VT);
1947
1948   bool N0IsConst = false;
1949   bool N1IsConst = false;
1950   APInt ConstValue0, ConstValue1;
1951   // fold vector ops
1952   if (VT.isVector()) {
1953     SDValue FoldedVOp = SimplifyVBinOp(N);
1954     if (FoldedVOp.getNode()) return FoldedVOp;
1955
1956     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1957     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1958   } else {
1959     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1960     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1961                             : APInt();
1962     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1963     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1964                             : APInt();
1965   }
1966
1967   // fold (mul c1, c2) -> c1*c2
1968   if (N0IsConst && N1IsConst)
1969     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1970
1971   // canonicalize constant to RHS
1972   if (N0IsConst && !N1IsConst)
1973     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1974   // fold (mul x, 0) -> 0
1975   if (N1IsConst && ConstValue1 == 0)
1976     return N1;
1977   // We require a splat of the entire scalar bit width for non-contiguous
1978   // bit patterns.
1979   bool IsFullSplat =
1980     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1981   // fold (mul x, 1) -> x
1982   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1983     return N0;
1984   // fold (mul x, -1) -> 0-x
1985   if (N1IsConst && ConstValue1.isAllOnesValue())
1986     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1987                        DAG.getConstant(0, VT), N0);
1988   // fold (mul x, (1 << c)) -> x << c
1989   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1990     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1991                        DAG.getConstant(ConstValue1.logBase2(),
1992                                        getShiftAmountTy(N0.getValueType())));
1993   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1994   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1995     unsigned Log2Val = (-ConstValue1).logBase2();
1996     // FIXME: If the input is something that is easily negated (e.g. a
1997     // single-use add), we should put the negate there.
1998     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1999                        DAG.getConstant(0, VT),
2000                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2001                             DAG.getConstant(Log2Val,
2002                                       getShiftAmountTy(N0.getValueType()))));
2003   }
2004
2005   APInt Val;
2006   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2007   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2008       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2010     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2011                              N1, N0.getOperand(1));
2012     AddToWorklist(C3.getNode());
2013     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2014                        N0.getOperand(0), C3);
2015   }
2016
2017   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2018   // use.
2019   {
2020     SDValue Sh(nullptr,0), Y(nullptr,0);
2021     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2022     if (N0.getOpcode() == ISD::SHL &&
2023         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2024                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2025         N0.getNode()->hasOneUse()) {
2026       Sh = N0; Y = N1;
2027     } else if (N1.getOpcode() == ISD::SHL &&
2028                isa<ConstantSDNode>(N1.getOperand(1)) &&
2029                N1.getNode()->hasOneUse()) {
2030       Sh = N1; Y = N0;
2031     }
2032
2033     if (Sh.getNode()) {
2034       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2035                                 Sh.getOperand(0), Y);
2036       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2037                          Mul, Sh.getOperand(1));
2038     }
2039   }
2040
2041   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2042   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2043       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2044                      isa<ConstantSDNode>(N0.getOperand(1))))
2045     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2046                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2047                                    N0.getOperand(0), N1),
2048                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2049                                    N0.getOperand(1), N1));
2050
2051   // reassociate mul
2052   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2053   if (RMUL.getNode())
2054     return RMUL;
2055
2056   return SDValue();
2057 }
2058
2059 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2060   SDValue N0 = N->getOperand(0);
2061   SDValue N1 = N->getOperand(1);
2062   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2063   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2064   EVT VT = N->getValueType(0);
2065
2066   // fold vector ops
2067   if (VT.isVector()) {
2068     SDValue FoldedVOp = SimplifyVBinOp(N);
2069     if (FoldedVOp.getNode()) return FoldedVOp;
2070   }
2071
2072   // fold (sdiv c1, c2) -> c1/c2
2073   if (N0C && N1C && !N1C->isNullValue())
2074     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2075   // fold (sdiv X, 1) -> X
2076   if (N1C && N1C->getAPIntValue() == 1LL)
2077     return N0;
2078   // fold (sdiv X, -1) -> 0-X
2079   if (N1C && N1C->isAllOnesValue())
2080     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2081                        DAG.getConstant(0, VT), N0);
2082   // If we know the sign bits of both operands are zero, strength reduce to a
2083   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2084   if (!VT.isVector()) {
2085     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2086       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2087                          N0, N1);
2088   }
2089
2090   // fold (sdiv X, pow2) -> simple ops after legalize
2091   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2092                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2093     // If dividing by powers of two is cheap, then don't perform the following
2094     // fold.
2095     if (TLI.isPow2SDivCheap())
2096       return SDValue();
2097
2098     // Target-specific implementation of sdiv x, pow2.
2099     SDValue Res = BuildSDIVPow2(N);
2100     if (Res.getNode())
2101       return Res;
2102
2103     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2104
2105     // Splat the sign bit into the register
2106     SDValue SGN =
2107         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2108                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2109                                     getShiftAmountTy(N0.getValueType())));
2110     AddToWorklist(SGN.getNode());
2111
2112     // Add (N0 < 0) ? abs2 - 1 : 0;
2113     SDValue SRL =
2114         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2115                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2116                                     getShiftAmountTy(SGN.getValueType())));
2117     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2118     AddToWorklist(SRL.getNode());
2119     AddToWorklist(ADD.getNode());    // Divide by pow2
2120     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2121                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2122
2123     // If we're dividing by a positive value, we're done.  Otherwise, we must
2124     // negate the result.
2125     if (N1C->getAPIntValue().isNonNegative())
2126       return SRA;
2127
2128     AddToWorklist(SRA.getNode());
2129     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2130   }
2131
2132   // if integer divide is expensive and we satisfy the requirements, emit an
2133   // alternate sequence.
2134   if (N1C && !TLI.isIntDivCheap()) {
2135     SDValue Op = BuildSDIV(N);
2136     if (Op.getNode()) return Op;
2137   }
2138
2139   // undef / X -> 0
2140   if (N0.getOpcode() == ISD::UNDEF)
2141     return DAG.getConstant(0, VT);
2142   // X / undef -> undef
2143   if (N1.getOpcode() == ISD::UNDEF)
2144     return N1;
2145
2146   return SDValue();
2147 }
2148
2149 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2150   SDValue N0 = N->getOperand(0);
2151   SDValue N1 = N->getOperand(1);
2152   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2153   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2154   EVT VT = N->getValueType(0);
2155
2156   // fold vector ops
2157   if (VT.isVector()) {
2158     SDValue FoldedVOp = SimplifyVBinOp(N);
2159     if (FoldedVOp.getNode()) return FoldedVOp;
2160   }
2161
2162   // fold (udiv c1, c2) -> c1/c2
2163   if (N0C && N1C && !N1C->isNullValue())
2164     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2165   // fold (udiv x, (1 << c)) -> x >>u c
2166   if (N1C && N1C->getAPIntValue().isPowerOf2())
2167     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2168                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2169                                        getShiftAmountTy(N0.getValueType())));
2170   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2171   if (N1.getOpcode() == ISD::SHL) {
2172     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2173       if (SHC->getAPIntValue().isPowerOf2()) {
2174         EVT ADDVT = N1.getOperand(1).getValueType();
2175         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2176                                   N1.getOperand(1),
2177                                   DAG.getConstant(SHC->getAPIntValue()
2178                                                                   .logBase2(),
2179                                                   ADDVT));
2180         AddToWorklist(Add.getNode());
2181         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2182       }
2183     }
2184   }
2185   // fold (udiv x, c) -> alternate
2186   if (N1C && !TLI.isIntDivCheap()) {
2187     SDValue Op = BuildUDIV(N);
2188     if (Op.getNode()) return Op;
2189   }
2190
2191   // undef / X -> 0
2192   if (N0.getOpcode() == ISD::UNDEF)
2193     return DAG.getConstant(0, VT);
2194   // X / undef -> undef
2195   if (N1.getOpcode() == ISD::UNDEF)
2196     return N1;
2197
2198   return SDValue();
2199 }
2200
2201 SDValue DAGCombiner::visitSREM(SDNode *N) {
2202   SDValue N0 = N->getOperand(0);
2203   SDValue N1 = N->getOperand(1);
2204   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2205   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2206   EVT VT = N->getValueType(0);
2207
2208   // fold (srem c1, c2) -> c1%c2
2209   if (N0C && N1C && !N1C->isNullValue())
2210     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2211   // If we know the sign bits of both operands are zero, strength reduce to a
2212   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2213   if (!VT.isVector()) {
2214     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2215       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2216   }
2217
2218   // If X/C can be simplified by the division-by-constant logic, lower
2219   // X%C to the equivalent of X-X/C*C.
2220   if (N1C && !N1C->isNullValue()) {
2221     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2222     AddToWorklist(Div.getNode());
2223     SDValue OptimizedDiv = combine(Div.getNode());
2224     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2225       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2226                                 OptimizedDiv, N1);
2227       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2228       AddToWorklist(Mul.getNode());
2229       return Sub;
2230     }
2231   }
2232
2233   // undef % X -> 0
2234   if (N0.getOpcode() == ISD::UNDEF)
2235     return DAG.getConstant(0, VT);
2236   // X % undef -> undef
2237   if (N1.getOpcode() == ISD::UNDEF)
2238     return N1;
2239
2240   return SDValue();
2241 }
2242
2243 SDValue DAGCombiner::visitUREM(SDNode *N) {
2244   SDValue N0 = N->getOperand(0);
2245   SDValue N1 = N->getOperand(1);
2246   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2247   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2248   EVT VT = N->getValueType(0);
2249
2250   // fold (urem c1, c2) -> c1%c2
2251   if (N0C && N1C && !N1C->isNullValue())
2252     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2253   // fold (urem x, pow2) -> (and x, pow2-1)
2254   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2255     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2256                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2257   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2258   if (N1.getOpcode() == ISD::SHL) {
2259     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2260       if (SHC->getAPIntValue().isPowerOf2()) {
2261         SDValue Add =
2262           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2263                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2264                                  VT));
2265         AddToWorklist(Add.getNode());
2266         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2267       }
2268     }
2269   }
2270
2271   // If X/C can be simplified by the division-by-constant logic, lower
2272   // X%C to the equivalent of X-X/C*C.
2273   if (N1C && !N1C->isNullValue()) {
2274     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2275     AddToWorklist(Div.getNode());
2276     SDValue OptimizedDiv = combine(Div.getNode());
2277     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2278       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2279                                 OptimizedDiv, N1);
2280       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2281       AddToWorklist(Mul.getNode());
2282       return Sub;
2283     }
2284   }
2285
2286   // undef % X -> 0
2287   if (N0.getOpcode() == ISD::UNDEF)
2288     return DAG.getConstant(0, VT);
2289   // X % undef -> undef
2290   if (N1.getOpcode() == ISD::UNDEF)
2291     return N1;
2292
2293   return SDValue();
2294 }
2295
2296 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2297   SDValue N0 = N->getOperand(0);
2298   SDValue N1 = N->getOperand(1);
2299   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2300   EVT VT = N->getValueType(0);
2301   SDLoc DL(N);
2302
2303   // fold (mulhs x, 0) -> 0
2304   if (N1C && N1C->isNullValue())
2305     return N1;
2306   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2307   if (N1C && N1C->getAPIntValue() == 1)
2308     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2309                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2310                                        getShiftAmountTy(N0.getValueType())));
2311   // fold (mulhs x, undef) -> 0
2312   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2313     return DAG.getConstant(0, VT);
2314
2315   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2316   // plus a shift.
2317   if (VT.isSimple() && !VT.isVector()) {
2318     MVT Simple = VT.getSimpleVT();
2319     unsigned SimpleSize = Simple.getSizeInBits();
2320     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2321     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2322       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2323       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2324       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2325       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2326             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2327       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2328     }
2329   }
2330
2331   return SDValue();
2332 }
2333
2334 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2335   SDValue N0 = N->getOperand(0);
2336   SDValue N1 = N->getOperand(1);
2337   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2338   EVT VT = N->getValueType(0);
2339   SDLoc DL(N);
2340
2341   // fold (mulhu x, 0) -> 0
2342   if (N1C && N1C->isNullValue())
2343     return N1;
2344   // fold (mulhu x, 1) -> 0
2345   if (N1C && N1C->getAPIntValue() == 1)
2346     return DAG.getConstant(0, N0.getValueType());
2347   // fold (mulhu x, undef) -> 0
2348   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2349     return DAG.getConstant(0, VT);
2350
2351   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2352   // plus a shift.
2353   if (VT.isSimple() && !VT.isVector()) {
2354     MVT Simple = VT.getSimpleVT();
2355     unsigned SimpleSize = Simple.getSizeInBits();
2356     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2357     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2358       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2359       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2360       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2361       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2362             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2363       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2364     }
2365   }
2366
2367   return SDValue();
2368 }
2369
2370 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2371 /// give the opcodes for the two computations that are being performed. Return
2372 /// true if a simplification was made.
2373 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2374                                                 unsigned HiOp) {
2375   // If the high half is not needed, just compute the low half.
2376   bool HiExists = N->hasAnyUseOfValue(1);
2377   if (!HiExists &&
2378       (!LegalOperations ||
2379        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2380     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2381     return CombineTo(N, Res, Res);
2382   }
2383
2384   // If the low half is not needed, just compute the high half.
2385   bool LoExists = N->hasAnyUseOfValue(0);
2386   if (!LoExists &&
2387       (!LegalOperations ||
2388        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2389     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2390     return CombineTo(N, Res, Res);
2391   }
2392
2393   // If both halves are used, return as it is.
2394   if (LoExists && HiExists)
2395     return SDValue();
2396
2397   // If the two computed results can be simplified separately, separate them.
2398   if (LoExists) {
2399     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2400     AddToWorklist(Lo.getNode());
2401     SDValue LoOpt = combine(Lo.getNode());
2402     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2403         (!LegalOperations ||
2404          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2405       return CombineTo(N, LoOpt, LoOpt);
2406   }
2407
2408   if (HiExists) {
2409     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2410     AddToWorklist(Hi.getNode());
2411     SDValue HiOpt = combine(Hi.getNode());
2412     if (HiOpt.getNode() && HiOpt != Hi &&
2413         (!LegalOperations ||
2414          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2415       return CombineTo(N, HiOpt, HiOpt);
2416   }
2417
2418   return SDValue();
2419 }
2420
2421 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2422   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2423   if (Res.getNode()) return Res;
2424
2425   EVT VT = N->getValueType(0);
2426   SDLoc DL(N);
2427
2428   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2429   // plus a shift.
2430   if (VT.isSimple() && !VT.isVector()) {
2431     MVT Simple = VT.getSimpleVT();
2432     unsigned SimpleSize = Simple.getSizeInBits();
2433     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2434     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2435       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2436       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2437       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2438       // Compute the high part as N1.
2439       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2440             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2441       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2442       // Compute the low part as N0.
2443       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2444       return CombineTo(N, Lo, Hi);
2445     }
2446   }
2447
2448   return SDValue();
2449 }
2450
2451 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2452   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2453   if (Res.getNode()) return Res;
2454
2455   EVT VT = N->getValueType(0);
2456   SDLoc DL(N);
2457
2458   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2459   // plus a shift.
2460   if (VT.isSimple() && !VT.isVector()) {
2461     MVT Simple = VT.getSimpleVT();
2462     unsigned SimpleSize = Simple.getSizeInBits();
2463     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2464     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2465       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2466       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2467       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2468       // Compute the high part as N1.
2469       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2470             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2471       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2472       // Compute the low part as N0.
2473       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2474       return CombineTo(N, Lo, Hi);
2475     }
2476   }
2477
2478   return SDValue();
2479 }
2480
2481 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2482   // (smulo x, 2) -> (saddo x, x)
2483   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2484     if (C2->getAPIntValue() == 2)
2485       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2486                          N->getOperand(0), N->getOperand(0));
2487
2488   return SDValue();
2489 }
2490
2491 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2492   // (umulo x, 2) -> (uaddo x, x)
2493   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2494     if (C2->getAPIntValue() == 2)
2495       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2496                          N->getOperand(0), N->getOperand(0));
2497
2498   return SDValue();
2499 }
2500
2501 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2502   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2503   if (Res.getNode()) return Res;
2504
2505   return SDValue();
2506 }
2507
2508 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2509   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2510   if (Res.getNode()) return Res;
2511
2512   return SDValue();
2513 }
2514
2515 /// If this is a binary operator with two operands of the same opcode, try to
2516 /// simplify it.
2517 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2518   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2519   EVT VT = N0.getValueType();
2520   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2521
2522   // Bail early if none of these transforms apply.
2523   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2524
2525   // For each of OP in AND/OR/XOR:
2526   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2527   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2528   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2529   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2530   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2531   //
2532   // do not sink logical op inside of a vector extend, since it may combine
2533   // into a vsetcc.
2534   EVT Op0VT = N0.getOperand(0).getValueType();
2535   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2536        N0.getOpcode() == ISD::SIGN_EXTEND ||
2537        N0.getOpcode() == ISD::BSWAP ||
2538        // Avoid infinite looping with PromoteIntBinOp.
2539        (N0.getOpcode() == ISD::ANY_EXTEND &&
2540         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2541        (N0.getOpcode() == ISD::TRUNCATE &&
2542         (!TLI.isZExtFree(VT, Op0VT) ||
2543          !TLI.isTruncateFree(Op0VT, VT)) &&
2544         TLI.isTypeLegal(Op0VT))) &&
2545       !VT.isVector() &&
2546       Op0VT == N1.getOperand(0).getValueType() &&
2547       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2548     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2549                                  N0.getOperand(0).getValueType(),
2550                                  N0.getOperand(0), N1.getOperand(0));
2551     AddToWorklist(ORNode.getNode());
2552     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2553   }
2554
2555   // For each of OP in SHL/SRL/SRA/AND...
2556   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2557   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2558   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2559   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2560        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2561       N0.getOperand(1) == N1.getOperand(1)) {
2562     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2563                                  N0.getOperand(0).getValueType(),
2564                                  N0.getOperand(0), N1.getOperand(0));
2565     AddToWorklist(ORNode.getNode());
2566     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2567                        ORNode, N0.getOperand(1));
2568   }
2569
2570   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2571   // Only perform this optimization after type legalization and before
2572   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2573   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2574   // we don't want to undo this promotion.
2575   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2576   // on scalars.
2577   if ((N0.getOpcode() == ISD::BITCAST ||
2578        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2579       Level == AfterLegalizeTypes) {
2580     SDValue In0 = N0.getOperand(0);
2581     SDValue In1 = N1.getOperand(0);
2582     EVT In0Ty = In0.getValueType();
2583     EVT In1Ty = In1.getValueType();
2584     SDLoc DL(N);
2585     // If both incoming values are integers, and the original types are the
2586     // same.
2587     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2588       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2589       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2590       AddToWorklist(Op.getNode());
2591       return BC;
2592     }
2593   }
2594
2595   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2596   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2597   // If both shuffles use the same mask, and both shuffle within a single
2598   // vector, then it is worthwhile to move the swizzle after the operation.
2599   // The type-legalizer generates this pattern when loading illegal
2600   // vector types from memory. In many cases this allows additional shuffle
2601   // optimizations.
2602   // There are other cases where moving the shuffle after the xor/and/or
2603   // is profitable even if shuffles don't perform a swizzle.
2604   // If both shuffles use the same mask, and both shuffles have the same first
2605   // or second operand, then it might still be profitable to move the shuffle
2606   // after the xor/and/or operation.
2607   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2608     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2609     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2610
2611     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2612            "Inputs to shuffles are not the same type");
2613
2614     // Check that both shuffles use the same mask. The masks are known to be of
2615     // the same length because the result vector type is the same.
2616     // Check also that shuffles have only one use to avoid introducing extra
2617     // instructions.
2618     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2619         SVN0->getMask().equals(SVN1->getMask())) {
2620       SDValue ShOp = N0->getOperand(1);
2621
2622       // Don't try to fold this node if it requires introducing a
2623       // build vector of all zeros that might be illegal at this stage.
2624       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2625         if (!LegalTypes)
2626           ShOp = DAG.getConstant(0, VT);
2627         else
2628           ShOp = SDValue();
2629       }
2630
2631       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2632       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2633       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2634       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2635         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2636                                       N0->getOperand(0), N1->getOperand(0));
2637         AddToWorklist(NewNode.getNode());
2638         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2639                                     &SVN0->getMask()[0]);
2640       }
2641
2642       // Don't try to fold this node if it requires introducing a
2643       // build vector of all zeros that might be illegal at this stage.
2644       ShOp = N0->getOperand(0);
2645       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2646         if (!LegalTypes)
2647           ShOp = DAG.getConstant(0, VT);
2648         else
2649           ShOp = SDValue();
2650       }
2651
2652       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2653       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2654       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2655       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2656         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2657                                       N0->getOperand(1), N1->getOperand(1));
2658         AddToWorklist(NewNode.getNode());
2659         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2660                                     &SVN0->getMask()[0]);
2661       }
2662     }
2663   }
2664
2665   return SDValue();
2666 }
2667
2668 SDValue DAGCombiner::visitAND(SDNode *N) {
2669   SDValue N0 = N->getOperand(0);
2670   SDValue N1 = N->getOperand(1);
2671   SDValue LL, LR, RL, RR, CC0, CC1;
2672   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2673   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2674   EVT VT = N1.getValueType();
2675   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2676
2677   // fold vector ops
2678   if (VT.isVector()) {
2679     SDValue FoldedVOp = SimplifyVBinOp(N);
2680     if (FoldedVOp.getNode()) return FoldedVOp;
2681
2682     // fold (and x, 0) -> 0, vector edition
2683     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2684       // do not return N0, because undef node may exist in N0
2685       return DAG.getConstant(
2686           APInt::getNullValue(
2687               N0.getValueType().getScalarType().getSizeInBits()),
2688           N0.getValueType());
2689     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2690       // do not return N1, because undef node may exist in N1
2691       return DAG.getConstant(
2692           APInt::getNullValue(
2693               N1.getValueType().getScalarType().getSizeInBits()),
2694           N1.getValueType());
2695
2696     // fold (and x, -1) -> x, vector edition
2697     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2698       return N1;
2699     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2700       return N0;
2701   }
2702
2703   // fold (and x, undef) -> 0
2704   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2705     return DAG.getConstant(0, VT);
2706   // fold (and c1, c2) -> c1&c2
2707   if (N0C && N1C)
2708     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2709   // canonicalize constant to RHS
2710   if (N0C && !N1C)
2711     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2712   // fold (and x, -1) -> x
2713   if (N1C && N1C->isAllOnesValue())
2714     return N0;
2715   // if (and x, c) is known to be zero, return 0
2716   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2717                                    APInt::getAllOnesValue(BitWidth)))
2718     return DAG.getConstant(0, VT);
2719   // reassociate and
2720   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2721   if (RAND.getNode())
2722     return RAND;
2723   // fold (and (or x, C), D) -> D if (C & D) == D
2724   if (N1C && N0.getOpcode() == ISD::OR)
2725     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2726       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2727         return N1;
2728   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2729   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2730     SDValue N0Op0 = N0.getOperand(0);
2731     APInt Mask = ~N1C->getAPIntValue();
2732     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2733     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2734       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2735                                  N0.getValueType(), N0Op0);
2736
2737       // Replace uses of the AND with uses of the Zero extend node.
2738       CombineTo(N, Zext);
2739
2740       // We actually want to replace all uses of the any_extend with the
2741       // zero_extend, to avoid duplicating things.  This will later cause this
2742       // AND to be folded.
2743       CombineTo(N0.getNode(), Zext);
2744       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2745     }
2746   }
2747   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2748   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2749   // already be zero by virtue of the width of the base type of the load.
2750   //
2751   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2752   // more cases.
2753   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2754        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2755       N0.getOpcode() == ISD::LOAD) {
2756     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2757                                          N0 : N0.getOperand(0) );
2758
2759     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2760     // This can be a pure constant or a vector splat, in which case we treat the
2761     // vector as a scalar and use the splat value.
2762     APInt Constant = APInt::getNullValue(1);
2763     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2764       Constant = C->getAPIntValue();
2765     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2766       APInt SplatValue, SplatUndef;
2767       unsigned SplatBitSize;
2768       bool HasAnyUndefs;
2769       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2770                                              SplatBitSize, HasAnyUndefs);
2771       if (IsSplat) {
2772         // Undef bits can contribute to a possible optimisation if set, so
2773         // set them.
2774         SplatValue |= SplatUndef;
2775
2776         // The splat value may be something like "0x00FFFFFF", which means 0 for
2777         // the first vector value and FF for the rest, repeating. We need a mask
2778         // that will apply equally to all members of the vector, so AND all the
2779         // lanes of the constant together.
2780         EVT VT = Vector->getValueType(0);
2781         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2782
2783         // If the splat value has been compressed to a bitlength lower
2784         // than the size of the vector lane, we need to re-expand it to
2785         // the lane size.
2786         if (BitWidth > SplatBitSize)
2787           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2788                SplatBitSize < BitWidth;
2789                SplatBitSize = SplatBitSize * 2)
2790             SplatValue |= SplatValue.shl(SplatBitSize);
2791
2792         Constant = APInt::getAllOnesValue(BitWidth);
2793         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2794           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2795       }
2796     }
2797
2798     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2799     // actually legal and isn't going to get expanded, else this is a false
2800     // optimisation.
2801     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2802                                                     Load->getMemoryVT());
2803
2804     // Resize the constant to the same size as the original memory access before
2805     // extension. If it is still the AllOnesValue then this AND is completely
2806     // unneeded.
2807     Constant =
2808       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2809
2810     bool B;
2811     switch (Load->getExtensionType()) {
2812     default: B = false; break;
2813     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2814     case ISD::ZEXTLOAD:
2815     case ISD::NON_EXTLOAD: B = true; break;
2816     }
2817
2818     if (B && Constant.isAllOnesValue()) {
2819       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2820       // preserve semantics once we get rid of the AND.
2821       SDValue NewLoad(Load, 0);
2822       if (Load->getExtensionType() == ISD::EXTLOAD) {
2823         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2824                               Load->getValueType(0), SDLoc(Load),
2825                               Load->getChain(), Load->getBasePtr(),
2826                               Load->getOffset(), Load->getMemoryVT(),
2827                               Load->getMemOperand());
2828         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2829         if (Load->getNumValues() == 3) {
2830           // PRE/POST_INC loads have 3 values.
2831           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2832                            NewLoad.getValue(2) };
2833           CombineTo(Load, To, 3, true);
2834         } else {
2835           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2836         }
2837       }
2838
2839       // Fold the AND away, taking care not to fold to the old load node if we
2840       // replaced it.
2841       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2842
2843       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2844     }
2845   }
2846   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2847   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2848     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2849     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2850
2851     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2852         LL.getValueType().isInteger()) {
2853       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2854       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2855         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2856                                      LR.getValueType(), LL, RL);
2857         AddToWorklist(ORNode.getNode());
2858         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2859       }
2860       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2861       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2862         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2863                                       LR.getValueType(), LL, RL);
2864         AddToWorklist(ANDNode.getNode());
2865         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2866       }
2867       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2868       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2869         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2870                                      LR.getValueType(), LL, RL);
2871         AddToWorklist(ORNode.getNode());
2872         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2873       }
2874     }
2875     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2876     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2877         Op0 == Op1 && LL.getValueType().isInteger() &&
2878       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2879                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2880                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2881                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2882       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2883                                     LL, DAG.getConstant(1, LL.getValueType()));
2884       AddToWorklist(ADDNode.getNode());
2885       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2886                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2887     }
2888     // canonicalize equivalent to ll == rl
2889     if (LL == RR && LR == RL) {
2890       Op1 = ISD::getSetCCSwappedOperands(Op1);
2891       std::swap(RL, RR);
2892     }
2893     if (LL == RL && LR == RR) {
2894       bool isInteger = LL.getValueType().isInteger();
2895       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2896       if (Result != ISD::SETCC_INVALID &&
2897           (!LegalOperations ||
2898            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2899             TLI.isOperationLegal(ISD::SETCC,
2900                             getSetCCResultType(N0.getSimpleValueType())))))
2901         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2902                             LL, LR, Result);
2903     }
2904   }
2905
2906   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2907   if (N0.getOpcode() == N1.getOpcode()) {
2908     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2909     if (Tmp.getNode()) return Tmp;
2910   }
2911
2912   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2913   // fold (and (sra)) -> (and (srl)) when possible.
2914   if (!VT.isVector() &&
2915       SimplifyDemandedBits(SDValue(N, 0)))
2916     return SDValue(N, 0);
2917
2918   // fold (zext_inreg (extload x)) -> (zextload x)
2919   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2920     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2921     EVT MemVT = LN0->getMemoryVT();
2922     // If we zero all the possible extended bits, then we can turn this into
2923     // a zextload if we are running before legalize or the operation is legal.
2924     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2925     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2926                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2927         ((!LegalOperations && !LN0->isVolatile()) ||
2928          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2929       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2930                                        LN0->getChain(), LN0->getBasePtr(),
2931                                        MemVT, LN0->getMemOperand());
2932       AddToWorklist(N);
2933       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2934       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2935     }
2936   }
2937   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2938   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2939       N0.hasOneUse()) {
2940     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2941     EVT MemVT = LN0->getMemoryVT();
2942     // If we zero all the possible extended bits, then we can turn this into
2943     // a zextload if we are running before legalize or the operation is legal.
2944     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2945     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2946                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2947         ((!LegalOperations && !LN0->isVolatile()) ||
2948          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2949       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2950                                        LN0->getChain(), LN0->getBasePtr(),
2951                                        MemVT, LN0->getMemOperand());
2952       AddToWorklist(N);
2953       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2954       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2955     }
2956   }
2957
2958   // fold (and (load x), 255) -> (zextload x, i8)
2959   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2960   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2961   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2962               (N0.getOpcode() == ISD::ANY_EXTEND &&
2963                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2964     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2965     LoadSDNode *LN0 = HasAnyExt
2966       ? cast<LoadSDNode>(N0.getOperand(0))
2967       : cast<LoadSDNode>(N0);
2968     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2969         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2970       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2971       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2972         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2973         EVT LoadedVT = LN0->getMemoryVT();
2974
2975         if (ExtVT == LoadedVT &&
2976             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2977           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2978
2979           SDValue NewLoad =
2980             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2981                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2982                            LN0->getMemOperand());
2983           AddToWorklist(N);
2984           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2985           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2986         }
2987
2988         // Do not change the width of a volatile load.
2989         // Do not generate loads of non-round integer types since these can
2990         // be expensive (and would be wrong if the type is not byte sized).
2991         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2992             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2993           EVT PtrType = LN0->getOperand(1).getValueType();
2994
2995           unsigned Alignment = LN0->getAlignment();
2996           SDValue NewPtr = LN0->getBasePtr();
2997
2998           // For big endian targets, we need to add an offset to the pointer
2999           // to load the correct bytes.  For little endian systems, we merely
3000           // need to read fewer bytes from the same pointer.
3001           if (TLI.isBigEndian()) {
3002             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3003             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3004             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3005             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3006                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3007             Alignment = MinAlign(Alignment, PtrOff);
3008           }
3009
3010           AddToWorklist(NewPtr.getNode());
3011
3012           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3013           SDValue Load =
3014             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3015                            LN0->getChain(), NewPtr,
3016                            LN0->getPointerInfo(),
3017                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3018                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3019           AddToWorklist(N);
3020           CombineTo(LN0, Load, Load.getValue(1));
3021           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3022         }
3023       }
3024     }
3025   }
3026
3027   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3028       VT.getSizeInBits() <= 64) {
3029     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3030       APInt ADDC = ADDI->getAPIntValue();
3031       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3032         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3033         // immediate for an add, but it is legal if its top c2 bits are set,
3034         // transform the ADD so the immediate doesn't need to be materialized
3035         // in a register.
3036         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3037           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3038                                              SRLI->getZExtValue());
3039           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3040             ADDC |= Mask;
3041             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3042               SDValue NewAdd =
3043                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3044                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3045               CombineTo(N0.getNode(), NewAdd);
3046               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3047             }
3048           }
3049         }
3050       }
3051     }
3052   }
3053
3054   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3055   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3056     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3057                                        N0.getOperand(1), false);
3058     if (BSwap.getNode())
3059       return BSwap;
3060   }
3061
3062   return SDValue();
3063 }
3064
3065 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3066 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3067                                         bool DemandHighBits) {
3068   if (!LegalOperations)
3069     return SDValue();
3070
3071   EVT VT = N->getValueType(0);
3072   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3073     return SDValue();
3074   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3075     return SDValue();
3076
3077   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3078   bool LookPassAnd0 = false;
3079   bool LookPassAnd1 = false;
3080   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3081       std::swap(N0, N1);
3082   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3083       std::swap(N0, N1);
3084   if (N0.getOpcode() == ISD::AND) {
3085     if (!N0.getNode()->hasOneUse())
3086       return SDValue();
3087     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3088     if (!N01C || N01C->getZExtValue() != 0xFF00)
3089       return SDValue();
3090     N0 = N0.getOperand(0);
3091     LookPassAnd0 = true;
3092   }
3093
3094   if (N1.getOpcode() == ISD::AND) {
3095     if (!N1.getNode()->hasOneUse())
3096       return SDValue();
3097     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3098     if (!N11C || N11C->getZExtValue() != 0xFF)
3099       return SDValue();
3100     N1 = N1.getOperand(0);
3101     LookPassAnd1 = true;
3102   }
3103
3104   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3105     std::swap(N0, N1);
3106   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3107     return SDValue();
3108   if (!N0.getNode()->hasOneUse() ||
3109       !N1.getNode()->hasOneUse())
3110     return SDValue();
3111
3112   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3113   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3114   if (!N01C || !N11C)
3115     return SDValue();
3116   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3117     return SDValue();
3118
3119   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3120   SDValue N00 = N0->getOperand(0);
3121   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3122     if (!N00.getNode()->hasOneUse())
3123       return SDValue();
3124     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3125     if (!N001C || N001C->getZExtValue() != 0xFF)
3126       return SDValue();
3127     N00 = N00.getOperand(0);
3128     LookPassAnd0 = true;
3129   }
3130
3131   SDValue N10 = N1->getOperand(0);
3132   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3133     if (!N10.getNode()->hasOneUse())
3134       return SDValue();
3135     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3136     if (!N101C || N101C->getZExtValue() != 0xFF00)
3137       return SDValue();
3138     N10 = N10.getOperand(0);
3139     LookPassAnd1 = true;
3140   }
3141
3142   if (N00 != N10)
3143     return SDValue();
3144
3145   // Make sure everything beyond the low halfword gets set to zero since the SRL
3146   // 16 will clear the top bits.
3147   unsigned OpSizeInBits = VT.getSizeInBits();
3148   if (DemandHighBits && OpSizeInBits > 16) {
3149     // If the left-shift isn't masked out then the only way this is a bswap is
3150     // if all bits beyond the low 8 are 0. In that case the entire pattern
3151     // reduces to a left shift anyway: leave it for other parts of the combiner.
3152     if (!LookPassAnd0)
3153       return SDValue();
3154
3155     // However, if the right shift isn't masked out then it might be because
3156     // it's not needed. See if we can spot that too.
3157     if (!LookPassAnd1 &&
3158         !DAG.MaskedValueIsZero(
3159             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3160       return SDValue();
3161   }
3162
3163   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3164   if (OpSizeInBits > 16)
3165     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3166                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3167   return Res;
3168 }
3169
3170 /// Return true if the specified node is an element that makes up a 32-bit
3171 /// packed halfword byteswap.
3172 /// ((x & 0x000000ff) << 8) |
3173 /// ((x & 0x0000ff00) >> 8) |
3174 /// ((x & 0x00ff0000) << 8) |
3175 /// ((x & 0xff000000) >> 8)
3176 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3177   if (!N.getNode()->hasOneUse())
3178     return false;
3179
3180   unsigned Opc = N.getOpcode();
3181   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3182     return false;
3183
3184   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3185   if (!N1C)
3186     return false;
3187
3188   unsigned Num;
3189   switch (N1C->getZExtValue()) {
3190   default:
3191     return false;
3192   case 0xFF:       Num = 0; break;
3193   case 0xFF00:     Num = 1; break;
3194   case 0xFF0000:   Num = 2; break;
3195   case 0xFF000000: Num = 3; break;
3196   }
3197
3198   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3199   SDValue N0 = N.getOperand(0);
3200   if (Opc == ISD::AND) {
3201     if (Num == 0 || Num == 2) {
3202       // (x >> 8) & 0xff
3203       // (x >> 8) & 0xff0000
3204       if (N0.getOpcode() != ISD::SRL)
3205         return false;
3206       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3207       if (!C || C->getZExtValue() != 8)
3208         return false;
3209     } else {
3210       // (x << 8) & 0xff00
3211       // (x << 8) & 0xff000000
3212       if (N0.getOpcode() != ISD::SHL)
3213         return false;
3214       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3215       if (!C || C->getZExtValue() != 8)
3216         return false;
3217     }
3218   } else if (Opc == ISD::SHL) {
3219     // (x & 0xff) << 8
3220     // (x & 0xff0000) << 8
3221     if (Num != 0 && Num != 2)
3222       return false;
3223     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3224     if (!C || C->getZExtValue() != 8)
3225       return false;
3226   } else { // Opc == ISD::SRL
3227     // (x & 0xff00) >> 8
3228     // (x & 0xff000000) >> 8
3229     if (Num != 1 && Num != 3)
3230       return false;
3231     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3232     if (!C || C->getZExtValue() != 8)
3233       return false;
3234   }
3235
3236   if (Parts[Num])
3237     return false;
3238
3239   Parts[Num] = N0.getOperand(0).getNode();
3240   return true;
3241 }
3242
3243 /// Match a 32-bit packed halfword bswap. That is
3244 /// ((x & 0x000000ff) << 8) |
3245 /// ((x & 0x0000ff00) >> 8) |
3246 /// ((x & 0x00ff0000) << 8) |
3247 /// ((x & 0xff000000) >> 8)
3248 /// => (rotl (bswap x), 16)
3249 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3250   if (!LegalOperations)
3251     return SDValue();
3252
3253   EVT VT = N->getValueType(0);
3254   if (VT != MVT::i32)
3255     return SDValue();
3256   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3257     return SDValue();
3258
3259   // Look for either
3260   // (or (or (and), (and)), (or (and), (and)))
3261   // (or (or (or (and), (and)), (and)), (and))
3262   if (N0.getOpcode() != ISD::OR)
3263     return SDValue();
3264   SDValue N00 = N0.getOperand(0);
3265   SDValue N01 = N0.getOperand(1);
3266   SDNode *Parts[4] = {};
3267
3268   if (N1.getOpcode() == ISD::OR &&
3269       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3270     // (or (or (and), (and)), (or (and), (and)))
3271     SDValue N000 = N00.getOperand(0);
3272     if (!isBSwapHWordElement(N000, Parts))
3273       return SDValue();
3274
3275     SDValue N001 = N00.getOperand(1);
3276     if (!isBSwapHWordElement(N001, Parts))
3277       return SDValue();
3278     SDValue N010 = N01.getOperand(0);
3279     if (!isBSwapHWordElement(N010, Parts))
3280       return SDValue();
3281     SDValue N011 = N01.getOperand(1);
3282     if (!isBSwapHWordElement(N011, Parts))
3283       return SDValue();
3284   } else {
3285     // (or (or (or (and), (and)), (and)), (and))
3286     if (!isBSwapHWordElement(N1, Parts))
3287       return SDValue();
3288     if (!isBSwapHWordElement(N01, Parts))
3289       return SDValue();
3290     if (N00.getOpcode() != ISD::OR)
3291       return SDValue();
3292     SDValue N000 = N00.getOperand(0);
3293     if (!isBSwapHWordElement(N000, Parts))
3294       return SDValue();
3295     SDValue N001 = N00.getOperand(1);
3296     if (!isBSwapHWordElement(N001, Parts))
3297       return SDValue();
3298   }
3299
3300   // Make sure the parts are all coming from the same node.
3301   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3302     return SDValue();
3303
3304   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3305                               SDValue(Parts[0],0));
3306
3307   // Result of the bswap should be rotated by 16. If it's not legal, then
3308   // do  (x << 16) | (x >> 16).
3309   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3310   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3311     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3312   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3313     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3314   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3315                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3316                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3317 }
3318
3319 SDValue DAGCombiner::visitOR(SDNode *N) {
3320   SDValue N0 = N->getOperand(0);
3321   SDValue N1 = N->getOperand(1);
3322   SDValue LL, LR, RL, RR, CC0, CC1;
3323   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3324   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3325   EVT VT = N1.getValueType();
3326
3327   // fold vector ops
3328   if (VT.isVector()) {
3329     SDValue FoldedVOp = SimplifyVBinOp(N);
3330     if (FoldedVOp.getNode()) return FoldedVOp;
3331
3332     // fold (or x, 0) -> x, vector edition
3333     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3334       return N1;
3335     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3336       return N0;
3337
3338     // fold (or x, -1) -> -1, vector edition
3339     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3340       // do not return N0, because undef node may exist in N0
3341       return DAG.getConstant(
3342           APInt::getAllOnesValue(
3343               N0.getValueType().getScalarType().getSizeInBits()),
3344           N0.getValueType());
3345     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3346       // do not return N1, because undef node may exist in N1
3347       return DAG.getConstant(
3348           APInt::getAllOnesValue(
3349               N1.getValueType().getScalarType().getSizeInBits()),
3350           N1.getValueType());
3351
3352     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3353     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3354     // Do this only if the resulting shuffle is legal.
3355     if (isa<ShuffleVectorSDNode>(N0) &&
3356         isa<ShuffleVectorSDNode>(N1) &&
3357         // Avoid folding a node with illegal type.
3358         TLI.isTypeLegal(VT) &&
3359         N0->getOperand(1) == N1->getOperand(1) &&
3360         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3361       bool CanFold = true;
3362       unsigned NumElts = VT.getVectorNumElements();
3363       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3364       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3365       // We construct two shuffle masks:
3366       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3367       // and N1 as the second operand.
3368       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3369       // and N0 as the second operand.
3370       // We do this because OR is commutable and therefore there might be
3371       // two ways to fold this node into a shuffle.
3372       SmallVector<int,4> Mask1;
3373       SmallVector<int,4> Mask2;
3374
3375       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3376         int M0 = SV0->getMaskElt(i);
3377         int M1 = SV1->getMaskElt(i);
3378
3379         // Both shuffle indexes are undef. Propagate Undef.
3380         if (M0 < 0 && M1 < 0) {
3381           Mask1.push_back(M0);
3382           Mask2.push_back(M0);
3383           continue;
3384         }
3385
3386         if (M0 < 0 || M1 < 0 ||
3387             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3388             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3389           CanFold = false;
3390           break;
3391         }
3392
3393         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3394         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3395       }
3396
3397       if (CanFold) {
3398         // Fold this sequence only if the resulting shuffle is 'legal'.
3399         if (TLI.isShuffleMaskLegal(Mask1, VT))
3400           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3401                                       N1->getOperand(0), &Mask1[0]);
3402         if (TLI.isShuffleMaskLegal(Mask2, VT))
3403           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3404                                       N0->getOperand(0), &Mask2[0]);
3405       }
3406     }
3407   }
3408
3409   // fold (or x, undef) -> -1
3410   if (!LegalOperations &&
3411       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3412     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3413     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3414   }
3415   // fold (or c1, c2) -> c1|c2
3416   if (N0C && N1C)
3417     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3418   // canonicalize constant to RHS
3419   if (N0C && !N1C)
3420     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3421   // fold (or x, 0) -> x
3422   if (N1C && N1C->isNullValue())
3423     return N0;
3424   // fold (or x, -1) -> -1
3425   if (N1C && N1C->isAllOnesValue())
3426     return N1;
3427   // fold (or x, c) -> c iff (x & ~c) == 0
3428   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3429     return N1;
3430
3431   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3432   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3433   if (BSwap.getNode())
3434     return BSwap;
3435   BSwap = MatchBSwapHWordLow(N, N0, N1);
3436   if (BSwap.getNode())
3437     return BSwap;
3438
3439   // reassociate or
3440   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3441   if (ROR.getNode())
3442     return ROR;
3443   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3444   // iff (c1 & c2) == 0.
3445   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3446              isa<ConstantSDNode>(N0.getOperand(1))) {
3447     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3448     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3449       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3450       if (!COR.getNode())
3451         return SDValue();
3452       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3453                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3454                                      N0.getOperand(0), N1), COR);
3455     }
3456   }
3457   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3458   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3459     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3460     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3461
3462     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3463         LL.getValueType().isInteger()) {
3464       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3465       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3466       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3467           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3468         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3469                                      LR.getValueType(), LL, RL);
3470         AddToWorklist(ORNode.getNode());
3471         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3472       }
3473       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3474       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3475       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3476           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3477         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3478                                       LR.getValueType(), LL, RL);
3479         AddToWorklist(ANDNode.getNode());
3480         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3481       }
3482     }
3483     // canonicalize equivalent to ll == rl
3484     if (LL == RR && LR == RL) {
3485       Op1 = ISD::getSetCCSwappedOperands(Op1);
3486       std::swap(RL, RR);
3487     }
3488     if (LL == RL && LR == RR) {
3489       bool isInteger = LL.getValueType().isInteger();
3490       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3491       if (Result != ISD::SETCC_INVALID &&
3492           (!LegalOperations ||
3493            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3494             TLI.isOperationLegal(ISD::SETCC,
3495               getSetCCResultType(N0.getValueType())))))
3496         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3497                             LL, LR, Result);
3498     }
3499   }
3500
3501   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3502   if (N0.getOpcode() == N1.getOpcode()) {
3503     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3504     if (Tmp.getNode()) return Tmp;
3505   }
3506
3507   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3508   if (N0.getOpcode() == ISD::AND &&
3509       N1.getOpcode() == ISD::AND &&
3510       N0.getOperand(1).getOpcode() == ISD::Constant &&
3511       N1.getOperand(1).getOpcode() == ISD::Constant &&
3512       // Don't increase # computations.
3513       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3514     // We can only do this xform if we know that bits from X that are set in C2
3515     // but not in C1 are already zero.  Likewise for Y.
3516     const APInt &LHSMask =
3517       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3518     const APInt &RHSMask =
3519       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3520
3521     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3522         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3523       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3524                               N0.getOperand(0), N1.getOperand(0));
3525       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3526                          DAG.getConstant(LHSMask | RHSMask, VT));
3527     }
3528   }
3529
3530   // See if this is some rotate idiom.
3531   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3532     return SDValue(Rot, 0);
3533
3534   // Simplify the operands using demanded-bits information.
3535   if (!VT.isVector() &&
3536       SimplifyDemandedBits(SDValue(N, 0)))
3537     return SDValue(N, 0);
3538
3539   return SDValue();
3540 }
3541
3542 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3543 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3544   if (Op.getOpcode() == ISD::AND) {
3545     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3546       Mask = Op.getOperand(1);
3547       Op = Op.getOperand(0);
3548     } else {
3549       return false;
3550     }
3551   }
3552
3553   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3554     Shift = Op;
3555     return true;
3556   }
3557
3558   return false;
3559 }
3560
3561 // Return true if we can prove that, whenever Neg and Pos are both in the
3562 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3563 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3564 //
3565 //     (or (shift1 X, Neg), (shift2 X, Pos))
3566 //
3567 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3568 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3569 // to consider shift amounts with defined behavior.
3570 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3571   // If OpSize is a power of 2 then:
3572   //
3573   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3574   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3575   //
3576   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3577   // for the stronger condition:
3578   //
3579   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3580   //
3581   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3582   // we can just replace Neg with Neg' for the rest of the function.
3583   //
3584   // In other cases we check for the even stronger condition:
3585   //
3586   //     Neg == OpSize - Pos                                    [B]
3587   //
3588   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3589   // behavior if Pos == 0 (and consequently Neg == OpSize).
3590   //
3591   // We could actually use [A] whenever OpSize is a power of 2, but the
3592   // only extra cases that it would match are those uninteresting ones
3593   // where Neg and Pos are never in range at the same time.  E.g. for
3594   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3595   // as well as (sub 32, Pos), but:
3596   //
3597   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3598   //
3599   // always invokes undefined behavior for 32-bit X.
3600   //
3601   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3602   unsigned MaskLoBits = 0;
3603   if (Neg.getOpcode() == ISD::AND &&
3604       isPowerOf2_64(OpSize) &&
3605       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3606       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3607     Neg = Neg.getOperand(0);
3608     MaskLoBits = Log2_64(OpSize);
3609   }
3610
3611   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3612   if (Neg.getOpcode() != ISD::SUB)
3613     return 0;
3614   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3615   if (!NegC)
3616     return 0;
3617   SDValue NegOp1 = Neg.getOperand(1);
3618
3619   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3620   // Pos'.  The truncation is redundant for the purpose of the equality.
3621   if (MaskLoBits &&
3622       Pos.getOpcode() == ISD::AND &&
3623       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3624       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3625     Pos = Pos.getOperand(0);
3626
3627   // The condition we need is now:
3628   //
3629   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3630   //
3631   // If NegOp1 == Pos then we need:
3632   //
3633   //              OpSize & Mask == NegC & Mask
3634   //
3635   // (because "x & Mask" is a truncation and distributes through subtraction).
3636   APInt Width;
3637   if (Pos == NegOp1)
3638     Width = NegC->getAPIntValue();
3639   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3640   // Then the condition we want to prove becomes:
3641   //
3642   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3643   //
3644   // which, again because "x & Mask" is a truncation, becomes:
3645   //
3646   //                NegC & Mask == (OpSize - PosC) & Mask
3647   //              OpSize & Mask == (NegC + PosC) & Mask
3648   else if (Pos.getOpcode() == ISD::ADD &&
3649            Pos.getOperand(0) == NegOp1 &&
3650            Pos.getOperand(1).getOpcode() == ISD::Constant)
3651     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3652              NegC->getAPIntValue());
3653   else
3654     return false;
3655
3656   // Now we just need to check that OpSize & Mask == Width & Mask.
3657   if (MaskLoBits)
3658     // Opsize & Mask is 0 since Mask is Opsize - 1.
3659     return Width.getLoBits(MaskLoBits) == 0;
3660   return Width == OpSize;
3661 }
3662
3663 // A subroutine of MatchRotate used once we have found an OR of two opposite
3664 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3665 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3666 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3667 // Neg with outer conversions stripped away.
3668 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3669                                        SDValue Neg, SDValue InnerPos,
3670                                        SDValue InnerNeg, unsigned PosOpcode,
3671                                        unsigned NegOpcode, SDLoc DL) {
3672   // fold (or (shl x, (*ext y)),
3673   //          (srl x, (*ext (sub 32, y)))) ->
3674   //   (rotl x, y) or (rotr x, (sub 32, y))
3675   //
3676   // fold (or (shl x, (*ext (sub 32, y))),
3677   //          (srl x, (*ext y))) ->
3678   //   (rotr x, y) or (rotl x, (sub 32, y))
3679   EVT VT = Shifted.getValueType();
3680   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3681     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3682     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3683                        HasPos ? Pos : Neg).getNode();
3684   }
3685
3686   return nullptr;
3687 }
3688
3689 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3690 // idioms for rotate, and if the target supports rotation instructions, generate
3691 // a rot[lr].
3692 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3693   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3694   EVT VT = LHS.getValueType();
3695   if (!TLI.isTypeLegal(VT)) return nullptr;
3696
3697   // The target must have at least one rotate flavor.
3698   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3699   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3700   if (!HasROTL && !HasROTR) return nullptr;
3701
3702   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3703   SDValue LHSShift;   // The shift.
3704   SDValue LHSMask;    // AND value if any.
3705   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3706     return nullptr; // Not part of a rotate.
3707
3708   SDValue RHSShift;   // The shift.
3709   SDValue RHSMask;    // AND value if any.
3710   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3711     return nullptr; // Not part of a rotate.
3712
3713   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3714     return nullptr;   // Not shifting the same value.
3715
3716   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3717     return nullptr;   // Shifts must disagree.
3718
3719   // Canonicalize shl to left side in a shl/srl pair.
3720   if (RHSShift.getOpcode() == ISD::SHL) {
3721     std::swap(LHS, RHS);
3722     std::swap(LHSShift, RHSShift);
3723     std::swap(LHSMask , RHSMask );
3724   }
3725
3726   unsigned OpSizeInBits = VT.getSizeInBits();
3727   SDValue LHSShiftArg = LHSShift.getOperand(0);
3728   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3729   SDValue RHSShiftArg = RHSShift.getOperand(0);
3730   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3731
3732   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3733   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3734   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3735       RHSShiftAmt.getOpcode() == ISD::Constant) {
3736     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3737     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3738     if ((LShVal + RShVal) != OpSizeInBits)
3739       return nullptr;
3740
3741     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3742                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3743
3744     // If there is an AND of either shifted operand, apply it to the result.
3745     if (LHSMask.getNode() || RHSMask.getNode()) {
3746       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3747
3748       if (LHSMask.getNode()) {
3749         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3750         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3751       }
3752       if (RHSMask.getNode()) {
3753         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3754         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3755       }
3756
3757       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3758     }
3759
3760     return Rot.getNode();
3761   }
3762
3763   // If there is a mask here, and we have a variable shift, we can't be sure
3764   // that we're masking out the right stuff.
3765   if (LHSMask.getNode() || RHSMask.getNode())
3766     return nullptr;
3767
3768   // If the shift amount is sign/zext/any-extended just peel it off.
3769   SDValue LExtOp0 = LHSShiftAmt;
3770   SDValue RExtOp0 = RHSShiftAmt;
3771   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3772        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3773        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3774        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3775       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3776        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3777        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3778        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3779     LExtOp0 = LHSShiftAmt.getOperand(0);
3780     RExtOp0 = RHSShiftAmt.getOperand(0);
3781   }
3782
3783   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3784                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3785   if (TryL)
3786     return TryL;
3787
3788   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3789                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3790   if (TryR)
3791     return TryR;
3792
3793   return nullptr;
3794 }
3795
3796 SDValue DAGCombiner::visitXOR(SDNode *N) {
3797   SDValue N0 = N->getOperand(0);
3798   SDValue N1 = N->getOperand(1);
3799   SDValue LHS, RHS, CC;
3800   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3801   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3802   EVT VT = N0.getValueType();
3803
3804   // fold vector ops
3805   if (VT.isVector()) {
3806     SDValue FoldedVOp = SimplifyVBinOp(N);
3807     if (FoldedVOp.getNode()) return FoldedVOp;
3808
3809     // fold (xor x, 0) -> x, vector edition
3810     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3811       return N1;
3812     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3813       return N0;
3814   }
3815
3816   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3817   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3818     return DAG.getConstant(0, VT);
3819   // fold (xor x, undef) -> undef
3820   if (N0.getOpcode() == ISD::UNDEF)
3821     return N0;
3822   if (N1.getOpcode() == ISD::UNDEF)
3823     return N1;
3824   // fold (xor c1, c2) -> c1^c2
3825   if (N0C && N1C)
3826     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3827   // canonicalize constant to RHS
3828   if (N0C && !N1C)
3829     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3830   // fold (xor x, 0) -> x
3831   if (N1C && N1C->isNullValue())
3832     return N0;
3833   // reassociate xor
3834   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3835   if (RXOR.getNode())
3836     return RXOR;
3837
3838   // fold !(x cc y) -> (x !cc y)
3839   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3840     bool isInt = LHS.getValueType().isInteger();
3841     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3842                                                isInt);
3843
3844     if (!LegalOperations ||
3845         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3846       switch (N0.getOpcode()) {
3847       default:
3848         llvm_unreachable("Unhandled SetCC Equivalent!");
3849       case ISD::SETCC:
3850         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3851       case ISD::SELECT_CC:
3852         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3853                                N0.getOperand(3), NotCC);
3854       }
3855     }
3856   }
3857
3858   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3859   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3860       N0.getNode()->hasOneUse() &&
3861       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3862     SDValue V = N0.getOperand(0);
3863     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3864                     DAG.getConstant(1, V.getValueType()));
3865     AddToWorklist(V.getNode());
3866     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3867   }
3868
3869   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3870   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3871       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3872     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3873     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3874       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3875       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3876       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3877       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3878       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3879     }
3880   }
3881   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3882   if (N1C && N1C->isAllOnesValue() &&
3883       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3884     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3885     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3886       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3887       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3888       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3889       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3890       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3891     }
3892   }
3893   // fold (xor (and x, y), y) -> (and (not x), y)
3894   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3895       N0->getOperand(1) == N1) {
3896     SDValue X = N0->getOperand(0);
3897     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3898     AddToWorklist(NotX.getNode());
3899     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3900   }
3901   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3902   if (N1C && N0.getOpcode() == ISD::XOR) {
3903     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3904     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3905     if (N00C)
3906       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3907                          DAG.getConstant(N1C->getAPIntValue() ^
3908                                          N00C->getAPIntValue(), VT));
3909     if (N01C)
3910       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3911                          DAG.getConstant(N1C->getAPIntValue() ^
3912                                          N01C->getAPIntValue(), VT));
3913   }
3914   // fold (xor x, x) -> 0
3915   if (N0 == N1)
3916     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3917
3918   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3919   if (N0.getOpcode() == N1.getOpcode()) {
3920     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3921     if (Tmp.getNode()) return Tmp;
3922   }
3923
3924   // Simplify the expression using non-local knowledge.
3925   if (!VT.isVector() &&
3926       SimplifyDemandedBits(SDValue(N, 0)))
3927     return SDValue(N, 0);
3928
3929   return SDValue();
3930 }
3931
3932 /// Handle transforms common to the three shifts, when the shift amount is a
3933 /// constant.
3934 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3935   // We can't and shouldn't fold opaque constants.
3936   if (Amt->isOpaque())
3937     return SDValue();
3938
3939   SDNode *LHS = N->getOperand(0).getNode();
3940   if (!LHS->hasOneUse()) return SDValue();
3941
3942   // We want to pull some binops through shifts, so that we have (and (shift))
3943   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3944   // thing happens with address calculations, so it's important to canonicalize
3945   // it.
3946   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3947
3948   switch (LHS->getOpcode()) {
3949   default: return SDValue();
3950   case ISD::OR:
3951   case ISD::XOR:
3952     HighBitSet = false; // We can only transform sra if the high bit is clear.
3953     break;
3954   case ISD::AND:
3955     HighBitSet = true;  // We can only transform sra if the high bit is set.
3956     break;
3957   case ISD::ADD:
3958     if (N->getOpcode() != ISD::SHL)
3959       return SDValue(); // only shl(add) not sr[al](add).
3960     HighBitSet = false; // We can only transform sra if the high bit is clear.
3961     break;
3962   }
3963
3964   // We require the RHS of the binop to be a constant and not opaque as well.
3965   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3966   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3967
3968   // FIXME: disable this unless the input to the binop is a shift by a constant.
3969   // If it is not a shift, it pessimizes some common cases like:
3970   //
3971   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3972   //    int bar(int *X, int i) { return X[i & 255]; }
3973   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3974   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3975        BinOpLHSVal->getOpcode() != ISD::SRA &&
3976        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3977       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3978     return SDValue();
3979
3980   EVT VT = N->getValueType(0);
3981
3982   // If this is a signed shift right, and the high bit is modified by the
3983   // logical operation, do not perform the transformation. The highBitSet
3984   // boolean indicates the value of the high bit of the constant which would
3985   // cause it to be modified for this operation.
3986   if (N->getOpcode() == ISD::SRA) {
3987     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3988     if (BinOpRHSSignSet != HighBitSet)
3989       return SDValue();
3990   }
3991
3992   if (!TLI.isDesirableToCommuteWithShift(LHS))
3993     return SDValue();
3994
3995   // Fold the constants, shifting the binop RHS by the shift amount.
3996   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3997                                N->getValueType(0),
3998                                LHS->getOperand(1), N->getOperand(1));
3999   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4000
4001   // Create the new shift.
4002   SDValue NewShift = DAG.getNode(N->getOpcode(),
4003                                  SDLoc(LHS->getOperand(0)),
4004                                  VT, LHS->getOperand(0), N->getOperand(1));
4005
4006   // Create the new binop.
4007   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4008 }
4009
4010 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4011   assert(N->getOpcode() == ISD::TRUNCATE);
4012   assert(N->getOperand(0).getOpcode() == ISD::AND);
4013
4014   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4015   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4016     SDValue N01 = N->getOperand(0).getOperand(1);
4017
4018     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4019       EVT TruncVT = N->getValueType(0);
4020       SDValue N00 = N->getOperand(0).getOperand(0);
4021       APInt TruncC = N01C->getAPIntValue();
4022       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4023
4024       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4025                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4026                          DAG.getConstant(TruncC, TruncVT));
4027     }
4028   }
4029
4030   return SDValue();
4031 }
4032
4033 SDValue DAGCombiner::visitRotate(SDNode *N) {
4034   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4035   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4036       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4037     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4038     if (NewOp1.getNode())
4039       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4040                          N->getOperand(0), NewOp1);
4041   }
4042   return SDValue();
4043 }
4044
4045 SDValue DAGCombiner::visitSHL(SDNode *N) {
4046   SDValue N0 = N->getOperand(0);
4047   SDValue N1 = N->getOperand(1);
4048   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4049   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4050   EVT VT = N0.getValueType();
4051   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4052
4053   // fold vector ops
4054   if (VT.isVector()) {
4055     SDValue FoldedVOp = SimplifyVBinOp(N);
4056     if (FoldedVOp.getNode()) return FoldedVOp;
4057
4058     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4059     // If setcc produces all-one true value then:
4060     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4061     if (N1CV && N1CV->isConstant()) {
4062       if (N0.getOpcode() == ISD::AND) {
4063         SDValue N00 = N0->getOperand(0);
4064         SDValue N01 = N0->getOperand(1);
4065         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4066
4067         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4068             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4069                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4070           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4071           if (C.getNode())
4072             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4073         }
4074       } else {
4075         N1C = isConstOrConstSplat(N1);
4076       }
4077     }
4078   }
4079
4080   // fold (shl c1, c2) -> c1<<c2
4081   if (N0C && N1C)
4082     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4083   // fold (shl 0, x) -> 0
4084   if (N0C && N0C->isNullValue())
4085     return N0;
4086   // fold (shl x, c >= size(x)) -> undef
4087   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4088     return DAG.getUNDEF(VT);
4089   // fold (shl x, 0) -> x
4090   if (N1C && N1C->isNullValue())
4091     return N0;
4092   // fold (shl undef, x) -> 0
4093   if (N0.getOpcode() == ISD::UNDEF)
4094     return DAG.getConstant(0, VT);
4095   // if (shl x, c) is known to be zero, return 0
4096   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4097                             APInt::getAllOnesValue(OpSizeInBits)))
4098     return DAG.getConstant(0, VT);
4099   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4100   if (N1.getOpcode() == ISD::TRUNCATE &&
4101       N1.getOperand(0).getOpcode() == ISD::AND) {
4102     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4103     if (NewOp1.getNode())
4104       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4105   }
4106
4107   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4108     return SDValue(N, 0);
4109
4110   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4111   if (N1C && N0.getOpcode() == ISD::SHL) {
4112     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4113       uint64_t c1 = N0C1->getZExtValue();
4114       uint64_t c2 = N1C->getZExtValue();
4115       if (c1 + c2 >= OpSizeInBits)
4116         return DAG.getConstant(0, VT);
4117       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4118                          DAG.getConstant(c1 + c2, N1.getValueType()));
4119     }
4120   }
4121
4122   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4123   // For this to be valid, the second form must not preserve any of the bits
4124   // that are shifted out by the inner shift in the first form.  This means
4125   // the outer shift size must be >= the number of bits added by the ext.
4126   // As a corollary, we don't care what kind of ext it is.
4127   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4128               N0.getOpcode() == ISD::ANY_EXTEND ||
4129               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4130       N0.getOperand(0).getOpcode() == ISD::SHL) {
4131     SDValue N0Op0 = N0.getOperand(0);
4132     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4133       uint64_t c1 = N0Op0C1->getZExtValue();
4134       uint64_t c2 = N1C->getZExtValue();
4135       EVT InnerShiftVT = N0Op0.getValueType();
4136       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4137       if (c2 >= OpSizeInBits - InnerShiftSize) {
4138         if (c1 + c2 >= OpSizeInBits)
4139           return DAG.getConstant(0, VT);
4140         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4141                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4142                                        N0Op0->getOperand(0)),
4143                            DAG.getConstant(c1 + c2, N1.getValueType()));
4144       }
4145     }
4146   }
4147
4148   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4149   // Only fold this if the inner zext has no other uses to avoid increasing
4150   // the total number of instructions.
4151   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4152       N0.getOperand(0).getOpcode() == ISD::SRL) {
4153     SDValue N0Op0 = N0.getOperand(0);
4154     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4155       uint64_t c1 = N0Op0C1->getZExtValue();
4156       if (c1 < VT.getScalarSizeInBits()) {
4157         uint64_t c2 = N1C->getZExtValue();
4158         if (c1 == c2) {
4159           SDValue NewOp0 = N0.getOperand(0);
4160           EVT CountVT = NewOp0.getOperand(1).getValueType();
4161           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4162                                        NewOp0, DAG.getConstant(c2, CountVT));
4163           AddToWorklist(NewSHL.getNode());
4164           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4165         }
4166       }
4167     }
4168   }
4169
4170   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4171   //                               (and (srl x, (sub c1, c2), MASK)
4172   // Only fold this if the inner shift has no other uses -- if it does, folding
4173   // this will increase the total number of instructions.
4174   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4175     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4176       uint64_t c1 = N0C1->getZExtValue();
4177       if (c1 < OpSizeInBits) {
4178         uint64_t c2 = N1C->getZExtValue();
4179         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4180         SDValue Shift;
4181         if (c2 > c1) {
4182           Mask = Mask.shl(c2 - c1);
4183           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4184                               DAG.getConstant(c2 - c1, N1.getValueType()));
4185         } else {
4186           Mask = Mask.lshr(c1 - c2);
4187           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4188                               DAG.getConstant(c1 - c2, N1.getValueType()));
4189         }
4190         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4191                            DAG.getConstant(Mask, VT));
4192       }
4193     }
4194   }
4195   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4196   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4197     unsigned BitSize = VT.getScalarSizeInBits();
4198     SDValue HiBitsMask =
4199       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4200                                             BitSize - N1C->getZExtValue()), VT);
4201     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4202                        HiBitsMask);
4203   }
4204
4205   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4206   // Variant of version done on multiply, except mul by a power of 2 is turned
4207   // into a shift.
4208   APInt Val;
4209   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4210       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4211        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4212     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4213     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4214     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4215   }
4216
4217   if (N1C) {
4218     SDValue NewSHL = visitShiftByConstant(N, N1C);
4219     if (NewSHL.getNode())
4220       return NewSHL;
4221   }
4222
4223   return SDValue();
4224 }
4225
4226 SDValue DAGCombiner::visitSRA(SDNode *N) {
4227   SDValue N0 = N->getOperand(0);
4228   SDValue N1 = N->getOperand(1);
4229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4231   EVT VT = N0.getValueType();
4232   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4233
4234   // fold vector ops
4235   if (VT.isVector()) {
4236     SDValue FoldedVOp = SimplifyVBinOp(N);
4237     if (FoldedVOp.getNode()) return FoldedVOp;
4238
4239     N1C = isConstOrConstSplat(N1);
4240   }
4241
4242   // fold (sra c1, c2) -> (sra c1, c2)
4243   if (N0C && N1C)
4244     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4245   // fold (sra 0, x) -> 0
4246   if (N0C && N0C->isNullValue())
4247     return N0;
4248   // fold (sra -1, x) -> -1
4249   if (N0C && N0C->isAllOnesValue())
4250     return N0;
4251   // fold (sra x, (setge c, size(x))) -> undef
4252   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4253     return DAG.getUNDEF(VT);
4254   // fold (sra x, 0) -> x
4255   if (N1C && N1C->isNullValue())
4256     return N0;
4257   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4258   // sext_inreg.
4259   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4260     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4261     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4262     if (VT.isVector())
4263       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4264                                ExtVT, VT.getVectorNumElements());
4265     if ((!LegalOperations ||
4266          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4267       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4268                          N0.getOperand(0), DAG.getValueType(ExtVT));
4269   }
4270
4271   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4272   if (N1C && N0.getOpcode() == ISD::SRA) {
4273     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4274       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4275       if (Sum >= OpSizeInBits)
4276         Sum = OpSizeInBits - 1;
4277       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4278                          DAG.getConstant(Sum, N1.getValueType()));
4279     }
4280   }
4281
4282   // fold (sra (shl X, m), (sub result_size, n))
4283   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4284   // result_size - n != m.
4285   // If truncate is free for the target sext(shl) is likely to result in better
4286   // code.
4287   if (N0.getOpcode() == ISD::SHL && N1C) {
4288     // Get the two constanst of the shifts, CN0 = m, CN = n.
4289     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4290     if (N01C) {
4291       LLVMContext &Ctx = *DAG.getContext();
4292       // Determine what the truncate's result bitsize and type would be.
4293       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4294
4295       if (VT.isVector())
4296         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4297
4298       // Determine the residual right-shift amount.
4299       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4300
4301       // If the shift is not a no-op (in which case this should be just a sign
4302       // extend already), the truncated to type is legal, sign_extend is legal
4303       // on that type, and the truncate to that type is both legal and free,
4304       // perform the transform.
4305       if ((ShiftAmt > 0) &&
4306           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4307           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4308           TLI.isTruncateFree(VT, TruncVT)) {
4309
4310           SDValue Amt = DAG.getConstant(ShiftAmt,
4311               getShiftAmountTy(N0.getOperand(0).getValueType()));
4312           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4313                                       N0.getOperand(0), Amt);
4314           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4315                                       Shift);
4316           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4317                              N->getValueType(0), Trunc);
4318       }
4319     }
4320   }
4321
4322   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4323   if (N1.getOpcode() == ISD::TRUNCATE &&
4324       N1.getOperand(0).getOpcode() == ISD::AND) {
4325     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4326     if (NewOp1.getNode())
4327       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4328   }
4329
4330   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4331   //      if c1 is equal to the number of bits the trunc removes
4332   if (N0.getOpcode() == ISD::TRUNCATE &&
4333       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4334        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4335       N0.getOperand(0).hasOneUse() &&
4336       N0.getOperand(0).getOperand(1).hasOneUse() &&
4337       N1C) {
4338     SDValue N0Op0 = N0.getOperand(0);
4339     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4340       unsigned LargeShiftVal = LargeShift->getZExtValue();
4341       EVT LargeVT = N0Op0.getValueType();
4342
4343       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4344         SDValue Amt =
4345           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4346                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4347         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4348                                   N0Op0.getOperand(0), Amt);
4349         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4350       }
4351     }
4352   }
4353
4354   // Simplify, based on bits shifted out of the LHS.
4355   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4356     return SDValue(N, 0);
4357
4358
4359   // If the sign bit is known to be zero, switch this to a SRL.
4360   if (DAG.SignBitIsZero(N0))
4361     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4362
4363   if (N1C) {
4364     SDValue NewSRA = visitShiftByConstant(N, N1C);
4365     if (NewSRA.getNode())
4366       return NewSRA;
4367   }
4368
4369   return SDValue();
4370 }
4371
4372 SDValue DAGCombiner::visitSRL(SDNode *N) {
4373   SDValue N0 = N->getOperand(0);
4374   SDValue N1 = N->getOperand(1);
4375   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4376   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4377   EVT VT = N0.getValueType();
4378   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4379
4380   // fold vector ops
4381   if (VT.isVector()) {
4382     SDValue FoldedVOp = SimplifyVBinOp(N);
4383     if (FoldedVOp.getNode()) return FoldedVOp;
4384
4385     N1C = isConstOrConstSplat(N1);
4386   }
4387
4388   // fold (srl c1, c2) -> c1 >>u c2
4389   if (N0C && N1C)
4390     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4391   // fold (srl 0, x) -> 0
4392   if (N0C && N0C->isNullValue())
4393     return N0;
4394   // fold (srl x, c >= size(x)) -> undef
4395   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4396     return DAG.getUNDEF(VT);
4397   // fold (srl x, 0) -> x
4398   if (N1C && N1C->isNullValue())
4399     return N0;
4400   // if (srl x, c) is known to be zero, return 0
4401   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4402                                    APInt::getAllOnesValue(OpSizeInBits)))
4403     return DAG.getConstant(0, VT);
4404
4405   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4406   if (N1C && N0.getOpcode() == ISD::SRL) {
4407     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4408       uint64_t c1 = N01C->getZExtValue();
4409       uint64_t c2 = N1C->getZExtValue();
4410       if (c1 + c2 >= OpSizeInBits)
4411         return DAG.getConstant(0, VT);
4412       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4413                          DAG.getConstant(c1 + c2, N1.getValueType()));
4414     }
4415   }
4416
4417   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4418   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4419       N0.getOperand(0).getOpcode() == ISD::SRL &&
4420       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4421     uint64_t c1 =
4422       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4423     uint64_t c2 = N1C->getZExtValue();
4424     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4425     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4426     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4427     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4428     if (c1 + OpSizeInBits == InnerShiftSize) {
4429       if (c1 + c2 >= InnerShiftSize)
4430         return DAG.getConstant(0, VT);
4431       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4432                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4433                                      N0.getOperand(0)->getOperand(0),
4434                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4435     }
4436   }
4437
4438   // fold (srl (shl x, c), c) -> (and x, cst2)
4439   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4440     unsigned BitSize = N0.getScalarValueSizeInBits();
4441     if (BitSize <= 64) {
4442       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4443       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4444                          DAG.getConstant(~0ULL >> ShAmt, VT));
4445     }
4446   }
4447
4448   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4449   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4450     // Shifting in all undef bits?
4451     EVT SmallVT = N0.getOperand(0).getValueType();
4452     unsigned BitSize = SmallVT.getScalarSizeInBits();
4453     if (N1C->getZExtValue() >= BitSize)
4454       return DAG.getUNDEF(VT);
4455
4456     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4457       uint64_t ShiftAmt = N1C->getZExtValue();
4458       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4459                                        N0.getOperand(0),
4460                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4461       AddToWorklist(SmallShift.getNode());
4462       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4463       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4464                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4465                          DAG.getConstant(Mask, VT));
4466     }
4467   }
4468
4469   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4470   // bit, which is unmodified by sra.
4471   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4472     if (N0.getOpcode() == ISD::SRA)
4473       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4474   }
4475
4476   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4477   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4478       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4479     APInt KnownZero, KnownOne;
4480     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4481
4482     // If any of the input bits are KnownOne, then the input couldn't be all
4483     // zeros, thus the result of the srl will always be zero.
4484     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4485
4486     // If all of the bits input the to ctlz node are known to be zero, then
4487     // the result of the ctlz is "32" and the result of the shift is one.
4488     APInt UnknownBits = ~KnownZero;
4489     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4490
4491     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4492     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4493       // Okay, we know that only that the single bit specified by UnknownBits
4494       // could be set on input to the CTLZ node. If this bit is set, the SRL
4495       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4496       // to an SRL/XOR pair, which is likely to simplify more.
4497       unsigned ShAmt = UnknownBits.countTrailingZeros();
4498       SDValue Op = N0.getOperand(0);
4499
4500       if (ShAmt) {
4501         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4502                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4503         AddToWorklist(Op.getNode());
4504       }
4505
4506       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4507                          Op, DAG.getConstant(1, VT));
4508     }
4509   }
4510
4511   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4512   if (N1.getOpcode() == ISD::TRUNCATE &&
4513       N1.getOperand(0).getOpcode() == ISD::AND) {
4514     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4515     if (NewOp1.getNode())
4516       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4517   }
4518
4519   // fold operands of srl based on knowledge that the low bits are not
4520   // demanded.
4521   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4522     return SDValue(N, 0);
4523
4524   if (N1C) {
4525     SDValue NewSRL = visitShiftByConstant(N, N1C);
4526     if (NewSRL.getNode())
4527       return NewSRL;
4528   }
4529
4530   // Attempt to convert a srl of a load into a narrower zero-extending load.
4531   SDValue NarrowLoad = ReduceLoadWidth(N);
4532   if (NarrowLoad.getNode())
4533     return NarrowLoad;
4534
4535   // Here is a common situation. We want to optimize:
4536   //
4537   //   %a = ...
4538   //   %b = and i32 %a, 2
4539   //   %c = srl i32 %b, 1
4540   //   brcond i32 %c ...
4541   //
4542   // into
4543   //
4544   //   %a = ...
4545   //   %b = and %a, 2
4546   //   %c = setcc eq %b, 0
4547   //   brcond %c ...
4548   //
4549   // However when after the source operand of SRL is optimized into AND, the SRL
4550   // itself may not be optimized further. Look for it and add the BRCOND into
4551   // the worklist.
4552   if (N->hasOneUse()) {
4553     SDNode *Use = *N->use_begin();
4554     if (Use->getOpcode() == ISD::BRCOND)
4555       AddToWorklist(Use);
4556     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4557       // Also look pass the truncate.
4558       Use = *Use->use_begin();
4559       if (Use->getOpcode() == ISD::BRCOND)
4560         AddToWorklist(Use);
4561     }
4562   }
4563
4564   return SDValue();
4565 }
4566
4567 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4568   SDValue N0 = N->getOperand(0);
4569   EVT VT = N->getValueType(0);
4570
4571   // fold (ctlz c1) -> c2
4572   if (isa<ConstantSDNode>(N0))
4573     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4574   return SDValue();
4575 }
4576
4577 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4578   SDValue N0 = N->getOperand(0);
4579   EVT VT = N->getValueType(0);
4580
4581   // fold (ctlz_zero_undef c1) -> c2
4582   if (isa<ConstantSDNode>(N0))
4583     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4584   return SDValue();
4585 }
4586
4587 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4588   SDValue N0 = N->getOperand(0);
4589   EVT VT = N->getValueType(0);
4590
4591   // fold (cttz c1) -> c2
4592   if (isa<ConstantSDNode>(N0))
4593     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4594   return SDValue();
4595 }
4596
4597 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4598   SDValue N0 = N->getOperand(0);
4599   EVT VT = N->getValueType(0);
4600
4601   // fold (cttz_zero_undef c1) -> c2
4602   if (isa<ConstantSDNode>(N0))
4603     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4604   return SDValue();
4605 }
4606
4607 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4608   SDValue N0 = N->getOperand(0);
4609   EVT VT = N->getValueType(0);
4610
4611   // fold (ctpop c1) -> c2
4612   if (isa<ConstantSDNode>(N0))
4613     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4614   return SDValue();
4615 }
4616
4617 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4618   SDValue N0 = N->getOperand(0);
4619   SDValue N1 = N->getOperand(1);
4620   SDValue N2 = N->getOperand(2);
4621   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4622   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4623   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4624   EVT VT = N->getValueType(0);
4625   EVT VT0 = N0.getValueType();
4626
4627   // fold (select C, X, X) -> X
4628   if (N1 == N2)
4629     return N1;
4630   // fold (select true, X, Y) -> X
4631   if (N0C && !N0C->isNullValue())
4632     return N1;
4633   // fold (select false, X, Y) -> Y
4634   if (N0C && N0C->isNullValue())
4635     return N2;
4636   // fold (select C, 1, X) -> (or C, X)
4637   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4638     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4639   // fold (select C, 0, 1) -> (xor C, 1)
4640   // We can't do this reliably if integer based booleans have different contents
4641   // to floating point based booleans. This is because we can't tell whether we
4642   // have an integer-based boolean or a floating-point-based boolean unless we
4643   // can find the SETCC that produced it and inspect its operands. This is
4644   // fairly easy if C is the SETCC node, but it can potentially be
4645   // undiscoverable (or not reasonably discoverable). For example, it could be
4646   // in another basic block or it could require searching a complicated
4647   // expression.
4648   if (VT.isInteger() &&
4649       (VT0 == MVT::i1 || (VT0.isInteger() &&
4650                           TLI.getBooleanContents(false, false) ==
4651                               TLI.getBooleanContents(false, true) &&
4652                           TLI.getBooleanContents(false, false) ==
4653                               TargetLowering::ZeroOrOneBooleanContent)) &&
4654       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4655     SDValue XORNode;
4656     if (VT == VT0)
4657       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4658                          N0, DAG.getConstant(1, VT0));
4659     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4660                           N0, DAG.getConstant(1, VT0));
4661     AddToWorklist(XORNode.getNode());
4662     if (VT.bitsGT(VT0))
4663       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4664     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4665   }
4666   // fold (select C, 0, X) -> (and (not C), X)
4667   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4668     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4669     AddToWorklist(NOTNode.getNode());
4670     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4671   }
4672   // fold (select C, X, 1) -> (or (not C), X)
4673   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4674     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4675     AddToWorklist(NOTNode.getNode());
4676     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4677   }
4678   // fold (select C, X, 0) -> (and C, X)
4679   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4680     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4681   // fold (select X, X, Y) -> (or X, Y)
4682   // fold (select X, 1, Y) -> (or X, Y)
4683   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4684     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4685   // fold (select X, Y, X) -> (and X, Y)
4686   // fold (select X, Y, 0) -> (and X, Y)
4687   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4688     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4689
4690   // If we can fold this based on the true/false value, do so.
4691   if (SimplifySelectOps(N, N1, N2))
4692     return SDValue(N, 0);  // Don't revisit N.
4693
4694   // fold selects based on a setcc into other things, such as min/max/abs
4695   if (N0.getOpcode() == ISD::SETCC) {
4696     if ((!LegalOperations &&
4697          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4698         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4699       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4700                          N0.getOperand(0), N0.getOperand(1),
4701                          N1, N2, N0.getOperand(2));
4702     return SimplifySelect(SDLoc(N), N0, N1, N2);
4703   }
4704
4705   return SDValue();
4706 }
4707
4708 static
4709 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4710   SDLoc DL(N);
4711   EVT LoVT, HiVT;
4712   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4713
4714   // Split the inputs.
4715   SDValue Lo, Hi, LL, LH, RL, RH;
4716   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4717   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4718
4719   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4720   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4721
4722   return std::make_pair(Lo, Hi);
4723 }
4724
4725 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4726 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4727 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4728   SDLoc dl(N);
4729   SDValue Cond = N->getOperand(0);
4730   SDValue LHS = N->getOperand(1);
4731   SDValue RHS = N->getOperand(2);
4732   EVT VT = N->getValueType(0);
4733   int NumElems = VT.getVectorNumElements();
4734   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4735          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4736          Cond.getOpcode() == ISD::BUILD_VECTOR);
4737
4738   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4739   // binary ones here.
4740   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4741     return SDValue();
4742
4743   // We're sure we have an even number of elements due to the
4744   // concat_vectors we have as arguments to vselect.
4745   // Skip BV elements until we find one that's not an UNDEF
4746   // After we find an UNDEF element, keep looping until we get to half the
4747   // length of the BV and see if all the non-undef nodes are the same.
4748   ConstantSDNode *BottomHalf = nullptr;
4749   for (int i = 0; i < NumElems / 2; ++i) {
4750     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4751       continue;
4752
4753     if (BottomHalf == nullptr)
4754       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4755     else if (Cond->getOperand(i).getNode() != BottomHalf)
4756       return SDValue();
4757   }
4758
4759   // Do the same for the second half of the BuildVector
4760   ConstantSDNode *TopHalf = nullptr;
4761   for (int i = NumElems / 2; i < NumElems; ++i) {
4762     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4763       continue;
4764
4765     if (TopHalf == nullptr)
4766       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4767     else if (Cond->getOperand(i).getNode() != TopHalf)
4768       return SDValue();
4769   }
4770
4771   assert(TopHalf && BottomHalf &&
4772          "One half of the selector was all UNDEFs and the other was all the "
4773          "same value. This should have been addressed before this function.");
4774   return DAG.getNode(
4775       ISD::CONCAT_VECTORS, dl, VT,
4776       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4777       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4778 }
4779
4780 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4781
4782   if (Level >= AfterLegalizeTypes)
4783     return SDValue();
4784
4785   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4786   SDValue Mask = MST->getMask();
4787   SDValue Data  = MST->getData();
4788   SDLoc DL(N);
4789
4790   // If the MSTORE data type requires splitting and the mask is provided by a
4791   // SETCC, then split both nodes and its operands before legalization. This
4792   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4793   // and enables future optimizations (e.g. min/max pattern matching on X86).
4794   if (Mask.getOpcode() == ISD::SETCC) {
4795
4796     // Check if any splitting is required.
4797     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4798         TargetLowering::TypeSplitVector)
4799       return SDValue();
4800
4801     SDValue MaskLo, MaskHi, Lo, Hi;
4802     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4803
4804     EVT LoVT, HiVT;
4805     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4806
4807     SDValue Chain = MST->getChain();
4808     SDValue Ptr   = MST->getBasePtr();
4809
4810     EVT MemoryVT = MST->getMemoryVT();
4811     unsigned Alignment = MST->getOriginalAlignment();
4812
4813     // if Alignment is equal to the vector size,
4814     // take the half of it for the second part
4815     unsigned SecondHalfAlignment =
4816       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4817          Alignment/2 : Alignment;
4818
4819     EVT LoMemVT, HiMemVT;
4820     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4821
4822     SDValue DataLo, DataHi;
4823     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4824
4825     MachineMemOperand *MMO = DAG.getMachineFunction().
4826       getMachineMemOperand(MST->getPointerInfo(), 
4827                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4828                            Alignment, MST->getAAInfo(), MST->getRanges());
4829
4830     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4831
4832     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4833     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4834                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4835
4836     MMO = DAG.getMachineFunction().
4837       getMachineMemOperand(MST->getPointerInfo(), 
4838                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4839                            SecondHalfAlignment, MST->getAAInfo(),
4840                            MST->getRanges());
4841
4842     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4843
4844     AddToWorklist(Lo.getNode());
4845     AddToWorklist(Hi.getNode());
4846
4847     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4848   }
4849   return SDValue();
4850 }
4851
4852 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4853
4854   if (Level >= AfterLegalizeTypes)
4855     return SDValue();
4856
4857   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4858   SDValue Mask = MLD->getMask();
4859   SDLoc DL(N);
4860
4861   // If the MLOAD result requires splitting and the mask is provided by a
4862   // SETCC, then split both nodes and its operands before legalization. This
4863   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4864   // and enables future optimizations (e.g. min/max pattern matching on X86).
4865
4866   if (Mask.getOpcode() == ISD::SETCC) {
4867     EVT VT = N->getValueType(0);
4868
4869     // Check if any splitting is required.
4870     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4871         TargetLowering::TypeSplitVector)
4872       return SDValue();
4873
4874     SDValue MaskLo, MaskHi, Lo, Hi;
4875     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4876
4877     SDValue Src0 = MLD->getSrc0();
4878     SDValue Src0Lo, Src0Hi;
4879     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4880
4881     EVT LoVT, HiVT;
4882     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4883
4884     SDValue Chain = MLD->getChain();
4885     SDValue Ptr   = MLD->getBasePtr();
4886     EVT MemoryVT = MLD->getMemoryVT();
4887     unsigned Alignment = MLD->getOriginalAlignment();
4888
4889     // if Alignment is equal to the vector size,
4890     // take the half of it for the second part
4891     unsigned SecondHalfAlignment =
4892       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4893          Alignment/2 : Alignment;
4894
4895     EVT LoMemVT, HiMemVT;
4896     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4897
4898     MachineMemOperand *MMO = DAG.getMachineFunction().
4899     getMachineMemOperand(MLD->getPointerInfo(), 
4900                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4901                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4902
4903     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4904
4905     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4906     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4907                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4908
4909     MMO = DAG.getMachineFunction().
4910     getMachineMemOperand(MLD->getPointerInfo(), 
4911                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
4912                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4913
4914     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4915
4916     AddToWorklist(Lo.getNode());
4917     AddToWorklist(Hi.getNode());
4918
4919     // Build a factor node to remember that this load is independent of the
4920     // other one.
4921     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4922                         Hi.getValue(1));
4923
4924     // Legalized the chain result - switch anything that used the old chain to
4925     // use the new one.
4926     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4927
4928     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4929
4930     SDValue RetOps[] = { LoadRes, Chain };
4931     return DAG.getMergeValues(RetOps, DL);
4932   }
4933   return SDValue();
4934 }
4935
4936 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4937   SDValue N0 = N->getOperand(0);
4938   SDValue N1 = N->getOperand(1);
4939   SDValue N2 = N->getOperand(2);
4940   SDLoc DL(N);
4941
4942   // Canonicalize integer abs.
4943   // vselect (setg[te] X,  0),  X, -X ->
4944   // vselect (setgt    X, -1),  X, -X ->
4945   // vselect (setl[te] X,  0), -X,  X ->
4946   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4947   if (N0.getOpcode() == ISD::SETCC) {
4948     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4949     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4950     bool isAbs = false;
4951     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4952
4953     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4954          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4955         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4956       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4957     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4958              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4959       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4960
4961     if (isAbs) {
4962       EVT VT = LHS.getValueType();
4963       SDValue Shift = DAG.getNode(
4964           ISD::SRA, DL, VT, LHS,
4965           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4966       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4967       AddToWorklist(Shift.getNode());
4968       AddToWorklist(Add.getNode());
4969       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4970     }
4971   }
4972
4973   // If the VSELECT result requires splitting and the mask is provided by a
4974   // SETCC, then split both nodes and its operands before legalization. This
4975   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4976   // and enables future optimizations (e.g. min/max pattern matching on X86).
4977   if (N0.getOpcode() == ISD::SETCC) {
4978     EVT VT = N->getValueType(0);
4979
4980     // Check if any splitting is required.
4981     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4982         TargetLowering::TypeSplitVector)
4983       return SDValue();
4984
4985     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4986     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4987     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4988     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4989
4990     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4991     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4992
4993     // Add the new VSELECT nodes to the work list in case they need to be split
4994     // again.
4995     AddToWorklist(Lo.getNode());
4996     AddToWorklist(Hi.getNode());
4997
4998     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4999   }
5000
5001   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5002   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5003     return N1;
5004   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5005   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5006     return N2;
5007
5008   // The ConvertSelectToConcatVector function is assuming both the above
5009   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5010   // and addressed.
5011   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5012       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5013       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5014     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5015     if (CV.getNode())
5016       return CV;
5017   }
5018
5019   return SDValue();
5020 }
5021
5022 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5023   SDValue N0 = N->getOperand(0);
5024   SDValue N1 = N->getOperand(1);
5025   SDValue N2 = N->getOperand(2);
5026   SDValue N3 = N->getOperand(3);
5027   SDValue N4 = N->getOperand(4);
5028   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5029
5030   // fold select_cc lhs, rhs, x, x, cc -> x
5031   if (N2 == N3)
5032     return N2;
5033
5034   // Determine if the condition we're dealing with is constant
5035   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5036                               N0, N1, CC, SDLoc(N), false);
5037   if (SCC.getNode()) {
5038     AddToWorklist(SCC.getNode());
5039
5040     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5041       if (!SCCC->isNullValue())
5042         return N2;    // cond always true -> true val
5043       else
5044         return N3;    // cond always false -> false val
5045     }
5046
5047     // Fold to a simpler select_cc
5048     if (SCC.getOpcode() == ISD::SETCC)
5049       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5050                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5051                          SCC.getOperand(2));
5052   }
5053
5054   // If we can fold this based on the true/false value, do so.
5055   if (SimplifySelectOps(N, N2, N3))
5056     return SDValue(N, 0);  // Don't revisit N.
5057
5058   // fold select_cc into other things, such as min/max/abs
5059   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5060 }
5061
5062 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5063   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5064                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5065                        SDLoc(N));
5066 }
5067
5068 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5069 // dag node into a ConstantSDNode or a build_vector of constants.
5070 // This function is called by the DAGCombiner when visiting sext/zext/aext
5071 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5072 // Vector extends are not folded if operations are legal; this is to
5073 // avoid introducing illegal build_vector dag nodes.
5074 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5075                                          SelectionDAG &DAG, bool LegalTypes,
5076                                          bool LegalOperations) {
5077   unsigned Opcode = N->getOpcode();
5078   SDValue N0 = N->getOperand(0);
5079   EVT VT = N->getValueType(0);
5080
5081   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5082          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5083
5084   // fold (sext c1) -> c1
5085   // fold (zext c1) -> c1
5086   // fold (aext c1) -> c1
5087   if (isa<ConstantSDNode>(N0))
5088     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5089
5090   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5091   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5092   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5093   EVT SVT = VT.getScalarType();
5094   if (!(VT.isVector() &&
5095       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5096       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5097     return nullptr;
5098
5099   // We can fold this node into a build_vector.
5100   unsigned VTBits = SVT.getSizeInBits();
5101   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5102   unsigned ShAmt = VTBits - EVTBits;
5103   SmallVector<SDValue, 8> Elts;
5104   unsigned NumElts = N0->getNumOperands();
5105   SDLoc DL(N);
5106
5107   for (unsigned i=0; i != NumElts; ++i) {
5108     SDValue Op = N0->getOperand(i);
5109     if (Op->getOpcode() == ISD::UNDEF) {
5110       Elts.push_back(DAG.getUNDEF(SVT));
5111       continue;
5112     }
5113
5114     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5115     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5116     if (Opcode == ISD::SIGN_EXTEND)
5117       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5118                                      SVT));
5119     else
5120       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5121                                      SVT));
5122   }
5123
5124   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5125 }
5126
5127 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5128 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5129 // transformation. Returns true if extension are possible and the above
5130 // mentioned transformation is profitable.
5131 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5132                                     unsigned ExtOpc,
5133                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5134                                     const TargetLowering &TLI) {
5135   bool HasCopyToRegUses = false;
5136   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5137   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5138                             UE = N0.getNode()->use_end();
5139        UI != UE; ++UI) {
5140     SDNode *User = *UI;
5141     if (User == N)
5142       continue;
5143     if (UI.getUse().getResNo() != N0.getResNo())
5144       continue;
5145     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5146     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5147       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5148       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5149         // Sign bits will be lost after a zext.
5150         return false;
5151       bool Add = false;
5152       for (unsigned i = 0; i != 2; ++i) {
5153         SDValue UseOp = User->getOperand(i);
5154         if (UseOp == N0)
5155           continue;
5156         if (!isa<ConstantSDNode>(UseOp))
5157           return false;
5158         Add = true;
5159       }
5160       if (Add)
5161         ExtendNodes.push_back(User);
5162       continue;
5163     }
5164     // If truncates aren't free and there are users we can't
5165     // extend, it isn't worthwhile.
5166     if (!isTruncFree)
5167       return false;
5168     // Remember if this value is live-out.
5169     if (User->getOpcode() == ISD::CopyToReg)
5170       HasCopyToRegUses = true;
5171   }
5172
5173   if (HasCopyToRegUses) {
5174     bool BothLiveOut = false;
5175     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5176          UI != UE; ++UI) {
5177       SDUse &Use = UI.getUse();
5178       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5179         BothLiveOut = true;
5180         break;
5181       }
5182     }
5183     if (BothLiveOut)
5184       // Both unextended and extended values are live out. There had better be
5185       // a good reason for the transformation.
5186       return ExtendNodes.size();
5187   }
5188   return true;
5189 }
5190
5191 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5192                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5193                                   ISD::NodeType ExtType) {
5194   // Extend SetCC uses if necessary.
5195   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5196     SDNode *SetCC = SetCCs[i];
5197     SmallVector<SDValue, 4> Ops;
5198
5199     for (unsigned j = 0; j != 2; ++j) {
5200       SDValue SOp = SetCC->getOperand(j);
5201       if (SOp == Trunc)
5202         Ops.push_back(ExtLoad);
5203       else
5204         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5205     }
5206
5207     Ops.push_back(SetCC->getOperand(2));
5208     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5209   }
5210 }
5211
5212 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5213   SDValue N0 = N->getOperand(0);
5214   EVT VT = N->getValueType(0);
5215
5216   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5217                                               LegalOperations))
5218     return SDValue(Res, 0);
5219
5220   // fold (sext (sext x)) -> (sext x)
5221   // fold (sext (aext x)) -> (sext x)
5222   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5223     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5224                        N0.getOperand(0));
5225
5226   if (N0.getOpcode() == ISD::TRUNCATE) {
5227     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5228     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5229     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5230     if (NarrowLoad.getNode()) {
5231       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5232       if (NarrowLoad.getNode() != N0.getNode()) {
5233         CombineTo(N0.getNode(), NarrowLoad);
5234         // CombineTo deleted the truncate, if needed, but not what's under it.
5235         AddToWorklist(oye);
5236       }
5237       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5238     }
5239
5240     // See if the value being truncated is already sign extended.  If so, just
5241     // eliminate the trunc/sext pair.
5242     SDValue Op = N0.getOperand(0);
5243     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5244     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5245     unsigned DestBits = VT.getScalarType().getSizeInBits();
5246     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5247
5248     if (OpBits == DestBits) {
5249       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5250       // bits, it is already ready.
5251       if (NumSignBits > DestBits-MidBits)
5252         return Op;
5253     } else if (OpBits < DestBits) {
5254       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5255       // bits, just sext from i32.
5256       if (NumSignBits > OpBits-MidBits)
5257         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5258     } else {
5259       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5260       // bits, just truncate to i32.
5261       if (NumSignBits > OpBits-MidBits)
5262         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5263     }
5264
5265     // fold (sext (truncate x)) -> (sextinreg x).
5266     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5267                                                  N0.getValueType())) {
5268       if (OpBits < DestBits)
5269         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5270       else if (OpBits > DestBits)
5271         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5272       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5273                          DAG.getValueType(N0.getValueType()));
5274     }
5275   }
5276
5277   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5278   // None of the supported targets knows how to perform load and sign extend
5279   // on vectors in one instruction.  We only perform this transformation on
5280   // scalars.
5281   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5282       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5283       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5284        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5285     bool DoXform = true;
5286     SmallVector<SDNode*, 4> SetCCs;
5287     if (!N0.hasOneUse())
5288       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5289     if (DoXform) {
5290       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5291       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5292                                        LN0->getChain(),
5293                                        LN0->getBasePtr(), N0.getValueType(),
5294                                        LN0->getMemOperand());
5295       CombineTo(N, ExtLoad);
5296       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5297                                   N0.getValueType(), ExtLoad);
5298       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5299       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5300                       ISD::SIGN_EXTEND);
5301       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5302     }
5303   }
5304
5305   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5306   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5307   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5308       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5309     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5310     EVT MemVT = LN0->getMemoryVT();
5311     if ((!LegalOperations && !LN0->isVolatile()) ||
5312         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5313       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5314                                        LN0->getChain(),
5315                                        LN0->getBasePtr(), MemVT,
5316                                        LN0->getMemOperand());
5317       CombineTo(N, ExtLoad);
5318       CombineTo(N0.getNode(),
5319                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5320                             N0.getValueType(), ExtLoad),
5321                 ExtLoad.getValue(1));
5322       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5323     }
5324   }
5325
5326   // fold (sext (and/or/xor (load x), cst)) ->
5327   //      (and/or/xor (sextload x), (sext cst))
5328   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5329        N0.getOpcode() == ISD::XOR) &&
5330       isa<LoadSDNode>(N0.getOperand(0)) &&
5331       N0.getOperand(1).getOpcode() == ISD::Constant &&
5332       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5333       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5334     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5335     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5336       bool DoXform = true;
5337       SmallVector<SDNode*, 4> SetCCs;
5338       if (!N0.hasOneUse())
5339         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5340                                           SetCCs, TLI);
5341       if (DoXform) {
5342         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5343                                          LN0->getChain(), LN0->getBasePtr(),
5344                                          LN0->getMemoryVT(),
5345                                          LN0->getMemOperand());
5346         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5347         Mask = Mask.sext(VT.getSizeInBits());
5348         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5349                                   ExtLoad, DAG.getConstant(Mask, VT));
5350         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5351                                     SDLoc(N0.getOperand(0)),
5352                                     N0.getOperand(0).getValueType(), ExtLoad);
5353         CombineTo(N, And);
5354         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5355         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5356                         ISD::SIGN_EXTEND);
5357         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5358       }
5359     }
5360   }
5361
5362   if (N0.getOpcode() == ISD::SETCC) {
5363     EVT N0VT = N0.getOperand(0).getValueType();
5364     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5365     // Only do this before legalize for now.
5366     if (VT.isVector() && !LegalOperations &&
5367         TLI.getBooleanContents(N0VT) ==
5368             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5369       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5370       // of the same size as the compared operands. Only optimize sext(setcc())
5371       // if this is the case.
5372       EVT SVT = getSetCCResultType(N0VT);
5373
5374       // We know that the # elements of the results is the same as the
5375       // # elements of the compare (and the # elements of the compare result
5376       // for that matter).  Check to see that they are the same size.  If so,
5377       // we know that the element size of the sext'd result matches the
5378       // element size of the compare operands.
5379       if (VT.getSizeInBits() == SVT.getSizeInBits())
5380         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5381                              N0.getOperand(1),
5382                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5383
5384       // If the desired elements are smaller or larger than the source
5385       // elements we can use a matching integer vector type and then
5386       // truncate/sign extend
5387       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5388       if (SVT == MatchingVectorType) {
5389         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5390                                N0.getOperand(0), N0.getOperand(1),
5391                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5392         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5393       }
5394     }
5395
5396     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5397     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5398     SDValue NegOne =
5399       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5400     SDValue SCC =
5401       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5402                        NegOne, DAG.getConstant(0, VT),
5403                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5404     if (SCC.getNode()) return SCC;
5405
5406     if (!VT.isVector()) {
5407       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5408       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5409         SDLoc DL(N);
5410         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5411         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5412                                      N0.getOperand(0), N0.getOperand(1), CC);
5413         return DAG.getSelect(DL, VT, SetCC,
5414                              NegOne, DAG.getConstant(0, VT));
5415       }
5416     }
5417   }
5418
5419   // fold (sext x) -> (zext x) if the sign bit is known zero.
5420   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5421       DAG.SignBitIsZero(N0))
5422     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5423
5424   return SDValue();
5425 }
5426
5427 // isTruncateOf - If N is a truncate of some other value, return true, record
5428 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5429 // This function computes KnownZero to avoid a duplicated call to
5430 // computeKnownBits in the caller.
5431 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5432                          APInt &KnownZero) {
5433   APInt KnownOne;
5434   if (N->getOpcode() == ISD::TRUNCATE) {
5435     Op = N->getOperand(0);
5436     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5437     return true;
5438   }
5439
5440   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5441       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5442     return false;
5443
5444   SDValue Op0 = N->getOperand(0);
5445   SDValue Op1 = N->getOperand(1);
5446   assert(Op0.getValueType() == Op1.getValueType());
5447
5448   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5449   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5450   if (COp0 && COp0->isNullValue())
5451     Op = Op1;
5452   else if (COp1 && COp1->isNullValue())
5453     Op = Op0;
5454   else
5455     return false;
5456
5457   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5458
5459   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5460     return false;
5461
5462   return true;
5463 }
5464
5465 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5466   SDValue N0 = N->getOperand(0);
5467   EVT VT = N->getValueType(0);
5468
5469   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5470                                               LegalOperations))
5471     return SDValue(Res, 0);
5472
5473   // fold (zext (zext x)) -> (zext x)
5474   // fold (zext (aext x)) -> (zext x)
5475   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5476     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5477                        N0.getOperand(0));
5478
5479   // fold (zext (truncate x)) -> (zext x) or
5480   //      (zext (truncate x)) -> (truncate x)
5481   // This is valid when the truncated bits of x are already zero.
5482   // FIXME: We should extend this to work for vectors too.
5483   SDValue Op;
5484   APInt KnownZero;
5485   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5486     APInt TruncatedBits =
5487       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5488       APInt(Op.getValueSizeInBits(), 0) :
5489       APInt::getBitsSet(Op.getValueSizeInBits(),
5490                         N0.getValueSizeInBits(),
5491                         std::min(Op.getValueSizeInBits(),
5492                                  VT.getSizeInBits()));
5493     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5494       if (VT.bitsGT(Op.getValueType()))
5495         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5496       if (VT.bitsLT(Op.getValueType()))
5497         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5498
5499       return Op;
5500     }
5501   }
5502
5503   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5504   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5505   if (N0.getOpcode() == ISD::TRUNCATE) {
5506     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5507     if (NarrowLoad.getNode()) {
5508       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5509       if (NarrowLoad.getNode() != N0.getNode()) {
5510         CombineTo(N0.getNode(), NarrowLoad);
5511         // CombineTo deleted the truncate, if needed, but not what's under it.
5512         AddToWorklist(oye);
5513       }
5514       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5515     }
5516   }
5517
5518   // fold (zext (truncate x)) -> (and x, mask)
5519   if (N0.getOpcode() == ISD::TRUNCATE &&
5520       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5521
5522     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5523     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5524     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5525     if (NarrowLoad.getNode()) {
5526       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5527       if (NarrowLoad.getNode() != N0.getNode()) {
5528         CombineTo(N0.getNode(), NarrowLoad);
5529         // CombineTo deleted the truncate, if needed, but not what's under it.
5530         AddToWorklist(oye);
5531       }
5532       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5533     }
5534
5535     SDValue Op = N0.getOperand(0);
5536     if (Op.getValueType().bitsLT(VT)) {
5537       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5538       AddToWorklist(Op.getNode());
5539     } else if (Op.getValueType().bitsGT(VT)) {
5540       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5541       AddToWorklist(Op.getNode());
5542     }
5543     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5544                                   N0.getValueType().getScalarType());
5545   }
5546
5547   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5548   // if either of the casts is not free.
5549   if (N0.getOpcode() == ISD::AND &&
5550       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5551       N0.getOperand(1).getOpcode() == ISD::Constant &&
5552       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5553                            N0.getValueType()) ||
5554        !TLI.isZExtFree(N0.getValueType(), VT))) {
5555     SDValue X = N0.getOperand(0).getOperand(0);
5556     if (X.getValueType().bitsLT(VT)) {
5557       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5558     } else if (X.getValueType().bitsGT(VT)) {
5559       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5560     }
5561     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5562     Mask = Mask.zext(VT.getSizeInBits());
5563     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5564                        X, DAG.getConstant(Mask, VT));
5565   }
5566
5567   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5568   // None of the supported targets knows how to perform load and vector_zext
5569   // on vectors in one instruction.  We only perform this transformation on
5570   // scalars.
5571   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5572       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5573       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5574        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5575     bool DoXform = true;
5576     SmallVector<SDNode*, 4> SetCCs;
5577     if (!N0.hasOneUse())
5578       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5579     if (DoXform) {
5580       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5581       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5582                                        LN0->getChain(),
5583                                        LN0->getBasePtr(), N0.getValueType(),
5584                                        LN0->getMemOperand());
5585       CombineTo(N, ExtLoad);
5586       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5587                                   N0.getValueType(), ExtLoad);
5588       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5589
5590       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5591                       ISD::ZERO_EXTEND);
5592       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5593     }
5594   }
5595
5596   // fold (zext (and/or/xor (load x), cst)) ->
5597   //      (and/or/xor (zextload x), (zext cst))
5598   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5599        N0.getOpcode() == ISD::XOR) &&
5600       isa<LoadSDNode>(N0.getOperand(0)) &&
5601       N0.getOperand(1).getOpcode() == ISD::Constant &&
5602       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5603       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5604     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5605     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5606       bool DoXform = true;
5607       SmallVector<SDNode*, 4> SetCCs;
5608       if (!N0.hasOneUse())
5609         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5610                                           SetCCs, TLI);
5611       if (DoXform) {
5612         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5613                                          LN0->getChain(), LN0->getBasePtr(),
5614                                          LN0->getMemoryVT(),
5615                                          LN0->getMemOperand());
5616         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5617         Mask = Mask.zext(VT.getSizeInBits());
5618         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5619                                   ExtLoad, DAG.getConstant(Mask, VT));
5620         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5621                                     SDLoc(N0.getOperand(0)),
5622                                     N0.getOperand(0).getValueType(), ExtLoad);
5623         CombineTo(N, And);
5624         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5625         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5626                         ISD::ZERO_EXTEND);
5627         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5628       }
5629     }
5630   }
5631
5632   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5633   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5634   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5635       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5636     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5637     EVT MemVT = LN0->getMemoryVT();
5638     if ((!LegalOperations && !LN0->isVolatile()) ||
5639         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5640       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5641                                        LN0->getChain(),
5642                                        LN0->getBasePtr(), MemVT,
5643                                        LN0->getMemOperand());
5644       CombineTo(N, ExtLoad);
5645       CombineTo(N0.getNode(),
5646                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5647                             ExtLoad),
5648                 ExtLoad.getValue(1));
5649       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5650     }
5651   }
5652
5653   if (N0.getOpcode() == ISD::SETCC) {
5654     if (!LegalOperations && VT.isVector() &&
5655         N0.getValueType().getVectorElementType() == MVT::i1) {
5656       EVT N0VT = N0.getOperand(0).getValueType();
5657       if (getSetCCResultType(N0VT) == N0.getValueType())
5658         return SDValue();
5659
5660       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5661       // Only do this before legalize for now.
5662       EVT EltVT = VT.getVectorElementType();
5663       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5664                                     DAG.getConstant(1, EltVT));
5665       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5666         // We know that the # elements of the results is the same as the
5667         // # elements of the compare (and the # elements of the compare result
5668         // for that matter).  Check to see that they are the same size.  If so,
5669         // we know that the element size of the sext'd result matches the
5670         // element size of the compare operands.
5671         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5672                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5673                                          N0.getOperand(1),
5674                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5675                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5676                                        OneOps));
5677
5678       // If the desired elements are smaller or larger than the source
5679       // elements we can use a matching integer vector type and then
5680       // truncate/sign extend
5681       EVT MatchingElementType =
5682         EVT::getIntegerVT(*DAG.getContext(),
5683                           N0VT.getScalarType().getSizeInBits());
5684       EVT MatchingVectorType =
5685         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5686                          N0VT.getVectorNumElements());
5687       SDValue VsetCC =
5688         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5689                       N0.getOperand(1),
5690                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5691       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5692                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5693                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5694     }
5695
5696     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5697     SDValue SCC =
5698       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5699                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5700                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5701     if (SCC.getNode()) return SCC;
5702   }
5703
5704   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5705   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5706       isa<ConstantSDNode>(N0.getOperand(1)) &&
5707       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5708       N0.hasOneUse()) {
5709     SDValue ShAmt = N0.getOperand(1);
5710     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5711     if (N0.getOpcode() == ISD::SHL) {
5712       SDValue InnerZExt = N0.getOperand(0);
5713       // If the original shl may be shifting out bits, do not perform this
5714       // transformation.
5715       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5716         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5717       if (ShAmtVal > KnownZeroBits)
5718         return SDValue();
5719     }
5720
5721     SDLoc DL(N);
5722
5723     // Ensure that the shift amount is wide enough for the shifted value.
5724     if (VT.getSizeInBits() >= 256)
5725       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5726
5727     return DAG.getNode(N0.getOpcode(), DL, VT,
5728                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5729                        ShAmt);
5730   }
5731
5732   return SDValue();
5733 }
5734
5735 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5736   SDValue N0 = N->getOperand(0);
5737   EVT VT = N->getValueType(0);
5738
5739   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5740                                               LegalOperations))
5741     return SDValue(Res, 0);
5742
5743   // fold (aext (aext x)) -> (aext x)
5744   // fold (aext (zext x)) -> (zext x)
5745   // fold (aext (sext x)) -> (sext x)
5746   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5747       N0.getOpcode() == ISD::ZERO_EXTEND ||
5748       N0.getOpcode() == ISD::SIGN_EXTEND)
5749     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5750
5751   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5752   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5753   if (N0.getOpcode() == ISD::TRUNCATE) {
5754     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5755     if (NarrowLoad.getNode()) {
5756       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5757       if (NarrowLoad.getNode() != N0.getNode()) {
5758         CombineTo(N0.getNode(), NarrowLoad);
5759         // CombineTo deleted the truncate, if needed, but not what's under it.
5760         AddToWorklist(oye);
5761       }
5762       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5763     }
5764   }
5765
5766   // fold (aext (truncate x))
5767   if (N0.getOpcode() == ISD::TRUNCATE) {
5768     SDValue TruncOp = N0.getOperand(0);
5769     if (TruncOp.getValueType() == VT)
5770       return TruncOp; // x iff x size == zext size.
5771     if (TruncOp.getValueType().bitsGT(VT))
5772       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5773     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5774   }
5775
5776   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5777   // if the trunc is not free.
5778   if (N0.getOpcode() == ISD::AND &&
5779       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5780       N0.getOperand(1).getOpcode() == ISD::Constant &&
5781       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5782                           N0.getValueType())) {
5783     SDValue X = N0.getOperand(0).getOperand(0);
5784     if (X.getValueType().bitsLT(VT)) {
5785       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5786     } else if (X.getValueType().bitsGT(VT)) {
5787       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5788     }
5789     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5790     Mask = Mask.zext(VT.getSizeInBits());
5791     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5792                        X, DAG.getConstant(Mask, VT));
5793   }
5794
5795   // fold (aext (load x)) -> (aext (truncate (extload x)))
5796   // None of the supported targets knows how to perform load and any_ext
5797   // on vectors in one instruction.  We only perform this transformation on
5798   // scalars.
5799   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5800       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5801       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5802     bool DoXform = true;
5803     SmallVector<SDNode*, 4> SetCCs;
5804     if (!N0.hasOneUse())
5805       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5806     if (DoXform) {
5807       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5808       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5809                                        LN0->getChain(),
5810                                        LN0->getBasePtr(), N0.getValueType(),
5811                                        LN0->getMemOperand());
5812       CombineTo(N, ExtLoad);
5813       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5814                                   N0.getValueType(), ExtLoad);
5815       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5816       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5817                       ISD::ANY_EXTEND);
5818       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5819     }
5820   }
5821
5822   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5823   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5824   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5825   if (N0.getOpcode() == ISD::LOAD &&
5826       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5827       N0.hasOneUse()) {
5828     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5829     ISD::LoadExtType ExtType = LN0->getExtensionType();
5830     EVT MemVT = LN0->getMemoryVT();
5831     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5832       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5833                                        VT, LN0->getChain(), LN0->getBasePtr(),
5834                                        MemVT, LN0->getMemOperand());
5835       CombineTo(N, ExtLoad);
5836       CombineTo(N0.getNode(),
5837                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5838                             N0.getValueType(), ExtLoad),
5839                 ExtLoad.getValue(1));
5840       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5841     }
5842   }
5843
5844   if (N0.getOpcode() == ISD::SETCC) {
5845     // For vectors:
5846     // aext(setcc) -> vsetcc
5847     // aext(setcc) -> truncate(vsetcc)
5848     // aext(setcc) -> aext(vsetcc)
5849     // Only do this before legalize for now.
5850     if (VT.isVector() && !LegalOperations) {
5851       EVT N0VT = N0.getOperand(0).getValueType();
5852         // We know that the # elements of the results is the same as the
5853         // # elements of the compare (and the # elements of the compare result
5854         // for that matter).  Check to see that they are the same size.  If so,
5855         // we know that the element size of the sext'd result matches the
5856         // element size of the compare operands.
5857       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5858         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5859                              N0.getOperand(1),
5860                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5861       // If the desired elements are smaller or larger than the source
5862       // elements we can use a matching integer vector type and then
5863       // truncate/any extend
5864       else {
5865         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5866         SDValue VsetCC =
5867           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5868                         N0.getOperand(1),
5869                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5870         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5871       }
5872     }
5873
5874     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5875     SDValue SCC =
5876       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5877                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5878                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5879     if (SCC.getNode())
5880       return SCC;
5881   }
5882
5883   return SDValue();
5884 }
5885
5886 /// See if the specified operand can be simplified with the knowledge that only
5887 /// the bits specified by Mask are used.  If so, return the simpler operand,
5888 /// otherwise return a null SDValue.
5889 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5890   switch (V.getOpcode()) {
5891   default: break;
5892   case ISD::Constant: {
5893     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5894     assert(CV && "Const value should be ConstSDNode.");
5895     const APInt &CVal = CV->getAPIntValue();
5896     APInt NewVal = CVal & Mask;
5897     if (NewVal != CVal)
5898       return DAG.getConstant(NewVal, V.getValueType());
5899     break;
5900   }
5901   case ISD::OR:
5902   case ISD::XOR:
5903     // If the LHS or RHS don't contribute bits to the or, drop them.
5904     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5905       return V.getOperand(1);
5906     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5907       return V.getOperand(0);
5908     break;
5909   case ISD::SRL:
5910     // Only look at single-use SRLs.
5911     if (!V.getNode()->hasOneUse())
5912       break;
5913     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5914       // See if we can recursively simplify the LHS.
5915       unsigned Amt = RHSC->getZExtValue();
5916
5917       // Watch out for shift count overflow though.
5918       if (Amt >= Mask.getBitWidth()) break;
5919       APInt NewMask = Mask << Amt;
5920       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5921       if (SimplifyLHS.getNode())
5922         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5923                            SimplifyLHS, V.getOperand(1));
5924     }
5925   }
5926   return SDValue();
5927 }
5928
5929 /// If the result of a wider load is shifted to right of N  bits and then
5930 /// truncated to a narrower type and where N is a multiple of number of bits of
5931 /// the narrower type, transform it to a narrower load from address + N / num of
5932 /// bits of new type. If the result is to be extended, also fold the extension
5933 /// to form a extending load.
5934 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5935   unsigned Opc = N->getOpcode();
5936
5937   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5938   SDValue N0 = N->getOperand(0);
5939   EVT VT = N->getValueType(0);
5940   EVT ExtVT = VT;
5941
5942   // This transformation isn't valid for vector loads.
5943   if (VT.isVector())
5944     return SDValue();
5945
5946   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5947   // extended to VT.
5948   if (Opc == ISD::SIGN_EXTEND_INREG) {
5949     ExtType = ISD::SEXTLOAD;
5950     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5951   } else if (Opc == ISD::SRL) {
5952     // Another special-case: SRL is basically zero-extending a narrower value.
5953     ExtType = ISD::ZEXTLOAD;
5954     N0 = SDValue(N, 0);
5955     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5956     if (!N01) return SDValue();
5957     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5958                               VT.getSizeInBits() - N01->getZExtValue());
5959   }
5960   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5961     return SDValue();
5962
5963   unsigned EVTBits = ExtVT.getSizeInBits();
5964
5965   // Do not generate loads of non-round integer types since these can
5966   // be expensive (and would be wrong if the type is not byte sized).
5967   if (!ExtVT.isRound())
5968     return SDValue();
5969
5970   unsigned ShAmt = 0;
5971   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5972     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5973       ShAmt = N01->getZExtValue();
5974       // Is the shift amount a multiple of size of VT?
5975       if ((ShAmt & (EVTBits-1)) == 0) {
5976         N0 = N0.getOperand(0);
5977         // Is the load width a multiple of size of VT?
5978         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5979           return SDValue();
5980       }
5981
5982       // At this point, we must have a load or else we can't do the transform.
5983       if (!isa<LoadSDNode>(N0)) return SDValue();
5984
5985       // Because a SRL must be assumed to *need* to zero-extend the high bits
5986       // (as opposed to anyext the high bits), we can't combine the zextload
5987       // lowering of SRL and an sextload.
5988       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5989         return SDValue();
5990
5991       // If the shift amount is larger than the input type then we're not
5992       // accessing any of the loaded bytes.  If the load was a zextload/extload
5993       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5994       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5995         return SDValue();
5996     }
5997   }
5998
5999   // If the load is shifted left (and the result isn't shifted back right),
6000   // we can fold the truncate through the shift.
6001   unsigned ShLeftAmt = 0;
6002   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6003       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6004     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6005       ShLeftAmt = N01->getZExtValue();
6006       N0 = N0.getOperand(0);
6007     }
6008   }
6009
6010   // If we haven't found a load, we can't narrow it.  Don't transform one with
6011   // multiple uses, this would require adding a new load.
6012   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6013     return SDValue();
6014
6015   // Don't change the width of a volatile load.
6016   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6017   if (LN0->isVolatile())
6018     return SDValue();
6019
6020   // Verify that we are actually reducing a load width here.
6021   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6022     return SDValue();
6023
6024   // For the transform to be legal, the load must produce only two values
6025   // (the value loaded and the chain).  Don't transform a pre-increment
6026   // load, for example, which produces an extra value.  Otherwise the
6027   // transformation is not equivalent, and the downstream logic to replace
6028   // uses gets things wrong.
6029   if (LN0->getNumValues() > 2)
6030     return SDValue();
6031
6032   // If the load that we're shrinking is an extload and we're not just
6033   // discarding the extension we can't simply shrink the load. Bail.
6034   // TODO: It would be possible to merge the extensions in some cases.
6035   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6036       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6037     return SDValue();
6038
6039   EVT PtrType = N0.getOperand(1).getValueType();
6040
6041   if (PtrType == MVT::Untyped || PtrType.isExtended())
6042     // It's not possible to generate a constant of extended or untyped type.
6043     return SDValue();
6044
6045   // For big endian targets, we need to adjust the offset to the pointer to
6046   // load the correct bytes.
6047   if (TLI.isBigEndian()) {
6048     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6049     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6050     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6051   }
6052
6053   uint64_t PtrOff = ShAmt / 8;
6054   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6055   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6056                                PtrType, LN0->getBasePtr(),
6057                                DAG.getConstant(PtrOff, PtrType));
6058   AddToWorklist(NewPtr.getNode());
6059
6060   SDValue Load;
6061   if (ExtType == ISD::NON_EXTLOAD)
6062     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6063                         LN0->getPointerInfo().getWithOffset(PtrOff),
6064                         LN0->isVolatile(), LN0->isNonTemporal(),
6065                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6066   else
6067     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6068                           LN0->getPointerInfo().getWithOffset(PtrOff),
6069                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6070                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6071
6072   // Replace the old load's chain with the new load's chain.
6073   WorklistRemover DeadNodes(*this);
6074   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6075
6076   // Shift the result left, if we've swallowed a left shift.
6077   SDValue Result = Load;
6078   if (ShLeftAmt != 0) {
6079     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6080     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6081       ShImmTy = VT;
6082     // If the shift amount is as large as the result size (but, presumably,
6083     // no larger than the source) then the useful bits of the result are
6084     // zero; we can't simply return the shortened shift, because the result
6085     // of that operation is undefined.
6086     if (ShLeftAmt >= VT.getSizeInBits())
6087       Result = DAG.getConstant(0, VT);
6088     else
6089       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6090                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6091   }
6092
6093   // Return the new loaded value.
6094   return Result;
6095 }
6096
6097 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6098   SDValue N0 = N->getOperand(0);
6099   SDValue N1 = N->getOperand(1);
6100   EVT VT = N->getValueType(0);
6101   EVT EVT = cast<VTSDNode>(N1)->getVT();
6102   unsigned VTBits = VT.getScalarType().getSizeInBits();
6103   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6104
6105   // fold (sext_in_reg c1) -> c1
6106   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6107     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6108
6109   // If the input is already sign extended, just drop the extension.
6110   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6111     return N0;
6112
6113   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6114   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6115       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6116     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6117                        N0.getOperand(0), N1);
6118
6119   // fold (sext_in_reg (sext x)) -> (sext x)
6120   // fold (sext_in_reg (aext x)) -> (sext x)
6121   // if x is small enough.
6122   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6123     SDValue N00 = N0.getOperand(0);
6124     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6125         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6126       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6127   }
6128
6129   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6130   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6131     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6132
6133   // fold operands of sext_in_reg based on knowledge that the top bits are not
6134   // demanded.
6135   if (SimplifyDemandedBits(SDValue(N, 0)))
6136     return SDValue(N, 0);
6137
6138   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6139   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6140   SDValue NarrowLoad = ReduceLoadWidth(N);
6141   if (NarrowLoad.getNode())
6142     return NarrowLoad;
6143
6144   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6145   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6146   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6147   if (N0.getOpcode() == ISD::SRL) {
6148     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6149       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6150         // We can turn this into an SRA iff the input to the SRL is already sign
6151         // extended enough.
6152         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6153         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6154           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6155                              N0.getOperand(0), N0.getOperand(1));
6156       }
6157   }
6158
6159   // fold (sext_inreg (extload x)) -> (sextload x)
6160   if (ISD::isEXTLoad(N0.getNode()) &&
6161       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6162       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6163       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6164        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6165     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6166     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6167                                      LN0->getChain(),
6168                                      LN0->getBasePtr(), EVT,
6169                                      LN0->getMemOperand());
6170     CombineTo(N, ExtLoad);
6171     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6172     AddToWorklist(ExtLoad.getNode());
6173     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6174   }
6175   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6176   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6177       N0.hasOneUse() &&
6178       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6179       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6180        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6181     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6182     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6183                                      LN0->getChain(),
6184                                      LN0->getBasePtr(), EVT,
6185                                      LN0->getMemOperand());
6186     CombineTo(N, ExtLoad);
6187     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6188     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6189   }
6190
6191   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6192   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6193     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6194                                        N0.getOperand(1), false);
6195     if (BSwap.getNode())
6196       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6197                          BSwap, N1);
6198   }
6199
6200   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6201   // into a build_vector.
6202   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6203     SmallVector<SDValue, 8> Elts;
6204     unsigned NumElts = N0->getNumOperands();
6205     unsigned ShAmt = VTBits - EVTBits;
6206
6207     for (unsigned i = 0; i != NumElts; ++i) {
6208       SDValue Op = N0->getOperand(i);
6209       if (Op->getOpcode() == ISD::UNDEF) {
6210         Elts.push_back(Op);
6211         continue;
6212       }
6213
6214       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6215       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6216       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6217                                      Op.getValueType()));
6218     }
6219
6220     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6221   }
6222
6223   return SDValue();
6224 }
6225
6226 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6227   SDValue N0 = N->getOperand(0);
6228   EVT VT = N->getValueType(0);
6229   bool isLE = TLI.isLittleEndian();
6230
6231   // noop truncate
6232   if (N0.getValueType() == N->getValueType(0))
6233     return N0;
6234   // fold (truncate c1) -> c1
6235   if (isa<ConstantSDNode>(N0))
6236     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6237   // fold (truncate (truncate x)) -> (truncate x)
6238   if (N0.getOpcode() == ISD::TRUNCATE)
6239     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6240   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6241   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6242       N0.getOpcode() == ISD::SIGN_EXTEND ||
6243       N0.getOpcode() == ISD::ANY_EXTEND) {
6244     if (N0.getOperand(0).getValueType().bitsLT(VT))
6245       // if the source is smaller than the dest, we still need an extend
6246       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6247                          N0.getOperand(0));
6248     if (N0.getOperand(0).getValueType().bitsGT(VT))
6249       // if the source is larger than the dest, than we just need the truncate
6250       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6251     // if the source and dest are the same type, we can drop both the extend
6252     // and the truncate.
6253     return N0.getOperand(0);
6254   }
6255
6256   // Fold extract-and-trunc into a narrow extract. For example:
6257   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6258   //   i32 y = TRUNCATE(i64 x)
6259   //        -- becomes --
6260   //   v16i8 b = BITCAST (v2i64 val)
6261   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6262   //
6263   // Note: We only run this optimization after type legalization (which often
6264   // creates this pattern) and before operation legalization after which
6265   // we need to be more careful about the vector instructions that we generate.
6266   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6267       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6268
6269     EVT VecTy = N0.getOperand(0).getValueType();
6270     EVT ExTy = N0.getValueType();
6271     EVT TrTy = N->getValueType(0);
6272
6273     unsigned NumElem = VecTy.getVectorNumElements();
6274     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6275
6276     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6277     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6278
6279     SDValue EltNo = N0->getOperand(1);
6280     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6281       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6282       EVT IndexTy = TLI.getVectorIdxTy();
6283       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6284
6285       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6286                               NVT, N0.getOperand(0));
6287
6288       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6289                          SDLoc(N), TrTy, V,
6290                          DAG.getConstant(Index, IndexTy));
6291     }
6292   }
6293
6294   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6295   if (N0.getOpcode() == ISD::SELECT) {
6296     EVT SrcVT = N0.getValueType();
6297     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6298         TLI.isTruncateFree(SrcVT, VT)) {
6299       SDLoc SL(N0);
6300       SDValue Cond = N0.getOperand(0);
6301       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6302       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6303       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6304     }
6305   }
6306
6307   // Fold a series of buildvector, bitcast, and truncate if possible.
6308   // For example fold
6309   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6310   //   (2xi32 (buildvector x, y)).
6311   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6312       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6313       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6314       N0.getOperand(0).hasOneUse()) {
6315
6316     SDValue BuildVect = N0.getOperand(0);
6317     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6318     EVT TruncVecEltTy = VT.getVectorElementType();
6319
6320     // Check that the element types match.
6321     if (BuildVectEltTy == TruncVecEltTy) {
6322       // Now we only need to compute the offset of the truncated elements.
6323       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6324       unsigned TruncVecNumElts = VT.getVectorNumElements();
6325       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6326
6327       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6328              "Invalid number of elements");
6329
6330       SmallVector<SDValue, 8> Opnds;
6331       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6332         Opnds.push_back(BuildVect.getOperand(i));
6333
6334       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6335     }
6336   }
6337
6338   // See if we can simplify the input to this truncate through knowledge that
6339   // only the low bits are being used.
6340   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6341   // Currently we only perform this optimization on scalars because vectors
6342   // may have different active low bits.
6343   if (!VT.isVector()) {
6344     SDValue Shorter =
6345       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6346                                                VT.getSizeInBits()));
6347     if (Shorter.getNode())
6348       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6349   }
6350   // fold (truncate (load x)) -> (smaller load x)
6351   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6352   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6353     SDValue Reduced = ReduceLoadWidth(N);
6354     if (Reduced.getNode())
6355       return Reduced;
6356     // Handle the case where the load remains an extending load even
6357     // after truncation.
6358     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6359       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6360       if (!LN0->isVolatile() &&
6361           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6362         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6363                                          VT, LN0->getChain(), LN0->getBasePtr(),
6364                                          LN0->getMemoryVT(),
6365                                          LN0->getMemOperand());
6366         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6367         return NewLoad;
6368       }
6369     }
6370   }
6371   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6372   // where ... are all 'undef'.
6373   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6374     SmallVector<EVT, 8> VTs;
6375     SDValue V;
6376     unsigned Idx = 0;
6377     unsigned NumDefs = 0;
6378
6379     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6380       SDValue X = N0.getOperand(i);
6381       if (X.getOpcode() != ISD::UNDEF) {
6382         V = X;
6383         Idx = i;
6384         NumDefs++;
6385       }
6386       // Stop if more than one members are non-undef.
6387       if (NumDefs > 1)
6388         break;
6389       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6390                                      VT.getVectorElementType(),
6391                                      X.getValueType().getVectorNumElements()));
6392     }
6393
6394     if (NumDefs == 0)
6395       return DAG.getUNDEF(VT);
6396
6397     if (NumDefs == 1) {
6398       assert(V.getNode() && "The single defined operand is empty!");
6399       SmallVector<SDValue, 8> Opnds;
6400       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6401         if (i != Idx) {
6402           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6403           continue;
6404         }
6405         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6406         AddToWorklist(NV.getNode());
6407         Opnds.push_back(NV);
6408       }
6409       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6410     }
6411   }
6412
6413   // Simplify the operands using demanded-bits information.
6414   if (!VT.isVector() &&
6415       SimplifyDemandedBits(SDValue(N, 0)))
6416     return SDValue(N, 0);
6417
6418   return SDValue();
6419 }
6420
6421 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6422   SDValue Elt = N->getOperand(i);
6423   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6424     return Elt.getNode();
6425   return Elt.getOperand(Elt.getResNo()).getNode();
6426 }
6427
6428 /// build_pair (load, load) -> load
6429 /// if load locations are consecutive.
6430 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6431   assert(N->getOpcode() == ISD::BUILD_PAIR);
6432
6433   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6434   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6435   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6436       LD1->getAddressSpace() != LD2->getAddressSpace())
6437     return SDValue();
6438   EVT LD1VT = LD1->getValueType(0);
6439
6440   if (ISD::isNON_EXTLoad(LD2) &&
6441       LD2->hasOneUse() &&
6442       // If both are volatile this would reduce the number of volatile loads.
6443       // If one is volatile it might be ok, but play conservative and bail out.
6444       !LD1->isVolatile() &&
6445       !LD2->isVolatile() &&
6446       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6447     unsigned Align = LD1->getAlignment();
6448     unsigned NewAlign = TLI.getDataLayout()->
6449       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6450
6451     if (NewAlign <= Align &&
6452         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6453       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6454                          LD1->getBasePtr(), LD1->getPointerInfo(),
6455                          false, false, false, Align);
6456   }
6457
6458   return SDValue();
6459 }
6460
6461 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6462   SDValue N0 = N->getOperand(0);
6463   EVT VT = N->getValueType(0);
6464
6465   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6466   // Only do this before legalize, since afterward the target may be depending
6467   // on the bitconvert.
6468   // First check to see if this is all constant.
6469   if (!LegalTypes &&
6470       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6471       VT.isVector()) {
6472     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6473
6474     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6475     assert(!DestEltVT.isVector() &&
6476            "Element type of vector ValueType must not be vector!");
6477     if (isSimple)
6478       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6479   }
6480
6481   // If the input is a constant, let getNode fold it.
6482   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6483     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6484     if (Res.getNode() != N) {
6485       if (!LegalOperations ||
6486           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6487         return Res;
6488
6489       // Folding it resulted in an illegal node, and it's too late to
6490       // do that. Clean up the old node and forego the transformation.
6491       // Ideally this won't happen very often, because instcombine
6492       // and the earlier dagcombine runs (where illegal nodes are
6493       // permitted) should have folded most of them already.
6494       deleteAndRecombine(Res.getNode());
6495     }
6496   }
6497
6498   // (conv (conv x, t1), t2) -> (conv x, t2)
6499   if (N0.getOpcode() == ISD::BITCAST)
6500     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6501                        N0.getOperand(0));
6502
6503   // fold (conv (load x)) -> (load (conv*)x)
6504   // If the resultant load doesn't need a higher alignment than the original!
6505   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6506       // Do not change the width of a volatile load.
6507       !cast<LoadSDNode>(N0)->isVolatile() &&
6508       // Do not remove the cast if the types differ in endian layout.
6509       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6510       TLI.hasBigEndianPartOrdering(VT) &&
6511       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6512       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6513     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6514     unsigned Align = TLI.getDataLayout()->
6515       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6516     unsigned OrigAlign = LN0->getAlignment();
6517
6518     if (Align <= OrigAlign) {
6519       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6520                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6521                                  LN0->isVolatile(), LN0->isNonTemporal(),
6522                                  LN0->isInvariant(), OrigAlign,
6523                                  LN0->getAAInfo());
6524       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6525       return Load;
6526     }
6527   }
6528
6529   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6530   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6531   // This often reduces constant pool loads.
6532   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6533        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6534       N0.getNode()->hasOneUse() && VT.isInteger() &&
6535       !VT.isVector() && !N0.getValueType().isVector()) {
6536     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6537                                   N0.getOperand(0));
6538     AddToWorklist(NewConv.getNode());
6539
6540     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6541     if (N0.getOpcode() == ISD::FNEG)
6542       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6543                          NewConv, DAG.getConstant(SignBit, VT));
6544     assert(N0.getOpcode() == ISD::FABS);
6545     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6546                        NewConv, DAG.getConstant(~SignBit, VT));
6547   }
6548
6549   // fold (bitconvert (fcopysign cst, x)) ->
6550   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6551   // Note that we don't handle (copysign x, cst) because this can always be
6552   // folded to an fneg or fabs.
6553   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6554       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6555       VT.isInteger() && !VT.isVector()) {
6556     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6557     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6558     if (isTypeLegal(IntXVT)) {
6559       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6560                               IntXVT, N0.getOperand(1));
6561       AddToWorklist(X.getNode());
6562
6563       // If X has a different width than the result/lhs, sext it or truncate it.
6564       unsigned VTWidth = VT.getSizeInBits();
6565       if (OrigXWidth < VTWidth) {
6566         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6567         AddToWorklist(X.getNode());
6568       } else if (OrigXWidth > VTWidth) {
6569         // To get the sign bit in the right place, we have to shift it right
6570         // before truncating.
6571         X = DAG.getNode(ISD::SRL, SDLoc(X),
6572                         X.getValueType(), X,
6573                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6574         AddToWorklist(X.getNode());
6575         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6576         AddToWorklist(X.getNode());
6577       }
6578
6579       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6580       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6581                       X, DAG.getConstant(SignBit, VT));
6582       AddToWorklist(X.getNode());
6583
6584       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6585                                 VT, N0.getOperand(0));
6586       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6587                         Cst, DAG.getConstant(~SignBit, VT));
6588       AddToWorklist(Cst.getNode());
6589
6590       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6591     }
6592   }
6593
6594   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6595   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6596     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6597     if (CombineLD.getNode())
6598       return CombineLD;
6599   }
6600
6601   return SDValue();
6602 }
6603
6604 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6605   EVT VT = N->getValueType(0);
6606   return CombineConsecutiveLoads(N, VT);
6607 }
6608
6609 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6610 /// operands. DstEltVT indicates the destination element value type.
6611 SDValue DAGCombiner::
6612 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6613   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6614
6615   // If this is already the right type, we're done.
6616   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6617
6618   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6619   unsigned DstBitSize = DstEltVT.getSizeInBits();
6620
6621   // If this is a conversion of N elements of one type to N elements of another
6622   // type, convert each element.  This handles FP<->INT cases.
6623   if (SrcBitSize == DstBitSize) {
6624     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6625                               BV->getValueType(0).getVectorNumElements());
6626
6627     // Due to the FP element handling below calling this routine recursively,
6628     // we can end up with a scalar-to-vector node here.
6629     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6630       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6631                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6632                                      DstEltVT, BV->getOperand(0)));
6633
6634     SmallVector<SDValue, 8> Ops;
6635     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6636       SDValue Op = BV->getOperand(i);
6637       // If the vector element type is not legal, the BUILD_VECTOR operands
6638       // are promoted and implicitly truncated.  Make that explicit here.
6639       if (Op.getValueType() != SrcEltVT)
6640         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6641       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6642                                 DstEltVT, Op));
6643       AddToWorklist(Ops.back().getNode());
6644     }
6645     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6646   }
6647
6648   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6649   // handle annoying details of growing/shrinking FP values, we convert them to
6650   // int first.
6651   if (SrcEltVT.isFloatingPoint()) {
6652     // Convert the input float vector to a int vector where the elements are the
6653     // same sizes.
6654     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6655     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6656     SrcEltVT = IntVT;
6657   }
6658
6659   // Now we know the input is an integer vector.  If the output is a FP type,
6660   // convert to integer first, then to FP of the right size.
6661   if (DstEltVT.isFloatingPoint()) {
6662     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6663     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6664
6665     // Next, convert to FP elements of the same size.
6666     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6667   }
6668
6669   // Okay, we know the src/dst types are both integers of differing types.
6670   // Handling growing first.
6671   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6672   if (SrcBitSize < DstBitSize) {
6673     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6674
6675     SmallVector<SDValue, 8> Ops;
6676     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6677          i += NumInputsPerOutput) {
6678       bool isLE = TLI.isLittleEndian();
6679       APInt NewBits = APInt(DstBitSize, 0);
6680       bool EltIsUndef = true;
6681       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6682         // Shift the previously computed bits over.
6683         NewBits <<= SrcBitSize;
6684         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6685         if (Op.getOpcode() == ISD::UNDEF) continue;
6686         EltIsUndef = false;
6687
6688         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6689                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6690       }
6691
6692       if (EltIsUndef)
6693         Ops.push_back(DAG.getUNDEF(DstEltVT));
6694       else
6695         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6696     }
6697
6698     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6699     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6700   }
6701
6702   // Finally, this must be the case where we are shrinking elements: each input
6703   // turns into multiple outputs.
6704   bool isS2V = ISD::isScalarToVector(BV);
6705   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6706   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6707                             NumOutputsPerInput*BV->getNumOperands());
6708   SmallVector<SDValue, 8> Ops;
6709
6710   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6711     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6712       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6713         Ops.push_back(DAG.getUNDEF(DstEltVT));
6714       continue;
6715     }
6716
6717     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6718                   getAPIntValue().zextOrTrunc(SrcBitSize);
6719
6720     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6721       APInt ThisVal = OpVal.trunc(DstBitSize);
6722       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6723       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6724         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6725         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6726                            Ops[0]);
6727       OpVal = OpVal.lshr(DstBitSize);
6728     }
6729
6730     // For big endian targets, swap the order of the pieces of each element.
6731     if (TLI.isBigEndian())
6732       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6733   }
6734
6735   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6736 }
6737
6738 SDValue DAGCombiner::visitFADD(SDNode *N) {
6739   SDValue N0 = N->getOperand(0);
6740   SDValue N1 = N->getOperand(1);
6741   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6742   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6743   EVT VT = N->getValueType(0);
6744   const TargetOptions &Options = DAG.getTarget().Options;
6745
6746   // fold vector ops
6747   if (VT.isVector()) {
6748     SDValue FoldedVOp = SimplifyVBinOp(N);
6749     if (FoldedVOp.getNode()) return FoldedVOp;
6750   }
6751
6752   // fold (fadd c1, c2) -> c1 + c2
6753   if (N0CFP && N1CFP)
6754     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6755
6756   // canonicalize constant to RHS
6757   if (N0CFP && !N1CFP)
6758     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6759
6760   // fold (fadd A, (fneg B)) -> (fsub A, B)
6761   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6762       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6763     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6764                        GetNegatedExpression(N1, DAG, LegalOperations));
6765
6766   // fold (fadd (fneg A), B) -> (fsub B, A)
6767   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6768       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6769     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6770                        GetNegatedExpression(N0, DAG, LegalOperations));
6771
6772   // If 'unsafe math' is enabled, fold lots of things.
6773   if (Options.UnsafeFPMath) {
6774     // No FP constant should be created after legalization as Instruction
6775     // Selection pass has a hard time dealing with FP constants.
6776     bool AllowNewConst = (Level < AfterLegalizeDAG);
6777
6778     // fold (fadd A, 0) -> A
6779     if (N1CFP && N1CFP->getValueAPF().isZero())
6780       return N0;
6781
6782     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6783     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6784         isa<ConstantFPSDNode>(N0.getOperand(1)))
6785       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6786                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6787                                      N0.getOperand(1), N1));
6788
6789     // If allowed, fold (fadd (fneg x), x) -> 0.0
6790     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6791       return DAG.getConstantFP(0.0, VT);
6792
6793     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6794     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6795       return DAG.getConstantFP(0.0, VT);
6796
6797     // We can fold chains of FADD's of the same value into multiplications.
6798     // This transform is not safe in general because we are reducing the number
6799     // of rounding steps.
6800     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6801       if (N0.getOpcode() == ISD::FMUL) {
6802         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6803         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6804
6805         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6806         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6807           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6808                                        SDValue(CFP01, 0),
6809                                        DAG.getConstantFP(1.0, VT));
6810           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6811         }
6812
6813         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6814         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6815             N1.getOperand(0) == N1.getOperand(1) &&
6816             N0.getOperand(0) == N1.getOperand(0)) {
6817           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6818                                        SDValue(CFP01, 0),
6819                                        DAG.getConstantFP(2.0, VT));
6820           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6821                              N0.getOperand(0), NewCFP);
6822         }
6823       }
6824
6825       if (N1.getOpcode() == ISD::FMUL) {
6826         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6827         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6828
6829         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6830         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6831           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6832                                        SDValue(CFP11, 0),
6833                                        DAG.getConstantFP(1.0, VT));
6834           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6835         }
6836
6837         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6838         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6839             N0.getOperand(0) == N0.getOperand(1) &&
6840             N1.getOperand(0) == N0.getOperand(0)) {
6841           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6842                                        SDValue(CFP11, 0),
6843                                        DAG.getConstantFP(2.0, VT));
6844           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6845         }
6846       }
6847
6848       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6849         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6850         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6851         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6852             (N0.getOperand(0) == N1))
6853           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6854                              N1, DAG.getConstantFP(3.0, VT));
6855       }
6856
6857       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6858         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6859         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6860         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6861             N1.getOperand(0) == N0)
6862           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6863                              N0, DAG.getConstantFP(3.0, VT));
6864       }
6865
6866       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6867       if (AllowNewConst &&
6868           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6869           N0.getOperand(0) == N0.getOperand(1) &&
6870           N1.getOperand(0) == N1.getOperand(1) &&
6871           N0.getOperand(0) == N1.getOperand(0))
6872         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6873                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6874     }
6875   } // enable-unsafe-fp-math
6876
6877   // FADD -> FMA combines:
6878   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6879       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6880       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6881
6882     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6883     if (N0.getOpcode() == ISD::FMUL &&
6884         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6885       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6886                          N0.getOperand(0), N0.getOperand(1), N1);
6887
6888     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6889     // Note: Commutes FADD operands.
6890     if (N1.getOpcode() == ISD::FMUL &&
6891         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6892       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6893                          N1.getOperand(0), N1.getOperand(1), N0);
6894   }
6895
6896   return SDValue();
6897 }
6898
6899 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6900   SDValue N0 = N->getOperand(0);
6901   SDValue N1 = N->getOperand(1);
6902   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6903   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6904   EVT VT = N->getValueType(0);
6905   SDLoc dl(N);
6906   const TargetOptions &Options = DAG.getTarget().Options;
6907
6908   // fold vector ops
6909   if (VT.isVector()) {
6910     SDValue FoldedVOp = SimplifyVBinOp(N);
6911     if (FoldedVOp.getNode()) return FoldedVOp;
6912   }
6913
6914   // fold (fsub c1, c2) -> c1-c2
6915   if (N0CFP && N1CFP)
6916     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6917
6918   // fold (fsub A, (fneg B)) -> (fadd A, B)
6919   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6920     return DAG.getNode(ISD::FADD, dl, VT, N0,
6921                        GetNegatedExpression(N1, DAG, LegalOperations));
6922
6923   // If 'unsafe math' is enabled, fold lots of things.
6924   if (Options.UnsafeFPMath) {
6925     // (fsub A, 0) -> A
6926     if (N1CFP && N1CFP->getValueAPF().isZero())
6927       return N0;
6928
6929     // (fsub 0, B) -> -B
6930     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6931       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6932         return GetNegatedExpression(N1, DAG, LegalOperations);
6933       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6934         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6935     }
6936
6937     // (fsub x, x) -> 0.0
6938     if (N0 == N1)
6939       return DAG.getConstantFP(0.0f, VT);
6940
6941     // (fsub x, (fadd x, y)) -> (fneg y)
6942     // (fsub x, (fadd y, x)) -> (fneg y)
6943     if (N1.getOpcode() == ISD::FADD) {
6944       SDValue N10 = N1->getOperand(0);
6945       SDValue N11 = N1->getOperand(1);
6946
6947       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6948         return GetNegatedExpression(N11, DAG, LegalOperations);
6949
6950       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6951         return GetNegatedExpression(N10, DAG, LegalOperations);
6952     }
6953   }
6954
6955   // FSUB -> FMA combines:
6956   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6957       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6958       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6959
6960     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6961     if (N0.getOpcode() == ISD::FMUL &&
6962         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6963       return DAG.getNode(ISD::FMA, dl, VT,
6964                          N0.getOperand(0), N0.getOperand(1),
6965                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6966
6967     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6968     // Note: Commutes FSUB operands.
6969     if (N1.getOpcode() == ISD::FMUL &&
6970         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6971       return DAG.getNode(ISD::FMA, dl, VT,
6972                          DAG.getNode(ISD::FNEG, dl, VT,
6973                          N1.getOperand(0)),
6974                          N1.getOperand(1), N0);
6975
6976     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6977     if (N0.getOpcode() == ISD::FNEG &&
6978         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6979         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6980             TLI.enableAggressiveFMAFusion(VT))) {
6981       SDValue N00 = N0.getOperand(0).getOperand(0);
6982       SDValue N01 = N0.getOperand(0).getOperand(1);
6983       return DAG.getNode(ISD::FMA, dl, VT,
6984                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6985                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6986     }
6987   }
6988
6989   return SDValue();
6990 }
6991
6992 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6993   SDValue N0 = N->getOperand(0);
6994   SDValue N1 = N->getOperand(1);
6995   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6996   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6997   EVT VT = N->getValueType(0);
6998   const TargetOptions &Options = DAG.getTarget().Options;
6999
7000   // fold vector ops
7001   if (VT.isVector()) {
7002     // This just handles C1 * C2 for vectors. Other vector folds are below.
7003     SDValue FoldedVOp = SimplifyVBinOp(N);
7004     if (FoldedVOp.getNode())
7005       return FoldedVOp;
7006     // Canonicalize vector constant to RHS.
7007     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7008         N1.getOpcode() != ISD::BUILD_VECTOR)
7009       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7010         if (BV0->isConstant())
7011           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7012   }
7013
7014   // fold (fmul c1, c2) -> c1*c2
7015   if (N0CFP && N1CFP)
7016     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7017
7018   // canonicalize constant to RHS
7019   if (N0CFP && !N1CFP)
7020     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7021
7022   // fold (fmul A, 1.0) -> A
7023   if (N1CFP && N1CFP->isExactlyValue(1.0))
7024     return N0;
7025
7026   if (Options.UnsafeFPMath) {
7027     // fold (fmul A, 0) -> 0
7028     if (N1CFP && N1CFP->getValueAPF().isZero())
7029       return N1;
7030
7031     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7032     if (N0.getOpcode() == ISD::FMUL) {
7033       // Fold scalars or any vector constants (not just splats).
7034       // This fold is done in general by InstCombine, but extra fmul insts
7035       // may have been generated during lowering.
7036       SDValue N01 = N0.getOperand(1);
7037       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7038       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7039       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7040           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7041         SDLoc SL(N);
7042         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7043         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7044       }
7045     }
7046
7047     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7048     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7049     // during an early run of DAGCombiner can prevent folding with fmuls
7050     // inserted during lowering.
7051     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7052       SDLoc SL(N);
7053       const SDValue Two = DAG.getConstantFP(2.0, VT);
7054       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7055       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7056     }
7057   }
7058
7059   // fold (fmul X, 2.0) -> (fadd X, X)
7060   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7061     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7062
7063   // fold (fmul X, -1.0) -> (fneg X)
7064   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7065     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7066       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7067
7068   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7069   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7070     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7071       // Both can be negated for free, check to see if at least one is cheaper
7072       // negated.
7073       if (LHSNeg == 2 || RHSNeg == 2)
7074         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7075                            GetNegatedExpression(N0, DAG, LegalOperations),
7076                            GetNegatedExpression(N1, DAG, LegalOperations));
7077     }
7078   }
7079
7080   return SDValue();
7081 }
7082
7083 SDValue DAGCombiner::visitFMA(SDNode *N) {
7084   SDValue N0 = N->getOperand(0);
7085   SDValue N1 = N->getOperand(1);
7086   SDValue N2 = N->getOperand(2);
7087   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7088   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7089   EVT VT = N->getValueType(0);
7090   SDLoc dl(N);
7091   const TargetOptions &Options = DAG.getTarget().Options;
7092
7093   // Constant fold FMA.
7094   if (isa<ConstantFPSDNode>(N0) &&
7095       isa<ConstantFPSDNode>(N1) &&
7096       isa<ConstantFPSDNode>(N2)) {
7097     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7098   }
7099
7100   if (Options.UnsafeFPMath) {
7101     if (N0CFP && N0CFP->isZero())
7102       return N2;
7103     if (N1CFP && N1CFP->isZero())
7104       return N2;
7105   }
7106   if (N0CFP && N0CFP->isExactlyValue(1.0))
7107     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7108   if (N1CFP && N1CFP->isExactlyValue(1.0))
7109     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7110
7111   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7112   if (N0CFP && !N1CFP)
7113     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7114
7115   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7116   if (Options.UnsafeFPMath && N1CFP &&
7117       N2.getOpcode() == ISD::FMUL &&
7118       N0 == N2.getOperand(0) &&
7119       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7120     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7121                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7122   }
7123
7124
7125   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7126   if (Options.UnsafeFPMath &&
7127       N0.getOpcode() == ISD::FMUL && N1CFP &&
7128       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7129     return DAG.getNode(ISD::FMA, dl, VT,
7130                        N0.getOperand(0),
7131                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7132                        N2);
7133   }
7134
7135   // (fma x, 1, y) -> (fadd x, y)
7136   // (fma x, -1, y) -> (fadd (fneg x), y)
7137   if (N1CFP) {
7138     if (N1CFP->isExactlyValue(1.0))
7139       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7140
7141     if (N1CFP->isExactlyValue(-1.0) &&
7142         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7143       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7144       AddToWorklist(RHSNeg.getNode());
7145       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7146     }
7147   }
7148
7149   // (fma x, c, x) -> (fmul x, (c+1))
7150   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7151     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7152                        DAG.getNode(ISD::FADD, dl, VT,
7153                                    N1, DAG.getConstantFP(1.0, VT)));
7154
7155   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7156   if (Options.UnsafeFPMath && N1CFP &&
7157       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7158     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7159                        DAG.getNode(ISD::FADD, dl, VT,
7160                                    N1, DAG.getConstantFP(-1.0, VT)));
7161
7162
7163   return SDValue();
7164 }
7165
7166 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7167   SDValue N0 = N->getOperand(0);
7168   SDValue N1 = N->getOperand(1);
7169   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7170   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7171   EVT VT = N->getValueType(0);
7172   SDLoc DL(N);
7173   const TargetOptions &Options = DAG.getTarget().Options;
7174
7175   // fold vector ops
7176   if (VT.isVector()) {
7177     SDValue FoldedVOp = SimplifyVBinOp(N);
7178     if (FoldedVOp.getNode()) return FoldedVOp;
7179   }
7180
7181   // fold (fdiv c1, c2) -> c1/c2
7182   if (N0CFP && N1CFP)
7183     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7184
7185   if (Options.UnsafeFPMath) {
7186     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7187     if (N1CFP) {
7188       // Compute the reciprocal 1.0 / c2.
7189       APFloat N1APF = N1CFP->getValueAPF();
7190       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7191       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7192       // Only do the transform if the reciprocal is a legal fp immediate that
7193       // isn't too nasty (eg NaN, denormal, ...).
7194       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7195           (!LegalOperations ||
7196            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7197            // backend)... we should handle this gracefully after Legalize.
7198            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7199            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7200            TLI.isFPImmLegal(Recip, VT)))
7201         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7202                            DAG.getConstantFP(Recip, VT));
7203     }
7204
7205     // If this FDIV is part of a reciprocal square root, it may be folded
7206     // into a target-specific square root estimate instruction.
7207     if (N1.getOpcode() == ISD::FSQRT) {
7208       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7209         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7210       }
7211     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7212                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7213       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7214         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7215         AddToWorklist(RV.getNode());
7216         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7217       }
7218     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7219                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7220       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7221         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7222         AddToWorklist(RV.getNode());
7223         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7224       }
7225     } else if (N1.getOpcode() == ISD::FMUL) {
7226       // Look through an FMUL. Even though this won't remove the FDIV directly,
7227       // it's still worthwhile to get rid of the FSQRT if possible.
7228       SDValue SqrtOp;
7229       SDValue OtherOp;
7230       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7231         SqrtOp = N1.getOperand(0);
7232         OtherOp = N1.getOperand(1);
7233       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7234         SqrtOp = N1.getOperand(1);
7235         OtherOp = N1.getOperand(0);
7236       }
7237       if (SqrtOp.getNode()) {
7238         // We found a FSQRT, so try to make this fold:
7239         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7240         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7241           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7242           AddToWorklist(RV.getNode());
7243           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7244         }
7245       }
7246     }
7247
7248     // Fold into a reciprocal estimate and multiply instead of a real divide.
7249     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7250       AddToWorklist(RV.getNode());
7251       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7252     }
7253   }
7254
7255   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7256   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7257     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7258       // Both can be negated for free, check to see if at least one is cheaper
7259       // negated.
7260       if (LHSNeg == 2 || RHSNeg == 2)
7261         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7262                            GetNegatedExpression(N0, DAG, LegalOperations),
7263                            GetNegatedExpression(N1, DAG, LegalOperations));
7264     }
7265   }
7266
7267   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7268   // reciprocal.
7269   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7270   // Notice that this is not always beneficial. One reason is different target
7271   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7272   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7273   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7274   if (Options.UnsafeFPMath) {
7275     // Skip if current node is a reciprocal.
7276     if (N0CFP && N0CFP->isExactlyValue(1.0))
7277       return SDValue();
7278
7279     SmallVector<SDNode *, 4> Users;
7280     // Find all FDIV users of the same divisor.
7281     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7282                               UE = N1.getNode()->use_end();
7283          UI != UE; ++UI) {
7284       SDNode *User = UI.getUse().getUser();
7285       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7286         Users.push_back(User);
7287     }
7288
7289     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7290       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7291       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7292
7293       // Dividend / Divisor -> Dividend * Reciprocal
7294       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7295         if ((*I)->getOperand(0) != FPOne) {
7296           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7297                                         (*I)->getOperand(0), Reciprocal);
7298           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7299         }
7300       }
7301       return SDValue();
7302     }
7303   }
7304
7305   return SDValue();
7306 }
7307
7308 SDValue DAGCombiner::visitFREM(SDNode *N) {
7309   SDValue N0 = N->getOperand(0);
7310   SDValue N1 = N->getOperand(1);
7311   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7312   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7313   EVT VT = N->getValueType(0);
7314
7315   // fold (frem c1, c2) -> fmod(c1,c2)
7316   if (N0CFP && N1CFP)
7317     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7318
7319   return SDValue();
7320 }
7321
7322 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7323   if (DAG.getTarget().Options.UnsafeFPMath) {
7324     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7325     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7326       EVT VT = RV.getValueType();
7327       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7328       AddToWorklist(RV.getNode());
7329
7330       // Unfortunately, RV is now NaN if the input was exactly 0.
7331       // Select out this case and force the answer to 0.
7332       SDValue Zero = DAG.getConstantFP(0.0, VT);
7333       SDValue ZeroCmp =
7334         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7335                      N->getOperand(0), Zero, ISD::SETEQ);
7336       AddToWorklist(ZeroCmp.getNode());
7337       AddToWorklist(RV.getNode());
7338
7339       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7340                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7341       return RV;
7342     }
7343   }
7344   return SDValue();
7345 }
7346
7347 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7348   SDValue N0 = N->getOperand(0);
7349   SDValue N1 = N->getOperand(1);
7350   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7351   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7352   EVT VT = N->getValueType(0);
7353
7354   if (N0CFP && N1CFP)  // Constant fold
7355     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7356
7357   if (N1CFP) {
7358     const APFloat& V = N1CFP->getValueAPF();
7359     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7360     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7361     if (!V.isNegative()) {
7362       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7363         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7364     } else {
7365       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7366         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7367                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7368     }
7369   }
7370
7371   // copysign(fabs(x), y) -> copysign(x, y)
7372   // copysign(fneg(x), y) -> copysign(x, y)
7373   // copysign(copysign(x,z), y) -> copysign(x, y)
7374   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7375       N0.getOpcode() == ISD::FCOPYSIGN)
7376     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7377                        N0.getOperand(0), N1);
7378
7379   // copysign(x, abs(y)) -> abs(x)
7380   if (N1.getOpcode() == ISD::FABS)
7381     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7382
7383   // copysign(x, copysign(y,z)) -> copysign(x, z)
7384   if (N1.getOpcode() == ISD::FCOPYSIGN)
7385     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7386                        N0, N1.getOperand(1));
7387
7388   // copysign(x, fp_extend(y)) -> copysign(x, y)
7389   // copysign(x, fp_round(y)) -> copysign(x, y)
7390   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7391     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7392                        N0, N1.getOperand(0));
7393
7394   return SDValue();
7395 }
7396
7397 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7398   SDValue N0 = N->getOperand(0);
7399   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7400   EVT VT = N->getValueType(0);
7401   EVT OpVT = N0.getValueType();
7402
7403   // fold (sint_to_fp c1) -> c1fp
7404   if (N0C &&
7405       // ...but only if the target supports immediate floating-point values
7406       (!LegalOperations ||
7407        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7408     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7409
7410   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7411   // but UINT_TO_FP is legal on this target, try to convert.
7412   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7413       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7414     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7415     if (DAG.SignBitIsZero(N0))
7416       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7417   }
7418
7419   // The next optimizations are desirable only if SELECT_CC can be lowered.
7420   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7421     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7422     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7423         !VT.isVector() &&
7424         (!LegalOperations ||
7425          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7426       SDValue Ops[] =
7427         { N0.getOperand(0), N0.getOperand(1),
7428           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7429           N0.getOperand(2) };
7430       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7431     }
7432
7433     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7434     //      (select_cc x, y, 1.0, 0.0,, cc)
7435     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7436         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7437         (!LegalOperations ||
7438          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7439       SDValue Ops[] =
7440         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7441           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7442           N0.getOperand(0).getOperand(2) };
7443       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7444     }
7445   }
7446
7447   return SDValue();
7448 }
7449
7450 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7451   SDValue N0 = N->getOperand(0);
7452   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7453   EVT VT = N->getValueType(0);
7454   EVT OpVT = N0.getValueType();
7455
7456   // fold (uint_to_fp c1) -> c1fp
7457   if (N0C &&
7458       // ...but only if the target supports immediate floating-point values
7459       (!LegalOperations ||
7460        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7461     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7462
7463   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7464   // but SINT_TO_FP is legal on this target, try to convert.
7465   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7466       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7467     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7468     if (DAG.SignBitIsZero(N0))
7469       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7470   }
7471
7472   // The next optimizations are desirable only if SELECT_CC can be lowered.
7473   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7474     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7475
7476     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7477         (!LegalOperations ||
7478          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7479       SDValue Ops[] =
7480         { N0.getOperand(0), N0.getOperand(1),
7481           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7482           N0.getOperand(2) };
7483       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7484     }
7485   }
7486
7487   return SDValue();
7488 }
7489
7490 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7491   SDValue N0 = N->getOperand(0);
7492   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7493   EVT VT = N->getValueType(0);
7494
7495   // fold (fp_to_sint c1fp) -> c1
7496   if (N0CFP)
7497     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7498
7499   return SDValue();
7500 }
7501
7502 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7503   SDValue N0 = N->getOperand(0);
7504   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7505   EVT VT = N->getValueType(0);
7506
7507   // fold (fp_to_uint c1fp) -> c1
7508   if (N0CFP)
7509     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7510
7511   return SDValue();
7512 }
7513
7514 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7515   SDValue N0 = N->getOperand(0);
7516   SDValue N1 = N->getOperand(1);
7517   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7518   EVT VT = N->getValueType(0);
7519
7520   // fold (fp_round c1fp) -> c1fp
7521   if (N0CFP)
7522     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7523
7524   // fold (fp_round (fp_extend x)) -> x
7525   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7526     return N0.getOperand(0);
7527
7528   // fold (fp_round (fp_round x)) -> (fp_round x)
7529   if (N0.getOpcode() == ISD::FP_ROUND) {
7530     // This is a value preserving truncation if both round's are.
7531     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7532                    N0.getNode()->getConstantOperandVal(1) == 1;
7533     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7534                        DAG.getIntPtrConstant(IsTrunc));
7535   }
7536
7537   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7538   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7539     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7540                               N0.getOperand(0), N1);
7541     AddToWorklist(Tmp.getNode());
7542     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7543                        Tmp, N0.getOperand(1));
7544   }
7545
7546   return SDValue();
7547 }
7548
7549 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7550   SDValue N0 = N->getOperand(0);
7551   EVT VT = N->getValueType(0);
7552   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7553   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7554
7555   // fold (fp_round_inreg c1fp) -> c1fp
7556   if (N0CFP && isTypeLegal(EVT)) {
7557     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7558     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7559   }
7560
7561   return SDValue();
7562 }
7563
7564 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7565   SDValue N0 = N->getOperand(0);
7566   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7567   EVT VT = N->getValueType(0);
7568
7569   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7570   if (N->hasOneUse() &&
7571       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7572     return SDValue();
7573
7574   // fold (fp_extend c1fp) -> c1fp
7575   if (N0CFP)
7576     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7577
7578   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7579   // value of X.
7580   if (N0.getOpcode() == ISD::FP_ROUND
7581       && N0.getNode()->getConstantOperandVal(1) == 1) {
7582     SDValue In = N0.getOperand(0);
7583     if (In.getValueType() == VT) return In;
7584     if (VT.bitsLT(In.getValueType()))
7585       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7586                          In, N0.getOperand(1));
7587     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7588   }
7589
7590   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7591   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7592        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7593     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7594     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7595                                      LN0->getChain(),
7596                                      LN0->getBasePtr(), N0.getValueType(),
7597                                      LN0->getMemOperand());
7598     CombineTo(N, ExtLoad);
7599     CombineTo(N0.getNode(),
7600               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7601                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7602               ExtLoad.getValue(1));
7603     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7604   }
7605
7606   return SDValue();
7607 }
7608
7609 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7610   SDValue N0 = N->getOperand(0);
7611   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7612   EVT VT = N->getValueType(0);
7613
7614   // fold (fceil c1) -> fceil(c1)
7615   if (N0CFP)
7616     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7617
7618   return SDValue();
7619 }
7620
7621 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7622   SDValue N0 = N->getOperand(0);
7623   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7624   EVT VT = N->getValueType(0);
7625
7626   // fold (ftrunc c1) -> ftrunc(c1)
7627   if (N0CFP)
7628     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7629
7630   return SDValue();
7631 }
7632
7633 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7634   SDValue N0 = N->getOperand(0);
7635   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7636   EVT VT = N->getValueType(0);
7637
7638   // fold (ffloor c1) -> ffloor(c1)
7639   if (N0CFP)
7640     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7641
7642   return SDValue();
7643 }
7644
7645 // FIXME: FNEG and FABS have a lot in common; refactor.
7646 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7647   SDValue N0 = N->getOperand(0);
7648   EVT VT = N->getValueType(0);
7649
7650   if (VT.isVector()) {
7651     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7652     if (FoldedVOp.getNode()) return FoldedVOp;
7653   }
7654
7655   // Constant fold FNEG.
7656   if (isa<ConstantFPSDNode>(N0))
7657     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7658
7659   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7660                          &DAG.getTarget().Options))
7661     return GetNegatedExpression(N0, DAG, LegalOperations);
7662
7663   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7664   // constant pool values.
7665   if (!TLI.isFNegFree(VT) &&
7666       N0.getOpcode() == ISD::BITCAST &&
7667       N0.getNode()->hasOneUse()) {
7668     SDValue Int = N0.getOperand(0);
7669     EVT IntVT = Int.getValueType();
7670     if (IntVT.isInteger() && !IntVT.isVector()) {
7671       APInt SignMask;
7672       if (N0.getValueType().isVector()) {
7673         // For a vector, get a mask such as 0x80... per scalar element
7674         // and splat it.
7675         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7676         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7677       } else {
7678         // For a scalar, just generate 0x80...
7679         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7680       }
7681       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7682                         DAG.getConstant(SignMask, IntVT));
7683       AddToWorklist(Int.getNode());
7684       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7685     }
7686   }
7687
7688   // (fneg (fmul c, x)) -> (fmul -c, x)
7689   if (N0.getOpcode() == ISD::FMUL) {
7690     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7691     if (CFP1) {
7692       APFloat CVal = CFP1->getValueAPF();
7693       CVal.changeSign();
7694       if (Level >= AfterLegalizeDAG &&
7695           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7696            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7697         return DAG.getNode(
7698             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7699             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7700     }
7701   }
7702
7703   return SDValue();
7704 }
7705
7706 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7707   SDValue N0 = N->getOperand(0);
7708   SDValue N1 = N->getOperand(1);
7709   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7710   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7711
7712   if (N0CFP && N1CFP) {
7713     const APFloat &C0 = N0CFP->getValueAPF();
7714     const APFloat &C1 = N1CFP->getValueAPF();
7715     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7716   }
7717
7718   if (N0CFP) {
7719     EVT VT = N->getValueType(0);
7720     // Canonicalize to constant on RHS.
7721     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7722   }
7723
7724   return SDValue();
7725 }
7726
7727 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7728   SDValue N0 = N->getOperand(0);
7729   SDValue N1 = N->getOperand(1);
7730   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7731   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7732
7733   if (N0CFP && N1CFP) {
7734     const APFloat &C0 = N0CFP->getValueAPF();
7735     const APFloat &C1 = N1CFP->getValueAPF();
7736     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7737   }
7738
7739   if (N0CFP) {
7740     EVT VT = N->getValueType(0);
7741     // Canonicalize to constant on RHS.
7742     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7743   }
7744
7745   return SDValue();
7746 }
7747
7748 SDValue DAGCombiner::visitFABS(SDNode *N) {
7749   SDValue N0 = N->getOperand(0);
7750   EVT VT = N->getValueType(0);
7751
7752   if (VT.isVector()) {
7753     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7754     if (FoldedVOp.getNode()) return FoldedVOp;
7755   }
7756
7757   // fold (fabs c1) -> fabs(c1)
7758   if (isa<ConstantFPSDNode>(N0))
7759     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7760
7761   // fold (fabs (fabs x)) -> (fabs x)
7762   if (N0.getOpcode() == ISD::FABS)
7763     return N->getOperand(0);
7764
7765   // fold (fabs (fneg x)) -> (fabs x)
7766   // fold (fabs (fcopysign x, y)) -> (fabs x)
7767   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7768     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7769
7770   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7771   // constant pool values.
7772   if (!TLI.isFAbsFree(VT) &&
7773       N0.getOpcode() == ISD::BITCAST &&
7774       N0.getNode()->hasOneUse()) {
7775     SDValue Int = N0.getOperand(0);
7776     EVT IntVT = Int.getValueType();
7777     if (IntVT.isInteger() && !IntVT.isVector()) {
7778       APInt SignMask;
7779       if (N0.getValueType().isVector()) {
7780         // For a vector, get a mask such as 0x7f... per scalar element
7781         // and splat it.
7782         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7783         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7784       } else {
7785         // For a scalar, just generate 0x7f...
7786         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7787       }
7788       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7789                         DAG.getConstant(SignMask, IntVT));
7790       AddToWorklist(Int.getNode());
7791       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7792     }
7793   }
7794
7795   return SDValue();
7796 }
7797
7798 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7799   SDValue Chain = N->getOperand(0);
7800   SDValue N1 = N->getOperand(1);
7801   SDValue N2 = N->getOperand(2);
7802
7803   // If N is a constant we could fold this into a fallthrough or unconditional
7804   // branch. However that doesn't happen very often in normal code, because
7805   // Instcombine/SimplifyCFG should have handled the available opportunities.
7806   // If we did this folding here, it would be necessary to update the
7807   // MachineBasicBlock CFG, which is awkward.
7808
7809   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7810   // on the target.
7811   if (N1.getOpcode() == ISD::SETCC &&
7812       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7813                                    N1.getOperand(0).getValueType())) {
7814     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7815                        Chain, N1.getOperand(2),
7816                        N1.getOperand(0), N1.getOperand(1), N2);
7817   }
7818
7819   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7820       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7821        (N1.getOperand(0).hasOneUse() &&
7822         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7823     SDNode *Trunc = nullptr;
7824     if (N1.getOpcode() == ISD::TRUNCATE) {
7825       // Look pass the truncate.
7826       Trunc = N1.getNode();
7827       N1 = N1.getOperand(0);
7828     }
7829
7830     // Match this pattern so that we can generate simpler code:
7831     //
7832     //   %a = ...
7833     //   %b = and i32 %a, 2
7834     //   %c = srl i32 %b, 1
7835     //   brcond i32 %c ...
7836     //
7837     // into
7838     //
7839     //   %a = ...
7840     //   %b = and i32 %a, 2
7841     //   %c = setcc eq %b, 0
7842     //   brcond %c ...
7843     //
7844     // This applies only when the AND constant value has one bit set and the
7845     // SRL constant is equal to the log2 of the AND constant. The back-end is
7846     // smart enough to convert the result into a TEST/JMP sequence.
7847     SDValue Op0 = N1.getOperand(0);
7848     SDValue Op1 = N1.getOperand(1);
7849
7850     if (Op0.getOpcode() == ISD::AND &&
7851         Op1.getOpcode() == ISD::Constant) {
7852       SDValue AndOp1 = Op0.getOperand(1);
7853
7854       if (AndOp1.getOpcode() == ISD::Constant) {
7855         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7856
7857         if (AndConst.isPowerOf2() &&
7858             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7859           SDValue SetCC =
7860             DAG.getSetCC(SDLoc(N),
7861                          getSetCCResultType(Op0.getValueType()),
7862                          Op0, DAG.getConstant(0, Op0.getValueType()),
7863                          ISD::SETNE);
7864
7865           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7866                                           MVT::Other, Chain, SetCC, N2);
7867           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7868           // will convert it back to (X & C1) >> C2.
7869           CombineTo(N, NewBRCond, false);
7870           // Truncate is dead.
7871           if (Trunc)
7872             deleteAndRecombine(Trunc);
7873           // Replace the uses of SRL with SETCC
7874           WorklistRemover DeadNodes(*this);
7875           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7876           deleteAndRecombine(N1.getNode());
7877           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7878         }
7879       }
7880     }
7881
7882     if (Trunc)
7883       // Restore N1 if the above transformation doesn't match.
7884       N1 = N->getOperand(1);
7885   }
7886
7887   // Transform br(xor(x, y)) -> br(x != y)
7888   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7889   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7890     SDNode *TheXor = N1.getNode();
7891     SDValue Op0 = TheXor->getOperand(0);
7892     SDValue Op1 = TheXor->getOperand(1);
7893     if (Op0.getOpcode() == Op1.getOpcode()) {
7894       // Avoid missing important xor optimizations.
7895       SDValue Tmp = visitXOR(TheXor);
7896       if (Tmp.getNode()) {
7897         if (Tmp.getNode() != TheXor) {
7898           DEBUG(dbgs() << "\nReplacing.8 ";
7899                 TheXor->dump(&DAG);
7900                 dbgs() << "\nWith: ";
7901                 Tmp.getNode()->dump(&DAG);
7902                 dbgs() << '\n');
7903           WorklistRemover DeadNodes(*this);
7904           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7905           deleteAndRecombine(TheXor);
7906           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7907                              MVT::Other, Chain, Tmp, N2);
7908         }
7909
7910         // visitXOR has changed XOR's operands or replaced the XOR completely,
7911         // bail out.
7912         return SDValue(N, 0);
7913       }
7914     }
7915
7916     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7917       bool Equal = false;
7918       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7919         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7920             Op0.getOpcode() == ISD::XOR) {
7921           TheXor = Op0.getNode();
7922           Equal = true;
7923         }
7924
7925       EVT SetCCVT = N1.getValueType();
7926       if (LegalTypes)
7927         SetCCVT = getSetCCResultType(SetCCVT);
7928       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7929                                    SetCCVT,
7930                                    Op0, Op1,
7931                                    Equal ? ISD::SETEQ : ISD::SETNE);
7932       // Replace the uses of XOR with SETCC
7933       WorklistRemover DeadNodes(*this);
7934       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7935       deleteAndRecombine(N1.getNode());
7936       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7937                          MVT::Other, Chain, SetCC, N2);
7938     }
7939   }
7940
7941   return SDValue();
7942 }
7943
7944 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7945 //
7946 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7947   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7948   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7949
7950   // If N is a constant we could fold this into a fallthrough or unconditional
7951   // branch. However that doesn't happen very often in normal code, because
7952   // Instcombine/SimplifyCFG should have handled the available opportunities.
7953   // If we did this folding here, it would be necessary to update the
7954   // MachineBasicBlock CFG, which is awkward.
7955
7956   // Use SimplifySetCC to simplify SETCC's.
7957   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7958                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7959                                false);
7960   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7961
7962   // fold to a simpler setcc
7963   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7964     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7965                        N->getOperand(0), Simp.getOperand(2),
7966                        Simp.getOperand(0), Simp.getOperand(1),
7967                        N->getOperand(4));
7968
7969   return SDValue();
7970 }
7971
7972 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7973 /// and that N may be folded in the load / store addressing mode.
7974 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7975                                     SelectionDAG &DAG,
7976                                     const TargetLowering &TLI) {
7977   EVT VT;
7978   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7979     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7980       return false;
7981     VT = Use->getValueType(0);
7982   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7983     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7984       return false;
7985     VT = ST->getValue().getValueType();
7986   } else
7987     return false;
7988
7989   TargetLowering::AddrMode AM;
7990   if (N->getOpcode() == ISD::ADD) {
7991     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7992     if (Offset)
7993       // [reg +/- imm]
7994       AM.BaseOffs = Offset->getSExtValue();
7995     else
7996       // [reg +/- reg]
7997       AM.Scale = 1;
7998   } else if (N->getOpcode() == ISD::SUB) {
7999     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8000     if (Offset)
8001       // [reg +/- imm]
8002       AM.BaseOffs = -Offset->getSExtValue();
8003     else
8004       // [reg +/- reg]
8005       AM.Scale = 1;
8006   } else
8007     return false;
8008
8009   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8010 }
8011
8012 /// Try turning a load/store into a pre-indexed load/store when the base
8013 /// pointer is an add or subtract and it has other uses besides the load/store.
8014 /// After the transformation, the new indexed load/store has effectively folded
8015 /// the add/subtract in and all of its other uses are redirected to the
8016 /// new load/store.
8017 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8018   if (Level < AfterLegalizeDAG)
8019     return false;
8020
8021   bool isLoad = true;
8022   SDValue Ptr;
8023   EVT VT;
8024   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8025     if (LD->isIndexed())
8026       return false;
8027     VT = LD->getMemoryVT();
8028     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8029         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8030       return false;
8031     Ptr = LD->getBasePtr();
8032   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8033     if (ST->isIndexed())
8034       return false;
8035     VT = ST->getMemoryVT();
8036     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8037         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8038       return false;
8039     Ptr = ST->getBasePtr();
8040     isLoad = false;
8041   } else {
8042     return false;
8043   }
8044
8045   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8046   // out.  There is no reason to make this a preinc/predec.
8047   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8048       Ptr.getNode()->hasOneUse())
8049     return false;
8050
8051   // Ask the target to do addressing mode selection.
8052   SDValue BasePtr;
8053   SDValue Offset;
8054   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8055   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8056     return false;
8057
8058   // Backends without true r+i pre-indexed forms may need to pass a
8059   // constant base with a variable offset so that constant coercion
8060   // will work with the patterns in canonical form.
8061   bool Swapped = false;
8062   if (isa<ConstantSDNode>(BasePtr)) {
8063     std::swap(BasePtr, Offset);
8064     Swapped = true;
8065   }
8066
8067   // Don't create a indexed load / store with zero offset.
8068   if (isa<ConstantSDNode>(Offset) &&
8069       cast<ConstantSDNode>(Offset)->isNullValue())
8070     return false;
8071
8072   // Try turning it into a pre-indexed load / store except when:
8073   // 1) The new base ptr is a frame index.
8074   // 2) If N is a store and the new base ptr is either the same as or is a
8075   //    predecessor of the value being stored.
8076   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8077   //    that would create a cycle.
8078   // 4) All uses are load / store ops that use it as old base ptr.
8079
8080   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8081   // (plus the implicit offset) to a register to preinc anyway.
8082   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8083     return false;
8084
8085   // Check #2.
8086   if (!isLoad) {
8087     SDValue Val = cast<StoreSDNode>(N)->getValue();
8088     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8089       return false;
8090   }
8091
8092   // If the offset is a constant, there may be other adds of constants that
8093   // can be folded with this one. We should do this to avoid having to keep
8094   // a copy of the original base pointer.
8095   SmallVector<SDNode *, 16> OtherUses;
8096   if (isa<ConstantSDNode>(Offset))
8097     for (SDNode *Use : BasePtr.getNode()->uses()) {
8098       if (Use == Ptr.getNode())
8099         continue;
8100
8101       if (Use->isPredecessorOf(N))
8102         continue;
8103
8104       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8105         OtherUses.clear();
8106         break;
8107       }
8108
8109       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8110       if (Op1.getNode() == BasePtr.getNode())
8111         std::swap(Op0, Op1);
8112       assert(Op0.getNode() == BasePtr.getNode() &&
8113              "Use of ADD/SUB but not an operand");
8114
8115       if (!isa<ConstantSDNode>(Op1)) {
8116         OtherUses.clear();
8117         break;
8118       }
8119
8120       // FIXME: In some cases, we can be smarter about this.
8121       if (Op1.getValueType() != Offset.getValueType()) {
8122         OtherUses.clear();
8123         break;
8124       }
8125
8126       OtherUses.push_back(Use);
8127     }
8128
8129   if (Swapped)
8130     std::swap(BasePtr, Offset);
8131
8132   // Now check for #3 and #4.
8133   bool RealUse = false;
8134
8135   // Caches for hasPredecessorHelper
8136   SmallPtrSet<const SDNode *, 32> Visited;
8137   SmallVector<const SDNode *, 16> Worklist;
8138
8139   for (SDNode *Use : Ptr.getNode()->uses()) {
8140     if (Use == N)
8141       continue;
8142     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8143       return false;
8144
8145     // If Ptr may be folded in addressing mode of other use, then it's
8146     // not profitable to do this transformation.
8147     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8148       RealUse = true;
8149   }
8150
8151   if (!RealUse)
8152     return false;
8153
8154   SDValue Result;
8155   if (isLoad)
8156     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8157                                 BasePtr, Offset, AM);
8158   else
8159     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8160                                  BasePtr, Offset, AM);
8161   ++PreIndexedNodes;
8162   ++NodesCombined;
8163   DEBUG(dbgs() << "\nReplacing.4 ";
8164         N->dump(&DAG);
8165         dbgs() << "\nWith: ";
8166         Result.getNode()->dump(&DAG);
8167         dbgs() << '\n');
8168   WorklistRemover DeadNodes(*this);
8169   if (isLoad) {
8170     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8171     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8172   } else {
8173     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8174   }
8175
8176   // Finally, since the node is now dead, remove it from the graph.
8177   deleteAndRecombine(N);
8178
8179   if (Swapped)
8180     std::swap(BasePtr, Offset);
8181
8182   // Replace other uses of BasePtr that can be updated to use Ptr
8183   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8184     unsigned OffsetIdx = 1;
8185     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8186       OffsetIdx = 0;
8187     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8188            BasePtr.getNode() && "Expected BasePtr operand");
8189
8190     // We need to replace ptr0 in the following expression:
8191     //   x0 * offset0 + y0 * ptr0 = t0
8192     // knowing that
8193     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8194     //
8195     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8196     // indexed load/store and the expresion that needs to be re-written.
8197     //
8198     // Therefore, we have:
8199     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8200
8201     ConstantSDNode *CN =
8202       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8203     int X0, X1, Y0, Y1;
8204     APInt Offset0 = CN->getAPIntValue();
8205     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8206
8207     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8208     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8209     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8210     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8211
8212     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8213
8214     APInt CNV = Offset0;
8215     if (X0 < 0) CNV = -CNV;
8216     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8217     else CNV = CNV - Offset1;
8218
8219     // We can now generate the new expression.
8220     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8221     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8222
8223     SDValue NewUse = DAG.getNode(Opcode,
8224                                  SDLoc(OtherUses[i]),
8225                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8226     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8227     deleteAndRecombine(OtherUses[i]);
8228   }
8229
8230   // Replace the uses of Ptr with uses of the updated base value.
8231   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8232   deleteAndRecombine(Ptr.getNode());
8233
8234   return true;
8235 }
8236
8237 /// Try to combine a load/store with a add/sub of the base pointer node into a
8238 /// post-indexed load/store. The transformation folded the add/subtract into the
8239 /// new indexed load/store effectively and all of its uses are redirected to the
8240 /// new load/store.
8241 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8242   if (Level < AfterLegalizeDAG)
8243     return false;
8244
8245   bool isLoad = true;
8246   SDValue Ptr;
8247   EVT VT;
8248   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8249     if (LD->isIndexed())
8250       return false;
8251     VT = LD->getMemoryVT();
8252     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8253         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8254       return false;
8255     Ptr = LD->getBasePtr();
8256   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8257     if (ST->isIndexed())
8258       return false;
8259     VT = ST->getMemoryVT();
8260     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8261         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8262       return false;
8263     Ptr = ST->getBasePtr();
8264     isLoad = false;
8265   } else {
8266     return false;
8267   }
8268
8269   if (Ptr.getNode()->hasOneUse())
8270     return false;
8271
8272   for (SDNode *Op : Ptr.getNode()->uses()) {
8273     if (Op == N ||
8274         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8275       continue;
8276
8277     SDValue BasePtr;
8278     SDValue Offset;
8279     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8280     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8281       // Don't create a indexed load / store with zero offset.
8282       if (isa<ConstantSDNode>(Offset) &&
8283           cast<ConstantSDNode>(Offset)->isNullValue())
8284         continue;
8285
8286       // Try turning it into a post-indexed load / store except when
8287       // 1) All uses are load / store ops that use it as base ptr (and
8288       //    it may be folded as addressing mmode).
8289       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8290       //    nor a successor of N. Otherwise, if Op is folded that would
8291       //    create a cycle.
8292
8293       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8294         continue;
8295
8296       // Check for #1.
8297       bool TryNext = false;
8298       for (SDNode *Use : BasePtr.getNode()->uses()) {
8299         if (Use == Ptr.getNode())
8300           continue;
8301
8302         // If all the uses are load / store addresses, then don't do the
8303         // transformation.
8304         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8305           bool RealUse = false;
8306           for (SDNode *UseUse : Use->uses()) {
8307             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8308               RealUse = true;
8309           }
8310
8311           if (!RealUse) {
8312             TryNext = true;
8313             break;
8314           }
8315         }
8316       }
8317
8318       if (TryNext)
8319         continue;
8320
8321       // Check for #2
8322       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8323         SDValue Result = isLoad
8324           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8325                                BasePtr, Offset, AM)
8326           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8327                                 BasePtr, Offset, AM);
8328         ++PostIndexedNodes;
8329         ++NodesCombined;
8330         DEBUG(dbgs() << "\nReplacing.5 ";
8331               N->dump(&DAG);
8332               dbgs() << "\nWith: ";
8333               Result.getNode()->dump(&DAG);
8334               dbgs() << '\n');
8335         WorklistRemover DeadNodes(*this);
8336         if (isLoad) {
8337           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8338           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8339         } else {
8340           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8341         }
8342
8343         // Finally, since the node is now dead, remove it from the graph.
8344         deleteAndRecombine(N);
8345
8346         // Replace the uses of Use with uses of the updated base value.
8347         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8348                                       Result.getValue(isLoad ? 1 : 0));
8349         deleteAndRecombine(Op);
8350         return true;
8351       }
8352     }
8353   }
8354
8355   return false;
8356 }
8357
8358 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8359 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8360   ISD::MemIndexedMode AM = LD->getAddressingMode();
8361   assert(AM != ISD::UNINDEXED);
8362   SDValue BP = LD->getOperand(1);
8363   SDValue Inc = LD->getOperand(2);
8364
8365   // Some backends use TargetConstants for load offsets, but don't expect
8366   // TargetConstants in general ADD nodes. We can convert these constants into
8367   // regular Constants (if the constant is not opaque).
8368   assert((Inc.getOpcode() != ISD::TargetConstant ||
8369           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8370          "Cannot split out indexing using opaque target constants");
8371   if (Inc.getOpcode() == ISD::TargetConstant) {
8372     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8373     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8374                           ConstInc->getValueType(0));
8375   }
8376
8377   unsigned Opc =
8378       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8379   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8380 }
8381
8382 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8383   LoadSDNode *LD  = cast<LoadSDNode>(N);
8384   SDValue Chain = LD->getChain();
8385   SDValue Ptr   = LD->getBasePtr();
8386
8387   // If load is not volatile and there are no uses of the loaded value (and
8388   // the updated indexed value in case of indexed loads), change uses of the
8389   // chain value into uses of the chain input (i.e. delete the dead load).
8390   if (!LD->isVolatile()) {
8391     if (N->getValueType(1) == MVT::Other) {
8392       // Unindexed loads.
8393       if (!N->hasAnyUseOfValue(0)) {
8394         // It's not safe to use the two value CombineTo variant here. e.g.
8395         // v1, chain2 = load chain1, loc
8396         // v2, chain3 = load chain2, loc
8397         // v3         = add v2, c
8398         // Now we replace use of chain2 with chain1.  This makes the second load
8399         // isomorphic to the one we are deleting, and thus makes this load live.
8400         DEBUG(dbgs() << "\nReplacing.6 ";
8401               N->dump(&DAG);
8402               dbgs() << "\nWith chain: ";
8403               Chain.getNode()->dump(&DAG);
8404               dbgs() << "\n");
8405         WorklistRemover DeadNodes(*this);
8406         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8407
8408         if (N->use_empty())
8409           deleteAndRecombine(N);
8410
8411         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8412       }
8413     } else {
8414       // Indexed loads.
8415       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8416
8417       // If this load has an opaque TargetConstant offset, then we cannot split
8418       // the indexing into an add/sub directly (that TargetConstant may not be
8419       // valid for a different type of node, and we cannot convert an opaque
8420       // target constant into a regular constant).
8421       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8422                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8423
8424       if (!N->hasAnyUseOfValue(0) &&
8425           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8426         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8427         SDValue Index;
8428         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8429           Index = SplitIndexingFromLoad(LD);
8430           // Try to fold the base pointer arithmetic into subsequent loads and
8431           // stores.
8432           AddUsersToWorklist(N);
8433         } else
8434           Index = DAG.getUNDEF(N->getValueType(1));
8435         DEBUG(dbgs() << "\nReplacing.7 ";
8436               N->dump(&DAG);
8437               dbgs() << "\nWith: ";
8438               Undef.getNode()->dump(&DAG);
8439               dbgs() << " and 2 other values\n");
8440         WorklistRemover DeadNodes(*this);
8441         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8442         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8443         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8444         deleteAndRecombine(N);
8445         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8446       }
8447     }
8448   }
8449
8450   // If this load is directly stored, replace the load value with the stored
8451   // value.
8452   // TODO: Handle store large -> read small portion.
8453   // TODO: Handle TRUNCSTORE/LOADEXT
8454   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8455     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8456       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8457       if (PrevST->getBasePtr() == Ptr &&
8458           PrevST->getValue().getValueType() == N->getValueType(0))
8459       return CombineTo(N, Chain.getOperand(1), Chain);
8460     }
8461   }
8462
8463   // Try to infer better alignment information than the load already has.
8464   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8465     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8466       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8467         SDValue NewLoad =
8468                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8469                               LD->getValueType(0),
8470                               Chain, Ptr, LD->getPointerInfo(),
8471                               LD->getMemoryVT(),
8472                               LD->isVolatile(), LD->isNonTemporal(),
8473                               LD->isInvariant(), Align, LD->getAAInfo());
8474         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8475       }
8476     }
8477   }
8478
8479   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8480                                                   : DAG.getSubtarget().useAA();
8481 #ifndef NDEBUG
8482   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8483       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8484     UseAA = false;
8485 #endif
8486   if (UseAA && LD->isUnindexed()) {
8487     // Walk up chain skipping non-aliasing memory nodes.
8488     SDValue BetterChain = FindBetterChain(N, Chain);
8489
8490     // If there is a better chain.
8491     if (Chain != BetterChain) {
8492       SDValue ReplLoad;
8493
8494       // Replace the chain to void dependency.
8495       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8496         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8497                                BetterChain, Ptr, LD->getMemOperand());
8498       } else {
8499         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8500                                   LD->getValueType(0),
8501                                   BetterChain, Ptr, LD->getMemoryVT(),
8502                                   LD->getMemOperand());
8503       }
8504
8505       // Create token factor to keep old chain connected.
8506       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8507                                   MVT::Other, Chain, ReplLoad.getValue(1));
8508
8509       // Make sure the new and old chains are cleaned up.
8510       AddToWorklist(Token.getNode());
8511
8512       // Replace uses with load result and token factor. Don't add users
8513       // to work list.
8514       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8515     }
8516   }
8517
8518   // Try transforming N to an indexed load.
8519   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8520     return SDValue(N, 0);
8521
8522   // Try to slice up N to more direct loads if the slices are mapped to
8523   // different register banks or pairing can take place.
8524   if (SliceUpLoad(N))
8525     return SDValue(N, 0);
8526
8527   return SDValue();
8528 }
8529
8530 namespace {
8531 /// \brief Helper structure used to slice a load in smaller loads.
8532 /// Basically a slice is obtained from the following sequence:
8533 /// Origin = load Ty1, Base
8534 /// Shift = srl Ty1 Origin, CstTy Amount
8535 /// Inst = trunc Shift to Ty2
8536 ///
8537 /// Then, it will be rewriten into:
8538 /// Slice = load SliceTy, Base + SliceOffset
8539 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8540 ///
8541 /// SliceTy is deduced from the number of bits that are actually used to
8542 /// build Inst.
8543 struct LoadedSlice {
8544   /// \brief Helper structure used to compute the cost of a slice.
8545   struct Cost {
8546     /// Are we optimizing for code size.
8547     bool ForCodeSize;
8548     /// Various cost.
8549     unsigned Loads;
8550     unsigned Truncates;
8551     unsigned CrossRegisterBanksCopies;
8552     unsigned ZExts;
8553     unsigned Shift;
8554
8555     Cost(bool ForCodeSize = false)
8556         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8557           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8558
8559     /// \brief Get the cost of one isolated slice.
8560     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8561         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8562           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8563       EVT TruncType = LS.Inst->getValueType(0);
8564       EVT LoadedType = LS.getLoadedType();
8565       if (TruncType != LoadedType &&
8566           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8567         ZExts = 1;
8568     }
8569
8570     /// \brief Account for slicing gain in the current cost.
8571     /// Slicing provide a few gains like removing a shift or a
8572     /// truncate. This method allows to grow the cost of the original
8573     /// load with the gain from this slice.
8574     void addSliceGain(const LoadedSlice &LS) {
8575       // Each slice saves a truncate.
8576       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8577       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8578                               LS.Inst->getOperand(0).getValueType()))
8579         ++Truncates;
8580       // If there is a shift amount, this slice gets rid of it.
8581       if (LS.Shift)
8582         ++Shift;
8583       // If this slice can merge a cross register bank copy, account for it.
8584       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8585         ++CrossRegisterBanksCopies;
8586     }
8587
8588     Cost &operator+=(const Cost &RHS) {
8589       Loads += RHS.Loads;
8590       Truncates += RHS.Truncates;
8591       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8592       ZExts += RHS.ZExts;
8593       Shift += RHS.Shift;
8594       return *this;
8595     }
8596
8597     bool operator==(const Cost &RHS) const {
8598       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8599              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8600              ZExts == RHS.ZExts && Shift == RHS.Shift;
8601     }
8602
8603     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8604
8605     bool operator<(const Cost &RHS) const {
8606       // Assume cross register banks copies are as expensive as loads.
8607       // FIXME: Do we want some more target hooks?
8608       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8609       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8610       // Unless we are optimizing for code size, consider the
8611       // expensive operation first.
8612       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8613         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8614       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8615              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8616     }
8617
8618     bool operator>(const Cost &RHS) const { return RHS < *this; }
8619
8620     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8621
8622     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8623   };
8624   // The last instruction that represent the slice. This should be a
8625   // truncate instruction.
8626   SDNode *Inst;
8627   // The original load instruction.
8628   LoadSDNode *Origin;
8629   // The right shift amount in bits from the original load.
8630   unsigned Shift;
8631   // The DAG from which Origin came from.
8632   // This is used to get some contextual information about legal types, etc.
8633   SelectionDAG *DAG;
8634
8635   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8636               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8637       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8638
8639   LoadedSlice(const LoadedSlice &LS)
8640       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8641
8642   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8643   /// \return Result is \p BitWidth and has used bits set to 1 and
8644   ///         not used bits set to 0.
8645   APInt getUsedBits() const {
8646     // Reproduce the trunc(lshr) sequence:
8647     // - Start from the truncated value.
8648     // - Zero extend to the desired bit width.
8649     // - Shift left.
8650     assert(Origin && "No original load to compare against.");
8651     unsigned BitWidth = Origin->getValueSizeInBits(0);
8652     assert(Inst && "This slice is not bound to an instruction");
8653     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8654            "Extracted slice is bigger than the whole type!");
8655     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8656     UsedBits.setAllBits();
8657     UsedBits = UsedBits.zext(BitWidth);
8658     UsedBits <<= Shift;
8659     return UsedBits;
8660   }
8661
8662   /// \brief Get the size of the slice to be loaded in bytes.
8663   unsigned getLoadedSize() const {
8664     unsigned SliceSize = getUsedBits().countPopulation();
8665     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8666     return SliceSize / 8;
8667   }
8668
8669   /// \brief Get the type that will be loaded for this slice.
8670   /// Note: This may not be the final type for the slice.
8671   EVT getLoadedType() const {
8672     assert(DAG && "Missing context");
8673     LLVMContext &Ctxt = *DAG->getContext();
8674     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8675   }
8676
8677   /// \brief Get the alignment of the load used for this slice.
8678   unsigned getAlignment() const {
8679     unsigned Alignment = Origin->getAlignment();
8680     unsigned Offset = getOffsetFromBase();
8681     if (Offset != 0)
8682       Alignment = MinAlign(Alignment, Alignment + Offset);
8683     return Alignment;
8684   }
8685
8686   /// \brief Check if this slice can be rewritten with legal operations.
8687   bool isLegal() const {
8688     // An invalid slice is not legal.
8689     if (!Origin || !Inst || !DAG)
8690       return false;
8691
8692     // Offsets are for indexed load only, we do not handle that.
8693     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8694       return false;
8695
8696     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8697
8698     // Check that the type is legal.
8699     EVT SliceType = getLoadedType();
8700     if (!TLI.isTypeLegal(SliceType))
8701       return false;
8702
8703     // Check that the load is legal for this type.
8704     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8705       return false;
8706
8707     // Check that the offset can be computed.
8708     // 1. Check its type.
8709     EVT PtrType = Origin->getBasePtr().getValueType();
8710     if (PtrType == MVT::Untyped || PtrType.isExtended())
8711       return false;
8712
8713     // 2. Check that it fits in the immediate.
8714     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8715       return false;
8716
8717     // 3. Check that the computation is legal.
8718     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8719       return false;
8720
8721     // Check that the zext is legal if it needs one.
8722     EVT TruncateType = Inst->getValueType(0);
8723     if (TruncateType != SliceType &&
8724         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8725       return false;
8726
8727     return true;
8728   }
8729
8730   /// \brief Get the offset in bytes of this slice in the original chunk of
8731   /// bits.
8732   /// \pre DAG != nullptr.
8733   uint64_t getOffsetFromBase() const {
8734     assert(DAG && "Missing context.");
8735     bool IsBigEndian =
8736         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8737     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8738     uint64_t Offset = Shift / 8;
8739     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8740     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8741            "The size of the original loaded type is not a multiple of a"
8742            " byte.");
8743     // If Offset is bigger than TySizeInBytes, it means we are loading all
8744     // zeros. This should have been optimized before in the process.
8745     assert(TySizeInBytes > Offset &&
8746            "Invalid shift amount for given loaded size");
8747     if (IsBigEndian)
8748       Offset = TySizeInBytes - Offset - getLoadedSize();
8749     return Offset;
8750   }
8751
8752   /// \brief Generate the sequence of instructions to load the slice
8753   /// represented by this object and redirect the uses of this slice to
8754   /// this new sequence of instructions.
8755   /// \pre this->Inst && this->Origin are valid Instructions and this
8756   /// object passed the legal check: LoadedSlice::isLegal returned true.
8757   /// \return The last instruction of the sequence used to load the slice.
8758   SDValue loadSlice() const {
8759     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8760     const SDValue &OldBaseAddr = Origin->getBasePtr();
8761     SDValue BaseAddr = OldBaseAddr;
8762     // Get the offset in that chunk of bytes w.r.t. the endianess.
8763     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8764     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8765     if (Offset) {
8766       // BaseAddr = BaseAddr + Offset.
8767       EVT ArithType = BaseAddr.getValueType();
8768       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8769                               DAG->getConstant(Offset, ArithType));
8770     }
8771
8772     // Create the type of the loaded slice according to its size.
8773     EVT SliceType = getLoadedType();
8774
8775     // Create the load for the slice.
8776     SDValue LastInst = DAG->getLoad(
8777         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8778         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8779         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8780     // If the final type is not the same as the loaded type, this means that
8781     // we have to pad with zero. Create a zero extend for that.
8782     EVT FinalType = Inst->getValueType(0);
8783     if (SliceType != FinalType)
8784       LastInst =
8785           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8786     return LastInst;
8787   }
8788
8789   /// \brief Check if this slice can be merged with an expensive cross register
8790   /// bank copy. E.g.,
8791   /// i = load i32
8792   /// f = bitcast i32 i to float
8793   bool canMergeExpensiveCrossRegisterBankCopy() const {
8794     if (!Inst || !Inst->hasOneUse())
8795       return false;
8796     SDNode *Use = *Inst->use_begin();
8797     if (Use->getOpcode() != ISD::BITCAST)
8798       return false;
8799     assert(DAG && "Missing context");
8800     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8801     EVT ResVT = Use->getValueType(0);
8802     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8803     const TargetRegisterClass *ArgRC =
8804         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8805     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8806       return false;
8807
8808     // At this point, we know that we perform a cross-register-bank copy.
8809     // Check if it is expensive.
8810     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8811     // Assume bitcasts are cheap, unless both register classes do not
8812     // explicitly share a common sub class.
8813     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8814       return false;
8815
8816     // Check if it will be merged with the load.
8817     // 1. Check the alignment constraint.
8818     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8819         ResVT.getTypeForEVT(*DAG->getContext()));
8820
8821     if (RequiredAlignment > getAlignment())
8822       return false;
8823
8824     // 2. Check that the load is a legal operation for that type.
8825     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8826       return false;
8827
8828     // 3. Check that we do not have a zext in the way.
8829     if (Inst->getValueType(0) != getLoadedType())
8830       return false;
8831
8832     return true;
8833   }
8834 };
8835 }
8836
8837 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8838 /// \p UsedBits looks like 0..0 1..1 0..0.
8839 static bool areUsedBitsDense(const APInt &UsedBits) {
8840   // If all the bits are one, this is dense!
8841   if (UsedBits.isAllOnesValue())
8842     return true;
8843
8844   // Get rid of the unused bits on the right.
8845   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8846   // Get rid of the unused bits on the left.
8847   if (NarrowedUsedBits.countLeadingZeros())
8848     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8849   // Check that the chunk of bits is completely used.
8850   return NarrowedUsedBits.isAllOnesValue();
8851 }
8852
8853 /// \brief Check whether or not \p First and \p Second are next to each other
8854 /// in memory. This means that there is no hole between the bits loaded
8855 /// by \p First and the bits loaded by \p Second.
8856 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8857                                      const LoadedSlice &Second) {
8858   assert(First.Origin == Second.Origin && First.Origin &&
8859          "Unable to match different memory origins.");
8860   APInt UsedBits = First.getUsedBits();
8861   assert((UsedBits & Second.getUsedBits()) == 0 &&
8862          "Slices are not supposed to overlap.");
8863   UsedBits |= Second.getUsedBits();
8864   return areUsedBitsDense(UsedBits);
8865 }
8866
8867 /// \brief Adjust the \p GlobalLSCost according to the target
8868 /// paring capabilities and the layout of the slices.
8869 /// \pre \p GlobalLSCost should account for at least as many loads as
8870 /// there is in the slices in \p LoadedSlices.
8871 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8872                                  LoadedSlice::Cost &GlobalLSCost) {
8873   unsigned NumberOfSlices = LoadedSlices.size();
8874   // If there is less than 2 elements, no pairing is possible.
8875   if (NumberOfSlices < 2)
8876     return;
8877
8878   // Sort the slices so that elements that are likely to be next to each
8879   // other in memory are next to each other in the list.
8880   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8881             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8882     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8883     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8884   });
8885   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8886   // First (resp. Second) is the first (resp. Second) potentially candidate
8887   // to be placed in a paired load.
8888   const LoadedSlice *First = nullptr;
8889   const LoadedSlice *Second = nullptr;
8890   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8891                 // Set the beginning of the pair.
8892                                                            First = Second) {
8893
8894     Second = &LoadedSlices[CurrSlice];
8895
8896     // If First is NULL, it means we start a new pair.
8897     // Get to the next slice.
8898     if (!First)
8899       continue;
8900
8901     EVT LoadedType = First->getLoadedType();
8902
8903     // If the types of the slices are different, we cannot pair them.
8904     if (LoadedType != Second->getLoadedType())
8905       continue;
8906
8907     // Check if the target supplies paired loads for this type.
8908     unsigned RequiredAlignment = 0;
8909     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8910       // move to the next pair, this type is hopeless.
8911       Second = nullptr;
8912       continue;
8913     }
8914     // Check if we meet the alignment requirement.
8915     if (RequiredAlignment > First->getAlignment())
8916       continue;
8917
8918     // Check that both loads are next to each other in memory.
8919     if (!areSlicesNextToEachOther(*First, *Second))
8920       continue;
8921
8922     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8923     --GlobalLSCost.Loads;
8924     // Move to the next pair.
8925     Second = nullptr;
8926   }
8927 }
8928
8929 /// \brief Check the profitability of all involved LoadedSlice.
8930 /// Currently, it is considered profitable if there is exactly two
8931 /// involved slices (1) which are (2) next to each other in memory, and
8932 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8933 ///
8934 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8935 /// the elements themselves.
8936 ///
8937 /// FIXME: When the cost model will be mature enough, we can relax
8938 /// constraints (1) and (2).
8939 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8940                                 const APInt &UsedBits, bool ForCodeSize) {
8941   unsigned NumberOfSlices = LoadedSlices.size();
8942   if (StressLoadSlicing)
8943     return NumberOfSlices > 1;
8944
8945   // Check (1).
8946   if (NumberOfSlices != 2)
8947     return false;
8948
8949   // Check (2).
8950   if (!areUsedBitsDense(UsedBits))
8951     return false;
8952
8953   // Check (3).
8954   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8955   // The original code has one big load.
8956   OrigCost.Loads = 1;
8957   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8958     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8959     // Accumulate the cost of all the slices.
8960     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8961     GlobalSlicingCost += SliceCost;
8962
8963     // Account as cost in the original configuration the gain obtained
8964     // with the current slices.
8965     OrigCost.addSliceGain(LS);
8966   }
8967
8968   // If the target supports paired load, adjust the cost accordingly.
8969   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8970   return OrigCost > GlobalSlicingCost;
8971 }
8972
8973 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8974 /// operations, split it in the various pieces being extracted.
8975 ///
8976 /// This sort of thing is introduced by SROA.
8977 /// This slicing takes care not to insert overlapping loads.
8978 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8979 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8980   if (Level < AfterLegalizeDAG)
8981     return false;
8982
8983   LoadSDNode *LD = cast<LoadSDNode>(N);
8984   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8985       !LD->getValueType(0).isInteger())
8986     return false;
8987
8988   // Keep track of already used bits to detect overlapping values.
8989   // In that case, we will just abort the transformation.
8990   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8991
8992   SmallVector<LoadedSlice, 4> LoadedSlices;
8993
8994   // Check if this load is used as several smaller chunks of bits.
8995   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8996   // of computation for each trunc.
8997   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8998        UI != UIEnd; ++UI) {
8999     // Skip the uses of the chain.
9000     if (UI.getUse().getResNo() != 0)
9001       continue;
9002
9003     SDNode *User = *UI;
9004     unsigned Shift = 0;
9005
9006     // Check if this is a trunc(lshr).
9007     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9008         isa<ConstantSDNode>(User->getOperand(1))) {
9009       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9010       User = *User->use_begin();
9011     }
9012
9013     // At this point, User is a Truncate, iff we encountered, trunc or
9014     // trunc(lshr).
9015     if (User->getOpcode() != ISD::TRUNCATE)
9016       return false;
9017
9018     // The width of the type must be a power of 2 and greater than 8-bits.
9019     // Otherwise the load cannot be represented in LLVM IR.
9020     // Moreover, if we shifted with a non-8-bits multiple, the slice
9021     // will be across several bytes. We do not support that.
9022     unsigned Width = User->getValueSizeInBits(0);
9023     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9024       return 0;
9025
9026     // Build the slice for this chain of computations.
9027     LoadedSlice LS(User, LD, Shift, &DAG);
9028     APInt CurrentUsedBits = LS.getUsedBits();
9029
9030     // Check if this slice overlaps with another.
9031     if ((CurrentUsedBits & UsedBits) != 0)
9032       return false;
9033     // Update the bits used globally.
9034     UsedBits |= CurrentUsedBits;
9035
9036     // Check if the new slice would be legal.
9037     if (!LS.isLegal())
9038       return false;
9039
9040     // Record the slice.
9041     LoadedSlices.push_back(LS);
9042   }
9043
9044   // Abort slicing if it does not seem to be profitable.
9045   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9046     return false;
9047
9048   ++SlicedLoads;
9049
9050   // Rewrite each chain to use an independent load.
9051   // By construction, each chain can be represented by a unique load.
9052
9053   // Prepare the argument for the new token factor for all the slices.
9054   SmallVector<SDValue, 8> ArgChains;
9055   for (SmallVectorImpl<LoadedSlice>::const_iterator
9056            LSIt = LoadedSlices.begin(),
9057            LSItEnd = LoadedSlices.end();
9058        LSIt != LSItEnd; ++LSIt) {
9059     SDValue SliceInst = LSIt->loadSlice();
9060     CombineTo(LSIt->Inst, SliceInst, true);
9061     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9062       SliceInst = SliceInst.getOperand(0);
9063     assert(SliceInst->getOpcode() == ISD::LOAD &&
9064            "It takes more than a zext to get to the loaded slice!!");
9065     ArgChains.push_back(SliceInst.getValue(1));
9066   }
9067
9068   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9069                               ArgChains);
9070   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9071   return true;
9072 }
9073
9074 /// Check to see if V is (and load (ptr), imm), where the load is having
9075 /// specific bytes cleared out.  If so, return the byte size being masked out
9076 /// and the shift amount.
9077 static std::pair<unsigned, unsigned>
9078 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9079   std::pair<unsigned, unsigned> Result(0, 0);
9080
9081   // Check for the structure we're looking for.
9082   if (V->getOpcode() != ISD::AND ||
9083       !isa<ConstantSDNode>(V->getOperand(1)) ||
9084       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9085     return Result;
9086
9087   // Check the chain and pointer.
9088   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9089   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9090
9091   // The store should be chained directly to the load or be an operand of a
9092   // tokenfactor.
9093   if (LD == Chain.getNode())
9094     ; // ok.
9095   else if (Chain->getOpcode() != ISD::TokenFactor)
9096     return Result; // Fail.
9097   else {
9098     bool isOk = false;
9099     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9100       if (Chain->getOperand(i).getNode() == LD) {
9101         isOk = true;
9102         break;
9103       }
9104     if (!isOk) return Result;
9105   }
9106
9107   // This only handles simple types.
9108   if (V.getValueType() != MVT::i16 &&
9109       V.getValueType() != MVT::i32 &&
9110       V.getValueType() != MVT::i64)
9111     return Result;
9112
9113   // Check the constant mask.  Invert it so that the bits being masked out are
9114   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9115   // follow the sign bit for uniformity.
9116   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9117   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9118   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9119   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9120   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9121   if (NotMaskLZ == 64) return Result;  // All zero mask.
9122
9123   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9124   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9125     return Result;
9126
9127   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9128   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9129     NotMaskLZ -= 64-V.getValueSizeInBits();
9130
9131   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9132   switch (MaskedBytes) {
9133   case 1:
9134   case 2:
9135   case 4: break;
9136   default: return Result; // All one mask, or 5-byte mask.
9137   }
9138
9139   // Verify that the first bit starts at a multiple of mask so that the access
9140   // is aligned the same as the access width.
9141   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9142
9143   Result.first = MaskedBytes;
9144   Result.second = NotMaskTZ/8;
9145   return Result;
9146 }
9147
9148
9149 /// Check to see if IVal is something that provides a value as specified by
9150 /// MaskInfo. If so, replace the specified store with a narrower store of
9151 /// truncated IVal.
9152 static SDNode *
9153 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9154                                 SDValue IVal, StoreSDNode *St,
9155                                 DAGCombiner *DC) {
9156   unsigned NumBytes = MaskInfo.first;
9157   unsigned ByteShift = MaskInfo.second;
9158   SelectionDAG &DAG = DC->getDAG();
9159
9160   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9161   // that uses this.  If not, this is not a replacement.
9162   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9163                                   ByteShift*8, (ByteShift+NumBytes)*8);
9164   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9165
9166   // Check that it is legal on the target to do this.  It is legal if the new
9167   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9168   // legalization.
9169   MVT VT = MVT::getIntegerVT(NumBytes*8);
9170   if (!DC->isTypeLegal(VT))
9171     return nullptr;
9172
9173   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9174   // shifted by ByteShift and truncated down to NumBytes.
9175   if (ByteShift)
9176     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9177                        DAG.getConstant(ByteShift*8,
9178                                     DC->getShiftAmountTy(IVal.getValueType())));
9179
9180   // Figure out the offset for the store and the alignment of the access.
9181   unsigned StOffset;
9182   unsigned NewAlign = St->getAlignment();
9183
9184   if (DAG.getTargetLoweringInfo().isLittleEndian())
9185     StOffset = ByteShift;
9186   else
9187     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9188
9189   SDValue Ptr = St->getBasePtr();
9190   if (StOffset) {
9191     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9192                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9193     NewAlign = MinAlign(NewAlign, StOffset);
9194   }
9195
9196   // Truncate down to the new size.
9197   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9198
9199   ++OpsNarrowed;
9200   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9201                       St->getPointerInfo().getWithOffset(StOffset),
9202                       false, false, NewAlign).getNode();
9203 }
9204
9205
9206 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9207 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9208 /// narrowing the load and store if it would end up being a win for performance
9209 /// or code size.
9210 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9211   StoreSDNode *ST  = cast<StoreSDNode>(N);
9212   if (ST->isVolatile())
9213     return SDValue();
9214
9215   SDValue Chain = ST->getChain();
9216   SDValue Value = ST->getValue();
9217   SDValue Ptr   = ST->getBasePtr();
9218   EVT VT = Value.getValueType();
9219
9220   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9221     return SDValue();
9222
9223   unsigned Opc = Value.getOpcode();
9224
9225   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9226   // is a byte mask indicating a consecutive number of bytes, check to see if
9227   // Y is known to provide just those bytes.  If so, we try to replace the
9228   // load + replace + store sequence with a single (narrower) store, which makes
9229   // the load dead.
9230   if (Opc == ISD::OR) {
9231     std::pair<unsigned, unsigned> MaskedLoad;
9232     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9233     if (MaskedLoad.first)
9234       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9235                                                   Value.getOperand(1), ST,this))
9236         return SDValue(NewST, 0);
9237
9238     // Or is commutative, so try swapping X and Y.
9239     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9240     if (MaskedLoad.first)
9241       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9242                                                   Value.getOperand(0), ST,this))
9243         return SDValue(NewST, 0);
9244   }
9245
9246   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9247       Value.getOperand(1).getOpcode() != ISD::Constant)
9248     return SDValue();
9249
9250   SDValue N0 = Value.getOperand(0);
9251   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9252       Chain == SDValue(N0.getNode(), 1)) {
9253     LoadSDNode *LD = cast<LoadSDNode>(N0);
9254     if (LD->getBasePtr() != Ptr ||
9255         LD->getPointerInfo().getAddrSpace() !=
9256         ST->getPointerInfo().getAddrSpace())
9257       return SDValue();
9258
9259     // Find the type to narrow it the load / op / store to.
9260     SDValue N1 = Value.getOperand(1);
9261     unsigned BitWidth = N1.getValueSizeInBits();
9262     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9263     if (Opc == ISD::AND)
9264       Imm ^= APInt::getAllOnesValue(BitWidth);
9265     if (Imm == 0 || Imm.isAllOnesValue())
9266       return SDValue();
9267     unsigned ShAmt = Imm.countTrailingZeros();
9268     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9269     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9270     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9271     while (NewBW < BitWidth &&
9272            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9273              TLI.isNarrowingProfitable(VT, NewVT))) {
9274       NewBW = NextPowerOf2(NewBW);
9275       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9276     }
9277     if (NewBW >= BitWidth)
9278       return SDValue();
9279
9280     // If the lsb changed does not start at the type bitwidth boundary,
9281     // start at the previous one.
9282     if (ShAmt % NewBW)
9283       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9284     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9285                                    std::min(BitWidth, ShAmt + NewBW));
9286     if ((Imm & Mask) == Imm) {
9287       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9288       if (Opc == ISD::AND)
9289         NewImm ^= APInt::getAllOnesValue(NewBW);
9290       uint64_t PtrOff = ShAmt / 8;
9291       // For big endian targets, we need to adjust the offset to the pointer to
9292       // load the correct bytes.
9293       if (TLI.isBigEndian())
9294         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9295
9296       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9297       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9298       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9299         return SDValue();
9300
9301       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9302                                    Ptr.getValueType(), Ptr,
9303                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9304       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9305                                   LD->getChain(), NewPtr,
9306                                   LD->getPointerInfo().getWithOffset(PtrOff),
9307                                   LD->isVolatile(), LD->isNonTemporal(),
9308                                   LD->isInvariant(), NewAlign,
9309                                   LD->getAAInfo());
9310       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9311                                    DAG.getConstant(NewImm, NewVT));
9312       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9313                                    NewVal, NewPtr,
9314                                    ST->getPointerInfo().getWithOffset(PtrOff),
9315                                    false, false, NewAlign);
9316
9317       AddToWorklist(NewPtr.getNode());
9318       AddToWorklist(NewLD.getNode());
9319       AddToWorklist(NewVal.getNode());
9320       WorklistRemover DeadNodes(*this);
9321       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9322       ++OpsNarrowed;
9323       return NewST;
9324     }
9325   }
9326
9327   return SDValue();
9328 }
9329
9330 /// For a given floating point load / store pair, if the load value isn't used
9331 /// by any other operations, then consider transforming the pair to integer
9332 /// load / store operations if the target deems the transformation profitable.
9333 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9334   StoreSDNode *ST  = cast<StoreSDNode>(N);
9335   SDValue Chain = ST->getChain();
9336   SDValue Value = ST->getValue();
9337   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9338       Value.hasOneUse() &&
9339       Chain == SDValue(Value.getNode(), 1)) {
9340     LoadSDNode *LD = cast<LoadSDNode>(Value);
9341     EVT VT = LD->getMemoryVT();
9342     if (!VT.isFloatingPoint() ||
9343         VT != ST->getMemoryVT() ||
9344         LD->isNonTemporal() ||
9345         ST->isNonTemporal() ||
9346         LD->getPointerInfo().getAddrSpace() != 0 ||
9347         ST->getPointerInfo().getAddrSpace() != 0)
9348       return SDValue();
9349
9350     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9351     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9352         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9353         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9354         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9355       return SDValue();
9356
9357     unsigned LDAlign = LD->getAlignment();
9358     unsigned STAlign = ST->getAlignment();
9359     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9360     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9361     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9362       return SDValue();
9363
9364     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9365                                 LD->getChain(), LD->getBasePtr(),
9366                                 LD->getPointerInfo(),
9367                                 false, false, false, LDAlign);
9368
9369     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9370                                  NewLD, ST->getBasePtr(),
9371                                  ST->getPointerInfo(),
9372                                  false, false, STAlign);
9373
9374     AddToWorklist(NewLD.getNode());
9375     AddToWorklist(NewST.getNode());
9376     WorklistRemover DeadNodes(*this);
9377     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9378     ++LdStFP2Int;
9379     return NewST;
9380   }
9381
9382   return SDValue();
9383 }
9384
9385 /// Helper struct to parse and store a memory address as base + index + offset.
9386 /// We ignore sign extensions when it is safe to do so.
9387 /// The following two expressions are not equivalent. To differentiate we need
9388 /// to store whether there was a sign extension involved in the index
9389 /// computation.
9390 ///  (load (i64 add (i64 copyfromreg %c)
9391 ///                 (i64 signextend (add (i8 load %index)
9392 ///                                      (i8 1))))
9393 /// vs
9394 ///
9395 /// (load (i64 add (i64 copyfromreg %c)
9396 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9397 ///                                         (i32 1)))))
9398 struct BaseIndexOffset {
9399   SDValue Base;
9400   SDValue Index;
9401   int64_t Offset;
9402   bool IsIndexSignExt;
9403
9404   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9405
9406   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9407                   bool IsIndexSignExt) :
9408     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9409
9410   bool equalBaseIndex(const BaseIndexOffset &Other) {
9411     return Other.Base == Base && Other.Index == Index &&
9412       Other.IsIndexSignExt == IsIndexSignExt;
9413   }
9414
9415   /// Parses tree in Ptr for base, index, offset addresses.
9416   static BaseIndexOffset match(SDValue Ptr) {
9417     bool IsIndexSignExt = false;
9418
9419     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9420     // instruction, then it could be just the BASE or everything else we don't
9421     // know how to handle. Just use Ptr as BASE and give up.
9422     if (Ptr->getOpcode() != ISD::ADD)
9423       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9424
9425     // We know that we have at least an ADD instruction. Try to pattern match
9426     // the simple case of BASE + OFFSET.
9427     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9428       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9429       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9430                               IsIndexSignExt);
9431     }
9432
9433     // Inside a loop the current BASE pointer is calculated using an ADD and a
9434     // MUL instruction. In this case Ptr is the actual BASE pointer.
9435     // (i64 add (i64 %array_ptr)
9436     //          (i64 mul (i64 %induction_var)
9437     //                   (i64 %element_size)))
9438     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9439       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9440
9441     // Look at Base + Index + Offset cases.
9442     SDValue Base = Ptr->getOperand(0);
9443     SDValue IndexOffset = Ptr->getOperand(1);
9444
9445     // Skip signextends.
9446     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9447       IndexOffset = IndexOffset->getOperand(0);
9448       IsIndexSignExt = true;
9449     }
9450
9451     // Either the case of Base + Index (no offset) or something else.
9452     if (IndexOffset->getOpcode() != ISD::ADD)
9453       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9454
9455     // Now we have the case of Base + Index + offset.
9456     SDValue Index = IndexOffset->getOperand(0);
9457     SDValue Offset = IndexOffset->getOperand(1);
9458
9459     if (!isa<ConstantSDNode>(Offset))
9460       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9461
9462     // Ignore signextends.
9463     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9464       Index = Index->getOperand(0);
9465       IsIndexSignExt = true;
9466     } else IsIndexSignExt = false;
9467
9468     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9469     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9470   }
9471 };
9472
9473 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9474 /// is located in a sequence of memory operations connected by a chain.
9475 struct MemOpLink {
9476   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9477     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9478   // Ptr to the mem node.
9479   LSBaseSDNode *MemNode;
9480   // Offset from the base ptr.
9481   int64_t OffsetFromBase;
9482   // What is the sequence number of this mem node.
9483   // Lowest mem operand in the DAG starts at zero.
9484   unsigned SequenceNum;
9485 };
9486
9487 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9488   EVT MemVT = St->getMemoryVT();
9489   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9490   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9491     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9492
9493   // Don't merge vectors into wider inputs.
9494   if (MemVT.isVector() || !MemVT.isSimple())
9495     return false;
9496
9497   // Perform an early exit check. Do not bother looking at stored values that
9498   // are not constants or loads.
9499   SDValue StoredVal = St->getValue();
9500   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9501   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9502       !IsLoadSrc)
9503     return false;
9504
9505   // Only look at ends of store sequences.
9506   SDValue Chain = SDValue(St, 0);
9507   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9508     return false;
9509
9510   // This holds the base pointer, index, and the offset in bytes from the base
9511   // pointer.
9512   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9513
9514   // We must have a base and an offset.
9515   if (!BasePtr.Base.getNode())
9516     return false;
9517
9518   // Do not handle stores to undef base pointers.
9519   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9520     return false;
9521
9522   // Save the LoadSDNodes that we find in the chain.
9523   // We need to make sure that these nodes do not interfere with
9524   // any of the store nodes.
9525   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9526
9527   // Save the StoreSDNodes that we find in the chain.
9528   SmallVector<MemOpLink, 8> StoreNodes;
9529
9530   // Walk up the chain and look for nodes with offsets from the same
9531   // base pointer. Stop when reaching an instruction with a different kind
9532   // or instruction which has a different base pointer.
9533   unsigned Seq = 0;
9534   StoreSDNode *Index = St;
9535   while (Index) {
9536     // If the chain has more than one use, then we can't reorder the mem ops.
9537     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9538       break;
9539
9540     // Find the base pointer and offset for this memory node.
9541     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9542
9543     // Check that the base pointer is the same as the original one.
9544     if (!Ptr.equalBaseIndex(BasePtr))
9545       break;
9546
9547     // Check that the alignment is the same.
9548     if (Index->getAlignment() != St->getAlignment())
9549       break;
9550
9551     // The memory operands must not be volatile.
9552     if (Index->isVolatile() || Index->isIndexed())
9553       break;
9554
9555     // No truncation.
9556     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9557       if (St->isTruncatingStore())
9558         break;
9559
9560     // The stored memory type must be the same.
9561     if (Index->getMemoryVT() != MemVT)
9562       break;
9563
9564     // We do not allow unaligned stores because we want to prevent overriding
9565     // stores.
9566     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9567       break;
9568
9569     // We found a potential memory operand to merge.
9570     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9571
9572     // Find the next memory operand in the chain. If the next operand in the
9573     // chain is a store then move up and continue the scan with the next
9574     // memory operand. If the next operand is a load save it and use alias
9575     // information to check if it interferes with anything.
9576     SDNode *NextInChain = Index->getChain().getNode();
9577     while (1) {
9578       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9579         // We found a store node. Use it for the next iteration.
9580         Index = STn;
9581         break;
9582       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9583         if (Ldn->isVolatile()) {
9584           Index = nullptr;
9585           break;
9586         }
9587
9588         // Save the load node for later. Continue the scan.
9589         AliasLoadNodes.push_back(Ldn);
9590         NextInChain = Ldn->getChain().getNode();
9591         continue;
9592       } else {
9593         Index = nullptr;
9594         break;
9595       }
9596     }
9597   }
9598
9599   // Check if there is anything to merge.
9600   if (StoreNodes.size() < 2)
9601     return false;
9602
9603   // Sort the memory operands according to their distance from the base pointer.
9604   std::sort(StoreNodes.begin(), StoreNodes.end(),
9605             [](MemOpLink LHS, MemOpLink RHS) {
9606     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9607            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9608             LHS.SequenceNum > RHS.SequenceNum);
9609   });
9610
9611   // Scan the memory operations on the chain and find the first non-consecutive
9612   // store memory address.
9613   unsigned LastConsecutiveStore = 0;
9614   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9615   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9616
9617     // Check that the addresses are consecutive starting from the second
9618     // element in the list of stores.
9619     if (i > 0) {
9620       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9621       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9622         break;
9623     }
9624
9625     bool Alias = false;
9626     // Check if this store interferes with any of the loads that we found.
9627     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9628       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9629         Alias = true;
9630         break;
9631       }
9632     // We found a load that alias with this store. Stop the sequence.
9633     if (Alias)
9634       break;
9635
9636     // Mark this node as useful.
9637     LastConsecutiveStore = i;
9638   }
9639
9640   // The node with the lowest store address.
9641   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9642
9643   // Store the constants into memory as one consecutive store.
9644   if (!IsLoadSrc) {
9645     unsigned LastLegalType = 0;
9646     unsigned LastLegalVectorType = 0;
9647     bool NonZero = false;
9648     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9649       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9650       SDValue StoredVal = St->getValue();
9651
9652       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9653         NonZero |= !C->isNullValue();
9654       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9655         NonZero |= !C->getConstantFPValue()->isNullValue();
9656       } else {
9657         // Non-constant.
9658         break;
9659       }
9660
9661       // Find a legal type for the constant store.
9662       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9663       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9664       if (TLI.isTypeLegal(StoreTy))
9665         LastLegalType = i+1;
9666       // Or check whether a truncstore is legal.
9667       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9668                TargetLowering::TypePromoteInteger) {
9669         EVT LegalizedStoredValueTy =
9670           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9671         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9672           LastLegalType = i+1;
9673       }
9674
9675       // Find a legal type for the vector store.
9676       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9677       if (TLI.isTypeLegal(Ty))
9678         LastLegalVectorType = i + 1;
9679     }
9680
9681     // We only use vectors if the constant is known to be zero and the
9682     // function is not marked with the noimplicitfloat attribute.
9683     if (NonZero || NoVectors)
9684       LastLegalVectorType = 0;
9685
9686     // Check if we found a legal integer type to store.
9687     if (LastLegalType == 0 && LastLegalVectorType == 0)
9688       return false;
9689
9690     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9691     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9692
9693     // Make sure we have something to merge.
9694     if (NumElem < 2)
9695       return false;
9696
9697     unsigned EarliestNodeUsed = 0;
9698     for (unsigned i=0; i < NumElem; ++i) {
9699       // Find a chain for the new wide-store operand. Notice that some
9700       // of the store nodes that we found may not be selected for inclusion
9701       // in the wide store. The chain we use needs to be the chain of the
9702       // earliest store node which is *used* and replaced by the wide store.
9703       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9704         EarliestNodeUsed = i;
9705     }
9706
9707     // The earliest Node in the DAG.
9708     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9709     SDLoc DL(StoreNodes[0].MemNode);
9710
9711     SDValue StoredVal;
9712     if (UseVector) {
9713       // Find a legal type for the vector store.
9714       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9715       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9716       StoredVal = DAG.getConstant(0, Ty);
9717     } else {
9718       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9719       APInt StoreInt(StoreBW, 0);
9720
9721       // Construct a single integer constant which is made of the smaller
9722       // constant inputs.
9723       bool IsLE = TLI.isLittleEndian();
9724       for (unsigned i = 0; i < NumElem ; ++i) {
9725         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9726         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9727         SDValue Val = St->getValue();
9728         StoreInt<<=ElementSizeBytes*8;
9729         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9730           StoreInt|=C->getAPIntValue().zext(StoreBW);
9731         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9732           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9733         } else {
9734           assert(false && "Invalid constant element type");
9735         }
9736       }
9737
9738       // Create the new Load and Store operations.
9739       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9740       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9741     }
9742
9743     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9744                                     FirstInChain->getBasePtr(),
9745                                     FirstInChain->getPointerInfo(),
9746                                     false, false,
9747                                     FirstInChain->getAlignment());
9748
9749     // Replace the first store with the new store
9750     CombineTo(EarliestOp, NewStore);
9751     // Erase all other stores.
9752     for (unsigned i = 0; i < NumElem ; ++i) {
9753       if (StoreNodes[i].MemNode == EarliestOp)
9754         continue;
9755       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9756       // ReplaceAllUsesWith will replace all uses that existed when it was
9757       // called, but graph optimizations may cause new ones to appear. For
9758       // example, the case in pr14333 looks like
9759       //
9760       //  St's chain -> St -> another store -> X
9761       //
9762       // And the only difference from St to the other store is the chain.
9763       // When we change it's chain to be St's chain they become identical,
9764       // get CSEed and the net result is that X is now a use of St.
9765       // Since we know that St is redundant, just iterate.
9766       while (!St->use_empty())
9767         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9768       deleteAndRecombine(St);
9769     }
9770
9771     return true;
9772   }
9773
9774   // Below we handle the case of multiple consecutive stores that
9775   // come from multiple consecutive loads. We merge them into a single
9776   // wide load and a single wide store.
9777
9778   // Look for load nodes which are used by the stored values.
9779   SmallVector<MemOpLink, 8> LoadNodes;
9780
9781   // Find acceptable loads. Loads need to have the same chain (token factor),
9782   // must not be zext, volatile, indexed, and they must be consecutive.
9783   BaseIndexOffset LdBasePtr;
9784   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9785     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9786     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9787     if (!Ld) break;
9788
9789     // Loads must only have one use.
9790     if (!Ld->hasNUsesOfValue(1, 0))
9791       break;
9792
9793     // Check that the alignment is the same as the stores.
9794     if (Ld->getAlignment() != St->getAlignment())
9795       break;
9796
9797     // The memory operands must not be volatile.
9798     if (Ld->isVolatile() || Ld->isIndexed())
9799       break;
9800
9801     // We do not accept ext loads.
9802     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9803       break;
9804
9805     // The stored memory type must be the same.
9806     if (Ld->getMemoryVT() != MemVT)
9807       break;
9808
9809     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9810     // If this is not the first ptr that we check.
9811     if (LdBasePtr.Base.getNode()) {
9812       // The base ptr must be the same.
9813       if (!LdPtr.equalBaseIndex(LdBasePtr))
9814         break;
9815     } else {
9816       // Check that all other base pointers are the same as this one.
9817       LdBasePtr = LdPtr;
9818     }
9819
9820     // We found a potential memory operand to merge.
9821     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9822   }
9823
9824   if (LoadNodes.size() < 2)
9825     return false;
9826
9827   // If we have load/store pair instructions and we only have two values,
9828   // don't bother.
9829   unsigned RequiredAlignment;
9830   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9831       St->getAlignment() >= RequiredAlignment)
9832     return false;
9833
9834   // Scan the memory operations on the chain and find the first non-consecutive
9835   // load memory address. These variables hold the index in the store node
9836   // array.
9837   unsigned LastConsecutiveLoad = 0;
9838   // This variable refers to the size and not index in the array.
9839   unsigned LastLegalVectorType = 0;
9840   unsigned LastLegalIntegerType = 0;
9841   StartAddress = LoadNodes[0].OffsetFromBase;
9842   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9843   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9844     // All loads much share the same chain.
9845     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9846       break;
9847
9848     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9849     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9850       break;
9851     LastConsecutiveLoad = i;
9852
9853     // Find a legal type for the vector store.
9854     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9855     if (TLI.isTypeLegal(StoreTy))
9856       LastLegalVectorType = i + 1;
9857
9858     // Find a legal type for the integer store.
9859     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9860     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9861     if (TLI.isTypeLegal(StoreTy))
9862       LastLegalIntegerType = i + 1;
9863     // Or check whether a truncstore and extload is legal.
9864     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9865              TargetLowering::TypePromoteInteger) {
9866       EVT LegalizedStoredValueTy =
9867         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9868       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9869           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9870           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9871           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9872         LastLegalIntegerType = i+1;
9873     }
9874   }
9875
9876   // Only use vector types if the vector type is larger than the integer type.
9877   // If they are the same, use integers.
9878   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9879   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9880
9881   // We add +1 here because the LastXXX variables refer to location while
9882   // the NumElem refers to array/index size.
9883   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9884   NumElem = std::min(LastLegalType, NumElem);
9885
9886   if (NumElem < 2)
9887     return false;
9888
9889   // The earliest Node in the DAG.
9890   unsigned EarliestNodeUsed = 0;
9891   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9892   for (unsigned i=1; i<NumElem; ++i) {
9893     // Find a chain for the new wide-store operand. Notice that some
9894     // of the store nodes that we found may not be selected for inclusion
9895     // in the wide store. The chain we use needs to be the chain of the
9896     // earliest store node which is *used* and replaced by the wide store.
9897     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9898       EarliestNodeUsed = i;
9899   }
9900
9901   // Find if it is better to use vectors or integers to load and store
9902   // to memory.
9903   EVT JointMemOpVT;
9904   if (UseVectorTy) {
9905     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9906   } else {
9907     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9908     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9909   }
9910
9911   SDLoc LoadDL(LoadNodes[0].MemNode);
9912   SDLoc StoreDL(StoreNodes[0].MemNode);
9913
9914   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9915   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9916                                 FirstLoad->getChain(),
9917                                 FirstLoad->getBasePtr(),
9918                                 FirstLoad->getPointerInfo(),
9919                                 false, false, false,
9920                                 FirstLoad->getAlignment());
9921
9922   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9923                                   FirstInChain->getBasePtr(),
9924                                   FirstInChain->getPointerInfo(), false, false,
9925                                   FirstInChain->getAlignment());
9926
9927   // Replace one of the loads with the new load.
9928   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9929   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9930                                 SDValue(NewLoad.getNode(), 1));
9931
9932   // Remove the rest of the load chains.
9933   for (unsigned i = 1; i < NumElem ; ++i) {
9934     // Replace all chain users of the old load nodes with the chain of the new
9935     // load node.
9936     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9937     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9938   }
9939
9940   // Replace the first store with the new store.
9941   CombineTo(EarliestOp, NewStore);
9942   // Erase all other stores.
9943   for (unsigned i = 0; i < NumElem ; ++i) {
9944     // Remove all Store nodes.
9945     if (StoreNodes[i].MemNode == EarliestOp)
9946       continue;
9947     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9948     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9949     deleteAndRecombine(St);
9950   }
9951
9952   return true;
9953 }
9954
9955 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9956   StoreSDNode *ST  = cast<StoreSDNode>(N);
9957   SDValue Chain = ST->getChain();
9958   SDValue Value = ST->getValue();
9959   SDValue Ptr   = ST->getBasePtr();
9960
9961   // If this is a store of a bit convert, store the input value if the
9962   // resultant store does not need a higher alignment than the original.
9963   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9964       ST->isUnindexed()) {
9965     unsigned OrigAlign = ST->getAlignment();
9966     EVT SVT = Value.getOperand(0).getValueType();
9967     unsigned Align = TLI.getDataLayout()->
9968       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9969     if (Align <= OrigAlign &&
9970         ((!LegalOperations && !ST->isVolatile()) ||
9971          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9972       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9973                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9974                           ST->isNonTemporal(), OrigAlign,
9975                           ST->getAAInfo());
9976   }
9977
9978   // Turn 'store undef, Ptr' -> nothing.
9979   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9980     return Chain;
9981
9982   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9983   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9984     // NOTE: If the original store is volatile, this transform must not increase
9985     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9986     // processor operation but an i64 (which is not legal) requires two.  So the
9987     // transform should not be done in this case.
9988     if (Value.getOpcode() != ISD::TargetConstantFP) {
9989       SDValue Tmp;
9990       switch (CFP->getSimpleValueType(0).SimpleTy) {
9991       default: llvm_unreachable("Unknown FP type");
9992       case MVT::f16:    // We don't do this for these yet.
9993       case MVT::f80:
9994       case MVT::f128:
9995       case MVT::ppcf128:
9996         break;
9997       case MVT::f32:
9998         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9999             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10000           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10001                               bitcastToAPInt().getZExtValue(), MVT::i32);
10002           return DAG.getStore(Chain, SDLoc(N), Tmp,
10003                               Ptr, ST->getMemOperand());
10004         }
10005         break;
10006       case MVT::f64:
10007         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10008              !ST->isVolatile()) ||
10009             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10010           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10011                                 getZExtValue(), MVT::i64);
10012           return DAG.getStore(Chain, SDLoc(N), Tmp,
10013                               Ptr, ST->getMemOperand());
10014         }
10015
10016         if (!ST->isVolatile() &&
10017             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10018           // Many FP stores are not made apparent until after legalize, e.g. for
10019           // argument passing.  Since this is so common, custom legalize the
10020           // 64-bit integer store into two 32-bit stores.
10021           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10022           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10023           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10024           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10025
10026           unsigned Alignment = ST->getAlignment();
10027           bool isVolatile = ST->isVolatile();
10028           bool isNonTemporal = ST->isNonTemporal();
10029           AAMDNodes AAInfo = ST->getAAInfo();
10030
10031           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10032                                      Ptr, ST->getPointerInfo(),
10033                                      isVolatile, isNonTemporal,
10034                                      ST->getAlignment(), AAInfo);
10035           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10036                             DAG.getConstant(4, Ptr.getValueType()));
10037           Alignment = MinAlign(Alignment, 4U);
10038           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10039                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10040                                      isVolatile, isNonTemporal,
10041                                      Alignment, AAInfo);
10042           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10043                              St0, St1);
10044         }
10045
10046         break;
10047       }
10048     }
10049   }
10050
10051   // Try to infer better alignment information than the store already has.
10052   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10053     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10054       if (Align > ST->getAlignment())
10055         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10056                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10057                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10058                                  ST->getAAInfo());
10059     }
10060   }
10061
10062   // Try transforming a pair floating point load / store ops to integer
10063   // load / store ops.
10064   SDValue NewST = TransformFPLoadStorePair(N);
10065   if (NewST.getNode())
10066     return NewST;
10067
10068   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10069                                                   : DAG.getSubtarget().useAA();
10070 #ifndef NDEBUG
10071   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10072       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10073     UseAA = false;
10074 #endif
10075   if (UseAA && ST->isUnindexed()) {
10076     // Walk up chain skipping non-aliasing memory nodes.
10077     SDValue BetterChain = FindBetterChain(N, Chain);
10078
10079     // If there is a better chain.
10080     if (Chain != BetterChain) {
10081       SDValue ReplStore;
10082
10083       // Replace the chain to avoid dependency.
10084       if (ST->isTruncatingStore()) {
10085         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10086                                       ST->getMemoryVT(), ST->getMemOperand());
10087       } else {
10088         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10089                                  ST->getMemOperand());
10090       }
10091
10092       // Create token to keep both nodes around.
10093       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10094                                   MVT::Other, Chain, ReplStore);
10095
10096       // Make sure the new and old chains are cleaned up.
10097       AddToWorklist(Token.getNode());
10098
10099       // Don't add users to work list.
10100       return CombineTo(N, Token, false);
10101     }
10102   }
10103
10104   // Try transforming N to an indexed store.
10105   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10106     return SDValue(N, 0);
10107
10108   // FIXME: is there such a thing as a truncating indexed store?
10109   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10110       Value.getValueType().isInteger()) {
10111     // See if we can simplify the input to this truncstore with knowledge that
10112     // only the low bits are being used.  For example:
10113     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10114     SDValue Shorter =
10115       GetDemandedBits(Value,
10116                       APInt::getLowBitsSet(
10117                         Value.getValueType().getScalarType().getSizeInBits(),
10118                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10119     AddToWorklist(Value.getNode());
10120     if (Shorter.getNode())
10121       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10122                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10123
10124     // Otherwise, see if we can simplify the operation with
10125     // SimplifyDemandedBits, which only works if the value has a single use.
10126     if (SimplifyDemandedBits(Value,
10127                         APInt::getLowBitsSet(
10128                           Value.getValueType().getScalarType().getSizeInBits(),
10129                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10130       return SDValue(N, 0);
10131   }
10132
10133   // If this is a load followed by a store to the same location, then the store
10134   // is dead/noop.
10135   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10136     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10137         ST->isUnindexed() && !ST->isVolatile() &&
10138         // There can't be any side effects between the load and store, such as
10139         // a call or store.
10140         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10141       // The store is dead, remove it.
10142       return Chain;
10143     }
10144   }
10145
10146   // If this is a store followed by a store with the same value to the same
10147   // location, then the store is dead/noop.
10148   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10149     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10150         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10151         ST1->isUnindexed() && !ST1->isVolatile()) {
10152       // The store is dead, remove it.
10153       return Chain;
10154     }
10155   }
10156
10157   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10158   // truncating store.  We can do this even if this is already a truncstore.
10159   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10160       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10161       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10162                             ST->getMemoryVT())) {
10163     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10164                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10165   }
10166
10167   // Only perform this optimization before the types are legal, because we
10168   // don't want to perform this optimization on every DAGCombine invocation.
10169   if (!LegalTypes) {
10170     bool EverChanged = false;
10171
10172     do {
10173       // There can be multiple store sequences on the same chain.
10174       // Keep trying to merge store sequences until we are unable to do so
10175       // or until we merge the last store on the chain.
10176       bool Changed = MergeConsecutiveStores(ST);
10177       EverChanged |= Changed;
10178       if (!Changed) break;
10179     } while (ST->getOpcode() != ISD::DELETED_NODE);
10180
10181     if (EverChanged)
10182       return SDValue(N, 0);
10183   }
10184
10185   return ReduceLoadOpStoreWidth(N);
10186 }
10187
10188 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10189   SDValue InVec = N->getOperand(0);
10190   SDValue InVal = N->getOperand(1);
10191   SDValue EltNo = N->getOperand(2);
10192   SDLoc dl(N);
10193
10194   // If the inserted element is an UNDEF, just use the input vector.
10195   if (InVal.getOpcode() == ISD::UNDEF)
10196     return InVec;
10197
10198   EVT VT = InVec.getValueType();
10199
10200   // If we can't generate a legal BUILD_VECTOR, exit
10201   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10202     return SDValue();
10203
10204   // Check that we know which element is being inserted
10205   if (!isa<ConstantSDNode>(EltNo))
10206     return SDValue();
10207   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10208
10209   // Canonicalize insert_vector_elt dag nodes.
10210   // Example:
10211   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10212   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10213   //
10214   // Do this only if the child insert_vector node has one use; also
10215   // do this only if indices are both constants and Idx1 < Idx0.
10216   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10217       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10218     unsigned OtherElt =
10219       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10220     if (Elt < OtherElt) {
10221       // Swap nodes.
10222       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10223                                   InVec.getOperand(0), InVal, EltNo);
10224       AddToWorklist(NewOp.getNode());
10225       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10226                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10227     }
10228   }
10229
10230   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10231   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10232   // vector elements.
10233   SmallVector<SDValue, 8> Ops;
10234   // Do not combine these two vectors if the output vector will not replace
10235   // the input vector.
10236   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10237     Ops.append(InVec.getNode()->op_begin(),
10238                InVec.getNode()->op_end());
10239   } else if (InVec.getOpcode() == ISD::UNDEF) {
10240     unsigned NElts = VT.getVectorNumElements();
10241     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10242   } else {
10243     return SDValue();
10244   }
10245
10246   // Insert the element
10247   if (Elt < Ops.size()) {
10248     // All the operands of BUILD_VECTOR must have the same type;
10249     // we enforce that here.
10250     EVT OpVT = Ops[0].getValueType();
10251     if (InVal.getValueType() != OpVT)
10252       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10253                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10254                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10255     Ops[Elt] = InVal;
10256   }
10257
10258   // Return the new vector
10259   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10260 }
10261
10262 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10263     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10264   EVT ResultVT = EVE->getValueType(0);
10265   EVT VecEltVT = InVecVT.getVectorElementType();
10266   unsigned Align = OriginalLoad->getAlignment();
10267   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10268       VecEltVT.getTypeForEVT(*DAG.getContext()));
10269
10270   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10271     return SDValue();
10272
10273   Align = NewAlign;
10274
10275   SDValue NewPtr = OriginalLoad->getBasePtr();
10276   SDValue Offset;
10277   EVT PtrType = NewPtr.getValueType();
10278   MachinePointerInfo MPI;
10279   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10280     int Elt = ConstEltNo->getZExtValue();
10281     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10282     if (TLI.isBigEndian())
10283       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10284     Offset = DAG.getConstant(PtrOff, PtrType);
10285     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10286   } else {
10287     Offset = DAG.getNode(
10288         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10289         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10290     if (TLI.isBigEndian())
10291       Offset = DAG.getNode(
10292           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10293           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10294     MPI = OriginalLoad->getPointerInfo();
10295   }
10296   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10297
10298   // The replacement we need to do here is a little tricky: we need to
10299   // replace an extractelement of a load with a load.
10300   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10301   // Note that this replacement assumes that the extractvalue is the only
10302   // use of the load; that's okay because we don't want to perform this
10303   // transformation in other cases anyway.
10304   SDValue Load;
10305   SDValue Chain;
10306   if (ResultVT.bitsGT(VecEltVT)) {
10307     // If the result type of vextract is wider than the load, then issue an
10308     // extending load instead.
10309     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10310                                    ? ISD::ZEXTLOAD
10311                                    : ISD::EXTLOAD;
10312     Load = DAG.getExtLoad(
10313         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10314         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10315         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10316     Chain = Load.getValue(1);
10317   } else {
10318     Load = DAG.getLoad(
10319         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10320         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10321         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10322     Chain = Load.getValue(1);
10323     if (ResultVT.bitsLT(VecEltVT))
10324       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10325     else
10326       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10327   }
10328   WorklistRemover DeadNodes(*this);
10329   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10330   SDValue To[] = { Load, Chain };
10331   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10332   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10333   // worklist explicitly as well.
10334   AddToWorklist(Load.getNode());
10335   AddUsersToWorklist(Load.getNode()); // Add users too
10336   // Make sure to revisit this node to clean it up; it will usually be dead.
10337   AddToWorklist(EVE);
10338   ++OpsNarrowed;
10339   return SDValue(EVE, 0);
10340 }
10341
10342 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10343   // (vextract (scalar_to_vector val, 0) -> val
10344   SDValue InVec = N->getOperand(0);
10345   EVT VT = InVec.getValueType();
10346   EVT NVT = N->getValueType(0);
10347
10348   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10349     // Check if the result type doesn't match the inserted element type. A
10350     // SCALAR_TO_VECTOR may truncate the inserted element and the
10351     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10352     SDValue InOp = InVec.getOperand(0);
10353     if (InOp.getValueType() != NVT) {
10354       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10355       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10356     }
10357     return InOp;
10358   }
10359
10360   SDValue EltNo = N->getOperand(1);
10361   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10362
10363   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10364   // We only perform this optimization before the op legalization phase because
10365   // we may introduce new vector instructions which are not backed by TD
10366   // patterns. For example on AVX, extracting elements from a wide vector
10367   // without using extract_subvector. However, if we can find an underlying
10368   // scalar value, then we can always use that.
10369   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10370       && ConstEltNo) {
10371     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10372     int NumElem = VT.getVectorNumElements();
10373     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10374     // Find the new index to extract from.
10375     int OrigElt = SVOp->getMaskElt(Elt);
10376
10377     // Extracting an undef index is undef.
10378     if (OrigElt == -1)
10379       return DAG.getUNDEF(NVT);
10380
10381     // Select the right vector half to extract from.
10382     SDValue SVInVec;
10383     if (OrigElt < NumElem) {
10384       SVInVec = InVec->getOperand(0);
10385     } else {
10386       SVInVec = InVec->getOperand(1);
10387       OrigElt -= NumElem;
10388     }
10389
10390     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10391       SDValue InOp = SVInVec.getOperand(OrigElt);
10392       if (InOp.getValueType() != NVT) {
10393         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10394         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10395       }
10396
10397       return InOp;
10398     }
10399
10400     // FIXME: We should handle recursing on other vector shuffles and
10401     // scalar_to_vector here as well.
10402
10403     if (!LegalOperations) {
10404       EVT IndexTy = TLI.getVectorIdxTy();
10405       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10406                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10407     }
10408   }
10409
10410   bool BCNumEltsChanged = false;
10411   EVT ExtVT = VT.getVectorElementType();
10412   EVT LVT = ExtVT;
10413
10414   // If the result of load has to be truncated, then it's not necessarily
10415   // profitable.
10416   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10417     return SDValue();
10418
10419   if (InVec.getOpcode() == ISD::BITCAST) {
10420     // Don't duplicate a load with other uses.
10421     if (!InVec.hasOneUse())
10422       return SDValue();
10423
10424     EVT BCVT = InVec.getOperand(0).getValueType();
10425     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10426       return SDValue();
10427     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10428       BCNumEltsChanged = true;
10429     InVec = InVec.getOperand(0);
10430     ExtVT = BCVT.getVectorElementType();
10431   }
10432
10433   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10434   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10435       ISD::isNormalLoad(InVec.getNode()) &&
10436       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10437     SDValue Index = N->getOperand(1);
10438     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10439       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10440                                                            OrigLoad);
10441   }
10442
10443   // Perform only after legalization to ensure build_vector / vector_shuffle
10444   // optimizations have already been done.
10445   if (!LegalOperations) return SDValue();
10446
10447   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10448   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10449   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10450
10451   if (ConstEltNo) {
10452     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10453
10454     LoadSDNode *LN0 = nullptr;
10455     const ShuffleVectorSDNode *SVN = nullptr;
10456     if (ISD::isNormalLoad(InVec.getNode())) {
10457       LN0 = cast<LoadSDNode>(InVec);
10458     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10459                InVec.getOperand(0).getValueType() == ExtVT &&
10460                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10461       // Don't duplicate a load with other uses.
10462       if (!InVec.hasOneUse())
10463         return SDValue();
10464
10465       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10466     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10467       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10468       // =>
10469       // (load $addr+1*size)
10470
10471       // Don't duplicate a load with other uses.
10472       if (!InVec.hasOneUse())
10473         return SDValue();
10474
10475       // If the bit convert changed the number of elements, it is unsafe
10476       // to examine the mask.
10477       if (BCNumEltsChanged)
10478         return SDValue();
10479
10480       // Select the input vector, guarding against out of range extract vector.
10481       unsigned NumElems = VT.getVectorNumElements();
10482       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10483       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10484
10485       if (InVec.getOpcode() == ISD::BITCAST) {
10486         // Don't duplicate a load with other uses.
10487         if (!InVec.hasOneUse())
10488           return SDValue();
10489
10490         InVec = InVec.getOperand(0);
10491       }
10492       if (ISD::isNormalLoad(InVec.getNode())) {
10493         LN0 = cast<LoadSDNode>(InVec);
10494         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10495         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10496       }
10497     }
10498
10499     // Make sure we found a non-volatile load and the extractelement is
10500     // the only use.
10501     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10502       return SDValue();
10503
10504     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10505     if (Elt == -1)
10506       return DAG.getUNDEF(LVT);
10507
10508     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10509   }
10510
10511   return SDValue();
10512 }
10513
10514 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10515 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10516   // We perform this optimization post type-legalization because
10517   // the type-legalizer often scalarizes integer-promoted vectors.
10518   // Performing this optimization before may create bit-casts which
10519   // will be type-legalized to complex code sequences.
10520   // We perform this optimization only before the operation legalizer because we
10521   // may introduce illegal operations.
10522   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10523     return SDValue();
10524
10525   unsigned NumInScalars = N->getNumOperands();
10526   SDLoc dl(N);
10527   EVT VT = N->getValueType(0);
10528
10529   // Check to see if this is a BUILD_VECTOR of a bunch of values
10530   // which come from any_extend or zero_extend nodes. If so, we can create
10531   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10532   // optimizations. We do not handle sign-extend because we can't fill the sign
10533   // using shuffles.
10534   EVT SourceType = MVT::Other;
10535   bool AllAnyExt = true;
10536
10537   for (unsigned i = 0; i != NumInScalars; ++i) {
10538     SDValue In = N->getOperand(i);
10539     // Ignore undef inputs.
10540     if (In.getOpcode() == ISD::UNDEF) continue;
10541
10542     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10543     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10544
10545     // Abort if the element is not an extension.
10546     if (!ZeroExt && !AnyExt) {
10547       SourceType = MVT::Other;
10548       break;
10549     }
10550
10551     // The input is a ZeroExt or AnyExt. Check the original type.
10552     EVT InTy = In.getOperand(0).getValueType();
10553
10554     // Check that all of the widened source types are the same.
10555     if (SourceType == MVT::Other)
10556       // First time.
10557       SourceType = InTy;
10558     else if (InTy != SourceType) {
10559       // Multiple income types. Abort.
10560       SourceType = MVT::Other;
10561       break;
10562     }
10563
10564     // Check if all of the extends are ANY_EXTENDs.
10565     AllAnyExt &= AnyExt;
10566   }
10567
10568   // In order to have valid types, all of the inputs must be extended from the
10569   // same source type and all of the inputs must be any or zero extend.
10570   // Scalar sizes must be a power of two.
10571   EVT OutScalarTy = VT.getScalarType();
10572   bool ValidTypes = SourceType != MVT::Other &&
10573                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10574                  isPowerOf2_32(SourceType.getSizeInBits());
10575
10576   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10577   // turn into a single shuffle instruction.
10578   if (!ValidTypes)
10579     return SDValue();
10580
10581   bool isLE = TLI.isLittleEndian();
10582   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10583   assert(ElemRatio > 1 && "Invalid element size ratio");
10584   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10585                                DAG.getConstant(0, SourceType);
10586
10587   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10588   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10589
10590   // Populate the new build_vector
10591   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10592     SDValue Cast = N->getOperand(i);
10593     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10594             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10595             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10596     SDValue In;
10597     if (Cast.getOpcode() == ISD::UNDEF)
10598       In = DAG.getUNDEF(SourceType);
10599     else
10600       In = Cast->getOperand(0);
10601     unsigned Index = isLE ? (i * ElemRatio) :
10602                             (i * ElemRatio + (ElemRatio - 1));
10603
10604     assert(Index < Ops.size() && "Invalid index");
10605     Ops[Index] = In;
10606   }
10607
10608   // The type of the new BUILD_VECTOR node.
10609   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10610   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10611          "Invalid vector size");
10612   // Check if the new vector type is legal.
10613   if (!isTypeLegal(VecVT)) return SDValue();
10614
10615   // Make the new BUILD_VECTOR.
10616   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10617
10618   // The new BUILD_VECTOR node has the potential to be further optimized.
10619   AddToWorklist(BV.getNode());
10620   // Bitcast to the desired type.
10621   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10622 }
10623
10624 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10625   EVT VT = N->getValueType(0);
10626
10627   unsigned NumInScalars = N->getNumOperands();
10628   SDLoc dl(N);
10629
10630   EVT SrcVT = MVT::Other;
10631   unsigned Opcode = ISD::DELETED_NODE;
10632   unsigned NumDefs = 0;
10633
10634   for (unsigned i = 0; i != NumInScalars; ++i) {
10635     SDValue In = N->getOperand(i);
10636     unsigned Opc = In.getOpcode();
10637
10638     if (Opc == ISD::UNDEF)
10639       continue;
10640
10641     // If all scalar values are floats and converted from integers.
10642     if (Opcode == ISD::DELETED_NODE &&
10643         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10644       Opcode = Opc;
10645     }
10646
10647     if (Opc != Opcode)
10648       return SDValue();
10649
10650     EVT InVT = In.getOperand(0).getValueType();
10651
10652     // If all scalar values are typed differently, bail out. It's chosen to
10653     // simplify BUILD_VECTOR of integer types.
10654     if (SrcVT == MVT::Other)
10655       SrcVT = InVT;
10656     if (SrcVT != InVT)
10657       return SDValue();
10658     NumDefs++;
10659   }
10660
10661   // If the vector has just one element defined, it's not worth to fold it into
10662   // a vectorized one.
10663   if (NumDefs < 2)
10664     return SDValue();
10665
10666   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10667          && "Should only handle conversion from integer to float.");
10668   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10669
10670   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10671
10672   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10673     return SDValue();
10674
10675   SmallVector<SDValue, 8> Opnds;
10676   for (unsigned i = 0; i != NumInScalars; ++i) {
10677     SDValue In = N->getOperand(i);
10678
10679     if (In.getOpcode() == ISD::UNDEF)
10680       Opnds.push_back(DAG.getUNDEF(SrcVT));
10681     else
10682       Opnds.push_back(In.getOperand(0));
10683   }
10684   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10685   AddToWorklist(BV.getNode());
10686
10687   return DAG.getNode(Opcode, dl, VT, BV);
10688 }
10689
10690 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10691   unsigned NumInScalars = N->getNumOperands();
10692   SDLoc dl(N);
10693   EVT VT = N->getValueType(0);
10694
10695   // A vector built entirely of undefs is undef.
10696   if (ISD::allOperandsUndef(N))
10697     return DAG.getUNDEF(VT);
10698
10699   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10700   if (V.getNode())
10701     return V;
10702
10703   V = reduceBuildVecConvertToConvertBuildVec(N);
10704   if (V.getNode())
10705     return V;
10706
10707   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10708   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10709   // at most two distinct vectors, turn this into a shuffle node.
10710
10711   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10712   if (!isTypeLegal(VT))
10713     return SDValue();
10714
10715   // May only combine to shuffle after legalize if shuffle is legal.
10716   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10717     return SDValue();
10718
10719   SDValue VecIn1, VecIn2;
10720   bool UsesZeroVector = false;
10721   for (unsigned i = 0; i != NumInScalars; ++i) {
10722     SDValue Op = N->getOperand(i);
10723     // Ignore undef inputs.
10724     if (Op.getOpcode() == ISD::UNDEF) continue;
10725
10726     // See if we can combine this build_vector into a blend with a zero vector.
10727     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10728         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10729         (Op.getOpcode() == ISD::ConstantFP &&
10730         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10731       UsesZeroVector = true;
10732       continue;
10733     }
10734
10735     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10736     // constant index, bail out.
10737     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10738         !isa<ConstantSDNode>(Op.getOperand(1))) {
10739       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10740       break;
10741     }
10742
10743     // We allow up to two distinct input vectors.
10744     SDValue ExtractedFromVec = Op.getOperand(0);
10745     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10746       continue;
10747
10748     if (!VecIn1.getNode()) {
10749       VecIn1 = ExtractedFromVec;
10750     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10751       VecIn2 = ExtractedFromVec;
10752     } else {
10753       // Too many inputs.
10754       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10755       break;
10756     }
10757   }
10758
10759   // If everything is good, we can make a shuffle operation.
10760   if (VecIn1.getNode()) {
10761     SmallVector<int, 8> Mask;
10762     for (unsigned i = 0; i != NumInScalars; ++i) {
10763       unsigned Opcode = N->getOperand(i).getOpcode();
10764       if (Opcode == ISD::UNDEF) {
10765         Mask.push_back(-1);
10766         continue;
10767       }
10768
10769       // Operands can also be zero.
10770       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10771         assert(UsesZeroVector &&
10772                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10773                "Unexpected node found!");
10774         Mask.push_back(NumInScalars+i);
10775         continue;
10776       }
10777
10778       // If extracting from the first vector, just use the index directly.
10779       SDValue Extract = N->getOperand(i);
10780       SDValue ExtVal = Extract.getOperand(1);
10781       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10782       if (Extract.getOperand(0) == VecIn1) {
10783         if (ExtIndex > VT.getVectorNumElements())
10784           return SDValue();
10785
10786         Mask.push_back(ExtIndex);
10787         continue;
10788       }
10789
10790       // Otherwise, use InIdx + VecSize
10791       Mask.push_back(NumInScalars+ExtIndex);
10792     }
10793
10794     // Avoid introducing illegal shuffles with zero.
10795     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10796       return SDValue();
10797
10798     // We can't generate a shuffle node with mismatched input and output types.
10799     // Attempt to transform a single input vector to the correct type.
10800     if ((VT != VecIn1.getValueType())) {
10801       // We don't support shuffeling between TWO values of different types.
10802       if (VecIn2.getNode())
10803         return SDValue();
10804
10805       // We only support widening of vectors which are half the size of the
10806       // output registers. For example XMM->YMM widening on X86 with AVX.
10807       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10808         return SDValue();
10809
10810       // If the input vector type has a different base type to the output
10811       // vector type, bail out.
10812       if (VecIn1.getValueType().getVectorElementType() !=
10813           VT.getVectorElementType())
10814         return SDValue();
10815
10816       // Widen the input vector by adding undef values.
10817       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10818                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10819     }
10820
10821     if (UsesZeroVector)
10822       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10823                                 DAG.getConstantFP(0.0, VT);
10824     else
10825       // If VecIn2 is unused then change it to undef.
10826       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10827
10828     // Check that we were able to transform all incoming values to the same
10829     // type.
10830     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10831         VecIn1.getValueType() != VT)
10832           return SDValue();
10833
10834     // Return the new VECTOR_SHUFFLE node.
10835     SDValue Ops[2];
10836     Ops[0] = VecIn1;
10837     Ops[1] = VecIn2;
10838     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10839   }
10840
10841   return SDValue();
10842 }
10843
10844 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10845   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10846   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10847   // inputs come from at most two distinct vectors, turn this into a shuffle
10848   // node.
10849
10850   // If we only have one input vector, we don't need to do any concatenation.
10851   if (N->getNumOperands() == 1)
10852     return N->getOperand(0);
10853
10854   // Check if all of the operands are undefs.
10855   EVT VT = N->getValueType(0);
10856   if (ISD::allOperandsUndef(N))
10857     return DAG.getUNDEF(VT);
10858
10859   // Optimize concat_vectors where one of the vectors is undef.
10860   if (N->getNumOperands() == 2 &&
10861       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10862     SDValue In = N->getOperand(0);
10863     assert(In.getValueType().isVector() && "Must concat vectors");
10864
10865     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10866     if (In->getOpcode() == ISD::BITCAST &&
10867         !In->getOperand(0)->getValueType(0).isVector()) {
10868       SDValue Scalar = In->getOperand(0);
10869       EVT SclTy = Scalar->getValueType(0);
10870
10871       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10872         return SDValue();
10873
10874       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10875                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10876       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10877         return SDValue();
10878
10879       SDLoc dl = SDLoc(N);
10880       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10881       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10882     }
10883   }
10884
10885   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10886   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10887   if (N->getNumOperands() == 2 &&
10888       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10889       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10890     EVT VT = N->getValueType(0);
10891     SDValue N0 = N->getOperand(0);
10892     SDValue N1 = N->getOperand(1);
10893     SmallVector<SDValue, 8> Opnds;
10894     unsigned BuildVecNumElts =  N0.getNumOperands();
10895
10896     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10897     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10898     if (SclTy0.isFloatingPoint()) {
10899       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10900         Opnds.push_back(N0.getOperand(i));
10901       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10902         Opnds.push_back(N1.getOperand(i));
10903     } else {
10904       // If BUILD_VECTOR are from built from integer, they may have different
10905       // operand types. Get the smaller type and truncate all operands to it.
10906       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10907       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10908         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10909                         N0.getOperand(i)));
10910       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10911         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10912                         N1.getOperand(i)));
10913     }
10914
10915     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10916   }
10917
10918   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10919   // nodes often generate nop CONCAT_VECTOR nodes.
10920   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10921   // place the incoming vectors at the exact same location.
10922   SDValue SingleSource = SDValue();
10923   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10924
10925   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10926     SDValue Op = N->getOperand(i);
10927
10928     if (Op.getOpcode() == ISD::UNDEF)
10929       continue;
10930
10931     // Check if this is the identity extract:
10932     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10933       return SDValue();
10934
10935     // Find the single incoming vector for the extract_subvector.
10936     if (SingleSource.getNode()) {
10937       if (Op.getOperand(0) != SingleSource)
10938         return SDValue();
10939     } else {
10940       SingleSource = Op.getOperand(0);
10941
10942       // Check the source type is the same as the type of the result.
10943       // If not, this concat may extend the vector, so we can not
10944       // optimize it away.
10945       if (SingleSource.getValueType() != N->getValueType(0))
10946         return SDValue();
10947     }
10948
10949     unsigned IdentityIndex = i * PartNumElem;
10950     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10951     // The extract index must be constant.
10952     if (!CS)
10953       return SDValue();
10954
10955     // Check that we are reading from the identity index.
10956     if (CS->getZExtValue() != IdentityIndex)
10957       return SDValue();
10958   }
10959
10960   if (SingleSource.getNode())
10961     return SingleSource;
10962
10963   return SDValue();
10964 }
10965
10966 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10967   EVT NVT = N->getValueType(0);
10968   SDValue V = N->getOperand(0);
10969
10970   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10971     // Combine:
10972     //    (extract_subvec (concat V1, V2, ...), i)
10973     // Into:
10974     //    Vi if possible
10975     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10976     // type.
10977     if (V->getOperand(0).getValueType() != NVT)
10978       return SDValue();
10979     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10980     unsigned NumElems = NVT.getVectorNumElements();
10981     assert((Idx % NumElems) == 0 &&
10982            "IDX in concat is not a multiple of the result vector length.");
10983     return V->getOperand(Idx / NumElems);
10984   }
10985
10986   // Skip bitcasting
10987   if (V->getOpcode() == ISD::BITCAST)
10988     V = V.getOperand(0);
10989
10990   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10991     SDLoc dl(N);
10992     // Handle only simple case where vector being inserted and vector
10993     // being extracted are of same type, and are half size of larger vectors.
10994     EVT BigVT = V->getOperand(0).getValueType();
10995     EVT SmallVT = V->getOperand(1).getValueType();
10996     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10997       return SDValue();
10998
10999     // Only handle cases where both indexes are constants with the same type.
11000     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11001     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11002
11003     if (InsIdx && ExtIdx &&
11004         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11005         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11006       // Combine:
11007       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11008       // Into:
11009       //    indices are equal or bit offsets are equal => V1
11010       //    otherwise => (extract_subvec V1, ExtIdx)
11011       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11012           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11013         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11014       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11015                          DAG.getNode(ISD::BITCAST, dl,
11016                                      N->getOperand(0).getValueType(),
11017                                      V->getOperand(0)), N->getOperand(1));
11018     }
11019   }
11020
11021   return SDValue();
11022 }
11023
11024 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11025                                                  SDValue V, SelectionDAG &DAG) {
11026   SDLoc DL(V);
11027   EVT VT = V.getValueType();
11028
11029   switch (V.getOpcode()) {
11030   default:
11031     return V;
11032
11033   case ISD::CONCAT_VECTORS: {
11034     EVT OpVT = V->getOperand(0).getValueType();
11035     int OpSize = OpVT.getVectorNumElements();
11036     SmallBitVector OpUsedElements(OpSize, false);
11037     bool FoundSimplification = false;
11038     SmallVector<SDValue, 4> NewOps;
11039     NewOps.reserve(V->getNumOperands());
11040     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11041       SDValue Op = V->getOperand(i);
11042       bool OpUsed = false;
11043       for (int j = 0; j < OpSize; ++j)
11044         if (UsedElements[i * OpSize + j]) {
11045           OpUsedElements[j] = true;
11046           OpUsed = true;
11047         }
11048       NewOps.push_back(
11049           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11050                  : DAG.getUNDEF(OpVT));
11051       FoundSimplification |= Op == NewOps.back();
11052       OpUsedElements.reset();
11053     }
11054     if (FoundSimplification)
11055       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11056     return V;
11057   }
11058
11059   case ISD::INSERT_SUBVECTOR: {
11060     SDValue BaseV = V->getOperand(0);
11061     SDValue SubV = V->getOperand(1);
11062     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11063     if (!IdxN)
11064       return V;
11065
11066     int SubSize = SubV.getValueType().getVectorNumElements();
11067     int Idx = IdxN->getZExtValue();
11068     bool SubVectorUsed = false;
11069     SmallBitVector SubUsedElements(SubSize, false);
11070     for (int i = 0; i < SubSize; ++i)
11071       if (UsedElements[i + Idx]) {
11072         SubVectorUsed = true;
11073         SubUsedElements[i] = true;
11074         UsedElements[i + Idx] = false;
11075       }
11076
11077     // Now recurse on both the base and sub vectors.
11078     SDValue SimplifiedSubV =
11079         SubVectorUsed
11080             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11081             : DAG.getUNDEF(SubV.getValueType());
11082     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11083     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11084       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11085                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11086     return V;
11087   }
11088   }
11089 }
11090
11091 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11092                                        SDValue N1, SelectionDAG &DAG) {
11093   EVT VT = SVN->getValueType(0);
11094   int NumElts = VT.getVectorNumElements();
11095   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11096   for (int M : SVN->getMask())
11097     if (M >= 0 && M < NumElts)
11098       N0UsedElements[M] = true;
11099     else if (M >= NumElts)
11100       N1UsedElements[M - NumElts] = true;
11101
11102   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11103   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11104   if (S0 == N0 && S1 == N1)
11105     return SDValue();
11106
11107   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11108 }
11109
11110 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11111 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11112   EVT VT = N->getValueType(0);
11113   unsigned NumElts = VT.getVectorNumElements();
11114
11115   SDValue N0 = N->getOperand(0);
11116   SDValue N1 = N->getOperand(1);
11117   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11118
11119   SmallVector<SDValue, 4> Ops;
11120   EVT ConcatVT = N0.getOperand(0).getValueType();
11121   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11122   unsigned NumConcats = NumElts / NumElemsPerConcat;
11123
11124   // Look at every vector that's inserted. We're looking for exact
11125   // subvector-sized copies from a concatenated vector
11126   for (unsigned I = 0; I != NumConcats; ++I) {
11127     // Make sure we're dealing with a copy.
11128     unsigned Begin = I * NumElemsPerConcat;
11129     bool AllUndef = true, NoUndef = true;
11130     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11131       if (SVN->getMaskElt(J) >= 0)
11132         AllUndef = false;
11133       else
11134         NoUndef = false;
11135     }
11136
11137     if (NoUndef) {
11138       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11139         return SDValue();
11140
11141       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11142         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11143           return SDValue();
11144
11145       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11146       if (FirstElt < N0.getNumOperands())
11147         Ops.push_back(N0.getOperand(FirstElt));
11148       else
11149         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11150
11151     } else if (AllUndef) {
11152       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11153     } else { // Mixed with general masks and undefs, can't do optimization.
11154       return SDValue();
11155     }
11156   }
11157
11158   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11159 }
11160
11161 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11162   EVT VT = N->getValueType(0);
11163   unsigned NumElts = VT.getVectorNumElements();
11164
11165   SDValue N0 = N->getOperand(0);
11166   SDValue N1 = N->getOperand(1);
11167
11168   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11169
11170   // Canonicalize shuffle undef, undef -> undef
11171   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11172     return DAG.getUNDEF(VT);
11173
11174   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11175
11176   // Canonicalize shuffle v, v -> v, undef
11177   if (N0 == N1) {
11178     SmallVector<int, 8> NewMask;
11179     for (unsigned i = 0; i != NumElts; ++i) {
11180       int Idx = SVN->getMaskElt(i);
11181       if (Idx >= (int)NumElts) Idx -= NumElts;
11182       NewMask.push_back(Idx);
11183     }
11184     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11185                                 &NewMask[0]);
11186   }
11187
11188   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11189   if (N0.getOpcode() == ISD::UNDEF) {
11190     SmallVector<int, 8> NewMask;
11191     for (unsigned i = 0; i != NumElts; ++i) {
11192       int Idx = SVN->getMaskElt(i);
11193       if (Idx >= 0) {
11194         if (Idx >= (int)NumElts)
11195           Idx -= NumElts;
11196         else
11197           Idx = -1; // remove reference to lhs
11198       }
11199       NewMask.push_back(Idx);
11200     }
11201     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11202                                 &NewMask[0]);
11203   }
11204
11205   // Remove references to rhs if it is undef
11206   if (N1.getOpcode() == ISD::UNDEF) {
11207     bool Changed = false;
11208     SmallVector<int, 8> NewMask;
11209     for (unsigned i = 0; i != NumElts; ++i) {
11210       int Idx = SVN->getMaskElt(i);
11211       if (Idx >= (int)NumElts) {
11212         Idx = -1;
11213         Changed = true;
11214       }
11215       NewMask.push_back(Idx);
11216     }
11217     if (Changed)
11218       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11219   }
11220
11221   // If it is a splat, check if the argument vector is another splat or a
11222   // build_vector with all scalar elements the same.
11223   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11224     SDNode *V = N0.getNode();
11225
11226     // If this is a bit convert that changes the element type of the vector but
11227     // not the number of vector elements, look through it.  Be careful not to
11228     // look though conversions that change things like v4f32 to v2f64.
11229     if (V->getOpcode() == ISD::BITCAST) {
11230       SDValue ConvInput = V->getOperand(0);
11231       if (ConvInput.getValueType().isVector() &&
11232           ConvInput.getValueType().getVectorNumElements() == NumElts)
11233         V = ConvInput.getNode();
11234     }
11235
11236     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11237       assert(V->getNumOperands() == NumElts &&
11238              "BUILD_VECTOR has wrong number of operands");
11239       SDValue Base;
11240       bool AllSame = true;
11241       for (unsigned i = 0; i != NumElts; ++i) {
11242         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11243           Base = V->getOperand(i);
11244           break;
11245         }
11246       }
11247       // Splat of <u, u, u, u>, return <u, u, u, u>
11248       if (!Base.getNode())
11249         return N0;
11250       for (unsigned i = 0; i != NumElts; ++i) {
11251         if (V->getOperand(i) != Base) {
11252           AllSame = false;
11253           break;
11254         }
11255       }
11256       // Splat of <x, x, x, x>, return <x, x, x, x>
11257       if (AllSame)
11258         return N0;
11259     }
11260   }
11261
11262   // There are various patterns used to build up a vector from smaller vectors,
11263   // subvectors, or elements. Scan chains of these and replace unused insertions
11264   // or components with undef.
11265   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11266     return S;
11267
11268   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11269       Level < AfterLegalizeVectorOps &&
11270       (N1.getOpcode() == ISD::UNDEF ||
11271       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11272        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11273     SDValue V = partitionShuffleOfConcats(N, DAG);
11274
11275     if (V.getNode())
11276       return V;
11277   }
11278
11279   // Canonicalize shuffles according to rules:
11280   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11281   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11282   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11283   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11284       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11285       TLI.isTypeLegal(VT)) {
11286     // The incoming shuffle must be of the same type as the result of the
11287     // current shuffle.
11288     assert(N1->getOperand(0).getValueType() == VT &&
11289            "Shuffle types don't match");
11290
11291     SDValue SV0 = N1->getOperand(0);
11292     SDValue SV1 = N1->getOperand(1);
11293     bool HasSameOp0 = N0 == SV0;
11294     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11295     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11296       // Commute the operands of this shuffle so that next rule
11297       // will trigger.
11298       return DAG.getCommutedVectorShuffle(*SVN);
11299   }
11300
11301   // Try to fold according to rules:
11302   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11303   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11304   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11305   // Don't try to fold shuffles with illegal type.
11306   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11307       TLI.isTypeLegal(VT)) {
11308     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11309
11310     // The incoming shuffle must be of the same type as the result of the
11311     // current shuffle.
11312     assert(OtherSV->getOperand(0).getValueType() == VT &&
11313            "Shuffle types don't match");
11314
11315     SDValue SV0, SV1;
11316     SmallVector<int, 4> Mask;
11317     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11318     // operand, and SV1 as the second operand.
11319     for (unsigned i = 0; i != NumElts; ++i) {
11320       int Idx = SVN->getMaskElt(i);
11321       if (Idx < 0) {
11322         // Propagate Undef.
11323         Mask.push_back(Idx);
11324         continue;
11325       }
11326
11327       SDValue CurrentVec;
11328       if (Idx < (int)NumElts) {
11329         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11330         // shuffle mask to identify which vector is actually referenced.
11331         Idx = OtherSV->getMaskElt(Idx);
11332         if (Idx < 0) {
11333           // Propagate Undef.
11334           Mask.push_back(Idx);
11335           continue;
11336         }
11337
11338         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11339                                            : OtherSV->getOperand(1);
11340       } else {
11341         // This shuffle index references an element within N1.
11342         CurrentVec = N1;
11343       }
11344
11345       // Simple case where 'CurrentVec' is UNDEF.
11346       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11347         Mask.push_back(-1);
11348         continue;
11349       }
11350
11351       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11352       // will be the first or second operand of the combined shuffle.
11353       Idx = Idx % NumElts;
11354       if (!SV0.getNode() || SV0 == CurrentVec) {
11355         // Ok. CurrentVec is the left hand side.
11356         // Update the mask accordingly.
11357         SV0 = CurrentVec;
11358         Mask.push_back(Idx);
11359         continue;
11360       }
11361
11362       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11363       if (SV1.getNode() && SV1 != CurrentVec)
11364         return SDValue();
11365
11366       // Ok. CurrentVec is the right hand side.
11367       // Update the mask accordingly.
11368       SV1 = CurrentVec;
11369       Mask.push_back(Idx + NumElts);
11370     }
11371
11372     // Check if all indices in Mask are Undef. In case, propagate Undef.
11373     bool isUndefMask = true;
11374     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11375       isUndefMask &= Mask[i] < 0;
11376
11377     if (isUndefMask)
11378       return DAG.getUNDEF(VT);
11379
11380     if (!SV0.getNode())
11381       SV0 = DAG.getUNDEF(VT);
11382     if (!SV1.getNode())
11383       SV1 = DAG.getUNDEF(VT);
11384
11385     // Avoid introducing shuffles with illegal mask.
11386     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11387       // Compute the commuted shuffle mask and test again.
11388       for (unsigned i = 0; i != NumElts; ++i) {
11389         int idx = Mask[i];
11390         if (idx < 0)
11391           continue;
11392         else if (idx < (int)NumElts)
11393           Mask[i] = idx + NumElts;
11394         else
11395           Mask[i] = idx - NumElts;
11396       }
11397
11398       if (!TLI.isShuffleMaskLegal(Mask, VT))
11399         return SDValue();
11400  
11401       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11402       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11403       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11404       std::swap(SV0, SV1);
11405     }
11406
11407     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11408     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11409     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11410     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11411   }
11412
11413   return SDValue();
11414 }
11415
11416 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11417   SDValue N0 = N->getOperand(0);
11418   SDValue N2 = N->getOperand(2);
11419
11420   // If the input vector is a concatenation, and the insert replaces
11421   // one of the halves, we can optimize into a single concat_vectors.
11422   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11423       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11424     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11425     EVT VT = N->getValueType(0);
11426
11427     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11428     // (concat_vectors Z, Y)
11429     if (InsIdx == 0)
11430       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11431                          N->getOperand(1), N0.getOperand(1));
11432
11433     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11434     // (concat_vectors X, Z)
11435     if (InsIdx == VT.getVectorNumElements()/2)
11436       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11437                          N0.getOperand(0), N->getOperand(1));
11438   }
11439
11440   return SDValue();
11441 }
11442
11443 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11444 /// with the destination vector and a zero vector.
11445 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11446 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11447 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11448   EVT VT = N->getValueType(0);
11449   SDLoc dl(N);
11450   SDValue LHS = N->getOperand(0);
11451   SDValue RHS = N->getOperand(1);
11452   if (N->getOpcode() == ISD::AND) {
11453     if (RHS.getOpcode() == ISD::BITCAST)
11454       RHS = RHS.getOperand(0);
11455     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11456       SmallVector<int, 8> Indices;
11457       unsigned NumElts = RHS.getNumOperands();
11458       for (unsigned i = 0; i != NumElts; ++i) {
11459         SDValue Elt = RHS.getOperand(i);
11460         if (!isa<ConstantSDNode>(Elt))
11461           return SDValue();
11462
11463         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11464           Indices.push_back(i);
11465         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11466           Indices.push_back(NumElts+i);
11467         else
11468           return SDValue();
11469       }
11470
11471       // Let's see if the target supports this vector_shuffle.
11472       EVT RVT = RHS.getValueType();
11473       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11474         return SDValue();
11475
11476       // Return the new VECTOR_SHUFFLE node.
11477       EVT EltVT = RVT.getVectorElementType();
11478       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11479                                      DAG.getConstant(0, EltVT));
11480       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11481       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11482       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11483       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11484     }
11485   }
11486
11487   return SDValue();
11488 }
11489
11490 /// Visit a binary vector operation, like ADD.
11491 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11492   assert(N->getValueType(0).isVector() &&
11493          "SimplifyVBinOp only works on vectors!");
11494
11495   SDValue LHS = N->getOperand(0);
11496   SDValue RHS = N->getOperand(1);
11497   SDValue Shuffle = XformToShuffleWithZero(N);
11498   if (Shuffle.getNode()) return Shuffle;
11499
11500   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11501   // this operation.
11502   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11503       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11504     // Check if both vectors are constants. If not bail out.
11505     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11506           cast<BuildVectorSDNode>(RHS)->isConstant()))
11507       return SDValue();
11508
11509     SmallVector<SDValue, 8> Ops;
11510     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11511       SDValue LHSOp = LHS.getOperand(i);
11512       SDValue RHSOp = RHS.getOperand(i);
11513
11514       // Can't fold divide by zero.
11515       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11516           N->getOpcode() == ISD::FDIV) {
11517         if ((RHSOp.getOpcode() == ISD::Constant &&
11518              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11519             (RHSOp.getOpcode() == ISD::ConstantFP &&
11520              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11521           break;
11522       }
11523
11524       EVT VT = LHSOp.getValueType();
11525       EVT RVT = RHSOp.getValueType();
11526       if (RVT != VT) {
11527         // Integer BUILD_VECTOR operands may have types larger than the element
11528         // size (e.g., when the element type is not legal).  Prior to type
11529         // legalization, the types may not match between the two BUILD_VECTORS.
11530         // Truncate one of the operands to make them match.
11531         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11532           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11533         } else {
11534           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11535           VT = RVT;
11536         }
11537       }
11538       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11539                                    LHSOp, RHSOp);
11540       if (FoldOp.getOpcode() != ISD::UNDEF &&
11541           FoldOp.getOpcode() != ISD::Constant &&
11542           FoldOp.getOpcode() != ISD::ConstantFP)
11543         break;
11544       Ops.push_back(FoldOp);
11545       AddToWorklist(FoldOp.getNode());
11546     }
11547
11548     if (Ops.size() == LHS.getNumOperands())
11549       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11550   }
11551
11552   // Type legalization might introduce new shuffles in the DAG.
11553   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11554   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11555   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11556       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11557       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11558       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11559     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11560     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11561
11562     if (SVN0->getMask().equals(SVN1->getMask())) {
11563       EVT VT = N->getValueType(0);
11564       SDValue UndefVector = LHS.getOperand(1);
11565       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11566                                      LHS.getOperand(0), RHS.getOperand(0));
11567       AddUsersToWorklist(N);
11568       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11569                                   &SVN0->getMask()[0]);
11570     }
11571   }
11572
11573   return SDValue();
11574 }
11575
11576 /// Visit a binary vector operation, like FABS/FNEG.
11577 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11578   assert(N->getValueType(0).isVector() &&
11579          "SimplifyVUnaryOp only works on vectors!");
11580
11581   SDValue N0 = N->getOperand(0);
11582
11583   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11584     return SDValue();
11585
11586   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11587   SmallVector<SDValue, 8> Ops;
11588   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11589     SDValue Op = N0.getOperand(i);
11590     if (Op.getOpcode() != ISD::UNDEF &&
11591         Op.getOpcode() != ISD::ConstantFP)
11592       break;
11593     EVT EltVT = Op.getValueType();
11594     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11595     if (FoldOp.getOpcode() != ISD::UNDEF &&
11596         FoldOp.getOpcode() != ISD::ConstantFP)
11597       break;
11598     Ops.push_back(FoldOp);
11599     AddToWorklist(FoldOp.getNode());
11600   }
11601
11602   if (Ops.size() != N0.getNumOperands())
11603     return SDValue();
11604
11605   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11606 }
11607
11608 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11609                                     SDValue N1, SDValue N2){
11610   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11611
11612   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11613                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11614
11615   // If we got a simplified select_cc node back from SimplifySelectCC, then
11616   // break it down into a new SETCC node, and a new SELECT node, and then return
11617   // the SELECT node, since we were called with a SELECT node.
11618   if (SCC.getNode()) {
11619     // Check to see if we got a select_cc back (to turn into setcc/select).
11620     // Otherwise, just return whatever node we got back, like fabs.
11621     if (SCC.getOpcode() == ISD::SELECT_CC) {
11622       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11623                                   N0.getValueType(),
11624                                   SCC.getOperand(0), SCC.getOperand(1),
11625                                   SCC.getOperand(4));
11626       AddToWorklist(SETCC.getNode());
11627       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11628                            SCC.getOperand(2), SCC.getOperand(3));
11629     }
11630
11631     return SCC;
11632   }
11633   return SDValue();
11634 }
11635
11636 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11637 /// being selected between, see if we can simplify the select.  Callers of this
11638 /// should assume that TheSelect is deleted if this returns true.  As such, they
11639 /// should return the appropriate thing (e.g. the node) back to the top-level of
11640 /// the DAG combiner loop to avoid it being looked at.
11641 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11642                                     SDValue RHS) {
11643
11644   // Cannot simplify select with vector condition
11645   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11646
11647   // If this is a select from two identical things, try to pull the operation
11648   // through the select.
11649   if (LHS.getOpcode() != RHS.getOpcode() ||
11650       !LHS.hasOneUse() || !RHS.hasOneUse())
11651     return false;
11652
11653   // If this is a load and the token chain is identical, replace the select
11654   // of two loads with a load through a select of the address to load from.
11655   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11656   // constants have been dropped into the constant pool.
11657   if (LHS.getOpcode() == ISD::LOAD) {
11658     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11659     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11660
11661     // Token chains must be identical.
11662     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11663         // Do not let this transformation reduce the number of volatile loads.
11664         LLD->isVolatile() || RLD->isVolatile() ||
11665         // If this is an EXTLOAD, the VT's must match.
11666         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11667         // If this is an EXTLOAD, the kind of extension must match.
11668         (LLD->getExtensionType() != RLD->getExtensionType() &&
11669          // The only exception is if one of the extensions is anyext.
11670          LLD->getExtensionType() != ISD::EXTLOAD &&
11671          RLD->getExtensionType() != ISD::EXTLOAD) ||
11672         // FIXME: this discards src value information.  This is
11673         // over-conservative. It would be beneficial to be able to remember
11674         // both potential memory locations.  Since we are discarding
11675         // src value info, don't do the transformation if the memory
11676         // locations are not in the default address space.
11677         LLD->getPointerInfo().getAddrSpace() != 0 ||
11678         RLD->getPointerInfo().getAddrSpace() != 0 ||
11679         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11680                                       LLD->getBasePtr().getValueType()))
11681       return false;
11682
11683     // Check that the select condition doesn't reach either load.  If so,
11684     // folding this will induce a cycle into the DAG.  If not, this is safe to
11685     // xform, so create a select of the addresses.
11686     SDValue Addr;
11687     if (TheSelect->getOpcode() == ISD::SELECT) {
11688       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11689       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11690           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11691         return false;
11692       // The loads must not depend on one another.
11693       if (LLD->isPredecessorOf(RLD) ||
11694           RLD->isPredecessorOf(LLD))
11695         return false;
11696       Addr = DAG.getSelect(SDLoc(TheSelect),
11697                            LLD->getBasePtr().getValueType(),
11698                            TheSelect->getOperand(0), LLD->getBasePtr(),
11699                            RLD->getBasePtr());
11700     } else {  // Otherwise SELECT_CC
11701       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11702       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11703
11704       if ((LLD->hasAnyUseOfValue(1) &&
11705            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11706           (RLD->hasAnyUseOfValue(1) &&
11707            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11708         return false;
11709
11710       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11711                          LLD->getBasePtr().getValueType(),
11712                          TheSelect->getOperand(0),
11713                          TheSelect->getOperand(1),
11714                          LLD->getBasePtr(), RLD->getBasePtr(),
11715                          TheSelect->getOperand(4));
11716     }
11717
11718     SDValue Load;
11719     // It is safe to replace the two loads if they have different alignments,
11720     // but the new load must be the minimum (most restrictive) alignment of the
11721     // inputs.
11722     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11723     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11724     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11725       Load = DAG.getLoad(TheSelect->getValueType(0),
11726                          SDLoc(TheSelect),
11727                          // FIXME: Discards pointer and AA info.
11728                          LLD->getChain(), Addr, MachinePointerInfo(),
11729                          LLD->isVolatile(), LLD->isNonTemporal(),
11730                          isInvariant, Alignment);
11731     } else {
11732       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11733                             RLD->getExtensionType() : LLD->getExtensionType(),
11734                             SDLoc(TheSelect),
11735                             TheSelect->getValueType(0),
11736                             // FIXME: Discards pointer and AA info.
11737                             LLD->getChain(), Addr, MachinePointerInfo(),
11738                             LLD->getMemoryVT(), LLD->isVolatile(),
11739                             LLD->isNonTemporal(), isInvariant, Alignment);
11740     }
11741
11742     // Users of the select now use the result of the load.
11743     CombineTo(TheSelect, Load);
11744
11745     // Users of the old loads now use the new load's chain.  We know the
11746     // old-load value is dead now.
11747     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11748     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11749     return true;
11750   }
11751
11752   return false;
11753 }
11754
11755 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11756 /// where 'cond' is the comparison specified by CC.
11757 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11758                                       SDValue N2, SDValue N3,
11759                                       ISD::CondCode CC, bool NotExtCompare) {
11760   // (x ? y : y) -> y.
11761   if (N2 == N3) return N2;
11762
11763   EVT VT = N2.getValueType();
11764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11765   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11766   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11767
11768   // Determine if the condition we're dealing with is constant
11769   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11770                               N0, N1, CC, DL, false);
11771   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11772   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11773
11774   // fold select_cc true, x, y -> x
11775   if (SCCC && !SCCC->isNullValue())
11776     return N2;
11777   // fold select_cc false, x, y -> y
11778   if (SCCC && SCCC->isNullValue())
11779     return N3;
11780
11781   // Check to see if we can simplify the select into an fabs node
11782   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11783     // Allow either -0.0 or 0.0
11784     if (CFP->getValueAPF().isZero()) {
11785       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11786       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11787           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11788           N2 == N3.getOperand(0))
11789         return DAG.getNode(ISD::FABS, DL, VT, N0);
11790
11791       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11792       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11793           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11794           N2.getOperand(0) == N3)
11795         return DAG.getNode(ISD::FABS, DL, VT, N3);
11796     }
11797   }
11798
11799   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11800   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11801   // in it.  This is a win when the constant is not otherwise available because
11802   // it replaces two constant pool loads with one.  We only do this if the FP
11803   // type is known to be legal, because if it isn't, then we are before legalize
11804   // types an we want the other legalization to happen first (e.g. to avoid
11805   // messing with soft float) and if the ConstantFP is not legal, because if
11806   // it is legal, we may not need to store the FP constant in a constant pool.
11807   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11808     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11809       if (TLI.isTypeLegal(N2.getValueType()) &&
11810           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11811                TargetLowering::Legal &&
11812            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11813            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11814           // If both constants have multiple uses, then we won't need to do an
11815           // extra load, they are likely around in registers for other users.
11816           (TV->hasOneUse() || FV->hasOneUse())) {
11817         Constant *Elts[] = {
11818           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11819           const_cast<ConstantFP*>(TV->getConstantFPValue())
11820         };
11821         Type *FPTy = Elts[0]->getType();
11822         const DataLayout &TD = *TLI.getDataLayout();
11823
11824         // Create a ConstantArray of the two constants.
11825         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11826         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11827                                             TD.getPrefTypeAlignment(FPTy));
11828         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11829
11830         // Get the offsets to the 0 and 1 element of the array so that we can
11831         // select between them.
11832         SDValue Zero = DAG.getIntPtrConstant(0);
11833         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11834         SDValue One = DAG.getIntPtrConstant(EltSize);
11835
11836         SDValue Cond = DAG.getSetCC(DL,
11837                                     getSetCCResultType(N0.getValueType()),
11838                                     N0, N1, CC);
11839         AddToWorklist(Cond.getNode());
11840         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11841                                           Cond, One, Zero);
11842         AddToWorklist(CstOffset.getNode());
11843         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11844                             CstOffset);
11845         AddToWorklist(CPIdx.getNode());
11846         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11847                            MachinePointerInfo::getConstantPool(), false,
11848                            false, false, Alignment);
11849
11850       }
11851     }
11852
11853   // Check to see if we can perform the "gzip trick", transforming
11854   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11855   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11856       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11857        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11858     EVT XType = N0.getValueType();
11859     EVT AType = N2.getValueType();
11860     if (XType.bitsGE(AType)) {
11861       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11862       // single-bit constant.
11863       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11864         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11865         ShCtV = XType.getSizeInBits()-ShCtV-1;
11866         SDValue ShCt = DAG.getConstant(ShCtV,
11867                                        getShiftAmountTy(N0.getValueType()));
11868         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11869                                     XType, N0, ShCt);
11870         AddToWorklist(Shift.getNode());
11871
11872         if (XType.bitsGT(AType)) {
11873           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11874           AddToWorklist(Shift.getNode());
11875         }
11876
11877         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11878       }
11879
11880       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11881                                   XType, N0,
11882                                   DAG.getConstant(XType.getSizeInBits()-1,
11883                                          getShiftAmountTy(N0.getValueType())));
11884       AddToWorklist(Shift.getNode());
11885
11886       if (XType.bitsGT(AType)) {
11887         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11888         AddToWorklist(Shift.getNode());
11889       }
11890
11891       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11892     }
11893   }
11894
11895   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11896   // where y is has a single bit set.
11897   // A plaintext description would be, we can turn the SELECT_CC into an AND
11898   // when the condition can be materialized as an all-ones register.  Any
11899   // single bit-test can be materialized as an all-ones register with
11900   // shift-left and shift-right-arith.
11901   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11902       N0->getValueType(0) == VT &&
11903       N1C && N1C->isNullValue() &&
11904       N2C && N2C->isNullValue()) {
11905     SDValue AndLHS = N0->getOperand(0);
11906     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11907     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11908       // Shift the tested bit over the sign bit.
11909       APInt AndMask = ConstAndRHS->getAPIntValue();
11910       SDValue ShlAmt =
11911         DAG.getConstant(AndMask.countLeadingZeros(),
11912                         getShiftAmountTy(AndLHS.getValueType()));
11913       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11914
11915       // Now arithmetic right shift it all the way over, so the result is either
11916       // all-ones, or zero.
11917       SDValue ShrAmt =
11918         DAG.getConstant(AndMask.getBitWidth()-1,
11919                         getShiftAmountTy(Shl.getValueType()));
11920       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11921
11922       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11923     }
11924   }
11925
11926   // fold select C, 16, 0 -> shl C, 4
11927   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11928       TLI.getBooleanContents(N0.getValueType()) ==
11929           TargetLowering::ZeroOrOneBooleanContent) {
11930
11931     // If the caller doesn't want us to simplify this into a zext of a compare,
11932     // don't do it.
11933     if (NotExtCompare && N2C->getAPIntValue() == 1)
11934       return SDValue();
11935
11936     // Get a SetCC of the condition
11937     // NOTE: Don't create a SETCC if it's not legal on this target.
11938     if (!LegalOperations ||
11939         TLI.isOperationLegal(ISD::SETCC,
11940           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11941       SDValue Temp, SCC;
11942       // cast from setcc result type to select result type
11943       if (LegalTypes) {
11944         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11945                             N0, N1, CC);
11946         if (N2.getValueType().bitsLT(SCC.getValueType()))
11947           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11948                                         N2.getValueType());
11949         else
11950           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11951                              N2.getValueType(), SCC);
11952       } else {
11953         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11954         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11955                            N2.getValueType(), SCC);
11956       }
11957
11958       AddToWorklist(SCC.getNode());
11959       AddToWorklist(Temp.getNode());
11960
11961       if (N2C->getAPIntValue() == 1)
11962         return Temp;
11963
11964       // shl setcc result by log2 n2c
11965       return DAG.getNode(
11966           ISD::SHL, DL, N2.getValueType(), Temp,
11967           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11968                           getShiftAmountTy(Temp.getValueType())));
11969     }
11970   }
11971
11972   // Check to see if this is the equivalent of setcc
11973   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11974   // otherwise, go ahead with the folds.
11975   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11976     EVT XType = N0.getValueType();
11977     if (!LegalOperations ||
11978         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11979       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11980       if (Res.getValueType() != VT)
11981         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11982       return Res;
11983     }
11984
11985     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11986     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11987         (!LegalOperations ||
11988          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11989       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11990       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11991                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11992                                        getShiftAmountTy(Ctlz.getValueType())));
11993     }
11994     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11995     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11996       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11997                                   XType, DAG.getConstant(0, XType), N0);
11998       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11999       return DAG.getNode(ISD::SRL, DL, XType,
12000                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12001                          DAG.getConstant(XType.getSizeInBits()-1,
12002                                          getShiftAmountTy(XType)));
12003     }
12004     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12005     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12006       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12007                                  DAG.getConstant(XType.getSizeInBits()-1,
12008                                          getShiftAmountTy(N0.getValueType())));
12009       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12010     }
12011   }
12012
12013   // Check to see if this is an integer abs.
12014   // select_cc setg[te] X,  0,  X, -X ->
12015   // select_cc setgt    X, -1,  X, -X ->
12016   // select_cc setl[te] X,  0, -X,  X ->
12017   // select_cc setlt    X,  1, -X,  X ->
12018   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12019   if (N1C) {
12020     ConstantSDNode *SubC = nullptr;
12021     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12022          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12023         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12024       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12025     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12026               (N1C->isOne() && CC == ISD::SETLT)) &&
12027              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12028       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12029
12030     EVT XType = N0.getValueType();
12031     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12032       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12033                                   N0,
12034                                   DAG.getConstant(XType.getSizeInBits()-1,
12035                                          getShiftAmountTy(N0.getValueType())));
12036       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12037                                 XType, N0, Shift);
12038       AddToWorklist(Shift.getNode());
12039       AddToWorklist(Add.getNode());
12040       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12041     }
12042   }
12043
12044   return SDValue();
12045 }
12046
12047 /// This is a stub for TargetLowering::SimplifySetCC.
12048 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12049                                    SDValue N1, ISD::CondCode Cond,
12050                                    SDLoc DL, bool foldBooleans) {
12051   TargetLowering::DAGCombinerInfo
12052     DagCombineInfo(DAG, Level, false, this);
12053   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12054 }
12055
12056 /// Given an ISD::SDIV node expressing a divide by constant, return
12057 /// a DAG expression to select that will generate the same value by multiplying
12058 /// by a magic number.
12059 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12060 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12061   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12062   if (!C)
12063     return SDValue();
12064
12065   // Avoid division by zero.
12066   if (!C->getAPIntValue())
12067     return SDValue();
12068
12069   std::vector<SDNode*> Built;
12070   SDValue S =
12071       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12072
12073   for (SDNode *N : Built)
12074     AddToWorklist(N);
12075   return S;
12076 }
12077
12078 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12079 /// DAG expression that will generate the same value by right shifting.
12080 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12081   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12082   if (!C)
12083     return SDValue();
12084
12085   // Avoid division by zero.
12086   if (!C->getAPIntValue())
12087     return SDValue();
12088
12089   std::vector<SDNode *> Built;
12090   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12091
12092   for (SDNode *N : Built)
12093     AddToWorklist(N);
12094   return S;
12095 }
12096
12097 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12098 /// expression that will generate the same value by multiplying by a magic
12099 /// number.
12100 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12101 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12102   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12103   if (!C)
12104     return SDValue();
12105
12106   // Avoid division by zero.
12107   if (!C->getAPIntValue())
12108     return SDValue();
12109
12110   std::vector<SDNode*> Built;
12111   SDValue S =
12112       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12113
12114   for (SDNode *N : Built)
12115     AddToWorklist(N);
12116   return S;
12117 }
12118
12119 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12120   if (Level >= AfterLegalizeDAG)
12121     return SDValue();
12122
12123   // Expose the DAG combiner to the target combiner implementations.
12124   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12125
12126   unsigned Iterations = 0;
12127   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12128     if (Iterations) {
12129       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12130       // For the reciprocal, we need to find the zero of the function:
12131       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12132       //     =>
12133       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12134       //     does not require additional intermediate precision]
12135       EVT VT = Op.getValueType();
12136       SDLoc DL(Op);
12137       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12138
12139       AddToWorklist(Est.getNode());
12140
12141       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12142       for (unsigned i = 0; i < Iterations; ++i) {
12143         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12144         AddToWorklist(NewEst.getNode());
12145
12146         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12147         AddToWorklist(NewEst.getNode());
12148
12149         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12150         AddToWorklist(NewEst.getNode());
12151
12152         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12153         AddToWorklist(Est.getNode());
12154       }
12155     }
12156     return Est;
12157   }
12158
12159   return SDValue();
12160 }
12161
12162 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12163 /// For the reciprocal sqrt, we need to find the zero of the function:
12164 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12165 ///     =>
12166 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12167 /// As a result, we precompute A/2 prior to the iteration loop.
12168 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12169                                           unsigned Iterations) {
12170   EVT VT = Arg.getValueType();
12171   SDLoc DL(Arg);
12172   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12173
12174   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12175   // this entire sequence requires only one FP constant.
12176   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12177   AddToWorklist(HalfArg.getNode());
12178
12179   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12180   AddToWorklist(HalfArg.getNode());
12181
12182   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12183   for (unsigned i = 0; i < Iterations; ++i) {
12184     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12185     AddToWorklist(NewEst.getNode());
12186
12187     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12188     AddToWorklist(NewEst.getNode());
12189
12190     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12191     AddToWorklist(NewEst.getNode());
12192
12193     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12194     AddToWorklist(Est.getNode());
12195   }
12196   return Est;
12197 }
12198
12199 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12200 /// For the reciprocal sqrt, we need to find the zero of the function:
12201 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12202 ///     =>
12203 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12204 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12205                                           unsigned Iterations) {
12206   EVT VT = Arg.getValueType();
12207   SDLoc DL(Arg);
12208   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12209   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12210
12211   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12212   for (unsigned i = 0; i < Iterations; ++i) {
12213     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12214     AddToWorklist(HalfEst.getNode());
12215
12216     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12217     AddToWorklist(Est.getNode());
12218
12219     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12220     AddToWorklist(Est.getNode());
12221
12222     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12223     AddToWorklist(Est.getNode());
12224
12225     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12226     AddToWorklist(Est.getNode());
12227   }
12228   return Est;
12229 }
12230
12231 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12232   if (Level >= AfterLegalizeDAG)
12233     return SDValue();
12234
12235   // Expose the DAG combiner to the target combiner implementations.
12236   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12237   unsigned Iterations = 0;
12238   bool UseOneConstNR = false;
12239   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12240     AddToWorklist(Est.getNode());
12241     if (Iterations) {
12242       Est = UseOneConstNR ?
12243         BuildRsqrtNROneConst(Op, Est, Iterations) :
12244         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12245     }
12246     return Est;
12247   }
12248
12249   return SDValue();
12250 }
12251
12252 /// Return true if base is a frame index, which is known not to alias with
12253 /// anything but itself.  Provides base object and offset as results.
12254 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12255                            const GlobalValue *&GV, const void *&CV) {
12256   // Assume it is a primitive operation.
12257   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12258
12259   // If it's an adding a simple constant then integrate the offset.
12260   if (Base.getOpcode() == ISD::ADD) {
12261     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12262       Base = Base.getOperand(0);
12263       Offset += C->getZExtValue();
12264     }
12265   }
12266
12267   // Return the underlying GlobalValue, and update the Offset.  Return false
12268   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12269   // by multiple nodes with different offsets.
12270   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12271     GV = G->getGlobal();
12272     Offset += G->getOffset();
12273     return false;
12274   }
12275
12276   // Return the underlying Constant value, and update the Offset.  Return false
12277   // for ConstantSDNodes since the same constant pool entry may be represented
12278   // by multiple nodes with different offsets.
12279   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12280     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12281                                          : (const void *)C->getConstVal();
12282     Offset += C->getOffset();
12283     return false;
12284   }
12285   // If it's any of the following then it can't alias with anything but itself.
12286   return isa<FrameIndexSDNode>(Base);
12287 }
12288
12289 /// Return true if there is any possibility that the two addresses overlap.
12290 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12291   // If they are the same then they must be aliases.
12292   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12293
12294   // If they are both volatile then they cannot be reordered.
12295   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12296
12297   // Gather base node and offset information.
12298   SDValue Base1, Base2;
12299   int64_t Offset1, Offset2;
12300   const GlobalValue *GV1, *GV2;
12301   const void *CV1, *CV2;
12302   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12303                                       Base1, Offset1, GV1, CV1);
12304   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12305                                       Base2, Offset2, GV2, CV2);
12306
12307   // If they have a same base address then check to see if they overlap.
12308   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12309     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12310              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12311
12312   // It is possible for different frame indices to alias each other, mostly
12313   // when tail call optimization reuses return address slots for arguments.
12314   // To catch this case, look up the actual index of frame indices to compute
12315   // the real alias relationship.
12316   if (isFrameIndex1 && isFrameIndex2) {
12317     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12318     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12319     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12320     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12321              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12322   }
12323
12324   // Otherwise, if we know what the bases are, and they aren't identical, then
12325   // we know they cannot alias.
12326   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12327     return false;
12328
12329   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12330   // compared to the size and offset of the access, we may be able to prove they
12331   // do not alias.  This check is conservative for now to catch cases created by
12332   // splitting vector types.
12333   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12334       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12335       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12336        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12337       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12338     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12339     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12340
12341     // There is no overlap between these relatively aligned accesses of similar
12342     // size, return no alias.
12343     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12344         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12345       return false;
12346   }
12347
12348   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12349                    ? CombinerGlobalAA
12350                    : DAG.getSubtarget().useAA();
12351 #ifndef NDEBUG
12352   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12353       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12354     UseAA = false;
12355 #endif
12356   if (UseAA &&
12357       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12358     // Use alias analysis information.
12359     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12360                                  Op1->getSrcValueOffset());
12361     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12362         Op0->getSrcValueOffset() - MinOffset;
12363     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12364         Op1->getSrcValueOffset() - MinOffset;
12365     AliasAnalysis::AliasResult AAResult =
12366         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12367                                          Overlap1,
12368                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12369                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12370                                          Overlap2,
12371                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12372     if (AAResult == AliasAnalysis::NoAlias)
12373       return false;
12374   }
12375
12376   // Otherwise we have to assume they alias.
12377   return true;
12378 }
12379
12380 /// Walk up chain skipping non-aliasing memory nodes,
12381 /// looking for aliasing nodes and adding them to the Aliases vector.
12382 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12383                                    SmallVectorImpl<SDValue> &Aliases) {
12384   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12385   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12386
12387   // Get alias information for node.
12388   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12389
12390   // Starting off.
12391   Chains.push_back(OriginalChain);
12392   unsigned Depth = 0;
12393
12394   // Look at each chain and determine if it is an alias.  If so, add it to the
12395   // aliases list.  If not, then continue up the chain looking for the next
12396   // candidate.
12397   while (!Chains.empty()) {
12398     SDValue Chain = Chains.back();
12399     Chains.pop_back();
12400
12401     // For TokenFactor nodes, look at each operand and only continue up the
12402     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12403     // find more and revert to original chain since the xform is unlikely to be
12404     // profitable.
12405     //
12406     // FIXME: The depth check could be made to return the last non-aliasing
12407     // chain we found before we hit a tokenfactor rather than the original
12408     // chain.
12409     if (Depth > 6 || Aliases.size() == 2) {
12410       Aliases.clear();
12411       Aliases.push_back(OriginalChain);
12412       return;
12413     }
12414
12415     // Don't bother if we've been before.
12416     if (!Visited.insert(Chain.getNode()).second)
12417       continue;
12418
12419     switch (Chain.getOpcode()) {
12420     case ISD::EntryToken:
12421       // Entry token is ideal chain operand, but handled in FindBetterChain.
12422       break;
12423
12424     case ISD::LOAD:
12425     case ISD::STORE: {
12426       // Get alias information for Chain.
12427       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12428           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12429
12430       // If chain is alias then stop here.
12431       if (!(IsLoad && IsOpLoad) &&
12432           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12433         Aliases.push_back(Chain);
12434       } else {
12435         // Look further up the chain.
12436         Chains.push_back(Chain.getOperand(0));
12437         ++Depth;
12438       }
12439       break;
12440     }
12441
12442     case ISD::TokenFactor:
12443       // We have to check each of the operands of the token factor for "small"
12444       // token factors, so we queue them up.  Adding the operands to the queue
12445       // (stack) in reverse order maintains the original order and increases the
12446       // likelihood that getNode will find a matching token factor (CSE.)
12447       if (Chain.getNumOperands() > 16) {
12448         Aliases.push_back(Chain);
12449         break;
12450       }
12451       for (unsigned n = Chain.getNumOperands(); n;)
12452         Chains.push_back(Chain.getOperand(--n));
12453       ++Depth;
12454       break;
12455
12456     default:
12457       // For all other instructions we will just have to take what we can get.
12458       Aliases.push_back(Chain);
12459       break;
12460     }
12461   }
12462
12463   // We need to be careful here to also search for aliases through the
12464   // value operand of a store, etc. Consider the following situation:
12465   //   Token1 = ...
12466   //   L1 = load Token1, %52
12467   //   S1 = store Token1, L1, %51
12468   //   L2 = load Token1, %52+8
12469   //   S2 = store Token1, L2, %51+8
12470   //   Token2 = Token(S1, S2)
12471   //   L3 = load Token2, %53
12472   //   S3 = store Token2, L3, %52
12473   //   L4 = load Token2, %53+8
12474   //   S4 = store Token2, L4, %52+8
12475   // If we search for aliases of S3 (which loads address %52), and we look
12476   // only through the chain, then we'll miss the trivial dependence on L1
12477   // (which also loads from %52). We then might change all loads and
12478   // stores to use Token1 as their chain operand, which could result in
12479   // copying %53 into %52 before copying %52 into %51 (which should
12480   // happen first).
12481   //
12482   // The problem is, however, that searching for such data dependencies
12483   // can become expensive, and the cost is not directly related to the
12484   // chain depth. Instead, we'll rule out such configurations here by
12485   // insisting that we've visited all chain users (except for users
12486   // of the original chain, which is not necessary). When doing this,
12487   // we need to look through nodes we don't care about (otherwise, things
12488   // like register copies will interfere with trivial cases).
12489
12490   SmallVector<const SDNode *, 16> Worklist;
12491   for (const SDNode *N : Visited)
12492     if (N != OriginalChain.getNode())
12493       Worklist.push_back(N);
12494
12495   while (!Worklist.empty()) {
12496     const SDNode *M = Worklist.pop_back_val();
12497
12498     // We have already visited M, and want to make sure we've visited any uses
12499     // of M that we care about. For uses that we've not visisted, and don't
12500     // care about, queue them to the worklist.
12501
12502     for (SDNode::use_iterator UI = M->use_begin(),
12503          UIE = M->use_end(); UI != UIE; ++UI)
12504       if (UI.getUse().getValueType() == MVT::Other &&
12505           Visited.insert(*UI).second) {
12506         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12507           // We've not visited this use, and we care about it (it could have an
12508           // ordering dependency with the original node).
12509           Aliases.clear();
12510           Aliases.push_back(OriginalChain);
12511           return;
12512         }
12513
12514         // We've not visited this use, but we don't care about it. Mark it as
12515         // visited and enqueue it to the worklist.
12516         Worklist.push_back(*UI);
12517       }
12518   }
12519 }
12520
12521 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12522 /// (aliasing node.)
12523 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12524   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12525
12526   // Accumulate all the aliases to this node.
12527   GatherAllAliases(N, OldChain, Aliases);
12528
12529   // If no operands then chain to entry token.
12530   if (Aliases.size() == 0)
12531     return DAG.getEntryNode();
12532
12533   // If a single operand then chain to it.  We don't need to revisit it.
12534   if (Aliases.size() == 1)
12535     return Aliases[0];
12536
12537   // Construct a custom tailored token factor.
12538   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12539 }
12540
12541 /// This is the entry point for the file.
12542 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12543                            CodeGenOpt::Level OptLevel) {
12544   /// This is the main entry point to this class.
12545   DAGCombiner(*this, AA, OptLevel).Run(Level);
12546 }